<commit_before>var DURATION = 2000;

var interval;

function cleanup()
{
    // Cancel any interval started by a previous slide
    clearInterval(interval);
}

function setupVisualizations(slideshow)
{
    slideshow.on('afterShowSlide', function (slide)
    {
        cleanup();

        if (slide.properties.viz && document.getElementById(slide.properties.viz))
        {
            d3.select('#' + slide.properties.viz).call(startViz);
        }
    });

    // start visualizations with a click in the container
    d3.selectAll(".viz-container").on("click", function()
    {
        cleanup();

        viz(this);
    });
}

function viz(element)
{
    startViz(d3.select(element));
}

function startViz(selection)
{
    var id = selection.attr("id");
    console.log('starting viz %s', id);
    window[id](selection);
}

////////////////////////////////////////////////////////////////////////

function vizSelections1(selection)
{
    selection.select('rect')
        .transition().duration(DURATION)
        .style("fill", "green");
}

function vizSelections2(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .style("fill", "green");
}

function vizSelections3(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .attr("height", "150")
        .transition().duration(DURATION)
        .attr("width", "100")
        .transition().duration(DURATION)
        .style("fill", "gray")
        .transition().duration(DURATION)
        .style("stroke", "indigo").style("stroke-width", 15);
}

function vizSelections4(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .attr("height", "150")
        .transition().duration(DURATION)
        .attr("width", 100)
        .transition().duration(DURATION)
        .style("fill", function (d, i) {
            return ["gray", "orange"][i];
        })
}

function vizSelectionsPractice(selection)
{
    selection.selectAll('circle')
        .transition().duration(DURATION)
        .attr("r", function () {
            return Math.random() * 200;
        })
        .attr("class", function (d, i) {
            return ['php', 'js', 'ruby'][i] + ' transparent';
        });
}

function vizDataJoin1(selection)
{
    var data = [200, 100, 15];

    var circles = selection.select('g').selectAll('circle').data(data);

    var circleEnter = circles.enter().append("circle").attr("r", 0);

    circles.transition().duration(DURATION)
        .attr("r", function (d, i)
        {
            return d;
        })
        .attr("class", function (d, i)
        {
            return ['js', 'php', 'ruby'][i];
        });

}

vizDataJoin2 = vizDataJoin1;

function vizEUE1(selection)
{
    var data = [
        {lang: 'js',   popularity: 200},
        {lang: 'php',  popularity: 100},
        {lang: 'ruby', popularity: 15},
    ];

    var circles = selection.select('g').selectAll('circle').data(data);

    var circleEnter = circles.enter().append("circle").attr("r", 0);

    circles.transition().duration(DURATION)
        .attr("r", function (d, i)
        {
            return d.popularity;
        })
        .attr("class", function (d, i)
        {
            return d.lang;
        });
}

// -----------------------------------------------------------------------------

var eue2Data = [
    {lang: 'js',   popularity: 200},
    {lang: 'php',  popularity: 100},
];

eue2Data.times = 2;

function vizEUE2(selection)
{
    switch (eue2Data.times++ % 3)
    {
        case 0:
            eue2Data.push({lang: 'ruby', popularity: 60});
            break;

        case 1:
            eue2Data[1].popularity = 70 + _.random(0, 130);
            break;

        case 2:
            eue2Data.length =  2;
            break;
    }

    console.log(JSON.stringify(eue2Data));

    var circles = selection.select('g').selectAll('circle').data(eue2Data);

    circles.enter()
        .append("circle")
        .style("opacity", 0)
        .attr("r", 0);

    circles
        .transition().duration(DURATION)
        .style("opacity", 1)
        .attr("r", function (d, i)
        {
            return d.popularity;
        })
        .attr("class", function (d, i)
        {
            return d.lang;
        });

    circles.exit()
        .transition().duration(DURATION)
        .style("opacity", 0)
        .remove();
}

function vizAxisDemo(selection)
{
    var svg = selection.select('svg');
    var $svg = jQuery(svg[0]).empty();

    svg.append("g");

    var factor = 1;

    var width = $svg.width();

    var tScale = d3.time.scale()
        .range([0, width])
        .nice();

    var tAxis = d3.svg.axis().ticks(5).scale(tScale);

    function refresh()
    {
        factor *=  1.02;

        offset = factor * 5 * 1e3;

        console.log("refresh %s", offset);

        if (offset > 1e3 * 60 * 60 * 24 * 365 * 10)
        {
            cleanup();
        }

        tScale.domain([
            Date.now() - offset,
            Date.now()
        ]);

        svg.transition().call(tAxis);
    }

    interval = setInterval(refresh, 100);
}

// -----------------------------------------------------------------------------
<commit_msg>adding function to compute width<commit_after>var DURATION = 2000;

var interval;

function cleanup()
{
    // Cancel any interval started by a previous slide
    clearInterval(interval);
}

function setupVisualizations(slideshow)
{
    slideshow.on('afterShowSlide', function (slide)
    {
        cleanup();

        if (slide.properties.viz && document.getElementById(slide.properties.viz))
        {
            d3.select('#' + slide.properties.viz).call(startViz);
        }
    });

    // start visualizations with a click in the container
    d3.selectAll(".viz-container").on("click", function()
    {
        cleanup();

        viz(this);
    });
}

function viz(element)
{
    startViz(d3.select(element));
}

function startViz(selection)
{
    var id = selection.attr("id");
    console.log('starting viz %s', id);
    window[id](selection);
}

function width(selection)
{
    var svg = selection.select('svg'),
        $svg = jQuery(svg[0]);

    return $svg.width();
}

////////////////////////////////////////////////////////////////////////

function vizSelections1(selection)
{
    selection.select('rect')
        .transition().duration(DURATION)
        .style("fill", "green");
}

function vizSelections2(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .style("fill", "green");
}

function vizSelections3(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .attr("height", "150")
        .transition().duration(DURATION)
        .attr("width", "100")
        .transition().duration(DURATION)
        .style("fill", "gray")
        .transition().duration(DURATION)
        .style("stroke", "indigo").style("stroke-width", 15);
}

function vizSelections4(selection)
{
    selection.selectAll('rect')
        .transition().duration(DURATION)
        .attr("height", "150")
        .transition().duration(DURATION)
        .attr("width", 100)
        .transition().duration(DURATION)
        .style("fill", function (d, i) {
            return ["gray", "orange"][i];
        })
}

function vizSelectionsPractice(selection)
{
    selection.selectAll('circle')
        .transition().duration(DURATION)
        .attr("r", function () {
            return Math.random() * 200;
        })
        .attr("class", function (d, i) {
            return ['php', 'js', 'ruby'][i] + ' transparent';
        });
}

function vizDataJoin1(selection)
{
    var data = [200, 100, 15];

    var circles = selection.select('g').selectAll('circle').data(data);

    var circleEnter = circles.enter().append("circle").attr("r", 0);

    circles.transition().duration(DURATION)
        .attr("r", function (d, i)
        {
            return d;
        })
        .attr("class", function (d, i)
        {
            return ['js', 'php', 'ruby'][i];
        });

}

vizDataJoin2 = vizDataJoin1;

function vizEUE1(selection)
{
    var data = [
        {lang: 'js',   popularity: 200},
        {lang: 'php',  popularity: 100},
        {lang: 'ruby', popularity: 15},
    ];

    var circles = selection.select('g').selectAll('circle').data(data);

    var circleEnter = circles.enter().append("circle").attr("r", 0);

    circles.transition().duration(DURATION)
        .attr("r", function (d, i)
        {
            return d.popularity;
        })
        .attr("class", function (d, i)
        {
            return d.lang;
        });
}

// -----------------------------------------------------------------------------

var eue2Data = [
    {lang: 'js',   popularity: 200},
    {lang: 'php',  popularity: 100},
];

eue2Data.times = 2;

function vizEUE2(selection)
{
    switch (eue2Data.times++ % 3)
    {
        case 0:
            eue2Data.push({lang: 'ruby', popularity: 60});
            break;

        case 1:
            eue2Data[1].popularity = 70 + _.random(0, 130);
            break;

        case 2:
            eue2Data.length =  2;
            break;
    }

    console.log(JSON.stringify(eue2Data));

    var circles = selection.select('g').selectAll('circle').data(eue2Data);

    circles.enter()
        .append("circle")
        .style("opacity", 0)
        .attr("r", 0);

    circles
        .transition().duration(DURATION)
        .style("opacity", 1)
        .attr("r", function (d, i)
        {
            return d.popularity;
        })
        .attr("class", function (d, i)
        {
            return d.lang;
        });

    circles.exit()
        .transition().duration(DURATION)
        .style("opacity", 0)
        .remove();
}

// -----------------------------------------------------------------------------

function vizAxisDemo(selection)
{
    var svg = selection.select('svg');

    svg.append("g");

    var factor = 1;

    var tScale = d3.time.scale()
        .range([0, width(selection)])
        .nice();

    var tAxis = d3.svg.axis().ticks(5).scale(tScale);

    function refresh()
    {
        factor *=  1.02;

        offset = factor * 5 * 1e3;

        console.log("refresh %s", offset);

        if (offset > 1e3 * 60 * 60 * 24 * 365 * 10)
        {
            cleanup();
        }

        tScale.domain([
            Date.now() - offset,
            Date.now()
        ]);

        svg.transition().call(tAxis);
    }

    interval = setInterval(refresh, 100);
}

// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>var doc = document,
    qs  = doc.querySelector;

// -- Sulaco -------------------------------------------------------------------
var Sulaco;

Sulaco = {
    lineCache: {},
    playbackMode: true,

    coalesceMessages: function (lineNum) {
        var lineEl     = Sulaco.getLineEl(lineNum),
            prevLineEl = lineEl && Sulaco.getLineEl(lineEl.previousElementSibling),
            prevSender = Sulaco.getSenderNick(prevLineEl),
            sender     = Sulaco.getSenderNick(lineEl);

        if (!sender || !prevSender) {
            return;
        }

        if (sender === prevSender
                && Sulaco.getLineType(lineEl) === 'privmsg'
                && Sulaco.getLineType(prevLineEl) === 'privmsg') {

            lineEl.classList.add('coalesced');
            Sulaco.getSenderEl(lineEl).innerHTML = '';
        }
    },

    getLineEl: function (lineNum) {
        if (typeof lineNum === 'string') {
            return doc.getElementById('line' + lineNum);
        }

        if (lineNum && lineNum.classList
                && lineNum.classList.contains('line')) {
            return lineNum;
        }

        return null;
    },

    getLineType: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.getAttribute('type') : null;
    },

    getMessage: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.querySelector('.message').textContent.trim() : null;
    },

    getSenderEl: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.querySelector('.sender') : null;
    },

    getSenderNick: function (line) {
        var senderEl = Sulaco.getSenderEl(line);
        return senderEl ? senderEl.getAttribute('nickname') : null;
    },

    handleBufferPlayback: function (lineNum) {
        var line = Sulaco.getLineEl(lineNum),
            message;

        if (Sulaco.getSenderNick(line) === '***') {
            message = Sulaco.getMessage(line);

            if (message === 'Buffer Playback...') {
                line.classList.add('znc-playback-start');
                Sulaco.playbackMode = true;
            } else if (message === 'Playback Complete.') {
                line.classList.add('znc-playback-end');
                Sulaco.playbackMode = false;
            }

            return;
        }

        if (Sulaco.playbackMode) {
            var match;

            line.classList.add('znc-playback');

            message = Sulaco.getMessage(line);
            match   = message.match(/^\[(\d\d:\d\d:\d\d)\] /);

            if (match) {
                var msgEl = line.querySelector('.message');

                line.querySelector('.time').textContent = match[1];
                msgEl.innerHTML = msgEl.innerHTML.replace(/^\s*\[\d\d:\d\d:\d\d\]/, '');
            }
        }
    },

    setDescriptiveClassNames: function (lineNum) {
      var line = Sulaco.getLineEl(lineNum);

      if (line.getAttribute('type') === 'debug' &&
          /Disconnect/.test(line.textContent))
        line.classList.add('disconnect');

      if (line.getAttribute('type') === 'mode')
        line.classList.add('mode');

      if (line.getAttribute('type') === 'topic')
        line.classList.add('topic');

      if (line.getAttribute('type') === 'website')
        line.classList.add('website');

      if (line.getAttribute('type') === 'join' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-join');

      if (line.getAttribute('type') === 'quit' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-quit');

      if (line.getAttribute('type') === 'part' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-part');

      if (line.getAttribute('type') === 'nick' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-nick');

      if (line.getAttribute('type') === 'quit' &&
          /query/i.test(line.textContent))
        line.classList.add('quit-query');

      if (line.getAttribute('type') === 'join' &&
          /query/i.test(line.textContent))
        line.classList.add('join-query');
    }
};

// -- Textual ------------------------------------------------------------------

// Defined in: "Textual.app -> Contents -> Resources -> JavaScript -> API -> core.js"

Textual.newMessagePostedToView = function (lineNum) {
    Sulaco.handleBufferPlayback(lineNum);
    Sulaco.coalesceMessages(lineNum);
    Sulaco.setDescriptiveClassNames(lineNum);
};

Textual.viewFinishedLoading = function () {
    Textual.fadeInLoadingScreen(1.00, 0.95);

    setTimeout(function () {
        Textual.scrollToBottomOfView();
    }, 300);
};

Textual.viewFinishedReload = function () {
    Textual.viewFinishedLoading();
};

/* When you join a channel, delete all the old disconnected messages */
Textual.handleEvent = function (event) {
  'use strict';
  var i, messages;

  if (event === 'channelJoined') {
    messages = document.querySelectorAll('div[command="-100"]');
    for (i = 0; i < messages.length; i++) {
      if (app.channelIsJoined() && (messages[i].getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1)) {
        messages[i].parentNode.removeChild(messages[i]);
      }
    }
  }
};
<commit_msg>another sync with current Textual 6 styling<commit_after>var doc = document,
    qs  = doc.querySelector;

// -- Sulaco -------------------------------------------------------------------
var Sulaco;

Sulaco = {
    lineCache: {},
    playbackMode: true,

    coalesceMessages: function (lineNum) {
        var lineEl     = Sulaco.getLineEl(lineNum),
            prevLineEl = lineEl && Sulaco.getLineEl(lineEl.previousElementSibling),
            prevSender = Sulaco.getSenderNick(prevLineEl),
            sender     = Sulaco.getSenderNick(lineEl);

        if (!sender || !prevSender) {
            return;
        }

        if (sender === prevSender
                && Sulaco.getLineType(lineEl) === 'privmsg'
                && Sulaco.getLineType(prevLineEl) === 'privmsg') {

            lineEl.classList.add('coalesced');
            Sulaco.getSenderEl(lineEl).innerHTML = '';
        }
    },

    getLineEl: function (lineNum) {
        if (typeof lineNum === 'string') {
            return doc.getElementById('line' + lineNum);
        }

        if (lineNum && lineNum.classList
                && lineNum.classList.contains('line')) {
            return lineNum;
        }

        return null;
    },

    getLineType: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.getAttribute('type') : null;
    },

    getMessage: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.querySelector('.message').textContent.trim() : null;
    },

    getSenderEl: function (line) {
        line = Sulaco.getLineEl(line);
        return line ? line.querySelector('.sender') : null;
    },

    getSenderNick: function (line) {
        var senderEl = Sulaco.getSenderEl(line);
        return senderEl ? senderEl.getAttribute('nickname') : null;
    },

    handleBufferPlayback: function (lineNum) {
        var line = Sulaco.getLineEl(lineNum),
            message;

        if (Sulaco.getSenderNick(line) === '***') {
            message = Sulaco.getMessage(line);

            if (message === 'Buffer Playback...') {
                line.classList.add('znc-playback-start');
                Sulaco.playbackMode = true;
            } else if (message === 'Playback Complete.') {
                line.classList.add('znc-playback-end');
                Sulaco.playbackMode = false;
            }

            return;
        }

        if (Sulaco.playbackMode) {
            var match;

            line.classList.add('znc-playback');

            message = Sulaco.getMessage(line);
            match   = message.match(/^\[(\d\d:\d\d:\d\d)\] /);

            if (match) {
                var msgEl = line.querySelector('.message');

                line.querySelector('.time').textContent = match[1];
                msgEl.innerHTML = msgEl.innerHTML.replace(/^\s*\[\d\d:\d\d:\d\d\]/, '');
            }
        }
    },

    setDescriptiveClassNames: function (lineNum) {
      var line = Sulaco.getLineEl(lineNum);

      if (line.getAttribute('type') === 'debug' &&
          /Disconnect/.test(line.textContent))
        line.classList.add('disconnect');

      if (line.getAttribute('type') === 'mode')
        line.classList.add('mode');

      if (line.getAttribute('type') === 'topic')
        line.classList.add('topic');

      if (line.getAttribute('type') === 'website')
        line.classList.add('website');

      if (line.getAttribute('type') === 'join' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-join');

      if (line.getAttribute('type') === 'quit' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-quit');

      if (line.getAttribute('type') === 'part' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-part');

      if (line.getAttribute('type') === 'nick' &&
          /Dominus/i.test(line.textContent))
        line.classList.add('dominus-nick');

      if (line.getAttribute('type') === 'quit' &&
          /query/i.test(line.textContent))
        line.classList.add('quit-query');

      if (line.getAttribute('type') === 'join' &&
          /query/i.test(line.textContent))
        line.classList.add('join-query');
    }
};

// -- Textual ------------------------------------------------------------------

// Defined in: "Textual.app -> Contents -> Resources -> JavaScript -> API -> core.js"

Textual.newMessagePostedToView = function (lineNum) {
    Sulaco.handleBufferPlayback(lineNum);
    Sulaco.coalesceMessages(lineNum);
    Sulaco.setDescriptiveClassNames(lineNum);
};

Textual.viewBodyDidLoad = function () {
  Textual.fadeOutLoadingScreen(1.00, 0.95);
};

Textual.viewFinishedReload = function () {
    Textual.viewFinishedLoading();
};

/* When you join a channel, delete all the old disconnected messages */
Textual.handleEvent = function (event) {
  'use strict';
  var i, messages;

  if (event === 'channelJoined') {
    messages = document.querySelectorAll('div[command="-100"]');
    for (i = 0; i < messages.length; i++) {
      if (app.channelIsJoined() && (messages[i].getElementsByClassName('message')[0].textContent.search('Disconnect') !== -1)) {
        messages[i].parentNode.removeChild(messages[i]);
      }
    }
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styles from './search-input.css';

const ENTER_KEY_CODE = 13;

class SearchInput extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			value: ''
		};
		this.search = this.search.bind(this);
		this.handleOnClick = this.handleOnClick.bind(this);
		this.handleOnChange = this.handleOnChange.bind(this);
		this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
	}

	handleOnChange(e) {
		this.setState({
			value: e.target.value
		});
	}

	handleOnKeyDown(e) {
		if (e.keyCode === ENTER_KEY_CODE) {
			this.search();
		}
	}

	handleOnClick() {
		this.search();
	}

	search() {
		if (this.state.value.trim()) {
			this.props.onSearch(this.state.value);
		}
	}

	render() {
		return (

				<input
					className={styles.input}
					type="text"
					placeholder={this.props.placeholder}
					autoFocus={1}
					onKeyDown={this.handleOnKeyDown}
					value={this.state.value}
					onChange={this.handleOnChange}
					/>
				<button className={styles.button} onClick={this.handleOnClick}>GO</button>

		);
	}
}

SearchInput.propTypes = {
	placeholder: PropTypes.string,
	onSearch: PropTypes.func.isRequired
};

SearchInput.defaultProps = {
	placeholder: 'Search query here...'
};

export default SearchInput;
<commit_msg>Ad empty space This commit resolves #4<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styles from './search-input.css';

const ENTER_KEY_CODE = 13;

class SearchInput extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			value: ''
		};
		this.search = this.search.bind(this);
		this.handleOnClick = this.handleOnClick.bind(this);
		this.handleOnChange = this.handleOnChange.bind(this);
		this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
	}

	handleOnChange(e) {
		this.setState({
			value: e.target.value
		});
	}

	handleOnKeyDown(e) {
		if (e.keyCode === ENTER_KEY_CODE) {
			this.search();
		}
	}

	handleOnClick() {
		this.search();
	}

	search() {
		if (this.state.value.trim()) {
			this.props.onSearch(this.state.value);
		}
	}

	render() {
		return (

				<input
					className={styles.input}
					type="text"
					placeholder={this.props.placeholder}
					autoFocus={1}
					onKeyDown={this.handleOnKeyDown}
					value={this.state.value}
					onChange={this.handleOnChange}
					/>
				<button className={styles.button} onClick={this.handleOnClick}>GO</button>

		);
	}
}

SearchInput.propTypes = {
	placeholder: PropTypes.string,
	onSearch: PropTypes.func.isRequired
};

SearchInput.defaultProps = {
	placeholder: 'Search query here ...'
};

export default SearchInput;
<|endoftext|>


<commit_before>/* This script file handles the game logic */
//Note that X/Y referred to here are in game coordinates
var maxX = 10;//Nums are for tileSize 40
var maxY = 15;
var tileSize = 40;
var maxIndex = maxX*maxY;
var board = new Array(maxIndex);
var tileSrc = "content/BoomBlock.qml";
var scoresURL = "http://qtfx-nokia.trolltech.com.au/samegame/scores.php";
var timer;
var component;

//Index function used instead of a 2D array
function index(xIdx,yIdx) {
    return xIdx + (yIdx * maxX);
}

function timeStr(msecs) {
    var secs = Math.floor(msecs/1000);
    var m = Math.floor(secs/60);
    var ret = "" + m + "m " + (secs%60) + "s";
    return ret;
}

function initBoard()
{
    for(i = 0; i<maxIndex; i++){
        //Delete old blocks
        if(board[i] != null)
            board[i].destroy();
    }

    maxX = Math.floor(gameCanvas.width/tileSize);
    maxY = Math.floor(gameCanvas.height/tileSize);
    maxIndex = maxY*maxX;

    //Initialize Board
    board = new Array(maxIndex);
    gameCanvas.score = 0;
    for(xIdx=0; xIdx<maxX; xIdx++){
        for(yIdx=0; yIdx<maxY; yIdx++){
            board[index(xIdx,yIdx)] = null;
            startCreatingBlock(xIdx,yIdx);
        }
    }
    timer = new Date();
}

var fillFound;//Set after a floodFill call to the number of tiles found
var floodBoard;//Set to 1 if the floodFill reaches off that node
//NOTE: Be careful with vars named x,y, as the calling object's x,y are still in scope
function handleClick(x,y)
{
    xIdx = Math.floor(x/tileSize);
    yIdx = Math.floor(y/tileSize);
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return;
    if(board[index(xIdx, yIdx)] == null)
        return;
    //If it's a valid tile, remove it and all connected (does nothing if it's not connected)
    floodFill(xIdx,yIdx, -1);
    if(fillFound <= 0)
        return;
    gameCanvas.score += (fillFound - 1) * (fillFound - 1);
    shuffleDown();
    victoryCheck();
}

function floodFill(xIdx,yIdx,type)
{
    if(board[index(xIdx, yIdx)] == null)
        return;
    var first = false;
    if(type == -1){
        first = true;
        type = board[index(xIdx,yIdx)].type;

        //Flood fill initialization
        fillFound = 0;
        floodBoard = new Array(maxIndex);
    }
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return;
    if(floodBoard[index(xIdx, yIdx)] == 1 || (!first && type != board[index(xIdx,yIdx)].type))
        return;
    floodBoard[index(xIdx, yIdx)] = 1;
    floodFill(xIdx+1,yIdx,type);
    floodFill(xIdx-1,yIdx,type);
    floodFill(xIdx,yIdx+1,type);
    floodFill(xIdx,yIdx-1,type);
    if(first==true && fillFound == 0)
        return;//Can't remove single tiles
    board[index(xIdx,yIdx)].dying = true;
    board[index(xIdx,yIdx)] = null;
    fillFound += 1;
}

function shuffleDown()
{
    //Fall down
    for(xIdx=0; xIdx<maxX; xIdx++){
        fallDist = 0;
        for(yIdx=maxY-1; yIdx>=0; yIdx--){
            if(board[index(xIdx,yIdx)] == null){
                fallDist += 1;
            }else{
                if(fallDist > 0){
                    obj = board[index(xIdx,yIdx)];
                    obj.targetY += fallDist * tileSize;
                    board[index(xIdx,yIdx+fallDist)] = obj;
                    board[index(xIdx,yIdx)] = null;
                }
            }
        }
    }
    //Fall to the left
    fallDist = 0;
    for(xIdx=0; xIdx<maxX; xIdx++){
        if(board[index(xIdx, maxY - 1)] == null){
            fallDist += 1;
        }else{
            if(fallDist > 0){
                for(yIdx=0; yIdx<maxY; yIdx++){
                    obj = board[index(xIdx,yIdx)];
                    if(obj == null)
                        continue;
                    obj.targetX -= fallDist * tileSize;
                    board[index(xIdx-fallDist,yIdx)] = obj;
                    board[index(xIdx,yIdx)] = null;
                }
            }
        }
    }
}

function victoryCheck()
{
    //awards bonuses for no tiles left
    deservesBonus = true;
    for(xIdx=maxX-1; xIdx>=0; xIdx--)
        if(board[index(xIdx, maxY - 1)] != null)
            deservesBonus = false;
    if(deservesBonus)
        gameCanvas.score += 500;
    //Checks for game over
    if(deservesBonus || !(floodMoveCheck(0,maxY-1, -1))){
        dialog.show("Game Over. Your score is " + gameCanvas.score);
        timer = new Date() - timer;
        if(scoresURL != "")
            scoreName.show("Please enter your name:                ");
    }
}

//only floods up and right, to see if it can find adjacent same-typed tiles
function floodMoveCheck(xIdx, yIdx, type)
{
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return false;
    if(board[index(xIdx, yIdx)] == null)
        return false;
    myType = board[index(xIdx, yIdx)].type;
    if(type == myType)
        return true;
    return floodMoveCheck(xIdx + 1, yIdx, myType) ||
           floodMoveCheck(xIdx, yIdx - 1, board[index(xIdx,yIdx)].type);
}

//If the component isn't ready, then the signal doesn't include the game x,y
//So we store any x,y sent that we couldn't create at the time, and use those
//if we are triggered by the signal.
var waitStack = new Array(maxIndex);
var waitTop = -1;

function finishCreatingBlock(xIdx,yIdx){
    if(component.isReady){
        if(xIdx == undefined){
            //Called without arguments, create a previously stored (xIdx,yIdx)
            if(waitTop == -1)
                return;//Don't have a previously stored (xIdx,yIdx)
            xIdx = waitStack[waitTop] % maxX;
            yIdx = Math.floor(waitStack[waitTop] / maxX);
            waitTop -= 1;
        }
        dynamicObject = component.createObject();
        if(dynamicObject == null){
            print("error creating block");
            print(component.errorsString());
            return false;
        }
        dynamicObject.type = Math.floor(Math.random() * 3);
        dynamicObject.parent = gameCanvas;
        dynamicObject.x = xIdx*tileSize;
        dynamicObject.targetX = xIdx*tileSize;
        dynamicObject.targetY = yIdx*tileSize;
        dynamicObject.width = tileSize;
        dynamicObject.height = tileSize;
        dynamicObject.spawned = true;
        board[index(xIdx,yIdx)] = dynamicObject;
        return true;
    }else if(component.isError){
        print("error creating block");
        print(component.errorsString());
    }else{
        //It isn't ready, but we'll be called again when it is.
        //So store the requested (xIdx,yIdx) for later use
        waitTop += 1;
        waitStack[waitTop] = index(xIdx,yIdx);
    }
    return false;
}

function startCreatingBlock(xIdx,yIdx){
    if(component!=null){
        finishCreatingBlock(xIdx,yIdx);
        return;
    }

    component = createComponent(tileSrc);
    if(finishCreatingBlock(xIdx,yIdx))
        return;
    component.statusChanged.connect(finishCreatingBlock());
    return;
}

function tweetHighScore(twitterName, twitterPass) {
    if(twitterName == '' || twitterPass == '')
        return false;//Can't login like that

    var scoreStr = "I just played the QML SameGame, and got " + gameCanvas.score + " points on a "
            + maxX + "x" + maxY + " grid. It took me " + timeStr(timer) + ".";
    var postData = "status=" + scoreStr;
    var postman = new XMLHttpRequest();
    postman.open("POST", "http://twitter.com/statuses/update.xml", true, twitterName,  twitterPass);
    postman.onreadystatechange = function() {
        if (postman.readyState == postman.DONE) {
            dialog.show("Your score has been tweeted for you.");
        }
    }
    postman.send(postData);
}

function sendHighScore(name) {
    var postman = new XMLHttpRequest()
    var postData = "name="+name+"&score="+gameCanvas.score
        +"&gridSize="+maxX+"x"+maxY +"&time="+Math.floor(timer/1000);
    postman.open("POST", scoresURL, true);
    postman.onreadystatechange = function() {
        if (postman.readyState == postman.DONE) {
            dialog.show("Your score has been uploaded.");
        }
    }
    postman.send(postData);
}
<commit_msg>Don't need to tweet high scores too<commit_after>/* This script file handles the game logic */
//Note that X/Y referred to here are in game coordinates
var maxX = 10;//Nums are for tileSize 40
var maxY = 15;
var tileSize = 40;
var maxIndex = maxX*maxY;
var board = new Array(maxIndex);
var tileSrc = "content/BoomBlock.qml";
var scoresURL = "http://qtfx-nokia.trolltech.com.au/samegame/scores.php";
var timer;
var component;

//Index function used instead of a 2D array
function index(xIdx,yIdx) {
    return xIdx + (yIdx * maxX);
}

function timeStr(msecs) {
    var secs = Math.floor(msecs/1000);
    var m = Math.floor(secs/60);
    var ret = "" + m + "m " + (secs%60) + "s";
    return ret;
}

function initBoard()
{
    for(i = 0; i<maxIndex; i++){
        //Delete old blocks
        if(board[i] != null)
            board[i].destroy();
    }

    maxX = Math.floor(gameCanvas.width/tileSize);
    maxY = Math.floor(gameCanvas.height/tileSize);
    maxIndex = maxY*maxX;

    //Initialize Board
    board = new Array(maxIndex);
    gameCanvas.score = 0;
    for(xIdx=0; xIdx<maxX; xIdx++){
        for(yIdx=0; yIdx<maxY; yIdx++){
            board[index(xIdx,yIdx)] = null;
            startCreatingBlock(xIdx,yIdx);
        }
    }
    timer = new Date();
}

var fillFound;//Set after a floodFill call to the number of tiles found
var floodBoard;//Set to 1 if the floodFill reaches off that node
//NOTE: Be careful with vars named x,y, as the calling object's x,y are still in scope
function handleClick(x,y)
{
    xIdx = Math.floor(x/tileSize);
    yIdx = Math.floor(y/tileSize);
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return;
    if(board[index(xIdx, yIdx)] == null)
        return;
    //If it's a valid tile, remove it and all connected (does nothing if it's not connected)
    floodFill(xIdx,yIdx, -1);
    if(fillFound <= 0)
        return;
    gameCanvas.score += (fillFound - 1) * (fillFound - 1);
    shuffleDown();
    victoryCheck();
}

function floodFill(xIdx,yIdx,type)
{
    if(board[index(xIdx, yIdx)] == null)
        return;
    var first = false;
    if(type == -1){
        first = true;
        type = board[index(xIdx,yIdx)].type;

        //Flood fill initialization
        fillFound = 0;
        floodBoard = new Array(maxIndex);
    }
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return;
    if(floodBoard[index(xIdx, yIdx)] == 1 || (!first && type != board[index(xIdx,yIdx)].type))
        return;
    floodBoard[index(xIdx, yIdx)] = 1;
    floodFill(xIdx+1,yIdx,type);
    floodFill(xIdx-1,yIdx,type);
    floodFill(xIdx,yIdx+1,type);
    floodFill(xIdx,yIdx-1,type);
    if(first==true && fillFound == 0)
        return;//Can't remove single tiles
    board[index(xIdx,yIdx)].dying = true;
    board[index(xIdx,yIdx)] = null;
    fillFound += 1;
}

function shuffleDown()
{
    //Fall down
    for(xIdx=0; xIdx<maxX; xIdx++){
        fallDist = 0;
        for(yIdx=maxY-1; yIdx>=0; yIdx--){
            if(board[index(xIdx,yIdx)] == null){
                fallDist += 1;
            }else{
                if(fallDist > 0){
                    obj = board[index(xIdx,yIdx)];
                    obj.targetY += fallDist * tileSize;
                    board[index(xIdx,yIdx+fallDist)] = obj;
                    board[index(xIdx,yIdx)] = null;
                }
            }
        }
    }
    //Fall to the left
    fallDist = 0;
    for(xIdx=0; xIdx<maxX; xIdx++){
        if(board[index(xIdx, maxY - 1)] == null){
            fallDist += 1;
        }else{
            if(fallDist > 0){
                for(yIdx=0; yIdx<maxY; yIdx++){
                    obj = board[index(xIdx,yIdx)];
                    if(obj == null)
                        continue;
                    obj.targetX -= fallDist * tileSize;
                    board[index(xIdx-fallDist,yIdx)] = obj;
                    board[index(xIdx,yIdx)] = null;
                }
            }
        }
    }
}

function victoryCheck()
{
    //awards bonuses for no tiles left
    deservesBonus = true;
    for(xIdx=maxX-1; xIdx>=0; xIdx--)
        if(board[index(xIdx, maxY - 1)] != null)
            deservesBonus = false;
    if(deservesBonus)
        gameCanvas.score += 500;
    //Checks for game over
    if(deservesBonus || !(floodMoveCheck(0,maxY-1, -1))){
        dialog.show("Game Over. Your score is " + gameCanvas.score);
        timer = new Date() - timer;
        if(scoresURL != "")
            scoreName.show("Please enter your name:                ");
    }
}

//only floods up and right, to see if it can find adjacent same-typed tiles
function floodMoveCheck(xIdx, yIdx, type)
{
    if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0)
        return false;
    if(board[index(xIdx, yIdx)] == null)
        return false;
    myType = board[index(xIdx, yIdx)].type;
    if(type == myType)
        return true;
    return floodMoveCheck(xIdx + 1, yIdx, myType) ||
           floodMoveCheck(xIdx, yIdx - 1, board[index(xIdx,yIdx)].type);
}

//If the component isn't ready, then the signal doesn't include the game x,y
//So we store any x,y sent that we couldn't create at the time, and use those
//if we are triggered by the signal.
var waitStack = new Array(maxIndex);
var waitTop = -1;

function finishCreatingBlock(xIdx,yIdx){
    if(component.isReady){
        if(xIdx == undefined){
            //Called without arguments, create a previously stored (xIdx,yIdx)
            if(waitTop == -1)
                return;//Don't have a previously stored (xIdx,yIdx)
            xIdx = waitStack[waitTop] % maxX;
            yIdx = Math.floor(waitStack[waitTop] / maxX);
            waitTop -= 1;
        }
        dynamicObject = component.createObject();
        if(dynamicObject == null){
            print("error creating block");
            print(component.errorsString());
            return false;
        }
        dynamicObject.type = Math.floor(Math.random() * 3);
        dynamicObject.parent = gameCanvas;
        dynamicObject.x = xIdx*tileSize;
        dynamicObject.targetX = xIdx*tileSize;
        dynamicObject.targetY = yIdx*tileSize;
        dynamicObject.width = tileSize;
        dynamicObject.height = tileSize;
        dynamicObject.spawned = true;
        board[index(xIdx,yIdx)] = dynamicObject;
        return true;
    }else if(component.isError){
        print("error creating block");
        print(component.errorsString());
    }else{
        //It isn't ready, but we'll be called again when it is.
        //So store the requested (xIdx,yIdx) for later use
        waitTop += 1;
        waitStack[waitTop] = index(xIdx,yIdx);
    }
    return false;
}

function startCreatingBlock(xIdx,yIdx){
    if(component!=null){
        finishCreatingBlock(xIdx,yIdx);
        return;
    }

    component = createComponent(tileSrc);
    if(finishCreatingBlock(xIdx,yIdx))
        return;
    component.statusChanged.connect(finishCreatingBlock());
    return;
}

function sendHighScore(name) {
    var postman = new XMLHttpRequest()
    var postData = "name="+name+"&score="+gameCanvas.score
        +"&gridSize="+maxX+"x"+maxY +"&time="+Math.floor(timer/1000);
    postman.open("POST", scoresURL, true);
    postman.onreadystatechange = function() {
        if (postman.readyState == postman.DONE) {
            dialog.show("Your score has been uploaded.");
        }
    }
    postman.send(postData);
}
<|endoftext|>


<commit_before>//Use this file to implement Part One of your project

// console.log("test")

var animal = {}

animal.username = "Daffy";

// console.log(animal['username']);

animal["tagline"] = "Ducks Rule!";

var empty = [];
animal.noises = empty;

console.log(animal);

var i = 0
for(var key in animal){
	i++;
	console.log(i);
	// console.log(animal[key]);
	if (key === "username")
		console.log("Hi, I my name is " + animal[key]);
	else if (key === "tagline")
		console.log(animal[key]);
};

// part 2 Array exercise===========================

var noiseArray = [];

noiseArray.unshift("quack");
noiseArray.push("Woof")
noiseArray[noiseArray.length] = ("neow")

// console.log(noiseArray.length);
// console.log(noiseArray[2]);

animal.noises = noiseArray;
// console.log(animal);

var quackers = { username: 'DaffyDuck', tagline: 'Yippeee!', noises: ['quack', 'honk', 'sneeze', 'growl'] }
var squirrel = { username: 'Bob', tagline: 'Nuts for nuts!', noises: ['chirp', 'screech'] }
var cow = { username: 'Milkmaid', tagline: 'Dairy for Life', noises: ['moo', 'moo moo', 'moooooo'] }

animals = [];

animals.push(animal, quackers, squirrel, cow);

console.log(animals);
console.log(animals.length);<commit_msg>quick function test for part 1 of exercise<commit_after>//Use this file to implement Part One of your project

// console.log("test")

var animal = {}

animal.username = "Daffy";

// console.log(animal['username']);

animal["tagline"] = "Ducks Rule!";

var empty = [];
animal.noises = empty;

console.log(animal);

var i = 0
for(var key in animal){
	i++;
	console.log(i);
	// console.log(animal[key]);
	if (key === "username")
		console.log("Hi, I my name is " + animal[key]);
	else if (key === "tagline")
		console.log(animal[key]);
};

// part 2 Array exercise===========================

var noiseArray = [];

noiseArray.unshift("quack");
noiseArray.push("Woof")
noiseArray[noiseArray.length] = ("neow")

// console.log(noiseArray.length);
// console.log(noiseArray[2]);

animal.noises = noiseArray;
// console.log(animal);

var quackers = { username: 'DaffyDuck', tagline: 'Yippeee!', noises: ['quack', 'honk', 'sneeze', 'growl'] }
var squirrel = { username: 'Bob', tagline: 'Nuts for nuts!', noises: ['chirp', 'screech'] }
var cow = { username: 'Milkmaid', tagline: 'Dairy for Life', noises: ['moo', 'moo moo', 'moooooo'] }

animals = [];

animals.push(animal, quackers, squirrel, cow);

console.log("Part 2- Arrays ===================================")
console.log(animals);
console.log(animals.length);

// part 3 Function exercise=====================================

var AnimalTestUser = function(username){
	return username;
}

console.log("Part 2- Arrays ===================================")
console.log(AnimalTestUser("Bob"));

<|endoftext|>


<commit_before>'use strict';

function percent(value, max){
    return core_number_format({
      'number': core_round({
        'number': (value / max) * 100,
      }),
    }) + '%';
}

function play(selected){
    core_storage_save();

    // Check how many games player wants to play.
    if(core_storage_data['repeat'] < 1
      || Number.isNaN(core_storage_data['repeat'])){
        return;
    }

    // Keep track of results.
    let opponent_plays = [
      0,
      0,
      0,
    ];
    let results = [
      0,
      0,
      0,
    ];
    total += core_storage_data['repeat'];

    // Loop through the games.
    let loop_counter = core_storage_data['repeat'] - 1;
    do{
        // Result is a loss by default.
        let result = 0;

        // Generate a random number (0, 1, or 2).
        let opponent_choice_int = core_random_integer({
          'max': 3,
        });
        opponent_choice = [
          'rock',
          'paper',
          'scissors',
        ][opponent_choice_int];
        opponent_plays[opponent_choice_int] += 1;

        // Check for ties.
        if(selected === opponent_choice){
            result = 2;

        // Check for wins.
        }else if((selected === 'rock' && opponent_choice === 'scissors')
          || (selected === 'paper' && opponent_choice === 'rock')
          || (selected === 'scissors' && opponent_choice === 'paper')){
            result = 1;
        }

        // Update loss/tie/win values and store them in a temporary array.
        results[result] += 1;
    }while(loop_counter--);

    losses += results[0];
    ties += results[2];
    wins += results[1];

    // Create result strings.
    let paper = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[1],
    }) + ' papers (';
    let rock = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[0],
    }) + ' rocks (';
    let scissors = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[2],
    }) + ' scissors (';

    if(selected === 'rock'){
        paper += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        rock += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        scissors += 'wins) ' + percent(results[1], core_storage_data['repeat']);

    }else if(selected === 'paper'){
        paper += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        rock += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        scissors += 'losses) ' + percent(results[0], core_storage_data['repeat']);

    }else{
        paper += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        rock += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        scissors += 'ties) ' + percent(results[2], core_storage_data['repeat']);
    }

    // Display game information.
    document.getElementById('results').innerHTML = 'You played '
      + selected
      + ' ' + core_number_format({
        'decimals-min': 0,
        'number': core_storage_data['repeat'],
      }) + ' times.
'
      + 'Your opponent played:
'
      + rock + '
'
      + paper + '
'
      + scissors + '
'
      + core_number_format({
        'decimals-min': 0,
        'number': total,
      }) + ' total games played
'
      + core_number_format({
        'decimals-min': 0,
        'number': losses,
      }) + ' losses (' + percent(losses, total) + ')
'
      + core_number_format({
        'decimals-min': 0,
        'number': ties,
      }) + ' ties (' + percent(ties, total) + ')
'
      + core_number_format({
        'decimals-min': 0,
        'number': wins,
      }) + ' wins (' + percent(wins, total) + ')';
}
<commit_msg>replaced some let with const<commit_after>'use strict';

function percent(value, max){
    return core_number_format({
      'number': core_round({
        'number': (value / max) * 100,
      }),
    }) + '%';
}

function play(selected){
    core_storage_save();

    // Check how many games player wants to play.
    if(core_storage_data['repeat'] < 1
      || Number.isNaN(core_storage_data['repeat'])){
        return;
    }

    // Keep track of results.
    const opponent_plays = [
      0,
      0,
      0,
    ];
    const results = [
      0,
      0,
      0,
    ];
    total += core_storage_data['repeat'];

    // Loop through the games.
    let loop_counter = core_storage_data['repeat'] - 1;
    do{
        // Result is a loss by default.
        let result = 0;

        // Generate a random number (0, 1, or 2).
        const opponent_choice_int = core_random_integer({
          'max': 3,
        });
        opponent_choice = [
          'rock',
          'paper',
          'scissors',
        ][opponent_choice_int];
        opponent_plays[opponent_choice_int] += 1;

        // Check for ties.
        if(selected === opponent_choice){
            result = 2;

        // Check for wins.
        }else if((selected === 'rock' && opponent_choice === 'scissors')
          || (selected === 'paper' && opponent_choice === 'rock')
          || (selected === 'scissors' && opponent_choice === 'paper')){
            result = 1;
        }

        // Update loss/tie/win values and store them in a temporary array.
        results[result] += 1;
    }while(loop_counter--);

    losses += results[0];
    ties += results[2];
    wins += results[1];

    // Create result strings.
    let paper = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[1],
    }) + ' papers (';
    let rock = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[0],
    }) + ' rocks (';
    let scissors = core_number_format({
      'decimals-min': 0,
      'number': opponent_plays[2],
    }) + ' scissors (';

    if(selected === 'rock'){
        paper += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        rock += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        scissors += 'wins) ' + percent(results[1], core_storage_data['repeat']);

    }else if(selected === 'paper'){
        paper += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        rock += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        scissors += 'losses) ' + percent(results[0], core_storage_data['repeat']);

    }else{
        paper += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        rock += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        scissors += 'ties) ' + percent(results[2], core_storage_data['repeat']);
    }

    // Display game information.
    document.getElementById('results').innerHTML = 'You played '
      + selected
      + ' ' + core_number_format({
        'decimals-min': 0,
        'number': core_storage_data['repeat'],
      }) + ' times.
'
      + 'Your opponent played:
'
      + rock + '
'
      + paper + '
'
      + scissors + '
'
      + core_number_format({
        'decimals-min': 0,
        'number': total,
      }) + ' total games played
'
      + core_number_format({
        'decimals-min': 0,
        'number': losses,
      }) + ' losses (' + percent(losses, total) + ')
'
      + core_number_format({
        'decimals-min': 0,
        'number': ties,
      }) + ' ties (' + percent(ties, total) + ')
'
      + core_number_format({
        'decimals-min': 0,
        'number': wins,
      }) + ' wins (' + percent(wins, total) + ')';
}
<|endoftext|>


<commit_before>'use strict';

function checkAll(){
    let checkboxes = document.getElementsByTagName('input');
    for(let checkbox in checkboxes){
        if(checkboxes[checkbox].type === 'checkbox'){
            checkboxes[checkbox].checked = true;
        }
    }
}

function check_checkbox(id){
    if(!document.getElementById(id)){
        return;
    }

    let element = document.getElementById('checkbox-' + id);
    element.checked = !element.checked;
}

function clearAll(){
    if(!window.confirm('window.localStorage.clear()?')){
        return;
    }

    window.localStorage.clear();
    refresh();
}

function refresh(){
    let output = '';

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        output += '
'
          + key
          + '
<input onclick="removeItem(\'' + key + '\')" type=button value=X><input disabled id="checkbox-'
          + key
          + '" type=checkbox><input onclick="updateItem(\'' + key + '\')" type=button value=Save><textarea id="textarea-' + key + '">'
          + window.localStorage.getItem(key)
          + '</textarea>';
    }

    document.getElementById('result').innerHTML = output;
}

function removeAll(){
    if(!window.confirm('removeAll()?')){
        return;
    }

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        window.localStorage.removeItem(key);
    }

    refresh();
}

function removeChecked(){
    if(!window.confirm('removeChecked()?')){
        return;
    }

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        if(document.getElementById('checkbox-' + key).checked){
            window.localStorage.removeItem(key);
        }
    }

    refresh();
}

function removeItem(key){
    if(!window.confirm('Remove ' + key + '?')){
        return;
    }

    window.localStorage.removeItem(key);
    document.getElementById(key).remove();
}

function updateItem(key){
    if(!window.confirm('Save ' + key + '?')){
        return;
    }

    window.localStorage.setItem(
      key,
      document.getElementById('textarea-' + key).value
    );
    console.log(document.getElementById('textarea-' + key).value);
}
<commit_msg>made keys link to parent repository<commit_after>'use strict';

function checkAll(){
    let checkboxes = document.getElementsByTagName('input');
    for(let checkbox in checkboxes){
        if(checkboxes[checkbox].type === 'checkbox'){
            checkboxes[checkbox].checked = true;
        }
    }
}

function check_checkbox(id){
    if(!document.getElementById(id)){
        return;
    }

    let element = document.getElementById('checkbox-' + id);
    element.checked = !element.checked;
}

function clearAll(){
    if(!window.confirm('window.localStorage.clear()?')){
        return;
    }

    window.localStorage.clear();
    refresh();
}

function refresh(){
    let output = '';

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        let repository = key.slice(0, key.indexOf('-'));

        output += '
'
          + '' + key + ''
          + '
<input onclick="removeItem(\'' + key + '\')" type=button value=X><input disabled id="checkbox-'
          + key
          + '" type=checkbox><input onclick="updateItem(\'' + key + '\')" type=button value=Save><textarea id="textarea-' + key + '">'
          + window.localStorage.getItem(key)
          + '</textarea>';
    }

    document.getElementById('result').innerHTML = output;
}

function removeAll(){
    if(!window.confirm('removeAll()?')){
        return;
    }

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        window.localStorage.removeItem(key);
    }

    refresh();
}

function removeChecked(){
    if(!window.confirm('removeChecked()?')){
        return;
    }

    for(let key in window.localStorage){
        if(!window.localStorage.hasOwnProperty(key)){
            continue;
        }

        if(document.getElementById('checkbox-' + key).checked){
            window.localStorage.removeItem(key);
        }
    }

    refresh();
}

function removeItem(key){
    if(!window.confirm('Remove ' + key + '?')){
        return;
    }

    window.localStorage.removeItem(key);
    document.getElementById(key).remove();
}

function updateItem(key){
    if(!window.confirm('Save ' + key + '?')){
        return;
    }

    window.localStorage.setItem(
      key,
      document.getElementById('textarea-' + key).value
    );
    console.log(document.getElementById('textarea-' + key).value);
}
<|endoftext|>


<commit_before>/*jslint on: true, eqeqeq: true */
/*
	TODOs:

	Fo sho:
		- The buffer is actually loading all the images at the same time, only load the next one on page.onload
		- Show a progress bar when buffering
		- use document.body.offsetWidth where present? (instead of window.innerWidth, the former excludes the width of scrollbars)
		- scroll two pages at a time in double page mode
		- manga mode
		- page controls
		- thumbnail browser
		- chrome frame

	Nice 2 have:
		- remember position (use localStorage)
		- maybe use local storage for the pages array too? might be easier to implement manga mode with that
		- offline mode
		- page turn animation

*/

/**
 * Merge two arrays. Any properties in b will replace the same properties in
 * a. New properties from b will be added to a.
 *
 * @param a {Object}
 * @param b {Object}
 */
function merge(a, b) {

	var prop;

	if (typeof b === "undefined") { b = {}; }

	for (prop in a) {
		if (a.hasOwnProperty(prop)) {
			if (prop in b) { continue; }
			b[prop] = a[prop];
		}
	}

	return b;
}

function ComicBook(id, srcs, opts) {

	this.id = id;		// canvas element id
	this.srcs = srcs;	// array of image srcs for pages

	var defaults = {
		displayMode: "double",	// single / double
		zoomMode: "fitWidth"	// manual / fitWidth
	};

	var options = merge(defaults, opts); // options array for internal use

	var pages = [];		// array of preloaded Image objects
	var canvas;			// the HTML5 canvas object
	var context;		// the 2d drawing context

	var buffer = 4;		// image preload buffer level
	var pointer = 0;	// the current page
	var loaded = 0;		// the amount of images that have been loaded so far

	var scale = 1;		// page zoom scale, 1 = 100%

	/**
	 * Figure out the cursor position relative to the canvas.
	 *
	 * Thanks to: Mark Pilgrim & http://diveintohtml5.org/canvas.html
	 */
	function getCursorPosition(e) {

		var x; // horizontal cursor position

		// check if page relative positions exist, if not figure them out
		if (e.pageX) {
			x = e.pageX;
		} else {
			x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		}

		// make the position relative to the canvas
		x -= canvas.offsetLeft;

		// check if the user clicked on the left or right side
		return (x <= canvas.width / 2) ? 'left' : 'right';
	}

	/*
	 * @param {String} id The canvas ID to draw the comic on.
	 * @param {Object} srcs An array of all the comic page srcs, in order
	 * @see #preload
	 */
	ComicBook.prototype.draw = function () {

		// setup canvas
		canvas = document.getElementById(this.id);
		context = canvas.getContext("2d");

		// preload images if needed
		if (pages.length !== this.srcs.length) { this.preload(this.srcs); }
		else { this.drawPage(); }

		// add page controls
		canvas.addEventListener("click", ComicBook.prototype.navigation, false);
	};

	/*
	 * Zoom the canvas
	 *
	 * @param new_scale {Number} Scale the canvas to this ratio
	 */
	ComicBook.prototype.zoom = function (new_scale) {
		options.zoomMode = "manual";
		scale = new_scale;
		if (typeof pages[pointer] === "object") { this.drawPage(); }
	};

	/**
	 * Preload all images, draw the page only after a given number have been loaded.
	 *
	 * @param srcs {Object} srcs
	 * @see #drawPage
	 */
	ComicBook.prototype.preload = function (srcs) {

		if (srcs.length < buffer) { buffer = srcs.length; } // don't get stuck if the buffer level is higher than the number of pages

		function preload(srcs) {

		}
		/*
		srcs.forEach(function(src, i) {

			var page = new Image();

			page.src = src;

			page.onload = function () {
				pages[i] = this; loaded++;
				if (loaded === buffer) { ComicBook.prototype.drawPage(); }
			};
		});
		*/
	};

	/**
	 * Draw the current page in the canvas
	 *
	 * TODO: break this down into drawSinglePage() & drawDoublePage()
	 * TODO: if the current browser doesn't have canvas support, use img tags
	 */
	ComicBook.prototype.drawPage = function () {

		var zoom_scale;
		var offsetW = 0, offsetH = 0;

		var page = pages[pointer];
		var page2 = pages[pointer + 1];

		if (typeof page !== "object") { throw "invalid page type '"+ typeof page +"'"; }

		var width = page.width;

		if (options.displayMode === "double") {

			// for double page spreads, factor in the width of both pages
			if (typeof page2 === "object") { width += page2.width; }

			// if this is the last page and there is no page2, still keep the canvas wide
			else { width += width; }
		}

		// update the page scale if a non manual mode has been chosen
		switch(options.zoomMode) {

			case "manual":
				zoom_scale = (options.displayMode === "double") ? scale * 2 : scale;
				break;

			case "fitWidth":
				zoom_scale =  (window.innerWidth > width) ? ((window.innerWidth - width) / window.innerWidth) + 1 // scale up if the window is wider than the page
					  : window.innerWidth / width; // scale down if the window is narrower than the page
				break;

			default:throw "invalid zoomMode";
		}

		var canvas_width  = page.width * zoom_scale;
		var canvas_height = page.height * zoom_scale;

		var page_width = (options.zoomMode === "manual") ? page.width * scale : canvas_width;
		var page_height = (options.zoomMode === "manual") ? page.height * scale : canvas_height;

		canvas_height = page_height;

		// make sure the canvas is always at least full screen, even if the page is more narrow than the screen
		canvas.width = (canvas_width < window.innerWidth) ? window.innerWidth : canvas_width;
		canvas.height = (canvas_height < window.innerHeight) ? window.innerHeight : canvas_height;

		// work out a horizonal position that will keep the pages always centred
		if (canvas_width < window.innerWidth && options.zoomMode === "manual") {
			offsetW = (window.innerWidth - page_width) / 2;
			if (options.displayMode === "double") { offsetW = offsetW - page_width / 2; }
		}

		// work out a vertical position that will keep the pages always centred
		if (canvas_height < window.innerHeight && options.zoomMode === "manual") {
			offsetH = (window.innerHeight - page_height) / 2;
		}

		// draw the page(s)
		context.drawImage(page, offsetW, offsetH, page_width, page_height);
		if (options.displayMode === "double" && typeof page2 === "object") { context.drawImage(page2, page_width + offsetW, offsetH, page_width, page_height); }

	};

	/**
	 * Increment the counter and draw the page in the canvas
	 *
	 * @see #drawPage
	 */
	ComicBook.prototype.drawNextPage = function () {
		if (pointer + 1 < pages.length) {
			pointer++;
			this.drawPage();
		}
	};

	/**
	 * Decrement the counter and draw the page in the canvas
	 *
	 * @see #drawPage
	 */
	ComicBook.prototype.drawPrevPage = function () {
		if (pointer > 0) {
			pointer--;
			this.drawPage();
		}
	};

	ComicBook.prototype.navigation = function (e) {

		if (e.type === "click") {
			switch (getCursorPosition(e)) {
				case "left": ComicBook.prototype.drawPrevPage(); break;
				case "right": ComicBook.prototype.drawNextPage(); break;
			}
		}
	};
}

var book;

window.onload = function() {

	var pages = [
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/00.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/01.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/02.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/03.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/04.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/05.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/06.jpg"
	];

	var options = {
		displayMode: "double",
		zoomMode: "fitWidth"
	};

	book = new ComicBook("comic", pages, options);
	book.draw();
};

window.onresize = function() {
	book.draw();
};
<commit_msg>starting a better preload method<commit_after>/*jslint on: true, eqeqeq: true */
/*
	TODOs:

	Fo sho:
		- The buffer is actually loading all the images at the same time, only load the next one on page.onload
		- Show a progress bar when buffering
		- use document.body.offsetWidth where present? (instead of window.innerWidth, the former excludes the width of scrollbars)
		- scroll two pages at a time in double page mode
		- manga mode
		- page controls
		- thumbnail browser
		- chrome frame

	Nice 2 have:
		- remember position (use localStorage)
		- maybe use local storage for the pages array too? might be easier to implement manga mode with that
		- offline mode
		- page turn animation

*/

/**
 * Merge two arrays. Any properties in b will replace the same properties in
 * a. New properties from b will be added to a.
 *
 * @param a {Object}
 * @param b {Object}
 */
function merge(a, b) {

	var prop;

	if (typeof b === "undefined") { b = {}; }

	for (prop in a) {
		if (a.hasOwnProperty(prop)) {
			if (prop in b) { continue; }
			b[prop] = a[prop];
		}
	}

	return b;
}

function ComicBook(id, srcs, opts) {

	this.id = id;		// canvas element id
	this.srcs = srcs;	// array of image srcs for pages

	var defaults = {
		displayMode: "double",	// single / double
		zoomMode: "fitWidth"	// manual / fitWidth
	};

	var options = merge(defaults, opts); // options array for internal use

	var pages = [];		// array of preloaded Image objects
	var canvas;			// the HTML5 canvas object
	var context;		// the 2d drawing context

	var buffer = 4;		// image preload buffer level
	var pointer = 0;	// the current page
	var loaded = 0;		// the amount of images that have been loaded so far

	var scale = 1;		// page zoom scale, 1 = 100%

	/**
	 * Figure out the cursor position relative to the canvas.
	 *
	 * Thanks to: Mark Pilgrim & http://diveintohtml5.org/canvas.html
	 */
	function getCursorPosition(e) {

		var x; // horizontal cursor position

		// check if page relative positions exist, if not figure them out
		if (e.pageX) {
			x = e.pageX;
		} else {
			x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		}

		// make the position relative to the canvas
		x -= canvas.offsetLeft;

		// check if the user clicked on the left or right side
		return (x <= canvas.width / 2) ? 'left' : 'right';
	}

	/*
	 * @param {String} id The canvas ID to draw the comic on.
	 * @param {Object} srcs An array of all the comic page srcs, in order
	 * @see #preload
	 */
	ComicBook.prototype.draw = function () {

		// setup canvas
		canvas = document.getElementById(this.id);
		context = canvas.getContext("2d");

		// preload images if needed
		if (pages.length !== this.srcs.length) { this.preload(this.srcs); }
		else { this.drawPage(); }

		// add page controls
		canvas.addEventListener("click", ComicBook.prototype.navigation, false);
	};

	/*
	 * Zoom the canvas
	 *
	 * @param new_scale {Number} Scale the canvas to this ratio
	 */
	ComicBook.prototype.zoom = function (new_scale) {
		options.zoomMode = "manual";
		scale = new_scale;
		if (typeof pages[pointer] === "object") { this.drawPage(); }
	};

	/**
	 * Preload all images, draw the page only after a given number have been loaded.
	 *
	 * @param srcs {Object} srcs
	 * @see #drawPage
	 */
	ComicBook.prototype.preload = function (srcs) {

		if (srcs.length < buffer) { buffer = srcs.length; } // don't get stuck if the buffer level is higher than the number of pages

		var i = 0; // the current page counter for this method

		// I am using recursion instead of a forEach loop so that the next image is
		// only loaded when the previous one has completely finished
		function preload(i) {

			var page = new Image();

			console.info("starting to load: " + srcs[i]);

			page.src = srcs[i];

			page.onload = function () {

				console.info("loaded: " + srcs[i]);

				pages[i] = this;
				loaded += 1;

				// there are still more pages to load, do it
				if (loaded < srcs.length) {
					i += 1;
					preload(i);
				}

				// start rendering the comic when the buffer level has been reached
				if (loaded === buffer + 1) { ComicBook.prototype.drawPage(); }
			};
		}

		if (i === 0) { preload(i); }
	};

	/**
	 * Draw the current page in the canvas
	 *
	 * TODO: break this down into drawSinglePage() & drawDoublePage()
	 * TODO: if the current browser doesn't have canvas support, use img tags
	 */
	ComicBook.prototype.drawPage = function () {

		var zoom_scale;
		var offsetW = 0, offsetH = 0;

		var page = pages[pointer];
		var page2 = pages[pointer + 1];

		if (typeof page !== "object") { throw "invalid page type '"+ typeof page +"'"; }

		var width = page.width;

		if (options.displayMode === "double") {

			// for double page spreads, factor in the width of both pages
			if (typeof page2 === "object") { width += page2.width; }

			// if this is the last page and there is no page2, still keep the canvas wide
			else { width += width; }
		}

		// update the page scale if a non manual mode has been chosen
		switch(options.zoomMode) {

			case "manual":
				zoom_scale = (options.displayMode === "double") ? scale * 2 : scale;
				break;

			case "fitWidth":
				zoom_scale =  (window.innerWidth > width) ? ((window.innerWidth - width) / window.innerWidth) + 1 // scale up if the window is wider than the page
					  : window.innerWidth / width; // scale down if the window is narrower than the page
				break;

			default:throw "invalid zoomMode";
		}

		var canvas_width  = page.width * zoom_scale;
		var canvas_height = page.height * zoom_scale;

		var page_width = (options.zoomMode === "manual") ? page.width * scale : canvas_width;
		var page_height = (options.zoomMode === "manual") ? page.height * scale : canvas_height;

		canvas_height = page_height;

		// make sure the canvas is always at least full screen, even if the page is more narrow than the screen
		canvas.width = (canvas_width < window.innerWidth) ? window.innerWidth : canvas_width;
		canvas.height = (canvas_height < window.innerHeight) ? window.innerHeight : canvas_height;

		// work out a horizonal position that will keep the pages always centred
		if (canvas_width < window.innerWidth && options.zoomMode === "manual") {
			offsetW = (window.innerWidth - page_width) / 2;
			if (options.displayMode === "double") { offsetW = offsetW - page_width / 2; }
		}

		// work out a vertical position that will keep the pages always centred
		if (canvas_height < window.innerHeight && options.zoomMode === "manual") {
			offsetH = (window.innerHeight - page_height) / 2;
		}

		// draw the page(s)
		context.drawImage(page, offsetW, offsetH, page_width, page_height);
		if (options.displayMode === "double" && typeof page2 === "object") { context.drawImage(page2, page_width + offsetW, offsetH, page_width, page_height); }

	};

	/**
	 * Increment the counter and draw the page in the canvas
	 *
	 * @see #drawPage
	 */
	ComicBook.prototype.drawNextPage = function () {
		if (pointer + 1 < pages.length) {
			pointer++;
			this.drawPage();
		}
	};

	/**
	 * Decrement the counter and draw the page in the canvas
	 *
	 * @see #drawPage
	 */
	ComicBook.prototype.drawPrevPage = function () {
		if (pointer > 0) {
			pointer--;
			this.drawPage();
		}
	};

	ComicBook.prototype.navigation = function (e) {

		if (e.type === "click") {
			switch (getCursorPosition(e)) {
				case "left": ComicBook.prototype.drawPrevPage(); break;
				case "right": ComicBook.prototype.drawNextPage(); break;
			}
		}
	};
}

var book;

window.onload = function() {

	var pages = [
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/00.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/01.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/02.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/03.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/04.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/05.jpg",
		"http://dev.justforcomics.com/get/image/?f=comics/extracted/oni_whiteout_melt_1/06.jpg"
	];

	var options = {
		displayMode: "double",
		zoomMode: "fitWidth"
	};

	book = new ComicBook("comic", pages, options);
	book.draw();
};

window.onresize = function() {
	book.draw();
};
<|endoftext|>


<commit_before>'use strict';

function create_obstacle(id, obstacle_x, obstacle_y){
    let obstacle_height = core_random_integer({
      'max': core_storage_data['obstacle-size'],
    }) + 5;
    let obstacle_width = core_random_integer({
      'max': core_storage_data['obstacle-size'],
    }) + 5;

    // Add new obstacle and mirror.
    core_entity_create({
      'id': 'obstacle-a' + id,
      'properties': {
        'height': obstacle_height,
        'width': obstacle_width,
        'x': obstacle_x - obstacle_width / 2,
        'y': obstacle_y - obstacle_height / 2,
      },
      'types': [
        'obstacle',
      ],
    });
    core_entity_create({
      'id': 'obstacle-b' + id,
      'properties': {
        'height': obstacle_height,
        'width': obstacle_width,
        'x': -obstacle_x - obstacle_width / 2,
        'y': -obstacle_y - obstacle_height / 2,
      },
      'types': [
        'obstacle',
      ],
    });
}

function load_data(id){
    canvas_properties['clearColor'] = '#3c3c3c';

    player_controlled = id === 1;

    // Get half of height and width of game area.
    let gamearea_height_half = core_storage_data['gamearea-height'] / 2;
    let gamearea_width_half = core_storage_data['gamearea-width'] / 2;

    // How far particles can go on x axis positive or negative.
    particle_x_limit = gamearea_width_half - 2;

    // Setup player information.
    core_entity_create({
      'id': 'player-0',
      'properties': {
        'color': core_storage_data['color-positive'],
        'goal-y': gamearea_height_half + 10,
        'paddle-y': gamearea_height_half,
      },
      'types': [
        'player',
      ],
    });
    core_entity_create({
      'id': 'player-1',
      'properties': {
        'color': core_storage_data['color-negative'],
        'goal-y': -gamearea_height_half - 30,
        'paddle-y': -gamearea_height_half - 5,
      },
      'types': [
        'player',
      ],
    });

    // Calculate distance between both players.
    gamearea_playerdist = Math.abs(core_entities['player-1']['paddle-y']) + core_entities['player-0']['paddle-y'] + 5;

    // Enforce valid spawners.
    core_storage_data['spawner-count'] = Math.max(
      core_storage_data['spawner-count'],
      1
    );
    core_storage_data['spawner-distance'] = Math.min(
      core_storage_data['spawner-distance'],
      core_storage_data['gamearea-width'] / 2 - 5
    );

    let loop_counter = core_storage_data['spawner-count'] - 1;
    do{
        let spawner_x = core_random_integer({
          'max': gamearea_width_half * 2,
        }) - gamearea_width_half;
        let spawner_y = core_random_integer({
          'max': (gamearea_playerdist - 25) / 4,
        });
        if(Math.abs(spawner_x) < core_storage_data['spawner-distance']){
            spawner_x += core_storage_data['spawner-distance'] * (spawner_x > 0
              ? 1
              : -1);
        }

        // Add new spawner and mirror.
        core_entity_create({
          'id': 'spawner-a' + loop_counter,
          'properties': {
            'x': spawner_x,
            'y': spawner_y,
          },
          'types': [
            'spawner',
          ],
        });
        core_entity_create({
          'id': 'spawner-b' + loop_counter,
          'properties': {
            'x': -spawner_x,
            'y': -spawner_y,
          },
          'types': [
            'spawner',
          ],
        });
    }while(loop_counter--);

    if(core_storage_data['obstacle-count'] > 0){
        let loop_counter = core_storage_data['obstacle-count'] - 1;
        do{
            let obstacle_x = core_random_integer({
              'max': gamearea_width_half * 2,
            }) - gamearea_width_half;
            if(Math.abs(obstacle_x) < core_storage_data['obstacle-distance']){
                obstacle_x += core_storage_data['obstacle-distance'] * (obstacle_x > 0
                  ? 1
                  : -1);
            }

            create_obstacle(
              loop_counter,
              obstacle_x,
              core_random_integer({
                'max': (gamearea_playerdist - 25) / 2,
              })
            );
        }while(loop_counter--);
    }
}
<commit_msg>made spawner-distance set instead of add<commit_after>'use strict';

function create_obstacle(id, obstacle_x, obstacle_y){
    let obstacle_height = core_random_integer({
      'max': core_storage_data['obstacle-size'],
    }) + 5;
    let obstacle_width = core_random_integer({
      'max': core_storage_data['obstacle-size'],
    }) + 5;

    // Add new obstacle and mirror.
    core_entity_create({
      'id': 'obstacle-a' + id,
      'properties': {
        'height': obstacle_height,
        'width': obstacle_width,
        'x': obstacle_x - obstacle_width / 2,
        'y': obstacle_y - obstacle_height / 2,
      },
      'types': [
        'obstacle',
      ],
    });
    core_entity_create({
      'id': 'obstacle-b' + id,
      'properties': {
        'height': obstacle_height,
        'width': obstacle_width,
        'x': -obstacle_x - obstacle_width / 2,
        'y': -obstacle_y - obstacle_height / 2,
      },
      'types': [
        'obstacle',
      ],
    });
}

function load_data(id){
    canvas_properties['clearColor'] = '#3c3c3c';

    player_controlled = id === 1;

    // Get half of height and width of game area.
    let gamearea_height_half = core_storage_data['gamearea-height'] / 2;
    let gamearea_width_half = core_storage_data['gamearea-width'] / 2;

    // How far particles can go on x axis positive or negative.
    particle_x_limit = gamearea_width_half - 2;

    // Setup player information.
    core_entity_create({
      'id': 'player-0',
      'properties': {
        'color': core_storage_data['color-positive'],
        'goal-y': gamearea_height_half + 10,
        'paddle-y': gamearea_height_half,
      },
      'types': [
        'player',
      ],
    });
    core_entity_create({
      'id': 'player-1',
      'properties': {
        'color': core_storage_data['color-negative'],
        'goal-y': -gamearea_height_half - 30,
        'paddle-y': -gamearea_height_half - 5,
      },
      'types': [
        'player',
      ],
    });

    // Calculate distance between both players.
    gamearea_playerdist = Math.abs(core_entities['player-1']['paddle-y']) + core_entities['player-0']['paddle-y'] + 5;

    // Enforce valid spawners.
    core_storage_data['spawner-count'] = Math.max(
      core_storage_data['spawner-count'],
      1
    );
    core_storage_data['spawner-distance'] = Math.min(
      core_storage_data['spawner-distance'],
      core_storage_data['gamearea-width'] / 2 - 5
    );

    let loop_counter = core_storage_data['spawner-count'] - 1;
    do{
        let spawner_x = core_random_integer({
          'max': gamearea_width_half * 2,
        }) - gamearea_width_half;
        let spawner_y = core_random_integer({
          'max': (gamearea_playerdist - 25) / 4,
        });
        if(Math.abs(spawner_x) < core_storage_data['spawner-distance']){
            spawner_x = core_storage_data['spawner-distance'] * (spawner_x > 0
              ? 1
              : -1);
        }

        // Add new spawner and mirror.
        core_entity_create({
          'id': 'spawner-a' + loop_counter,
          'properties': {
            'x': spawner_x,
            'y': spawner_y,
          },
          'types': [
            'spawner',
          ],
        });
        core_entity_create({
          'id': 'spawner-b' + loop_counter,
          'properties': {
            'x': -spawner_x,
            'y': -spawner_y,
          },
          'types': [
            'spawner',
          ],
        });
    }while(loop_counter--);

    if(core_storage_data['obstacle-count'] > 0){
        let loop_counter = core_storage_data['obstacle-count'] - 1;
        do{
            let obstacle_x = core_random_integer({
              'max': gamearea_width_half * 2,
            }) - gamearea_width_half;
            if(Math.abs(obstacle_x) < core_storage_data['obstacle-distance']){
                obstacle_x += core_storage_data['obstacle-distance'] * (obstacle_x > 0
                  ? 1
                  : -1);
            }

            create_obstacle(
              loop_counter,
              obstacle_x,
              core_random_integer({
                'max': (gamearea_playerdist - 25) / 2,
              })
            );
        }while(loop_counter--);
    }
}
<|endoftext|>


<commit_before>/* global $ */
$.jCanvas.defaults.fromCenter = false;

/* .getCanvasImage() don't work on Google Chrome if the page is served from a file URL (file://).
This is a limitation of Google Chrome’s sandboxing architecture, and therefore cannot be fixed */
if (window.location.protocol == 'file:' && window.navigator.vendor == "Google Inc.") {
	$('#offline_warning').show();
	$('select[name=type] option[value=menuhax2015]', "#settings").prop('disabled', true);
	$('select[name=type] option[value=menuhax2016]', "#settings").prop('disabled', true);
}

/* jCanvas has an option for write full strings but don't have a option for control letter spacing.
The font has a letter spacing of 2px, and the generator needs a spacing of 1px.
This function allows to write character by character with only 1px of spacing. */
var write = function(x, y, text, color = 'gray') {
	var letter = text.substr(0,1);

	/* Search for specials characters */
	if (letter == '_') {
		text = text.substr(1);
		letter = text.substr(0,1);
		if (color == 'gray') color = 'white';
		else if (color == 'white') color = 'gray';
	}

	/* Draw 1 character */
	$('#topscreen').drawText({
		fillStyle: color,
		x: x+2, y: y,
		fontSize: 13.5,
		fontFamily: 'PerfectDOSVGA437Win',
		align: 'left',
		text: letter
	});

	/* Remove the character writed from the string, and if itn't empty, continue recursive */
	text = text.substr(1);
	if (text != '')
		write(x+6.75, y, text, color);
}

var writesmaller = function(x, y, text, color = 'gray') {
	var letter = text.substr(0,1);

	/* Search for specials characters */
	if (letter == '_') {
		text = text.substr(1);
		letter = text.substr(0,1);
		if (color == 'gray') color = 'white';
		else if (color == 'white') color = 'gray';
	}

	/* Draw 1 character */
	$('#topscreen').drawText({
		fillStyle: color,
		x: x+2, y: y,
		fontSize: 13,
		fontFamily: 'PerfectDOSVGA437Win',
		align: 'left',
		text: letter
	});

	/* Remove the character writed from the string, and if itn't empty, continue recursive */
	text = text.substr(1);
	if (text != '')
		writesmaller(x+6.5, y, text, color);
}

/* This draw the entire splash screen with any change on the form */
$("#settings input, #settings select").on('change', function() {
	var $topscreen = $('#topscreen');

	var model = $('input[name=model]:checked', "#settings").val();
	var region = $('select[name=region] option:selected', "#settings").val();
	var sd = $('select[name=sd] option:selected', "#settings").val();
	var type = $('select[name=type] option:selected', "#settings").val();

	var line1 = $('select[name=type] option:selected', "#settings").text();
	var line2 = ''; var processor = 0; var use_bootinput = false; var use_auxinput = false;

	if ($('select[name=boottool] option:selected', "#settings").val() == 'custom') {
		$('input[name=boottool]', "#settings").show();
		$('select[name=boottool]', "#settings").hide();
		use_bootinput = true;
	}

	if ($('select[name=secondTool] option:selected', "#settings").val() == 'custom') {
		$('input[name=secondTool]', "#settings").show();
		$('select[name=secondTool]', "#settings").hide();
		use_auxinput = true;
	}

	switch(type) {
		case 'luma2016':
			$topscreen.attr('width', 320);
			line2 = 'Copyright(C) 2016, AuroraWright';
			break;
		case 'luma2017':
			$topscreen.attr('width', 320);
			line2 = 'Copyright(C) 2017, AuroraWright';
			break;
		case 'menuhax2015':
			$topscreen.attr('width', 640);
			line2 = 'Copyright(C) 2015, yellow8';
			break;
		case 'menuhax2016':
			$topscreen.attr('width', 640);
			line2 = 'Copyright(C) 2016, yellow8';
			break;
	}

	$topscreen.clearCanvas().drawRect({
		fillStyle: 'black',
		x: 0, y: 0,
		width: 320,
		height: 240
	}).drawImage({
		source: 'images/symbols.png',
		x: 1, y: 16,
		sWidth: 21,
		sHeight: 29,
		sx: 112, sy: 0
	});

	switch ($('select[name=logoOptions] option:selected', "#settings").val()) {
		case 'energyStar':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 236, y: 16,
				sWidth: 83,
				sHeight: 52,
				sx: 0, sy: 0
			});
			break;
		case 'energyLuma':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 236, y: 16,
				sWidth: 82,
				sHeight: 52,
				sx: 0, sy: 52
			});
			break;
		case 'lumaIcon':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 256, y: 8,
				sWidth: 53,
				sHeight: 52,
				sx: 0, sy: 104
			});
			break;
			case 'nintendoIcon':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 256, y: 5,
				sWidth: 53,
				sHeight: 32,
				sx: 0, sy: 158
			});
			break;
	}

	write(24, 16*1, line1);
	write(24, 16*2, line2);

	switch(model) {
		case '3DS':
			write(0, 16*5, 'Nintendo 3DS CTR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case '3DSXL':
			if (region == 'JPN')
				write(0, 16*5, 'Nintendo 3DS LL SPR-001('+region+')');
			else
				write(0, 16*5, 'Nintendo 3DS XL SPR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case '2DS':
			write(0, 16*5, 'Nintendo 2DS FTR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case 'n3DS':
			write(0, 16*5, 'New Nintendo 3DS KTR-001('+region+')');
			processor = 4; sd += ' microSD'
			break;
		case 'n3DSXL':
			if (region == 'JPN')
				write(0, 16*5, 'New Nintendo 3DS LL RED-001('+region+')');
			else
				write(0, 16*5, 'New Nintendo 3DS XL RED-001('+region+')');
			processor = 4; sd += ' microSD'
			break;
	}

	switch(processor) {
		case 2:
			write(0, 16*7, 'Main Processor       : Dual-core ARM11 MPCore');
			write(0, 16*8, 'Memory Testing       : 131072K OK');
			break;
		case 4:
			write(0, 16*7, 'Main Processor       : Quad-core ARM11 MPCore');
			write(0, 16*8, 'Memory Testing       : 262144K OK');
			break;
	}

	write(0, 16*9,  'Detecting Primary Master ... '+ processor/2 +'G Internal Memory');
	write(0, 16*10, 'Detecting Primary Slave  ... '+ sd +' Card');

	if (!use_bootinput)
		$('input[name=boottool]', "#settings").val($('select[name=boottool] option:selected', "#settings").text());

	if (!use_auxinput)
		$('input[name=secondTool]', "#settings").val($('select[name=secondTool] option:selected', "#settings").text());

	var boot_bool = $('input[name=hold]', "#settings").is(':checked');
	var boot_keys = $('select[name=onboot] option:selected', "#settings").val();
	var boot_tool = $('input[name=boottool]', "#settings").val();
	var boot_text = '_Hold ' + boot_keys + ' '+ $('select[name=firstTime] option:selected').text() +'_ to enter _' + boot_tool + '_.';

	var aux_bool = $('input[name=secondLine]', "#settings").is(':checked');
	var aux_keys = $('select[name=secondButton] option:selected').val();
	var aux_tool = $('input[name=secondTool]').val();
	var aux_text = '_Hold ' + aux_keys + ' '+ $('select[name=secondTime] option:selected').text() +'_ to enter _' + aux_tool + '_.';

	if (boot_bool && !aux_bool)
		writesmaller(0, 16*14, boot_text);
	else if (boot_bool)
		writesmaller(0, 16*13, boot_text);

	if (aux_bool)
		writesmaller(0, 16*14, aux_text);

	if ($topscreen.width() == 800) {
		$topscreen.drawImage({
			source: $topscreen.getCanvasImage(),
			x: 400, y: 0
		});
	}

});

$(document).ready(function() {

	$('canvas').drawImage({
		source: 'images/symbols.png',
		x: 0, y: 0,
		load: function() {
			$("select[name=region]", "#settings").trigger('change');
			if ($('#offline_warning').is(':hidden'))
				$('#downloadPNG, #downloadBIN').removeClass('disabled');
		}
	});

});

$('input[name=boottool]', "#settings").keyup(function() { $("#settings input").trigger('change'); });
$('input[name=auxtool]', "#settings").keyup(function() { $("#settings input").trigger('change'); });

/* Create a PNG downloadable of the canvas */
/* global download */
$('#downloadPNG').click(function() {
	if (!$(this).hasClass('disabled')) {
		var filename = ($('#topscreen').width() == 400) ? 'splash.png' : 'imagedisplay.png';
		var filedata = $('#topscreen').getCanvasImage();
		download(filedata, filename, "image/png");
	}
});

$('#downloadBIN').click(function() {
	if (!$(this).hasClass('disabled')) {
		var filename = ($('#topscreen').width() == 400) ? 'splash.bin' : 'menuhax_imagedisplay.bin';

		var width = $('#topscreen').height();
		var height = $('#topscreen').width();

		var $canvas = $('<canvas/>').css({ position: 'absolute', top: 0, left: -1*width }).appendTo('body');
		$canvas.attr('width', width).attr('height', height);

		$canvas.drawImage({
			source: $('#topscreen').getCanvasImage(),
			x: width/2, y: height/2,
			fromCenter: true,
			rotate: 90
		});

		var canvasdata = $canvas.get(0).getContext('2d').getImageData(0, 0, width, height).data;
		var filedata = '';

		for(var i = 0; i < canvasdata.length; i += 4)
			filedata += String.fromCharCode(canvasdata[i+2], canvasdata[i+1], canvasdata[i]);

		$canvas.remove();
		download('data:application/octet-stream;base64,' + window.btoa(filedata), filename);
	}
});<commit_msg>Fix menuhax and downloads<commit_after>/* global $ */
$.jCanvas.defaults.fromCenter = false;

/* .getCanvasImage() don't work on Google Chrome if the page is served from a file URL (file://).
This is a limitation of Google Chrome’s sandboxing architecture, and therefore cannot be fixed */
if (window.location.protocol == 'file:' && window.navigator.vendor == "Google Inc.") {
	$('#offline_warning').show();
	$('select[name=type] option[value=menuhax2015]', "#settings").prop('disabled', true);
	$('select[name=type] option[value=menuhax2016]', "#settings").prop('disabled', true);
}

/* jCanvas has an option for write full strings but don't have a option for control letter spacing.
The font has a letter spacing of 2px, and the generator needs a spacing of 1px.
This function allows to write character by character with only 1px of spacing. */
var write = function(x, y, text, color = 'gray') {
	var letter = text.substr(0,1);

	/* Search for specials characters */
	if (letter == '_') {
		text = text.substr(1);
		letter = text.substr(0,1);
		if (color == 'gray') color = 'white';
		else if (color == 'white') color = 'gray';
	}

	/* Draw 1 character */
	$('#topscreen').drawText({
		fillStyle: color,
		x: x+2, y: y,
		fontSize: 13.5,
		fontFamily: 'PerfectDOSVGA437Win',
		align: 'left',
		text: letter
	});

	/* Remove the character writed from the string, and if itn't empty, continue recursive */
	text = text.substr(1);
	if (text != '')
		write(x+6.75, y, text, color);
}

var writesmaller = function(x, y, text, color = 'gray') {
	var letter = text.substr(0,1);

	/* Search for specials characters */
	if (letter == '_') {
		text = text.substr(1);
		letter = text.substr(0,1);
		if (color == 'gray') color = 'white';
		else if (color == 'white') color = 'gray';
	}

	/* Draw 1 character */
	$('#topscreen').drawText({
		fillStyle: color,
		x: x+2, y: y,
		fontSize: 13,
		fontFamily: 'PerfectDOSVGA437Win',
		align: 'left',
		text: letter
	});

	/* Remove the character writed from the string, and if itn't empty, continue recursive */
	text = text.substr(1);
	if (text != '')
		writesmaller(x+6.5, y, text, color);
}

/* This draw the entire splash screen with any change on the form */
$("#settings input, #settings select").on('change', function() {
	var $topscreen = $('#topscreen');

	var model = $('input[name=model]:checked', "#settings").val();
	var region = $('select[name=region] option:selected', "#settings").val();
	var sd = $('select[name=sd] option:selected', "#settings").val();
	var type = $('select[name=type] option:selected', "#settings").val();

	var line1 = $('select[name=type] option:selected', "#settings").text();
	var line2 = ''; var processor = 0; var use_bootinput = false; var use_auxinput = false;

	if ($('select[name=boottool] option:selected', "#settings").val() == 'custom') {
		$('input[name=boottool]', "#settings").show();
		$('select[name=boottool]', "#settings").hide();
		use_bootinput = true;
	}

	if ($('select[name=secondTool] option:selected', "#settings").val() == 'custom') {
		$('input[name=secondTool]', "#settings").show();
		$('select[name=secondTool]', "#settings").hide();
		use_auxinput = true;
	}

	switch(type) {
		case 'luma2016':
			$topscreen.attr('width', 320);
			line2 = 'Copyright(C) 2016, AuroraWright';
			break;
		case 'luma2017':
			$topscreen.attr('width', 320);
			line2 = 'Copyright(C) 2017, AuroraWright';
			break;
		case 'menuhax2015':
			$topscreen.attr('width', 640);
			line2 = 'Copyright(C) 2015, yellow8';
			break;
		case 'menuhax2016':
			$topscreen.attr('width', 640);
			line2 = 'Copyright(C) 2016, yellow8';
			break;
	}

	$topscreen.clearCanvas().drawRect({
		fillStyle: 'black',
		x: 0, y: 0,
		width: 320,
		height: 240
	}).drawImage({
		source: 'images/symbols.png',
		x: 1, y: 16,
		sWidth: 21,
		sHeight: 29,
		sx: 112, sy: 0
	});

	switch ($('select[name=logoOptions] option:selected', "#settings").val()) {
		case 'energyStar':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 236, y: 16,
				sWidth: 83,
				sHeight: 52,
				sx: 0, sy: 0
			});
			break;
		case 'energyLuma':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 236, y: 16,
				sWidth: 82,
				sHeight: 52,
				sx: 0, sy: 52
			});
			break;
		case 'lumaIcon':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 256, y: 8,
				sWidth: 53,
				sHeight: 52,
				sx: 0, sy: 104
			});
			break;
			case 'nintendoIcon':
			$topscreen.drawImage({
				source: 'images/symbols.png',
				x: 256, y: 5,
				sWidth: 53,
				sHeight: 32,
				sx: 0, sy: 158
			});
			break;
	}

	write(24, 16*1, line1);
	write(24, 16*2, line2);

	switch(model) {
		case '3DS':
			write(0, 16*5, 'Nintendo 3DS CTR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case '3DSXL':
			if (region == 'JPN')
				write(0, 16*5, 'Nintendo 3DS LL SPR-001('+region+')');
			else
				write(0, 16*5, 'Nintendo 3DS XL SPR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case '2DS':
			write(0, 16*5, 'Nintendo 2DS FTR-001('+region+')');
			processor = 2; sd += ' SD'
			break;
		case 'n3DS':
			write(0, 16*5, 'New Nintendo 3DS KTR-001('+region+')');
			processor = 4; sd += ' microSD'
			break;
		case 'n3DSXL':
			if (region == 'JPN')
				write(0, 16*5, 'New Nintendo 3DS LL RED-001('+region+')');
			else
				write(0, 16*5, 'New Nintendo 3DS XL RED-001('+region+')');
			processor = 4; sd += ' microSD'
			break;
	}

	switch(processor) {
		case 2:
			write(0, 16*7, 'Main Processor       : Dual-core ARM11 MPCore');
			write(0, 16*8, 'Memory Testing       : 131072K OK');
			break;
		case 4:
			write(0, 16*7, 'Main Processor       : Quad-core ARM11 MPCore');
			write(0, 16*8, 'Memory Testing       : 262144K OK');
			break;
	}

	write(0, 16*9,  'Detecting Primary Master ... '+ processor/2 +'G Internal Memory');
	write(0, 16*10, 'Detecting Primary Slave  ... '+ sd +' Card');

	if (!use_bootinput)
		$('input[name=boottool]', "#settings").val($('select[name=boottool] option:selected', "#settings").text());

	if (!use_auxinput)
		$('input[name=secondTool]', "#settings").val($('select[name=secondTool] option:selected', "#settings").text());

	var boot_bool = $('input[name=hold]', "#settings").is(':checked');
	var boot_keys = $('select[name=onboot] option:selected', "#settings").val();
	var boot_tool = $('input[name=boottool]', "#settings").val();
	var boot_text = '_Hold ' + boot_keys + ' '+ $('select[name=firstTime] option:selected').text() +'_ to enter _' + boot_tool + '_.';

	var aux_bool = $('input[name=secondLine]', "#settings").is(':checked');
	var aux_keys = $('select[name=secondButton] option:selected').val();
	var aux_tool = $('input[name=secondTool]').val();
	var aux_text = '_Hold ' + aux_keys + ' '+ $('select[name=secondTime] option:selected').text() +'_ to enter _' + aux_tool + '_.';

	if (boot_bool && !aux_bool)
		writesmaller(0, 16*14, boot_text);
	else if (boot_bool)
		writesmaller(0, 16*13, boot_text);

	if (aux_bool)
		writesmaller(0, 16*14, aux_text);

	if ($topscreen.width() == 640) {
		$topscreen.drawImage({
			source: $topscreen.getCanvasImage(),
			x: 320, y: 0
		});
	}

});

$(document).ready(function() {

	$('canvas').drawImage({
		source: 'images/symbols.png',
		x: 0, y: 0,
		load: function() {
			$("select[name=region]", "#settings").trigger('change');
			if ($('#offline_warning').is(':hidden'))
				$('#downloadPNG, #downloadBIN').removeClass('disabled');
		}
	});

});

$('input[name=boottool]', "#settings").keyup(function() { $("#settings input").trigger('change'); });
$('input[name=auxtool]', "#settings").keyup(function() { $("#settings input").trigger('change'); });

/* Create a PNG downloadable of the canvas */
/* global download */
$('#downloadPNG').click(function() {
	if (!$(this).hasClass('disabled')) {
		var filename = ($('#topscreen').width() == 320) ? 'splash.png' : 'imagedisplay.png';
		var filedata = $('#topscreen').getCanvasImage();
		download(filedata, filename, "image/png");
	}
});

$('#downloadBIN').click(function() {
	if (!$(this).hasClass('disabled')) {
		var filename = ($('#topscreen').width() == 320) ? 'splash.bin' : 'menuhax_imagedisplay.bin';

		var width = $('#topscreen').height();
		var height = $('#topscreen').width();

		var $canvas = $('<canvas/>').css({ position: 'absolute', top: 0, left: -1*width }).appendTo('body');
		$canvas.attr('width', width).attr('height', height);

		$canvas.drawImage({
			source: $('#topscreen').getCanvasImage(),
			x: width/2, y: height/2,
			fromCenter: true,
			rotate: 90
		});

		var canvasdata = $canvas.get(0).getContext('2d').getImageData(0, 0, width, height).data;
		var filedata = '';

		for(var i = 0; i < canvasdata.length; i += 4)
			filedata += String.fromCharCode(canvasdata[i+2], canvasdata[i+1], canvasdata[i]);

		$canvas.remove();
		download('data:application/octet-stream;base64,' + window.btoa(filedata), filename);
	}
});<|endoftext|>