<commit_before>'use strict';

function calculate_wcag(source, offset, length){
    source = document.getElementById(source).value;
    let math = Number.parseInt(
      length === 4
        ? source[offset / 2] + source[offset / 2]
        : source.substring(
          offset - 1,
          offset + 1
        ),
      16
    ) / 255;

    return math <= .03928
      ? math / 12.92
      : Math.pow(
        ((math + .055) / 1.055),
        2.4
      );
}

function darken_lighten(change){
    let hex = document.getElementById('hex').value;
    let hexlength = hex.length === 3;

    // Get colors.
    let blue =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(2, 3) + hex.substring(2, 3)
            : hex.substring(4, 6),
          16
        )
      ) / 51) * .2;
    let green =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(1, 2) + hex.substring(1, 2)
            : hex.substring(2, 4),
          16
        )
      ) / 51) * .2;
    let red =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(0, 1) + hex.substring(0, 1)
            : hex.substring(0, 2),
          16
        )
      ) / 51) * .2;

    let Max = 0;
    let Min = 0;

    Max = eval(eval(red) >= eval(green)
      ? red
      : green
    );
    if(eval(blue) > eval(Max)){
        Max = eval(blue);
    }
    Min = eval(eval(red) <= eval(green)
      ? red
      : green
    );
    if(eval(blue) < eval(Min)){
        Min = eval(blue);
    }

    let H = 0;
    let L = Math.round(
      (eval(Max) + eval(Min)) * 50
    );
    let S = 0;

    // Luminosity calculations.
    L = (L + (change ? 6.25 : -6.25)) / 100;
    if(L > 1){
        L = 1;

    }else if(L < 0){
        L = 0;
    }

    if(eval(Max) != eval(Min)){
        let dx = (eval(Max) - eval(Min));
        if(red === Max){
            H = (eval(green) - eval(blue)) / dx;
        }
        if(green === Max){
            H = 2 + (eval(blue) - eval(red)) / dx;
        }
        if(blue === Max){
            H = 4 + (eval(red) - eval(green)) / dx;
        }
        S = dx
          / (L<.5
            ? eval(Max) + eval(Min)
            : 2 - eval(Max) - eval(Min)
          );
    }

    H = Math.round(H * 60);
    if(H < 0){
        H += 360;

    }else if(H >= 360){
        H -= 360;
    }

    let temp = L < .5
      ? L * (1 + S)
      : L + S - (L * S);
    let temp2 = 2 * L - temp;
    red = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H + 120
      ) * 255
    );
    green = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H
      ) * 255
    );
    blue = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H - 120
      ) * 255
    );

    document.getElementById('red-255').value =
      (red < 0 || red > 255)
        ? 0
        : red;
    document.getElementById('green-255').value =
      (green < 0 || green > 255)
        ? 0
        : green;
    document.getElementById('blue-255').value =
      (blue < 0 || blue > 255)
        ? 0
        : blue;

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_hex();
}

function darken_lighten_math(d0, d1, d2){
    if(d2 > 360){
        d2 = d2 - 360;

    }else if(d2 < 0){
        d2 = d2 + 360;
    }

    if(d2 < 60){
        return d0 + (d1 - d0) * d2 / 60;

    }else if(d2 < 180){
        return d1;

    }else if(d2 < 240){
        return d0 + (d1 - d0) * (240 - d2) / 60;

    }else{
        return d0;
    }
}

function hexvalues(i){
    return '0123456789abcdef'.charAt(i);
}

function random_color(color){
    color = color || 'hex';

    if(color === 'hex'){
        document.getElementById(color).value = core_random_hex();
        update_fromhex();

    }else{
        document.getElementById(color).value = core_random_integer({
          'max': 256,
        });
        update_fromslider(color);
    }
}

function update_display(){
    // Set hex-color value to hex value.
    document.getElementById('hex-color').value =
      '#' + document.getElementById('hex').value;

    // Update the background color for each display.
    document.getElementById('display-hex').style.background = 'rgb('
      + Number.parseInt(document.getElementById('red').value, 10) + ','
      + Number.parseInt(document.getElementById('green').value, 10) + ','
      + Number.parseInt(document.getElementById('blue').value, 10) + ')';
    document.getElementById('display-red').style.background = 'rgb('
      + Number.parseInt(document.getElementById('red').value, 10)
      + ',0,0)';
    document.getElementById('display-green').style.background = 'rgb(0,'
      + Number.parseInt(document.getElementById('green').value, 10)
      + ',0)';
    document.getElementById('display-blue').style.background = 'rgb(0,0,'
      + Number.parseInt(document.getElementById('blue').value, 10) + ')';
}

function update_from1(color){
    // Update value of slider when 0-1 text input is changed
    //   and validate 0-1 text input value isn't less than 0 or greater than 1.
    let color_value = document.getElementById(color + '-1').value;
    if(Number.isNaN(color_value)
      || color_value < 0
      || color_value > 1){
        color_value = 0;
        document.getElementById(color + '-1').value = color_value;
    }

    color_value = Math.round(color_value * 255);
    document.getElementById(color).value = color_value;
    document.getElementById(color + '-255').value = color_value;
    update_display();
}

function update_from255(color){
    // Update value of slider when 0-255 text input is changed
    //   and validate 0-255 text input value is a number that isn't less than 0 or greater than 255.
    let color_value = document.getElementById(color + '-255').value;
    if(Number.isNaN(color_value)
      || color_value < 0
      || color_value > 255){
        document.getElementById(color + '-255').value = 0;
    }

    // If 0-255 text input length is 0, just use color value of 0 instead of messing with user input.
    color_value = document.getElementById(color + '-255').value;
    document.getElementById(color).value = color_value.length < 1
      ? 0
      : color_value;
    document.getElementById(color + '-1').value = color_value.length < 1
      ? 0
      : (color_value / 255).toFixed(7);

    update_display();
}

function update_fromhex(){
    // Update values of slider/text inputs when hex input is changed.
    // Hex length of 3 is valid.
    let hex = document.getElementById('hex').value;
    let hexlength = hex.length === 3;

    document.getElementById('blue-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(2, 3) + hex.substring(2, 3)
          : hex.substring(4, 6),
        16
      );
    document.getElementById('green-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(1, 2) + hex.substring(1, 2)
          : hex.substring(2, 4),
        16
      );
    document.getElementById('red-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(0, 1) + hex.substring(0, 1)
          : hex.substring(0, 2),
        16
      );

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_display();
}

function update_fromslider(color){
    // Update values of hex and text inputs when slider is slided.
    let color_value = document.getElementById(color).value;
    document.getElementById(color + '-1').value = (color_value / 255).toFixed(7);
    document.getElementById(color + '-255').value = color_value;

    update_display();
    update_hex();
}

function update_hex(){
    // Update the hex value based on slider values.
    let red = Math.max(0, Math.min(Number.parseInt(document.getElementById('red').value, 10), 255));
    let green = Math.max(0, Math.min(Number.parseInt(document.getElementById('green').value, 10), 255));
    let blue = Math.max(0, Math.min(Number.parseInt(document.getElementById('blue').value, 10), 255));

    document.getElementById('hex').value =
      hexvalues((red - red % 16) / 16) + hexvalues(red % 16)
      + hexvalues((green - green % 16) / 16) + hexvalues(green % 16)
      + hexvalues((blue - blue % 16) / 16) + hexvalues(blue % 16);

    update_display();
}

function update_wcag(source_hex, length_background, length_foreground){
    if(length_foreground === -1){
        length_foreground = length_background;
    }

    let background_math =
      (.2126 * calculate_wcag('wcag-background-color', 2, length_background)
      + .7152 * calculate_wcag('wcag-background-color', 4, length_background)
      + .0722 * calculate_wcag('wcag-background-color', 6, length_background)
    );
    let foreground_math =
      (.2126 * calculate_wcag('wcag-foreground-color', 2, length_foreground)
      + .7152 * calculate_wcag('wcag-foreground-color', 4, length_foreground)
      + .0722 * calculate_wcag('wcag-foreground-color', 6, length_foreground)
    );

    let wcag_score = Math.round(
      (Math.max(background_math, foreground_math) + .05)
      / (Math.min(background_math, foreground_math) + .05)
      * 10
    ) / 10;

    document.getElementById('wcag-text-normal-result').innerHTML =
      wcag_score + ' / 7 = AAA '
      + (wcag_score > 7
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 4.5 = AA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      );
    document.getElementById('wcag-text-large-result').innerHTML =
      wcag_score + ' / 4.5 = AAA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 3 = AA '
      + (wcag_score > 3
        ? 'Passed'
        : 'Failed'
      );

    let background = document.getElementById('wcag-background-color').value;
    let foreground = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-background').value = length_background === 4
      ? '#'
        + background[1] + background[1]
        + background[2] + background[2]
        + background[3] + background[3]
      : background;
    document.getElementById('wcag-foreground').value = length_foreground === 4
      ? '#'
        + foreground[1] + foreground[1]
        + foreground[2] + foreground[2]
        + foreground[3] + foreground[3]
      : foreground;
    document.getElementById('wcag-text-normal').style.backgroundColor = background;
    document.getElementById('wcag-text-normal').style.color = foreground;
    document.getElementById('wcag-text-large').style.backgroundColor = background;
    document.getElementById('wcag-text-large').style.color = foreground;
}

function wcag_set(target){
    let color = '#' + document.getElementById('hex').value;

    document.getElementById('wcag-' + target + '-color').value = color;
    document.getElementById('display-' + target).style.backgroundColor = color;

    update_wcag(
      'wcag-' + target + '-color',
      document.getElementById('wcag-' + target + '-color').value.length,
      -1
    );
}

function wcag_switch(){
    let background = document.getElementById('wcag-background-color').value;
    let foreground = document.getElementById('wcag-foreground-color').value;

    document.getElementById('wcag-background-color').value = foreground;
    document.getElementById('wcag-foreground-color').value = background;
    document.getElementById('display-background').style.backgroundColor = foreground;
    document.getElementById('display-foreground').style.backgroundColor = background;

    update_wcag(
      'wcag-background-color',
      document.getElementById('wcag-background-color').value.length,
      temp.length
    );
}
<commit_msg>added color input update to wcag_switch()<commit_after>'use strict';

function calculate_wcag(source, offset, length){
    source = document.getElementById(source).value;
    let math = Number.parseInt(
      length === 4
        ? source[offset / 2] + source[offset / 2]
        : source.substring(
          offset - 1,
          offset + 1
        ),
      16
    ) / 255;

    return math <= .03928
      ? math / 12.92
      : Math.pow(
        ((math + .055) / 1.055),
        2.4
      );
}

function darken_lighten(change){
    let hex = document.getElementById('hex').value;
    let hexlength = hex.length === 3;

    // Get colors.
    let blue =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(2, 3) + hex.substring(2, 3)
            : hex.substring(4, 6),
          16
        )
      ) / 51) * .2;
    let green =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(1, 2) + hex.substring(1, 2)
            : hex.substring(2, 4),
          16
        )
      ) / 51) * .2;
    let red =
      (eval(
        Number.parseInt(
          hexlength
            ? hex.substring(0, 1) + hex.substring(0, 1)
            : hex.substring(0, 2),
          16
        )
      ) / 51) * .2;

    let Max = 0;
    let Min = 0;

    Max = eval(eval(red) >= eval(green)
      ? red
      : green
    );
    if(eval(blue) > eval(Max)){
        Max = eval(blue);
    }
    Min = eval(eval(red) <= eval(green)
      ? red
      : green
    );
    if(eval(blue) < eval(Min)){
        Min = eval(blue);
    }

    let H = 0;
    let L = Math.round(
      (eval(Max) + eval(Min)) * 50
    );
    let S = 0;

    // Luminosity calculations.
    L = (L + (change ? 6.25 : -6.25)) / 100;
    if(L > 1){
        L = 1;

    }else if(L < 0){
        L = 0;
    }

    if(eval(Max) != eval(Min)){
        let dx = (eval(Max) - eval(Min));
        if(red === Max){
            H = (eval(green) - eval(blue)) / dx;
        }
        if(green === Max){
            H = 2 + (eval(blue) - eval(red)) / dx;
        }
        if(blue === Max){
            H = 4 + (eval(red) - eval(green)) / dx;
        }
        S = dx
          / (L<.5
            ? eval(Max) + eval(Min)
            : 2 - eval(Max) - eval(Min)
          );
    }

    H = Math.round(H * 60);
    if(H < 0){
        H += 360;

    }else if(H >= 360){
        H -= 360;
    }

    let temp = L < .5
      ? L * (1 + S)
      : L + S - (L * S);
    let temp2 = 2 * L - temp;
    red = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H + 120
      ) * 255
    );
    green = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H
      ) * 255
    );
    blue = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H - 120
      ) * 255
    );

    document.getElementById('red-255').value =
      (red < 0 || red > 255)
        ? 0
        : red;
    document.getElementById('green-255').value =
      (green < 0 || green > 255)
        ? 0
        : green;
    document.getElementById('blue-255').value =
      (blue < 0 || blue > 255)
        ? 0
        : blue;

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_hex();
}

function darken_lighten_math(d0, d1, d2){
    if(d2 > 360){
        d2 = d2 - 360;

    }else if(d2 < 0){
        d2 = d2 + 360;
    }

    if(d2 < 60){
        return d0 + (d1 - d0) * d2 / 60;

    }else if(d2 < 180){
        return d1;

    }else if(d2 < 240){
        return d0 + (d1 - d0) * (240 - d2) / 60;

    }else{
        return d0;
    }
}

function hexvalues(i){
    return '0123456789abcdef'.charAt(i);
}

function random_color(color){
    color = color || 'hex';

    if(color === 'hex'){
        document.getElementById(color).value = core_random_hex();
        update_fromhex();

    }else{
        document.getElementById(color).value = core_random_integer({
          'max': 256,
        });
        update_fromslider(color);
    }
}

function update_display(){
    // Set hex-color value to hex value.
    document.getElementById('hex-color').value =
      '#' + document.getElementById('hex').value;

    // Update the background color for each display.
    document.getElementById('display-hex').style.background = 'rgb('
      + Number.parseInt(document.getElementById('red').value, 10) + ','
      + Number.parseInt(document.getElementById('green').value, 10) + ','
      + Number.parseInt(document.getElementById('blue').value, 10) + ')';
    document.getElementById('display-red').style.background = 'rgb('
      + Number.parseInt(document.getElementById('red').value, 10)
      + ',0,0)';
    document.getElementById('display-green').style.background = 'rgb(0,'
      + Number.parseInt(document.getElementById('green').value, 10)
      + ',0)';
    document.getElementById('display-blue').style.background = 'rgb(0,0,'
      + Number.parseInt(document.getElementById('blue').value, 10) + ')';
}

function update_from1(color){
    // Update value of slider when 0-1 text input is changed
    //   and validate 0-1 text input value isn't less than 0 or greater than 1.
    let color_value = document.getElementById(color + '-1').value;
    if(Number.isNaN(color_value)
      || color_value < 0
      || color_value > 1){
        color_value = 0;
        document.getElementById(color + '-1').value = color_value;
    }

    color_value = Math.round(color_value * 255);
    document.getElementById(color).value = color_value;
    document.getElementById(color + '-255').value = color_value;
    update_display();
}

function update_from255(color){
    // Update value of slider when 0-255 text input is changed
    //   and validate 0-255 text input value is a number that isn't less than 0 or greater than 255.
    let color_value = document.getElementById(color + '-255').value;
    if(Number.isNaN(color_value)
      || color_value < 0
      || color_value > 255){
        document.getElementById(color + '-255').value = 0;
    }

    // If 0-255 text input length is 0, just use color value of 0 instead of messing with user input.
    color_value = document.getElementById(color + '-255').value;
    document.getElementById(color).value = color_value.length < 1
      ? 0
      : color_value;
    document.getElementById(color + '-1').value = color_value.length < 1
      ? 0
      : (color_value / 255).toFixed(7);

    update_display();
}

function update_fromhex(){
    // Update values of slider/text inputs when hex input is changed.
    // Hex length of 3 is valid.
    let hex = document.getElementById('hex').value;
    let hexlength = hex.length === 3;

    document.getElementById('blue-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(2, 3) + hex.substring(2, 3)
          : hex.substring(4, 6),
        16
      );
    document.getElementById('green-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(1, 2) + hex.substring(1, 2)
          : hex.substring(2, 4),
        16
      );
    document.getElementById('red-255').value =
      Number.parseInt(
        hexlength
          ? hex.substring(0, 1) + hex.substring(0, 1)
          : hex.substring(0, 2),
        16
      );

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_display();
}

function update_fromslider(color){
    // Update values of hex and text inputs when slider is slided.
    let color_value = document.getElementById(color).value;
    document.getElementById(color + '-1').value = (color_value / 255).toFixed(7);
    document.getElementById(color + '-255').value = color_value;

    update_display();
    update_hex();
}

function update_hex(){
    // Update the hex value based on slider values.
    let red = Math.max(0, Math.min(Number.parseInt(document.getElementById('red').value, 10), 255));
    let green = Math.max(0, Math.min(Number.parseInt(document.getElementById('green').value, 10), 255));
    let blue = Math.max(0, Math.min(Number.parseInt(document.getElementById('blue').value, 10), 255));

    document.getElementById('hex').value =
      hexvalues((red - red % 16) / 16) + hexvalues(red % 16)
      + hexvalues((green - green % 16) / 16) + hexvalues(green % 16)
      + hexvalues((blue - blue % 16) / 16) + hexvalues(blue % 16);

    update_display();
}

function update_wcag(source_hex, length_background, length_foreground){
    if(length_foreground === -1){
        length_foreground = length_background;
    }

    let background_math =
      (.2126 * calculate_wcag('wcag-background-color', 2, length_background)
      + .7152 * calculate_wcag('wcag-background-color', 4, length_background)
      + .0722 * calculate_wcag('wcag-background-color', 6, length_background)
    );
    let foreground_math =
      (.2126 * calculate_wcag('wcag-foreground-color', 2, length_foreground)
      + .7152 * calculate_wcag('wcag-foreground-color', 4, length_foreground)
      + .0722 * calculate_wcag('wcag-foreground-color', 6, length_foreground)
    );

    let wcag_score = Math.round(
      (Math.max(background_math, foreground_math) + .05)
      / (Math.min(background_math, foreground_math) + .05)
      * 10
    ) / 10;

    document.getElementById('wcag-text-normal-result').innerHTML =
      wcag_score + ' / 7 = AAA '
      + (wcag_score > 7
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 4.5 = AA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      );
    document.getElementById('wcag-text-large-result').innerHTML =
      wcag_score + ' / 4.5 = AAA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 3 = AA '
      + (wcag_score > 3
        ? 'Passed'
        : 'Failed'
      );

    let background = document.getElementById('wcag-background-color').value;
    let foreground = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-background').value = length_background === 4
      ? '#'
        + background[1] + background[1]
        + background[2] + background[2]
        + background[3] + background[3]
      : background;
    document.getElementById('wcag-foreground').value = length_foreground === 4
      ? '#'
        + foreground[1] + foreground[1]
        + foreground[2] + foreground[2]
        + foreground[3] + foreground[3]
      : foreground;
    document.getElementById('wcag-text-normal').style.backgroundColor = background;
    document.getElementById('wcag-text-normal').style.color = foreground;
    document.getElementById('wcag-text-large').style.backgroundColor = background;
    document.getElementById('wcag-text-large').style.color = foreground;
}

function wcag_set(target){
    let color = '#' + document.getElementById('hex').value;

    document.getElementById('wcag-' + target + '-color').value = color;
    document.getElementById('display-' + target).style.backgroundColor = color;

    update_wcag(
      'wcag-' + target + '-color',
      document.getElementById('wcag-' + target + '-color').value.length,
      -1
    );
}

function wcag_switch(){
    let background = document.getElementById('wcag-background-color').value;
    let foreground = document.getElementById('wcag-foreground-color').value;

    document.getElementById('wcag-background').value = foreground;
    document.getElementById('wcag-foreground').value = background;
    document.getElementById('wcag-background-color').value = foreground;
    document.getElementById('wcag-foreground-color').value = background;
    document.getElementById('display-background').style.backgroundColor = foreground;
    document.getElementById('display-foreground').style.backgroundColor = background;

    update_wcag(
      'wcag-background-color',
      document.getElementById('wcag-background-color').value.length,
      temp.length
    );
}
<|endoftext|>


<commit_before>/*
*	drag Object
*	var m=new drag(moveObj,targetObj,[callback]);
*	editor: bluemoon
*	2015-3-21 10:23
*
*/
function drag(obj,target,callback){
	var that=this;
	this.move=true;
	this.call=false;
	this.x=null;
	this.y=null;
	this.objx=null;
	this.objy=null;
	this.Top=null;
	this.Left=null;
	this.bodyX=null;
	this.bodyY=null;
	this.objWidth=null;
	this.objHeight=null;
	this.opacity=attrStyle(target,"opacity")||1;
	that.copacity=0.8;
	obj.onmousedown=function(e){
		 e.preventDefault();
	     e.stopPropagation();
	     that.objWidth=obj.offsetWidth;
	     that.objHeight=obj.offsetHeight;
	     that.move=true;
	     that.call=true;
	     that.x=e.clientX;
	     that.y=e.clientY;
	     that.objx=target.offsetLeft;
	     that.objy=target.offsetTop;
	     that.bodyX=document.documentElement.clientWidth;
	     that.bodyY=document.documentElement.clientHeight;
		if(e.button==0){
			target.style.opacity=that.copacity;
			document.onmousemove=function(m){
				if(that.move){
					that.Top=(m.clientY-(that.y-that.objy));
					that.Left=(m.clientX-(that.x-that.objx));
					that.Top=(that.Top<0?0:(that.Top>(that.bodyY-target.offsetHeight)?(that.bodyY-target.offsetHeight):that.Top));
					that.Left=(that.Left<0?0:(that.Left>(that.bodyX-target.offsetWidth)?(that.bodyX-target.offsetWidth):that.Left));
					target.style.left=that.Left+"px";
					target.style.top=that.Top+"px";
				}else{
					return;
				}
			}
		}
	}
	document.onmouseup=function(e){
		 e.preventDefault();
	     e.stopPropagation();
	     target.style.opacity=that.opacity;
	     that.move=false;
	     if(callback&&that.call){
	     	that.call=false;
	     	callback();
	     }
	}
	//以下选择css属性函数来自网络
	function attrStyle(elem,attr){
		if(elem.attr){
			//若样式存在于html中,优先获取
			return elem.style[attr];
		}else if(elem.currentStyle){
			//IE下获取CSS属性最终样式(同于CSS优先级)
			return elem.currentStyle[attr];
		}else if(document.defaultView && document.defaultView.getComputedStyle){
			//W3C标准方法获取CSS属性最终样式(同于CSS优先级)
			//注意,此法属性原格式(text-align)获取的,故要转换一下
			attr=attr.replace(/([A-Z])/g,'-$1').toLowerCase();
			//获取样式对象并获取属性值
			return document.defaultView.getComputedStyle(elem,null).getPropertyValue(attr);
		}else{
			return null;
		}
	}

}

<commit_msg>drag.js<commit_after>/*
*	drag Object
*	var m=new drag(moveObj,targetObj,[callback]);
*	editor: bluemoon
*	2015-3-21 10:23
*
*/
function drag(obj,target,callback){
	var that=this;
	this.move=false;
	this.call=false;
	this.x=null;
	this.y=null;
	this.objx=null;
	this.objy=null;
	this.Top=null;
	this.Left=null;
	this.bodyX=null;
	this.bodyY=null;
	this.objWidth=null;
	this.objHeight=null;
	this.opacity=attrStyle(target,"opacity")||1;
	that.copacity=0.8;
	that.zIndex=attrStyle(target,"z-index")||1;
	that.maxzIndex=3000;
	console.log(that.zIndex);
	//that.czIndex=1;
	obj.onmousedown=function(e){
		 e.preventDefault();
	     e.stopPropagation();
	     that.objWidth=obj.offsetWidth;
	     that.objHeight=obj.offsetHeight;

	     that.move=true;
	     that.call=true;
	     that.x=e.clientX;
	     that.y=e.clientY;
	     that.objx=target.offsetLeft;
	     that.objy=target.offsetTop;
	     that.bodyX=document.documentElement.clientWidth;
	     that.bodyY=document.documentElement.clientHeight;
		if(e.button==0){
			target.style.opacity=that.copacity;
			target.style.zIndex=that.maxzIndex;
			document.onmousemove=function(m){
				if(that.move){

					that.Top=(m.clientY-(that.y-that.objy));
					that.Left=(m.clientX-(that.x-that.objx));
					that.Top=(that.Top<0?0:(that.Top>(that.bodyY-target.offsetHeight)?(that.bodyY-target.offsetHeight):that.Top));
					that.Left=(that.Left<0?0:(that.Left>(that.bodyX-target.offsetWidth)?(that.bodyX-target.offsetWidth):that.Left));
					target.style.left=that.Left+"px";
					target.style.top=that.Top+"px";
				}else{
					return;
				}
			}
		}
	}
	obj.onmouseup=function(e){
		 e.preventDefault();
	     e.stopPropagation();
	     target.style.opacity=that.opacity;
	     target.style.zIndex=that.zIndex;
	     that.move=false;
	     if(callback&&that.call){
	     	that.call=false;
	     	callback();
	     }
	}
	/*obj.onmouseleave=function(e){
		e.preventDefault();
	     e.stopPropagation();
	     target.style.opacity=that.opacity;
	     that.move=false;
	     console.log(that.move);
	     if(callback&&that.call){
	     	that.call=false;
	     	callback();
	     }
	}*/
	//以下选择css属性函数来自网络
	function attrStyle(elem,attr){
		if(elem.attr){
			//若样式存在于html中,优先获取
			return elem.style[attr];
		}else if(elem.currentStyle){
			//IE下获取CSS属性最终样式(同于CSS优先级)
			return elem.currentStyle[attr];
		}else if(document.defaultView && document.defaultView.getComputedStyle){
			//W3C标准方法获取CSS属性最终样式(同于CSS优先级)
			//注意,此法属性原格式(text-align)获取的,故要转换一下
			attr=attr.replace(/([A-Z])/g,'-$1').toLowerCase();
			//获取样式对象并获取属性值
			return document.defaultView.getComputedStyle(elem,null).getPropertyValue(attr);
		}else{
			return null;
		}
	}

}

<|endoftext|>


<commit_before>var drawModule = (function () {

  var bodySnake = function(x, y) {
        ctx.fillStyle = 'green';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.strokeStyle = 'darkgreen';
        ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
        ctx.fillStyle = 'yellow';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.fillStyle = 'red';
        ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2);
  }

  var scoreText = function() {
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue';
    ctx.fillText(score_text, 145, h-5);
  }

  var drawSnake = function() {
      var length = 4;
      snake = [];
      for (var i = length-1; i>=0; i--) {
          snake.push({x:i, y:0});
      }
  }

  var paint = function(){
      ctx.fillStyle = 'lightgrey';
      ctx.fillRect(0, 0, w, h);
      ctx.strokeStyle = 'black';
      ctx.strokeRect(0, 0, w, h);

      btn.setAttribute('disabled', true);

      var snakeX = snake[0].x;
      var snakeY = snake[0].y;

      if (direction == 'right') {
        snakeX++; }
      else if (direction == 'left') {
        snakeX--; }
      else if (direction == 'up') {
        snakeY--;
      } else if(direction == 'down') {
        snakeY++; }

      if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) {
          //restart game
          btn.removeAttribute('disabled', true);

          ctx.clearRect(0,0,w,h);
          gameloop = clearInterval(gameloop);
          return;
        }

        if(snakeX == food.x && snakeY == food.y) {
          var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail
          score ++;

          createFood(); //Create new food
        } else {
          var tail = snake.pop(); //pops out the last cell
          tail.x = snakeX;
          tail.y = snakeY;
        }
        //The snake can now eat the food.
        snake.unshift(tail); //puts back the tail as the first cell

        for(var i = 0; i < snake.length; i++) {
          bodySnake(snake[i].x, snake[i].y);
        }

        pizza(food.x, food.y);
        scoreText();
  }

  var createFood = function() {
      food = {
        x: Math.floor((Math.random() * 30) + 1),
        y: Math.floor((Math.random() * 30) + 1)
      }

      for (var i=0; i>snake.length; i++) {
        var snakeX = snake[i].x;
        var snakeY = snake[i].y;

        if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) {
          food.x = Math.floor((Math.random() * 30) + 1);
          food.y = Math.floor((Math.random() * 30) + 1);
        }
      }
  }

  var checkCollision = function(x, y, array) {
      for(var i = 0; i < array.length; i++) {
        if(array[i].x === x && array[i].y === y)
        return true;
      }
      return false;
  }

  var init = function(){
      direction = 'down';
      drawSnake();
      createFood();
      gameloop = setInterval(paint, 80);
  }

    return {
      init : init
    };

}());
<commit_msg>Update draw.js<commit_after>var drawModule = (function () {

  var bodySnake = function(x, y) {
        ctx.fillStyle = 'green';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.strokeStyle = 'darkgreen';
        ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
        ctx.fillStyle = 'orange';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.fillStyle = 'red';
        ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2);
  }

  var scoreText = function() {
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue';
    ctx.fillText(score_text, 145, h-5);
  }

  var drawSnake = function() {
      var length = 4;
      snake = [];
      for (var i = length-1; i>=0; i--) {
          snake.push({x:i, y:0});
      }
  }

  var paint = function(){
      ctx.fillStyle = 'lightgrey';
      ctx.fillRect(0, 0, w, h);
      ctx.strokeStyle = 'black';
      ctx.strokeRect(0, 0, w, h);

      btn.setAttribute('disabled', true);

      var snakeX = snake[0].x;
      var snakeY = snake[0].y;

      if (direction == 'right') {
        snakeX++; }
      else if (direction == 'left') {
        snakeX--; }
      else if (direction == 'up') {
        snakeY--;
      } else if(direction == 'down') {
        snakeY++; }

      if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) {
          //restart game
          btn.removeAttribute('disabled', true);

          ctx.clearRect(0,0,w,h);
          gameloop = clearInterval(gameloop);
          return;
        }

        if(snakeX == food.x && snakeY == food.y) {
          var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail
          score ++;

          createFood(); //Create new food
        } else {
          var tail = snake.pop(); //pops out the last cell
          tail.x = snakeX;
          tail.y = snakeY;
        }
        //The snake can now eat the food.
        snake.unshift(tail); //puts back the tail as the first cell

        for(var i = 0; i < snake.length; i++) {
          bodySnake(snake[i].x, snake[i].y);
        }

        pizza(food.x, food.y);
        scoreText();
  }

  var createFood = function() {
      food = {
        x: Math.floor((Math.random() * 30) + 1),
        y: Math.floor((Math.random() * 30) + 1)
      }

      for (var i=0; i>snake.length; i++) {
        var snakeX = snake[i].x;
        var snakeY = snake[i].y;

        if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) {
          food.x = Math.floor((Math.random() * 30) + 1);
          food.y = Math.floor((Math.random() * 30) + 1);
        }
      }
  }

  var checkCollision = function(x, y, array) {
      for(var i = 0; i < array.length; i++) {
        if(array[i].x === x && array[i].y === y)
        return true;
      }
      return false;
  }

  var init = function(){
      direction = 'down';
      drawSnake();
      createFood();
      gameloop = setInterval(paint, 80);
  }

    return {
      init : init
    };

}());
<|endoftext|>


<commit_before>var filmReview = function(){
    $('form').submit(function(event){
        event.preventDefault();
        var $searchField = $("#searchFilm");
        var query = $searchField.val();
        var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
        var api = "9cced63c6fde5aa51d72ec61a881f5e3:19:71855090"
        var article;
        var image;

        url += '?' + $.param({'api-key': api,
        'query': query,
        'critics-pick': "N"
        });

        $.ajax({
        url: url,
        method: 'GET',
            }).done(function(data) {
            /*var status = data.status;
            var copyright = data.copyright;
            var num_results = data.num_results;
            var title = data.results[0].display_title;
            var summary = data.results[0].summary_short
                console.log(status);
                console.log(copyright);
                console.log(num_results);
                console.log(title);
                console.log(summary);
                console.log(data);*/

                for (var i = 0; i < data.results.length; i++) {

                $('')
                    .attr('src', "" + data.results[i].multimedia.src + "")         // ADD IMAGE PROPERTIES.
                    .attr('title', data.results[i].display_title)
                    .attr('alt', "weiner")
                    .width(data.results[i].multimedia.width).height(data.results[i].multimedia.height)
                    .appendTo($('#image'));

                var critics_pick;
                if (data.results[i].critics_pick > 0){
                    critics_pick = "Yes";
                }
                else
                {
                    critics_pick = "No";
                }
                article = $('
');
                article.append('
' +  'Film: ' + data.results[i].display_title + "
");
                article.append('
' +  'Rating: ' + data.results[i].mpaa_rating + "
");
                article.append('
' +  'Critics Pick: ' + critics_pick + "
");
                article.append('
' + data.results[i].headline + "
");
                article.append('
' + 'Review By: ' + data.results[i].byline + "
");
                article.append('
' + data.results[i].summary_short + "
");
                $('#results').append(article);
                };

            }).fail(function(err) {
            throw err;

        });
    });
}

filmReview();

<commit_msg>add opening date and date conversion<commit_after>var filmReview = function(){
    $('form').submit(function(event){
        event.preventDefault();
        var $searchField = $("#searchFilm");
        var query = $searchField.val();
        var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
        var api = "9cced63c6fde5aa51d72ec61a881f5e3:19:71855090"
        var article;
        var image;
        var monthNames = ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul",
                          "Aug", "Sept", "Oct", "Nov", "Dec"];

        url += '?' + $.param({'api-key': api,
        'query': query,
        'critics-pick': "N"
        });

        $.ajax({
        url: url,
        method: 'GET',
            }).done(function(data) {
            /*var status = data.status;
            var copyright = data.copyright;
            var num_results = data.num_results;
            var title = data.results[0].display_title;
            var summary = data.results[0].summary_short
                console.log(status);
                console.log(copyright);
                console.log(num_results);
                console.log(title);
                console.log(summary);
                console.log(data);*/

                for (var i = 0; i < data.results.length; i++) {

                /* begin add image properties */

                $('')
                    .attr('src', "" + data.results[i].multimedia.src + "")
                    .attr('title', data.results[i].display_title)
                    .attr('alt', "weiner")
                    .width(data.results[i].multimedia.width).height(data.results[i].multimedia.height)
                    .appendTo($('#image'));

                /* end add image properties */

                /* begin critics pick check */

                    var critics_pick;
                        if (data.results[i].critics_pick > 0){
                            critics_pick = "Yes";
                    }
                        else
                    {
                            critics_pick = "No";
                    }
                /* end critics pick check */

                /* begin opening date check and conversion */

                    var date = new Date();
                    var day = date.getDate();
                    var monthIndex = date.getMonth();
                    var year = date.getFullYear();

                    console.log(day, monthNames[monthIndex], year);
                    var opening_date;
                        if (data.results[i].opening_date != null){
                            opening_date = day + ' ' + monthNames[monthIndex] + ' ' + year;
                    }
                        else
                    {
                            opening_date = "Date Not Announced";
                    }

                /* end opening date check and conversion */

                article = $('
');
                article.append('
' +  'Film: ' + data.results[i].display_title + "
");
                article.append('
' +  'Opening: ' + opening_date + "
");
                article.append('
' +  'Rating: ' + data.results[i].mpaa_rating + "
");
                article.append('
' +  'Critics Pick: ' + critics_pick + "
");
                article.append('
' + data.results[i].headline + "
");
                article.append('
' + 'Review By: ' + data.results[i].byline + "
");
                article.append('
' + data.results[i].summary_short + "
");
                $('#results').append(article);
                };

            }).fail(function(err) {
            throw err;

        });
    });
}

filmReview();

<|endoftext|>


<commit_before>//addShow Function
function addShow() {

}
//resetForm Function
function resetForm() {

}
//search Function
function search() {

}
//addVenue Function
function addVenue() {

}

//Get input
var searchButton = document.getElementById('search');
var addShowButton = document.getElementById('add_show');
var resetFormButton = document.getElementById('resetForm');
var addVenueButton = document.getElementById('add_venue');

//Event Listeners for 'Add Show', 'Add Venue', 'Search',  and 'Reset Form' buttons
searchButton.addEventListener('submit', searchFunction goes here);
addShowButton.addEventListener('submit', addShowFunction goes here);
resetFormButton.addEventListener('submit', resetFormFunction goes here);
addVenueButton.addEventListener('submit', addVenueFunction goes here);
<commit_msg>event listeners and function placeholders<commit_after>//addShow Function
function addShow() {

}
//resetForm Function
function resetForm() {

}
//search Function
function search() {

}
//addVenue Function
function addVenue() {

}

//Get input
var searchButton = document.getElementById('search');
var addShowButton = document.getElementById('add_show');
var resetFormButton = document.getElementById('reset_form');
var addVenueButton = document.getElementById('add_venue');

//Event Listeners for 'Add Show', 'Add Venue', 'Search',  and 'Reset Form' buttons
searchButton.addEventListener('submit', searchFunction goes here);
addShowButton.addEventListener('submit', addShowFunction goes here);
resetFormButton.addEventListener('click', resetFormFunction goes here);
addVenueButton.addEventListener('submit', addVenueFunction goes here);
<|endoftext|>


<commit_before>
/* global soundModule */
var yAxis = p2.vec2.fromValues(0, 1);
const DEADLINE_HEIGHT = 160;
const PLATFORM_WIDTH = 100;
const PLAYER_INIT_LIFE_COUNT = 4;

class State extends Phaser.State {
  preload() {
    game.load.image('character', 'assets/sprites/character.png');
    game.load.image('wall', 'assets/sprites/platform.png');
    game.load.image('background', 'assets/sprites/dayBG.png');
    game.load.image('spears', 'assets/sprites/spikes.png');
    game.load.image('scroll', 'assets/sprites/scroll.png');
  }

  create() {
    game.add.tileSprite(0, 0, 1280, 720, 'background');

    this.lifeText = game.add.text(20, 20, "4", {
      font: "20px Arial",
      fill: "#ff0044",
      align: "center"
    });

    this.lifeText.anchor.setTo(0, 0);

    game.stage.backgroundColor = "#4488AA";

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

    this.jumpTimer = 0;
    this.scrollGoal = 0;

    //  Enable p2 physics
    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.gravity.y = 200;
    game.physics.p2.world.defaultContactMaterial.friction = 0.3;
    game.physics.p2.world.setGlobalStiffness(1e5);

    //  Create our collision groups. One for the player, one for the music floors
    this.playerCollisionGroup = game.physics.p2.createCollisionGroup();
    this.musicFloorCollisionGroup = game.physics.p2.createCollisionGroup();
    this.deadCollisionGroup = game.physics.p2.createCollisionGroup();
    this.scrollCollisionGroup = game.physics.p2.createCollisionGroup();

    // to still collide with the world bounds
    game.physics.p2.updateBoundsCollisionGroup();

    // for (let i = 0; i < 100; i++) {
    //   const wall = this.createWall(100 * i, 500);
    // }
    this.musicFloors = [];
    const wall = this.createWall(PLATFORM_WIDTH/2, 500);
    var currentMusicX = PLATFORM_WIDTH* 1.5;
    while (currentMusicX < game.width) {
      const musicFloor = this.createMusicFloor(currentMusicX, 500);
      this.musicFloors.push(musicFloor);
      currentMusicX += PLATFORM_WIDTH;
    }

    this.player = game.add.sprite(PLATFORM_WIDTH/2, 300, 'character');
    this.player.lifeCount = PLAYER_INIT_LIFE_COUNT;
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(this.player);

    this.player.body.setCollisionGroup(this.playerCollisionGroup);
    this.player.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    this.player.body.collides(this.deadCollisionGroup);

    //  Check for the block hitting another object
    this.player.body.onBeginContact.add(this.hurtPlayer, this);
    this.deadzones = this.setupDeadZones();
    this.scrolls = this.setup_level_1();
    this.scrollGoal = this.scrolls.length;

    soundModule.signal.add((...params) => { this.onSound(...params); });
  }

  setup_level_1 () {
    var output = [];
    var scroll = game.add.sprite(1250, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_2 () {
    var output = [];

    var scrollCoord = [[1250,150],[830,400],[430,320]]

    for(var i = 0; i < scrollCoord.length;i++){
    var scroll = game.add.sprite(scrollCoord[i][0], 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
  }
    return output
  }

  setup_level_3_stage_1 () {
    var output = [];
      var scroll = game.add.sprite(230, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_2 () {
    var output = [];
      var scroll = game.add.sprite(430, 280, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_3 () {
    var output = [];
      var scroll = game.add.sprite(830, 380, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setupDeadZones() {
    var currentX = 0;
    var output = [];
    const deadline_y = game.height - DEADLINE_HEIGHT;
    while (currentX < game.width) {
      var deadzone = game.add.sprite(currentX, deadline_y, 'spears');
      game.physics.p2.enable(deadzone);
      deadzone.anchor.setTo(0,0);
      deadzone.body.static=true;
      deadzone.body.setCollisionGroup(this.deadCollisionGroup);

      deadzone.body.collides(this.playerCollisionGroup);
      output.push(deadzone);
      currentX += deadzone.width;
    }
    return output;
  }

  update() {

    if (this.cursors.left.isDown) {
      this.player.body.moveLeft(200);

      // if (player.facing != 'left') {
      //   player.facing = 'left';
      // }
    }
    else if (this.cursors.right.isDown) {
      this.player.body.moveRight(200);

      // if (player.facing != 'right') {
      //   player.facing = 'right';
      // }
    } else {
      this.player.body.velocity.x = 0;

      // if (player.facing != 'idle') {

      //   if (player.facing == 'left') {
      //   }
      //   else {
      //   }

      //   player.facing = 'idle';
      // }
    }

    if (this.cursors.up.isDown && game.time.now > this.jumpTimer && this.checkIfCanJump()) {
      this.player.body.moveUp(300);
      this.jumpTimer = game.time.now + 750;
    }
  }

  checkIfCanJump() {

    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
      var c = game.physics.p2.world.narrowphase.contactEquations[i];

      if (c.bodyA === this.player.body.data || c.bodyB === this.player.body.data) {
        var d = p2.vec2.dot(c.normalA, yAxis);

        if (c.bodyA === this.player.body.data) {
          d *= -1;
        }

        if (d > 0.5) {
          result = true;
        }
      }
    }

    return result;

  }

  hurtPlayer(body, bodyB, shapeA, shapeB, equation) {
    console.log("hurtPlayer");
    if (body && body.sprite && body.sprite.key === 'spears') {
      console.log("spears");
      this.player.lifeCount--;
      this.lifeText.setText(this.player.lifeCount);
      this.player.body.y = 30;
    }
  }

  getScroll(sprite1, sprite2) {
    this.player.scollGot++;
    if (this.player.scollGot >= this.scrollGoal) {
       //win
    }
  }

  onSound(y0Pitch, y1Pitch, y0Amplitude, y1Amplitude) {
    const normalized0 = y0Pitch / 6.5;
    const normalized1 = y1Pitch / 6.5;
    var index = Math.round(normalized0 * 12);
    var singIndex = Math.round(normalized0 * 11);
    // console.log('noteStrings', soundModule.noteStrings[index]);
    //console.log('onSound',
    // normalized0, soundModule.noteStrings[singIndex],
    // normalized1, '');
    this.musicFloors.forEach((elem, id) => {
      if (Math.abs(id - index) < 3) {
        // const heightLimit = 500 - y0Amplitude * 70;
        const heightLimit = 500 - 400;
        if (elem.y > heightLimit) {
          elem.body.moveUp(300);
        } else {
          elem.body.y = heightLimit;
          elem.body.setZeroVelocity();
        }
        elem.loadTexture('wall');
      } else {
        elem.loadTexture('wall');

        if (elem.y < game.height - DEADLINE_HEIGHT) {
          elem.body.moveDown(50);
        } else if (elem.y < game.height) {
          elem.body.moveDown(25);
        } else {
          elem.body.y = game.height;
          elem.body.setZeroVelocity();
        }

        // elem.y = Phaser.Math.linear(elem.y, 500, 0.01);
      }
    });
  }

  createWall(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.static = true;

    wall.body.setCollisionGroup(this.playerCollisionGroup);
    wall.body.collides([this.playerCollisionGroup]);
    return wall;
  }

  createMusicFloor(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.kinematic = true;

    wall.body.setCollisionGroup(this.musicFloorCollisionGroup);
    wall.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    return wall;
  }
}

var game = new Phaser.Game(
  1280, 720, Phaser.AUTO, 'wrapper', new State());
<commit_msg>+ Add scroll get logic and win entry point<commit_after>
/* global soundModule */
var yAxis = p2.vec2.fromValues(0, 1);
const DEADLINE_HEIGHT = 160;
const PLATFORM_WIDTH = 100;
const PLAYER_INIT_LIFE_COUNT = 4;

class State extends Phaser.State {
  preload() {
    game.load.image('character', 'assets/sprites/character.png');
    game.load.image('wall', 'assets/sprites/platform.png');
    game.load.image('background', 'assets/sprites/dayBG.png');
    game.load.image('spears', 'assets/sprites/spikes.png');
    game.load.image('scroll', 'assets/sprites/scroll.png');
  }

  create() {
    game.add.tileSprite(0, 0, 1280, 720, 'background');

    this.lifeText = game.add.text(20, 20, "4", {
      font: "20px Arial",
      fill: "#ff0044",
      align: "center"
    });

    this.lifeText.anchor.setTo(0, 0);

    game.stage.backgroundColor = "#4488AA";

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

    this.jumpTimer = 0;
    this.scrollGoal = 0;

    //  Enable p2 physics
    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.gravity.y = 200;
    game.physics.p2.world.defaultContactMaterial.friction = 0.3;
    game.physics.p2.world.setGlobalStiffness(1e5);

    //  Create our collision groups. One for the player, one for the music floors
    this.playerCollisionGroup = game.physics.p2.createCollisionGroup();
    this.musicFloorCollisionGroup = game.physics.p2.createCollisionGroup();
    this.deadCollisionGroup = game.physics.p2.createCollisionGroup();
    this.scrollCollisionGroup = game.physics.p2.createCollisionGroup();

    // to still collide with the world bounds
    game.physics.p2.updateBoundsCollisionGroup();

    // for (let i = 0; i < 100; i++) {
    //   const wall = this.createWall(100 * i, 500);
    // }
    this.musicFloors = [];
    const wall = this.createWall(PLATFORM_WIDTH/2, 500);
    var currentMusicX = PLATFORM_WIDTH* 1.5;
    while (currentMusicX < game.width) {
      const musicFloor = this.createMusicFloor(currentMusicX, 500);
      this.musicFloors.push(musicFloor);
      currentMusicX += PLATFORM_WIDTH;
    }

    this.player = game.add.sprite(PLATFORM_WIDTH/2, 300, 'character');
    this.player.lifeCount = PLAYER_INIT_LIFE_COUNT;
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(this.player);

    this.player.body.setCollisionGroup(this.playerCollisionGroup);
    this.player.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    this.player.body.collides(this.deadCollisionGroup);
    this.player.body.collides(this.scrollCollisionGroup);

    this.player.scollGot = 0;

    //  Check for the block hitting another object
    this.player.body.onBeginContact.add(this.touchPlayer, this);
    this.deadzones = this.setupDeadZones();
    this.scrolls = this.setup_level_1();
    this.scrollGoal = this.scrolls.length;

    soundModule.signal.add((...params) => { this.onSound(...params); });
  }

  setup_level_1 () {
    var output = [];
    var scroll = game.add.sprite(1250, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_2 () {
    var output = [];

    var scrollCoord = [[1250,150],[830,400],[430,320]]

    for(var i = 0; i < scrollCoord.length;i++){
    var scroll = game.add.sprite(scrollCoord[i][0], 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
  }
    return output
  }

  setup_level_3_stage_1 () {
    var output = [];
      var scroll = game.add.sprite(230, 150, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_2 () {
    var output = [];
      var scroll = game.add.sprite(430, 280, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setup_level_3_stage_3 () {
    var output = [];
      var scroll = game.add.sprite(830, 380, 'scroll');
    //  Enable if for physics. This creates a default rectangular body.
    game.physics.p2.enable(scroll);
    scroll.body.static = true;

    scroll.body.setCollisionGroup(this.scrollCollisionGroup);
    scroll.body.collides([this.playerCollisionGroup, this.scrollCollisionGroup]);
    output.push(scroll);
    return output
  }

  setupDeadZones() {
    var currentX = 0;
    var output = [];
    const deadline_y = game.height - DEADLINE_HEIGHT/2;
    while (currentX < game.width) {
      var deadzone = game.add.sprite(currentX, deadline_y, 'spears');
      deadzone.anchor.setTo(0,0);
      game.physics.p2.enable(deadzone);
      deadzone.body.static=true;
      deadzone.body.setCollisionGroup(this.deadCollisionGroup);

      deadzone.body.collides(this.playerCollisionGroup);
      output.push(deadzone);
      currentX += deadzone.width;
    }
    return output;
  }

  update() {

    if (this.cursors.left.isDown) {
      this.player.body.moveLeft(200);

      // if (player.facing != 'left') {
      //   player.facing = 'left';
      // }
    }
    else if (this.cursors.right.isDown) {
      this.player.body.moveRight(200);

      // if (player.facing != 'right') {
      //   player.facing = 'right';
      // }
    } else {
      this.player.body.velocity.x = 0;

      // if (player.facing != 'idle') {

      //   if (player.facing == 'left') {
      //   }
      //   else {
      //   }

      //   player.facing = 'idle';
      // }
    }

    if (this.cursors.up.isDown && game.time.now > this.jumpTimer && this.checkIfCanJump()) {
      this.player.body.moveUp(300);
      this.jumpTimer = game.time.now + 750;
    }
  }

  checkIfCanJump() {

    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
      var c = game.physics.p2.world.narrowphase.contactEquations[i];

      if (c.bodyA === this.player.body.data || c.bodyB === this.player.body.data) {
        var d = p2.vec2.dot(c.normalA, yAxis);

        if (c.bodyA === this.player.body.data) {
          d *= -1;
        }

        if (d > 0.5) {
          result = true;
        }
      }
    }

    return result;

  }

  touchPlayer(body, bodyB, shapeA, shapeB, equation) {
    console.log("touchPlayer");
    if (body && body.sprite && body.sprite.key === 'spears') {
      console.log("spears");
      this.player.lifeCount--;
      this.lifeText.setText(this.player.lifeCount);
      this.player.body.y = 30;
    } else if (body && body.sprite && body.sprite.key === 'scroll') {
      console.log("scroll");
      this.player.scollGot++;
      body.sprite.destroy();
      if (this.player.scollGot >= this.scrollGoal) {
         console.log("win");
      }
    }
  }

  onSound(y0Pitch, y1Pitch, y0Amplitude, y1Amplitude) {
    const normalized0 = y0Pitch / 6.5;
    const normalized1 = y1Pitch / 6.5;
    var index = Math.round(normalized0 * 12);
    var singIndex = Math.round(normalized0 * 11);
    // console.log('noteStrings', soundModule.noteStrings[index]);
    //console.log('onSound',
    // normalized0, soundModule.noteStrings[singIndex],
    // normalized1, '');
    this.musicFloors.forEach((elem, id) => {
      if (Math.abs(id - index) < 3) {
        // const heightLimit = 500 - y0Amplitude * 70;
        const heightLimit = 500 - 400;
        if (elem.y > heightLimit) {
          elem.body.moveUp(300);
        } else {
          elem.body.y = heightLimit;
          elem.body.setZeroVelocity();
        }
        elem.loadTexture('wall');
      } else {
        elem.loadTexture('wall');

        if (elem.y < game.height - DEADLINE_HEIGHT) {
          elem.body.moveDown(50);
        } else if (elem.y < game.height) {
          elem.body.moveDown(25);
        } else {
          elem.body.y = game.height;
          elem.body.setZeroVelocity();
        }

        // elem.y = Phaser.Math.linear(elem.y, 500, 0.01);
      }
    });
  }

  createWall(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.static = true;

    wall.body.setCollisionGroup(this.playerCollisionGroup);
    wall.body.collides([this.playerCollisionGroup]);
    return wall;
  }

  createMusicFloor(x, y) {
    var wall = game.add.sprite(x, y, 'wall');
    game.physics.p2.enable(wall);
    wall.body.kinematic = true;

    wall.body.setCollisionGroup(this.musicFloorCollisionGroup);
    wall.body.collides([this.playerCollisionGroup, this.musicFloorCollisionGroup]);
    return wall;
  }
}

var game = new Phaser.Game(
  1280, 720, Phaser.AUTO, 'wrapper', new State());
<|endoftext|>


<commit_before>//var games = [];

showMyGames();

function showMyGames(){
    /*$("#mygames").empty();

    for(var game in games){
        appendGame("#mygames", games, game);
    }*/
    $("#mygames").empty();

    var text_to_append = '

';

    for(var game in games){
        text_to_append += appendGame("#mygames", games, game);
    }

    text_to_append += "

";

    $('#mygames').append(text_to_append);

    for(var game in games){
        setEvents("#mygames", games, game);
    }
}

function showCommunityGames(){
    $("#community").empty();

    var text_to_append = '

';

    for(var game in games){
        if(games[game].public) text_to_append += appendGame("#community", games, game);
    }

    text_to_append += "

";

    $('#community').append(text_to_append);

    for(var game in games){
        if(games[game].public) setEvents("#community", games, game);
    }
}

function appendGame(parent, games, index){
    var url = gameTypeToUrl(games[index].type) + ".php?id=" + games[index].id;
    var type = gameTypeToDisplayName(games[index].type);

    var game = `

${games[index].name}

${games[index].description}

${type}

Last modified: ${games[index].last_update} GMT

                                <input data-index="${index}" class="pubpriv-toggle" type="checkbox" data-toggle="toggle" data-on="Public" data-off="Private" ${games[index].public?"checked":""}>

`;

    return game;
}

function setEvents(parent, games, index) {
    $('.pubpriv-toggle').bootstrapToggle();

    $('.pubpriv-toggle').change(function() {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            games[index].public = $(this).prop('checked');
            savePlot(games[index]);
            showCommunityGames();
        }
    });

    $(".gamerow .gameinfo").on('click', function(e) {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            var action = $(e.target).hasClass('fa-trash') ? "remove" : "";
            action = $(e.target).hasClass('fa-pencil') ? "edit" : action;
            action = $(e.target).hasClass('fa-copy') ? "duplicate" : action;

            if(action != "edit") e.preventDefault();

            gameOnClick(this, gameNumber, action);
        }
    });
    $("body").find("[data-index=" + index + "]").find('.gameType').ellipsis({
        lines: 3
    });

    $("body").find("[data-index=" + index + "]").find('.gameTitle').ellipsis({
        lines: 1
    });

    $("body").find("[data-index=" + index + "]").find(".fa-external-link").click(function(){
        var gameUrl = generateGameUrl(games[index]);
        showTestGame(gameUrl)

    });
}

$("body").find("[aria-controls='mygames']").on('click', function(e) {
    showMyGames();
});

$("body").find("[aria-controls='community']").on('click', function(e) {
    showCommunityGames();
});

function gameOnClick(parent, gameNumber, action){
    if(action == "remove"){
        showRemoveWarning(parent, gameNumber);
    }else if(action == "edit"){
    }else if(action == "duplicate"){
        var copy = games[gameNumber].copy();
        games.push(copy);
        duplicatePlot(copy, function(id){
            copy.id = id;
            $("#communitytab").parent().hasClass( "active" ) ? window.location="?tab=community" : window.location="";
        });
    }
}

function reorderPlots(){
    showMyGames();
    showCommunityGames();
}

function showTestGame(url){
    //TODO: mostarr modal para compartir
    window.open(url, '_blank');
}

function showRemoveWarning(parent, gameNumber){
    $("#remove-warning").modal('show');
    $(".warning-action-remove").click(function() {
        removePlot(games[gameNumber], function(){
            $("#communitytab").parent().hasClass( "active" ) ? window.location="?tab=community" : window.location="";
            $("#remove-warning").modal('hide');
        });
    });
    $(".warning-action-cancel").click(function(){
        $("#remove-warning").modal('hide');
    });
}

if ( tab == "community" ) { $('#communitytab').click(); }
<commit_msg>Game type in Desktop - bug fixed<commit_after>//var games = [];

showMyGames();

function showMyGames(){
    /*$("#mygames").empty();

    for(var game in games){
        appendGame("#mygames", games, game);
    }*/
    $("#mygames").empty();

    var text_to_append = '

';

    for(var game in games){
        text_to_append += appendGame("#mygames", games, game);
    }

    text_to_append += "

";

    $('#mygames').append(text_to_append);

    for(var game in games){
        setEvents("#mygames", games, game);
    }
}

function showCommunityGames(){
    $("#community").empty();

    var text_to_append = '

';

    for(var game in games){
        if(games[game].public) text_to_append += appendGame("#community", games, game);
    }

    text_to_append += "

";

    $('#community').append(text_to_append);

    for(var game in games){
        if(games[game].public) setEvents("#community", games, game);
    }
}

function appendGame(parent, games, index){
    var url = gameTypeToUrl(games[index].type) + ".php?id=" + games[index].id;
    var type = gameTypeToDisplayName(games[index].type);

    var game = `

${games[index].name}

${games[index].description}

${type}

Last modified: ${games[index].last_update} GMT

                                <input data-index="${index}" class="pubpriv-toggle" type="checkbox" data-toggle="toggle" data-on="Public" data-off="Private" ${games[index].public?"checked":""}>

`;

    return game;
}

function setEvents(parent, games, index) {
    $('.pubpriv-toggle').bootstrapToggle();

    $('.pubpriv-toggle').change(function() {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            games[index].public = $(this).prop('checked');
            savePlot(games[index]);
            showCommunityGames();
        }
    });

    $(".gamerow .gameinfo").on('click', function(e) {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            var action = $(e.target).hasClass('fa-trash') ? "remove" : "";
            action = $(e.target).hasClass('fa-pencil') ? "edit" : action;
            action = $(e.target).hasClass('fa-copy') ? "duplicate" : action;

            if(action != "edit") e.preventDefault();

            gameOnClick(this, gameNumber, action);
        }
    });
    $("body").find("[data-index=" + index + "]").find('.gameType').ellipsis({
        lines: 3
    });

    $("body").find("[data-index=" + index + "]").find('.gameTitle').ellipsis({
        lines: 1
    });

    $("body").find("[data-index=" + index + "]").find(".fa-external-link").click(function(){
        var gameUrl = generateGameUrl(games[index]);
        showTestGame(gameUrl)

    });
}

$("body").find("[aria-controls='mygames']").on('click', function(e) {
    showMyGames();
});

$("body").find("[aria-controls='community']").on('click', function(e) {
    showCommunityGames();
});

function gameOnClick(parent, gameNumber, action){
    if(action == "remove"){
        showRemoveWarning(parent, gameNumber);
    }else if(action == "edit"){
    }else if(action == "duplicate"){
        var copy = games[gameNumber].copy();
        games.push(copy);
        duplicatePlot(copy, function(id){
            copy.id = id;
            $("#communitytab").parent().hasClass( "active" ) ? window.location="?tab=community" : window.location="";
        });
    }
}

function reorderPlots(){
    showMyGames();
    showCommunityGames();
}

function showTestGame(url){
    //TODO: mostarr modal para compartir
    window.open(url, '_blank');
}

function showRemoveWarning(parent, gameNumber){
    $("#remove-warning").modal('show');
    $(".warning-action-remove").click(function() {
        removePlot(games[gameNumber], function(){
            $("#communitytab").parent().hasClass( "active" ) ? window.location="?tab=community" : window.location="";
            $("#remove-warning").modal('hide');
        });
    });
    $(".warning-action-cancel").click(function(){
        $("#remove-warning").modal('hide');
    });
}

if ( tab == "community" ) { $('#communitytab').click(); }
<|endoftext|>


<commit_before>// alert("Blasteroids- a phaser.JS game by MSRinteractive \n This game requires a keyboard. Use the arrow keys to steer your ship. Press the Space-Bar to Blast the Aliens. \n Click OK when you are ready to begin. ");
var thrust = false;
var fire = false;
var left = false;
var right = false;

var gameProperties = {
	screenWidth: window.innerWidth -50,
	screenHeight: window.innerHeight -50,

	delayToStartLevel: 3,
};

var states = {
	game: "game",
};

var graphicAssets = {
	ship: {URL:'assets/ship.png', name:'ship'},
	bullet: {URL:'assets/bullet.png', name:'bullet'},

	asteroidLarge: {URL:'assets/asteroidLarge.png', name:'asteroidLarge'},
	asteroidMedium: {URL:'assets/asteroidMedium.png', name:'asteroidMedium'},
	asteroidSmall: {URL:'assets/asteroidSmall.png', name:'asteroidSmall'},
};

var soundAssets = {
	fire: {URL:['assets/laser.m4a', 'assets/laser.ogg'], name: 'fire'},
	destroyed: {URL:['assets/explode.m4a', 'assets/explode.m4a'], name: 'destroyed'},
};

var shipProperties = {
    startX: window.innerWidth * 0.5,
    startY: window.innerHeight * 0.5,
	acceleration: 475,
	drag: 85,
	maxVelocity: 350,
	angularVelocity: 325,
	startingLives: 5,
	timeToReset: 3,
	blinkDelay: 0.2,
};

var bulletProperties = {
    speed: 1800,
    interval: 285,
    lifeSpan: 325,
    maxCount: 200,
    scatter: [0,  0.01, 0, 0.015, 0, 0.015, 0, -0.01, 0, -0.015, 0, -0.015, 0.0175, -0.0175]
}

var asteroidProperties = {
	startingAsteroids: 3,
	maxAsteroids: 20,
	incrementAsteroids: 2,

	asteroidLarge: {minVelocity: 50, maxVelocity: 125, minAngularVelocity: 0, maxAngularVelocity: 200, score: 20, nextSize: graphicAssets.asteroidMedium.name, pieces: 2},
	asteroidMedium: {minVelocity: 50, maxVelocity: 220, minAngularVelocity: 0, maxAngularVelocity: 200, score: 50, nextSize: graphicAssets.asteroidSmall.name, pieces: 2},
	asteroidSmall: {minVelocity: 50, maxVelocity: 325, minAngularVelocity: 0, maxAngularVelocity: 200, score: 100},
};

var fontAssets = {
	counterFontStyle: {font: '20px Arial', fill: '#FFFFFF', align: 'center'},
};

var gameState = function (game){
    this.shipSprite;
    this.shipIsInvulnerable;

    this.key_left;
    this.key_right;
    this.key_thrust;
    this.key_fire;

    this.bulletGroup;
    this.bulletInterval = 0;

    this.asteroidGroup;
    this.asteroidsCount= asteroidProperties.startingAsteroids;

    this.shipLives = shipProperties.startingLives;
    this.tf_lives;

    this.score = 0;
    this.tf_score;

    this.sndDestroyed;
    this.sndFire;
};

gameState.prototype = {

    preload: function () {
				game.load.spritesheet('buttonhorizontal', 'assets/button-horizontal.png',50,50);
	 			game.load.spritesheet('buttonfire', 'assets/button-round-a.png',50,50);
	 			game.load.spritesheet('buttonthrust', 'assets/button-round-b.png',50,50);

        game.load.image(graphicAssets.asteroidLarge.name, graphicAssets.asteroidLarge.URL);
        game.load.image(graphicAssets.asteroidMedium.name, graphicAssets.asteroidMedium.URL);
        game.load.image(graphicAssets.asteroidSmall.name, graphicAssets.asteroidSmall.URL);

        game.load.image(graphicAssets.bullet.name, graphicAssets.bullet.URL);
        game.load.image(graphicAssets.ship.name, graphicAssets.ship.URL);

        game.load.audio(soundAssets.destroyed.name, soundAssets.destroyed.URL);
        game.load.audio(soundAssets.fire.name, soundAssets.fire.URL);
    },

    create: function () {
        this.initGraphics();
        this.initSounds();
        this.initPhysics();
        this.initKeyboard();
        this.resetAsteroids();
				// create our virtual game controller buttons
				thrust_x = window.innerWidth - 100;

			 buttonthrust = game.add.button(window.innerWidth - 125, window.innerHeight - 200, 'buttonthrust', null, this, 0, 1, 0, 1);  //game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame
			 buttonthrust.fixedToCamera = true;  //our buttons should stay on the same place
			 buttonthrust.events.onInputOver.add(function(){thrust=true;});
			 buttonthrust.events.onInputOut.add(function(){thrust=false;});
			 buttonthrust.events.onInputDown.add(function(){thrust=true;});
			 buttonthrust.events.onInputUp.add(function(){thrust=false;});

			 buttonfire = game.add.button(window.innerWidth - 164, window.innerHeight - 150,  'buttonfire', null, this, 0, 1, 0, 1);
			 buttonfire.fixedToCamera = true;
			 buttonfire.events.onInputOver.add(function(){fire=true;});
			 buttonfire.events.onInputOut.add(function(){fire=false;});
			 buttonfire.events.onInputDown.add(function(){fire=true;});
			 buttonfire.events.onInputUp.add(function(){fire=false;});

			 buttonleft = game.add.button(20, window.innerHeight - 150, 'buttonhorizontal', null, this, 0, 1, 0, 1);
		   buttonleft.fixedToCamera = true;
			 buttonleft.events.onInputOver.add(function(){left=true;});
			 buttonleft.events.onInputOut.add(function(){left=false;});
			 buttonleft.events.onInputDown.add(function(){left=true;});
			 buttonleft.events.onInputUp.add(function(){left=false;});

			 buttonright = game.add.button(88, window.innerHeight - 150, 'buttonhorizontal', null, this, 0, 1, 0, 1);
		   buttonright.fixedToCamera = true;
		   buttonright.events.onInputOver.add(function(){right=true;});
		   buttonright.events.onInputOut.add(function(){right=false;});
		   buttonright.events.onInputDown.add(function(){right=true;});
		   buttonright.events.onInputUp.add(function(){right=false;});

    },

    update: function () {
        this.checkPlayerInput();
        this.checkBoundaries(this.shipSprite);
        this.bulletGroup.forEachExists(this.checkBoundaries, this);
        this.asteroidGroup.forEachExists(this.checkBoundaries, this);

        game.physics.arcade.overlap(this.bulletGroup, this.asteroidGroup, this.asteroidCollision, null, this);
        if (!this.shipIsInvulnerable) {
        game.physics.arcade.overlap(this.shipSprite, this.asteroidGroup, this.asteroidCollision, null, this);
        }
    },

    initGraphics: function () {
        this.shipSprite = game.add.sprite(shipProperties.startX, shipProperties.startY, graphicAssets.ship.name);
        this.shipSprite.angle = -90;
        this.shipSprite.anchor.set(0.5, 0.5);

        this.bulletGroup = game.add.group();
        this.asteroidGroup = game.add.group();

        this.tf_lives = game.add.text(20, 10, shipProperties.startingLives, fontAssets.counterFontStyle);

        this.tf_score = game.add.text(gameProperties.screenWidth - 20, 10, "0", fontAssets.counterFontStyle);
    	this.tf_score.align - 'right';
    	this.tf_score.anchor.set(1,0);
    },

    initSounds: function () {
    	this.sndDestroyed = game.add.audio(soundAssets.destroyed.name);
    	this.sndFire = game.add.audio(soundAssets.fire.name);
    },

    initPhysics: function () {
        game.physics.startSystem(Phaser.Physics.ARCADE);

        game.physics.enable(this.shipSprite, Phaser.Physics.ARCADE);
        this.shipSprite.body.drag.set(shipProperties.drag);
        this.shipSprite.body.maxVelocity.set(shipProperties.maxVelocity);

        this.bulletGroup.enableBody = true;
        this.bulletGroup.physicsBodyType = Phaser.Physics.ARCADE;
        this.bulletGroup.createMultiple(bulletProperties.maxCount, graphicAssets.bullet.name);
        this.bulletGroup.setAll('anchor.x', 0.5);
        this.bulletGroup.setAll('anchor.y', 0.5);
        this.bulletGroup.setAll('lifespan', bulletProperties.lifeSpan);

        this.asteroidGroup.enableBody = true;
        this.asteroidGroup.physicsBodyType = Phaser.Physics.ARCADE;
    },

    initKeyboard: function () {
        this.key_left = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
        this.key_right = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
        this.key_thrust = game.input.keyboard.addKey(Phaser.Keyboard.UP);
        this.key_fire = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    },

    checkPlayerInput: function () {
        if (this.key_left.isDown || left) {
            this.shipSprite.body.angularVelocity = -shipProperties.angularVelocity;
        } else if (this.key_right.isDown || right) {
            this.shipSprite.body.angularVelocity = shipProperties.angularVelocity;
        } else {
            this.shipSprite.body.angularVelocity = 0;
        }

        if (this.key_thrust.isDownfire || thrust) {
            game.physics.arcade.accelerationFromRotation(this.shipSprite.rotation, shipProperties.acceleration, this.shipSprite.body.acceleration);
        } else {
            this.shipSprite.body.acceleration.set(0);
        }

        if (this.key_fire.isDown || fire) {
            this.fire();
        }
    },

    checkBoundaries: function (sprite) {
        if (sprite.x < 0) {
            sprite.x = game.width;
        } else if (sprite.x > game.width) {
            sprite.x = 0;
        }

        if (sprite.y < 0) {
            sprite.y = game.height;
        } else if (sprite.y > game.height) {
            sprite.y = 0;
        }
    },

    fire:  function () {
        if (this.shipSprite.visible) {

        if (game.time.now > this.bulletInterval) {
        	this.sndFire.play();

            var bullet = this.bulletGroup.getFirstExists(false);

            if (bullet) {
                var length = this.shipSprite.width * 0.9;
                var x = this.shipSprite.x + (Math.cos(this.shipSprite.rotation) * length);
                var y = this.shipSprite.y + (Math.sin(this.shipSprite.rotation) * length);

                bullet.reset(x, y);
                bullet.lifespan = bulletProperties.lifeSpan;
                bullet.rotation = this.shipSprite.rotation;

                game.physics.arcade.velocityFromRotation( (this.shipSprite.rotation + bulletProperties.scatter[Math.floor(Math.random()*bulletProperties.scatter.length)]) , bulletProperties.speed, bullet.body.velocity);
                this.bulletInterval = game.time.now + bulletProperties.interval;
            }
        }

        }
    },

    createAsteroid: function (x, y, size, pieces) {
        if (pieces === undefined) { pieces = 1; }

        for (var i=0; i<pieces; i++) {
            var asteroid = this.asteroidGroup.create(x, y, size);
            asteroid.anchor.set(0.5, 0.5);
            asteroid.body.angularVelocity = game.rnd.integerInRange(asteroidProperties[size].minAngularVelocity, asteroidProperties[size].maxAngularVelocity);

            var randomAngle = game.math.degToRad(game.rnd.angle());
            var randomVelocity = game.rnd.integerInRange(asteroidProperties[size].minVelocity, asteroidProperties[size].maxVelocity);

            game.physics.arcade.velocityFromRotation(randomAngle, randomVelocity, asteroid.body.velocity);
        }
    },

    resetAsteroids: function () {
        for (var i=0; i < this.asteroidsCount; i++ ) {
            var side = Math.round(Math.random());
            var x;
            var y;

            if (side) {
                x = Math.round(Math.random()) * gameProperties.screenWidth;
                y = Math.random() * gameProperties.screenHeight;
            } else {
                x = Math.random() * gameProperties.screenWidth;
                y = Math.round(Math.random()) * gameProperties.screenWidth;
            }

            this.createAsteroid(x, y, graphicAssets.asteroidLarge.name);
        }
    },

    asteroidCollision: function (target, asteroid) {
    	this.sndDestroyed.play();

        target.kill();
        asteroid.kill();

        if (target.key == graphicAssets.ship.name) {
            this.destroyShip();
        }

        this.splitAsteroid(asteroid);
        this.updateScore(asteroidProperties[asteroid.key].score);

        if (!this.asteroidGroup.countLiving() ) {
        	game.time.events.add(Phaser.Timer.SECOND * gameProperties.delayToStartLevel, this.nextLevel, this);
        }
    },

    destroyShip: function () {
        this.shipLives --;
        this.tf_lives.text = this.shipLives;

        if (this.shipLives) {
            game.time.events.add(Phaser.Timer.SECOND * shipProperties.timeToReset, this.resetShip, this);
        }
    },

    resetShip: function () {
        this.shipIsInvulnerable = true;
        this.shipSprite.reset(shipProperties.startX, shipProperties.startY);
        this.shipSprite.angle = -90;

        game.time.events.add(Phaser.Timer.SECOND * shipProperties.timeToReset, this.shipReady, this);
        game.time.events.repeat(Phaser.Timer.SECOND * shipProperties.blinkDelay, shipProperties.timeToReset / shipProperties.blinkDelay, this.shipBlink, this);
    },

    shipReady: function() {
    	this.shipIsInvulnerable = false;
    	this.shipSprite.visible = true;
    },

    shipBlink: function() {
    	this.shipSprite.visible = !this.shipSprite.visible;
    },

    splitAsteroid: function (asteroid) {
        if (asteroidProperties[asteroid.key].nextSize) {
            this.createAsteroid(asteroid.x, asteroid.y, asteroidProperties[asteroid.key].nextSize, asteroidProperties[asteroid.key].pieces);
        }
    },

    updateScore: function(score){
    	this.score += score;
    	this.tf_score.text = this.score;
    },

    nextLevel: function() {
    	this.asteroidGroup.removeAll(true);

    	if (this.asteroidsCount < asteroidProperties.maxAsteroids) {
    		this.asteroidsCount += asteroidProperties.incrementAsteroids;
    	}

    	this.resetAsteroids();
    }
};

var game = new Phaser.Game(gameProperties.screenWidth, gameProperties.screenHeight, Phaser.AUTO, 'gameDiv');
game.state.add(states.game, gameState);
game.state.start(states.game);
<commit_msg>mobile 5<commit_after>// alert("Blasteroids- a phaser.JS game by MSRinteractive \n This game requires a keyboard. Use the arrow keys to steer your ship. Press the Space-Bar to Blast the Aliens. \n Click OK when you are ready to begin. ");
var thrust = false;
var fire = false;
var left = false;
var right = false;

var gameProperties = {
	screenWidth: window.innerWidth -50,
	screenHeight: window.innerHeight -50,

	delayToStartLevel: 3,
};

var states = {
	game: "game",
};

var graphicAssets = {
	ship: {URL:'assets/ship.png', name:'ship'},
	bullet: {URL:'assets/bullet.png', name:'bullet'},

	asteroidLarge: {URL:'assets/asteroidLarge.png', name:'asteroidLarge'},
	asteroidMedium: {URL:'assets/asteroidMedium.png', name:'asteroidMedium'},
	asteroidSmall: {URL:'assets/asteroidSmall.png', name:'asteroidSmall'},
};

var soundAssets = {
	fire: {URL:['assets/laser.m4a', 'assets/laser.ogg'], name: 'fire'},
	destroyed: {URL:['assets/explode.m4a', 'assets/explode.m4a'], name: 'destroyed'},
};

var shipProperties = {
    startX: window.innerWidth * 0.5,
    startY: window.innerHeight * 0.5,
	acceleration: 475,
	drag: 85,
	maxVelocity: 350,
	angularVelocity: 325,
	startingLives: 5,
	timeToReset: 3,
	blinkDelay: 0.2,
};

var bulletProperties = {
    speed: 1800,
    interval: 285,
    lifeSpan: 325,
    maxCount: 200,
    scatter: [0,  0.01, 0, 0.015, 0, 0.015, 0, -0.01, 0, -0.015, 0, -0.015, 0.0175, -0.0175]
}

var asteroidProperties = {
	startingAsteroids: 3,
	maxAsteroids: 20,
	incrementAsteroids: 2,

	asteroidLarge: {minVelocity: 50, maxVelocity: 125, minAngularVelocity: 0, maxAngularVelocity: 200, score: 20, nextSize: graphicAssets.asteroidMedium.name, pieces: 2},
	asteroidMedium: {minVelocity: 50, maxVelocity: 220, minAngularVelocity: 0, maxAngularVelocity: 200, score: 50, nextSize: graphicAssets.asteroidSmall.name, pieces: 2},
	asteroidSmall: {minVelocity: 50, maxVelocity: 325, minAngularVelocity: 0, maxAngularVelocity: 200, score: 100},
};

var fontAssets = {
	counterFontStyle: {font: '20px Arial', fill: '#FFFFFF', align: 'center'},
};

var gameState = function (game){
    this.shipSprite;
    this.shipIsInvulnerable;

    this.key_left;
    this.key_right;
    this.key_thrust;
    this.key_fire;

    this.bulletGroup;
    this.bulletInterval = 0;

    this.asteroidGroup;
    this.asteroidsCount= asteroidProperties.startingAsteroids;

    this.shipLives = shipProperties.startingLives;
    this.tf_lives;

    this.score = 0;
    this.tf_score;

    this.sndDestroyed;
    this.sndFire;
};

gameState.prototype = {

    preload: function () {
				game.load.spritesheet('buttonhorizontal', 'assets/button-horizontal.png',50,50);
	 			game.load.spritesheet('buttonfire', 'assets/button-round-a.png',50,50);
	 			game.load.spritesheet('buttonthrust', 'assets/button-round-b.png',50,50);

        game.load.image(graphicAssets.asteroidLarge.name, graphicAssets.asteroidLarge.URL);
        game.load.image(graphicAssets.asteroidMedium.name, graphicAssets.asteroidMedium.URL);
        game.load.image(graphicAssets.asteroidSmall.name, graphicAssets.asteroidSmall.URL);

        game.load.image(graphicAssets.bullet.name, graphicAssets.bullet.URL);
        game.load.image(graphicAssets.ship.name, graphicAssets.ship.URL);

        game.load.audio(soundAssets.destroyed.name, soundAssets.destroyed.URL);
        game.load.audio(soundAssets.fire.name, soundAssets.fire.URL);
    },

    create: function () {
        this.initGraphics();
        this.initSounds();
        this.initPhysics();
        this.initKeyboard();
        this.resetAsteroids();
				// create our virtual game controller buttons
				thrust_x = window.innerWidth - 100;

			 buttonthrust = game.add.button(window.innerWidth - 115, window.innerHeight - 220, 'buttonthrust', null, this, 0, 1, 0, 1);  //game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame
			 buttonthrust.fixedToCamera = true;  //our buttons should stay on the same place
			 buttonthrust.events.onInputOver.add(function(){thrust=true;});
			 buttonthrust.events.onInputOut.add(function(){thrust=false;});
			 buttonthrust.events.onInputDown.add(function(){thrust=true;});
			 buttonthrust.events.onInputUp.add(function(){thrust=false;});

			 buttonfire = game.add.button(window.innerWidth - 164, window.innerHeight - 150,  'buttonfire', null, this, 0, 1, 0, 1);
			 buttonfire.fixedToCamera = true;
			 buttonfire.events.onInputOver.add(function(){fire=true;});
			 buttonfire.events.onInputOut.add(function(){fire=false;});
			 buttonfire.events.onInputDown.add(function(){fire=true;});
			 buttonfire.events.onInputUp.add(function(){fire=false;});

			 buttonleft = game.add.button(20, window.innerHeight - 150, 'buttonhorizontal', null, this, 0, 1, 0, 1);
		   buttonleft.fixedToCamera = true;
			 buttonleft.events.onInputOver.add(function(){left=true;});
			 buttonleft.events.onInputOut.add(function(){left=false;});
			 buttonleft.events.onInputDown.add(function(){left=true;});
			 buttonleft.events.onInputUp.add(function(){left=false;});

			 buttonright = game.add.button(88, window.innerHeight - 150, 'buttonhorizontal', null, this, 0, 1, 0, 1);
		   buttonright.fixedToCamera = true;
		   buttonright.events.onInputOver.add(function(){right=true;});
		   buttonright.events.onInputOut.add(function(){right=false;});
		   buttonright.events.onInputDown.add(function(){right=true;});
		   buttonright.events.onInputUp.add(function(){right=false;});

    },

    update: function () {
        this.checkPlayerInput();
        this.checkBoundaries(this.shipSprite);
        this.bulletGroup.forEachExists(this.checkBoundaries, this);
        this.asteroidGroup.forEachExists(this.checkBoundaries, this);

        game.physics.arcade.overlap(this.bulletGroup, this.asteroidGroup, this.asteroidCollision, null, this);
        if (!this.shipIsInvulnerable) {
        game.physics.arcade.overlap(this.shipSprite, this.asteroidGroup, this.asteroidCollision, null, this);
        }
    },

    initGraphics: function () {
        this.shipSprite = game.add.sprite(shipProperties.startX, shipProperties.startY, graphicAssets.ship.name);
        this.shipSprite.angle = -90;
        this.shipSprite.anchor.set(0.5, 0.5);

        this.bulletGroup = game.add.group();
        this.asteroidGroup = game.add.group();

        this.tf_lives = game.add.text(20, 10, shipProperties.startingLives, fontAssets.counterFontStyle);

        this.tf_score = game.add.text(gameProperties.screenWidth - 20, 10, "0", fontAssets.counterFontStyle);
    	this.tf_score.align - 'right';
    	this.tf_score.anchor.set(1,0);
    },

    initSounds: function () {
    	this.sndDestroyed = game.add.audio(soundAssets.destroyed.name);
    	this.sndFire = game.add.audio(soundAssets.fire.name);
    },

    initPhysics: function () {
        game.physics.startSystem(Phaser.Physics.ARCADE);

        game.physics.enable(this.shipSprite, Phaser.Physics.ARCADE);
        this.shipSprite.body.drag.set(shipProperties.drag);
        this.shipSprite.body.maxVelocity.set(shipProperties.maxVelocity);

        this.bulletGroup.enableBody = true;
        this.bulletGroup.physicsBodyType = Phaser.Physics.ARCADE;
        this.bulletGroup.createMultiple(bulletProperties.maxCount, graphicAssets.bullet.name);
        this.bulletGroup.setAll('anchor.x', 0.5);
        this.bulletGroup.setAll('anchor.y', 0.5);
        this.bulletGroup.setAll('lifespan', bulletProperties.lifeSpan);

        this.asteroidGroup.enableBody = true;
        this.asteroidGroup.physicsBodyType = Phaser.Physics.ARCADE;
    },

    initKeyboard: function () {
        this.key_left = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
        this.key_right = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
        this.key_thrust = game.input.keyboard.addKey(Phaser.Keyboard.UP);
        this.key_fire = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    },

    checkPlayerInput: function () {
        if (this.key_left.isDown || left) {
            this.shipSprite.body.angularVelocity = -shipProperties.angularVelocity;
        } else if (this.key_right.isDown || right) {
            this.shipSprite.body.angularVelocity = shipProperties.angularVelocity;
        } else {
            this.shipSprite.body.angularVelocity = 0;
        }

        if (this.key_thrust.isDownfire || thrust) {
            game.physics.arcade.accelerationFromRotation(this.shipSprite.rotation, shipProperties.acceleration, this.shipSprite.body.acceleration);
        } else {
            this.shipSprite.body.acceleration.set(0);
        }

        if (this.key_fire.isDown || fire) {
            this.fire();
        }
    },

    checkBoundaries: function (sprite) {
        if (sprite.x < 0) {
            sprite.x = game.width;
        } else if (sprite.x > game.width) {
            sprite.x = 0;
        }

        if (sprite.y < 0) {
            sprite.y = game.height;
        } else if (sprite.y > game.height) {
            sprite.y = 0;
        }
    },

    fire:  function () {
        if (this.shipSprite.visible) {

        if (game.time.now > this.bulletInterval) {
        	this.sndFire.play();

            var bullet = this.bulletGroup.getFirstExists(false);

            if (bullet) {
                var length = this.shipSprite.width * 0.9;
                var x = this.shipSprite.x + (Math.cos(this.shipSprite.rotation) * length);
                var y = this.shipSprite.y + (Math.sin(this.shipSprite.rotation) * length);

                bullet.reset(x, y);
                bullet.lifespan = bulletProperties.lifeSpan;
                bullet.rotation = this.shipSprite.rotation;

                game.physics.arcade.velocityFromRotation( (this.shipSprite.rotation + bulletProperties.scatter[Math.floor(Math.random()*bulletProperties.scatter.length)]) , bulletProperties.speed, bullet.body.velocity);
                this.bulletInterval = game.time.now + bulletProperties.interval;
            }
        }

        }
    },

    createAsteroid: function (x, y, size, pieces) {
        if (pieces === undefined) { pieces = 1; }

        for (var i=0; i<pieces; i++) {
            var asteroid = this.asteroidGroup.create(x, y, size);
            asteroid.anchor.set(0.5, 0.5);
            asteroid.body.angularVelocity = game.rnd.integerInRange(asteroidProperties[size].minAngularVelocity, asteroidProperties[size].maxAngularVelocity);

            var randomAngle = game.math.degToRad(game.rnd.angle());
            var randomVelocity = game.rnd.integerInRange(asteroidProperties[size].minVelocity, asteroidProperties[size].maxVelocity);

            game.physics.arcade.velocityFromRotation(randomAngle, randomVelocity, asteroid.body.velocity);
        }
    },

    resetAsteroids: function () {
        for (var i=0; i < this.asteroidsCount; i++ ) {
            var side = Math.round(Math.random());
            var x;
            var y;

            if (side) {
                x = Math.round(Math.random()) * gameProperties.screenWidth;
                y = Math.random() * gameProperties.screenHeight;
            } else {
                x = Math.random() * gameProperties.screenWidth;
                y = Math.round(Math.random()) * gameProperties.screenWidth;
            }

            this.createAsteroid(x, y, graphicAssets.asteroidLarge.name);
        }
    },

    asteroidCollision: function (target, asteroid) {
    	this.sndDestroyed.play();

        target.kill();
        asteroid.kill();

        if (target.key == graphicAssets.ship.name) {
            this.destroyShip();
        }

        this.splitAsteroid(asteroid);
        this.updateScore(asteroidProperties[asteroid.key].score);

        if (!this.asteroidGroup.countLiving() ) {
        	game.time.events.add(Phaser.Timer.SECOND * gameProperties.delayToStartLevel, this.nextLevel, this);
        }
    },

    destroyShip: function () {
        this.shipLives --;
        this.tf_lives.text = this.shipLives;

        if (this.shipLives) {
            game.time.events.add(Phaser.Timer.SECOND * shipProperties.timeToReset, this.resetShip, this);
        }
    },

    resetShip: function () {
        this.shipIsInvulnerable = true;
        this.shipSprite.reset(shipProperties.startX, shipProperties.startY);
        this.shipSprite.angle = -90;

        game.time.events.add(Phaser.Timer.SECOND * shipProperties.timeToReset, this.shipReady, this);
        game.time.events.repeat(Phaser.Timer.SECOND * shipProperties.blinkDelay, shipProperties.timeToReset / shipProperties.blinkDelay, this.shipBlink, this);
    },

    shipReady: function() {
    	this.shipIsInvulnerable = false;
    	this.shipSprite.visible = true;
    },

    shipBlink: function() {
    	this.shipSprite.visible = !this.shipSprite.visible;
    },

    splitAsteroid: function (asteroid) {
        if (asteroidProperties[asteroid.key].nextSize) {
            this.createAsteroid(asteroid.x, asteroid.y, asteroidProperties[asteroid.key].nextSize, asteroidProperties[asteroid.key].pieces);
        }
    },

    updateScore: function(score){
    	this.score += score;
    	this.tf_score.text = this.score;
    },

    nextLevel: function() {
    	this.asteroidGroup.removeAll(true);

    	if (this.asteroidsCount < asteroidProperties.maxAsteroids) {
    		this.asteroidsCount += asteroidProperties.incrementAsteroids;
    	}

    	this.resetAsteroids();
    }
};

var game = new Phaser.Game(gameProperties.screenWidth, gameProperties.screenHeight, Phaser.AUTO, 'gameDiv');
game.state.add(states.game, gameState);
game.state.start(states.game);
<|endoftext|>