<commit_before>// VIE Widgets - Vienna IKS Editable Widgets
// (c) 2011 Sebastian Germesin, IKS Consortium
// VIE Widgets may be freely distributed under the MIT license.
// (see LICENSE)

(function($, undefined) {
    $.widget('view.vieImageSearch', {

        _create: function () {
            var self = this;
        },

        _init: function () {
            this.triggerSearch(this.options.entity);
        },

        _render: function (data) {
            var self = this;
            var photos = data.photos;
            var time = data.time;

            // clear the element
            $(self.element).empty();
            //render!
            for (var p = 0; p < photos.length; p++) {
                var photo = photos[p];
                var image = $('')
                    .append($(""));
                $(self.element).append(image);
            }
            if (photos.length) {
                var button = $('<button>')
                    .text(self.options.more_btn_txt)
                    .click(function () {
                        $(self.element).vieImageSearch({
                            page_num : self.options.page_num+1
                        })
                    });
                $(self.element)
                .append(button);
            }
        },

        triggerSearch: function (entity) {

            if (typeof entity === "string") {
                entity = this.options.vie.entities.get(entity);
            }

            if (entity) {
                this.options.entity = entity;
                for (var s in this.options.services) {
                    var service = this.options.services[s];
                    if (service.use) {
                        this._trigger('start_query', undefined, {service: s, time: new Date()});
                        service.query(entity, this);
                    }
                }
            }
        },

        _getUrlMainPartFromEntity : function (entity, service) {
            entity = ($.isArray(entity))? entity : [ entity ];

            for (var e = 0; e < entity.length; e++) {
                var types = entity[e].get('@type');
                types = ($.isArray(type))? types : [ types ];

                for (var t = 0; t < types.length; t++) {
                    var type = this.options.vie.types.get(types[t]);
                    if (type) {
                        for (var q in service.ts_url) {
                            if (type.isof(q)) {
                                var ret = service.ts_url[q].call(this, entity[e], service);
                                if (ret) {
                                    return ret;
                                }
                            }
                        }
                    }
                }
            }
            return "";
        },

        options: {
            vie         : new VIE(),
            more_btn_txt: "More images...",
            page_num    : 1,
            services    : {
                'europeana' : {
                    use       : false,
                    api_key   : undefined,
                    bin_size  : 10,
                    base_url  : "http://api.europeana.eu/api/opensearch.rss?",
                    tail_url  : function (widget, service) {
                        var url = "&sort=" + service.sort;

                        url += "&per_page=" + service.bin_size;
                        url += "&page=" + widget.options.page_num;
                        url += "&api_key=" + service.api_key;
                        url += "&extras=url_o&format=json&jsoncallback=?";

                        return url;
                    },
                    query : function (entity, widget) {
                        // assemble the URL
                        var url = this.base_url;
                        url += widget._getUrlMainPartFromEntity(entity, this);
                        url += this.tail_url(widget, this);
                        // trigger the search & receive the data via callback
                        $.getJSON(url, this.callback(widget, this));
                    },
                    callback : function (widget, service) {
                        //"searchTerms=bible&&startPage=1&wskey=x";
                        return function (data) {
                            var photos = [];
                            //TODO
                            debugger;
                            widget._pageNum++;
                            var data = {time: new Date(), photos: photos};
                            widget._trigger('end_query', undefined, data);
                            var render = (widget.options.render)? widget.options.render : widget._render;
                            render.call(widget, data);
                          };
                    },
                    ts_url : {
                        "Thing" : function (entity, service) {

                        }
                    }
                },
                'flickr' : {
                    use       : false,
                    api_key   : undefined,
                    bin_size  : 10,
                    sort      : 'relevance',
                    base_url  : "http://api.flickr.com/services/rest/?method=flickr.photos.search",
                    tail_url  : function (widget, service) {
                        var url = "&sort=" + service.sort;

                        url += "&per_page=" + service.bin_size;
                        url += "&page=" + widget.options.page_num;
                        url += "&api_key=" + service.api_key;
                        url += "&safe_search=1"; // safe search
                        url += "&extras=url_o&format=json&jsoncallback=?";

                        return url;
                    },
                    query : function (entity, widget) {
                        // assemble the URL
                        var url = this.base_url;
                        url += widget._getUrlMainPartFromEntity(entity, this);
                        url += this.tail_url(widget, this);
                        // trigger the search & receive the data via callback
                        $.getJSON(url, this.callback(widget, this));
                    },
                    callback  : function (widget, service) {
                        return function (data) {
                            var photos = [];
                              if (data.stat === 'ok' && data.photos.total > 0) {
                                  //put them into bins
                                  for (var i = 0; i < data.photos.photo.length; i++) {
                                      var photo = data.photos.photo[i];
                                      var imgS = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_s.jpg';

                                      var imgZ = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_z.jpg';

                                      var photoObj = {
                                              "thumbnail" : imgS,
                                              "original" : imgZ
                                      };
                                      photos.push(photoObj);
                                  }
                              }
                              widget._pageNum++;
                              var data = {service: service, time: new Date(), photos: photos};
                              widget._trigger('end_query', undefined, data);
                              var render = (widget.options.render)? widget.options.render : widget._render;
                              render.call(widget, data);
                          };
                    },
                    ts_url : {
                        //"Thing" : function (entity, service) {
                        //
                        //},
                        "Person" : function (entity, service) {
                            var url = "";

                            if (entity.has("name")) {
                                var name = entity.get("name");
                                if ($.isArray(name) && name.length > 0) {
                                    name = name[0]; //just take the first
                                }
                                url += "&text=portrait " + name;
                            }
                            return url;
                        },
                        "GeoCoordinates" : function (entity, service) {
                            var url = "";

                            if (entity.has('latitude') &&
                                entity.has('longitude')) {
                                var ts = Math.round((new Date()).getTime() / 1000);
                                var minUploadDate = ts - 604800 * 100; // last 100 weeks
                                var radius = 10;
                                var radiusUnits = "km";

                                var lat = entity.get("latitude");
                                if ($.isArray(lat) && lat.length > 0) {
                                    lat = lat[0]; //just take the first
                                }
                                var lon = entity.get("longitude");
                                if ($.isArray(lon) && lon.length > 0) {
                                    lon = lon[0]; //just take the first
                                }

                                url += "&lat=" + lat + "&lon=" + lon;
                                url += "&min_upload_date=" + minUploadDate;
                                url += "&radius=" + radius;
                                url += "&text=tourist attraction";
                                url += "&radius_units=" + radiusUnits;
                            }
                            return url;
                        },
                        "Place" : function (entity, service) {
                            var url = "";

                            if (entity.has('geo')) {
                                var geo = entity.get("geo");
                                return this._getUrlMainPartFromEntity(geo, service);
                            }else if (entity.has('containedIn')) {
                                var containedIn = entity.get('containedIn');
                                return this._getUrlMainPartFromEntity(containedIn, service);
                            } else if (entity.has('name')) {
                                var name = entity.get("name");
                                if ($.isArray(name) && name.length > 0) {
                                    name = name[0]; //just take the first
                                }
                                url += "&text=tourist attraction " + name;
                            }
                            return url;
                        }
                    }
                }
            },

            // helper
            render: undefined,
            entity: undefined,

            // events
            start_query: function () {},
            end_query: function () {}
        }

    });
})(jQuery);<commit_msg>adding type-ordering into search<commit_after>// VIE Widgets - Vienna IKS Editable Widgets
// (c) 2011 Sebastian Germesin, IKS Consortium
// VIE Widgets may be freely distributed under the MIT license.
// (see LICENSE)

(function($, undefined) {
    $.widget('view.vieImageSearch', {

        _create: function () {
            var self = this;
        },

        _init: function () {
            this.triggerSearch(this.options.entity);
        },

        _render: function (data) {
            var self = this;
            var photos = data.photos;
            var time = data.time;

            // clear the element
            $(self.element).empty();
            //render!
            for (var p = 0; p < photos.length; p++) {
                var photo = photos[p];
                var image = $('')
                    .append($(""));
                $(self.element).append(image);
            }
            if (photos.length) {
                var button = $('<button>')
                    .text(self.options.more_btn_txt)
                    .click(function () {
                        $(self.element).vieImageSearch({
                            page_num : self.options.page_num+1
                        })
                    });
                $(self.element)
                .append(button);
            }
        },

        triggerSearch: function (entity) {

            if (typeof entity === "string") {
                entity = this.options.vie.entities.get(entity);
            }

            if (entity) {
                this.options.entity = entity;
                for (var s in this.options.services) {
                    var service = this.options.services[s];
                    if (service.use) {
                        this._trigger('start_query', undefined, {service: s, time: new Date()});
                        service.query(entity, this);
                    }
                }
            }
        },

        _getUrlMainPartFromEntity : function (entity, service) {
            entity = ($.isArray(entity))? entity : [ entity ];

            for (var e = 0; e < entity.length; e++) {
                var types = entity[e].get('@type');
                types = ($.isArray(type))? types : [ types ];

                for (var t = 0; t < types.length; t++) {
                    var type = this.options.vie.types.get(types[t]);
                    if (type) {
                        var tsKeys = [];
                        for (var q in service.ts_url) {
                            tsKeys.push(q);
                        }
                        //sort the keys in ascending order!
                        tsKeys = this.options.vie.types.sort(tsKeys, false);
                        for (var q = 0; q < tsKeys.length; q++) {
                            var key = tsKeys[q];
                            if (type.isof(key)) {
                                var ret = service.ts_url[key].call(this, entity[e], service);
                                if (ret) {
                                    return ret;
                                }
                            }
                        }
                    }
                }
            }
            return "";
        },

        options: {
            vie         : new VIE(),
            more_btn_txt: "More images...",
            page_num    : 1,
            services    : {
                'europeana' : {
                    use       : false,
                    api_key   : undefined,
                    bin_size  : 10,
                    base_url  : "http://api.europeana.eu/api/opensearch.rss?",
                    tail_url  : function (widget, service) {
                        var url = "&sort=" + service.sort;

                        url += "&per_page=" + service.bin_size;
                        url += "&page=" + widget.options.page_num;
                        url += "&api_key=" + service.api_key;
                        url += "&extras=url_o&format=json&jsoncallback=?";

                        return url;
                    },
                    query : function (entity, widget) {
                        // assemble the URL
                        var url = this.base_url;
                        url += widget._getUrlMainPartFromEntity(entity, this);
                        url += this.tail_url(widget, this);
                        // trigger the search & receive the data via callback
                        $.getJSON(url, this.callback(widget, this));
                    },
                    callback : function (widget, service) {
                        //"searchTerms=bible&&startPage=1&wskey=x";
                        return function (data) {
                            var photos = [];
                            //TODO
                            debugger;
                            widget._pageNum++;
                            var data = {time: new Date(), photos: photos};
                            widget._trigger('end_query', undefined, data);
                            var render = (widget.options.render)? widget.options.render : widget._render;
                            render.call(widget, data);
                          };
                    },
                    ts_url : {
                        "Thing" : function (entity, service) {
                            return "";
                        }
                    }
                },
                'flickr' : {
                    use       : false,
                    api_key   : undefined,
                    bin_size  : 10,
                    sort      : 'relevance',
                    base_url  : "http://api.flickr.com/services/rest/?method=flickr.photos.search",
                    tail_url  : function (widget, service) {
                        var url = "&sort=" + service.sort;

                        url += "&per_page=" + service.bin_size;
                        url += "&page=" + widget.options.page_num;
                        url += "&api_key=" + service.api_key;
                        url += "&safe_search=1"; // safe search
                        url += "&extras=url_o&format=json&jsoncallback=?";

                        return url;
                    },
                    query : function (entity, widget) {
                        // assemble the URL
                        var url = this.base_url;
                        url += widget._getUrlMainPartFromEntity(entity, this);
                        url += this.tail_url(widget, this);
                        // trigger the search & receive the data via callback
                        $.getJSON(url, this.callback(widget, this));
                    },
                    callback  : function (widget, service) {
                        return function (data) {
                            var photos = [];
                              if (data.stat === 'ok' && data.photos.total > 0) {
                                  //put them into bins
                                  for (var i = 0; i < data.photos.photo.length; i++) {
                                      var photo = data.photos.photo[i];
                                      var imgS = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_s.jpg';

                                      var imgZ = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_z.jpg';

                                      var photoObj = {
                                              "thumbnail" : imgS,
                                              "original" : imgZ
                                      };
                                      photos.push(photoObj);
                                  }
                                  widget._pageNum++;
                              }
                              var data = {service: service, time: new Date(), photos: photos};
                              widget._trigger('end_query', undefined, data);
                              var render = (widget.options.render)? widget.options.render : widget._render;
                              render.call(widget, data);
                          };
                    },
                    ts_url : {
                        "Thing" : function (entity, service) {
                            var url = "";

                            if (entity.has("name")) {
                                var name = entity.get("name");
                                if ($.isArray(name) && name.length > 0) {
                                    name = name[0]; //just take the first
                                }
                                url += "&text="; // *no* type-specific keywords
                                url += name;
                            }
                            return url;
                        },
                        "Person" : function (entity, service) {
                            var url = "";

                            if (entity.has("name")) {
                                var name = entity.get("name");
                                if ($.isArray(name) && name.length > 0) {
                                    name = name[0]; //just take the first
                                }
                                url += "&text=portrait "; // type-specific keywords
                                url += name;
                            } else {
                                return undefined
                            }
                            return url;
                        },
                        "GeoCoordinates" : function (entity, service) {
                            var url = "";

                            if (entity.has('latitude') &&
                                entity.has('longitude')) {
                                var ts = Math.round((new Date()).getTime() / 1000);
                                var minUploadDate = ts - 604800 * 100; // last 100 weeks
                                var radius = 10;
                                var radiusUnits = "km";

                                var lat = entity.get("latitude");
                                if ($.isArray(lat) && lat.length > 0) {
                                    lat = lat[0]; //just take the first
                                }
                                var lon = entity.get("longitude");
                                if ($.isArray(lon) && lon.length > 0) {
                                    lon = lon[0]; //just take the first
                                }

                                url += "&lat=" + lat + "&lon=" + lon;
                                url += "&min_upload_date=" + minUploadDate;
                                url += "&radius=" + radius;
                                url += "&text=tourist attraction"; // type-specific keywords!
                                url += "&radius_units=" + radiusUnits;
                            } else {
                                return undefined
                            }
                            return url;
                        },
                        "Place" : function (entity, service) {
                            var url = "";

                            if (entity.has('geo')) {
                                var geo = entity.get("geo");
                                return this._getUrlMainPartFromEntity(geo, service);
                            } else if (entity.has('containedIn')) {
                                var containedIn = entity.get('containedIn');
                                return this._getUrlMainPartFromEntity(containedIn, service);
                            } else if (entity.has('name')) {
                                var name = entity.get("name");
                                if ($.isArray(name) && name.length > 0) {
                                    name = name[0]; //just take the first
                                }
                                url += "&text=tourist attraction "; // type-specific keywords
                                url += name;
                            } else {
                                return undefined
                            }
                            return url;
                        }
                    }
                }
            },

            // helper
            render: undefined,
            entity: undefined,

            // events
            start_query: function () {},
            end_query: function () {}
        }

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


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.5 - Developed by d4rkd0s & d3mn5pwn ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.CANVAS, '', { preload: preload, create: create, update: update, render: render });
    function preload() {
        //setting up starting vars
        apple_count = 1;
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('tree', 'assets/images/tree.png');
        game.load.image('sun', 'assets/images/sun.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects

        apple = game.add.sprite(100, 200, 'apple');

        // Stretch to fill
        game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        tree = game.add.sprite(450, 30, 'tree');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //add horse
        sun = game.add.sprite(80, 20, 'sun');

        //add player
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;

    game.scale.enterFullScreen.add(onEnterFullScreen, this);
    game.scale.leaveFullScreen.add(onLeaveFullScreen, this);

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

    //prime that apple
    apple.kill();
    }//create

    function onEnterFullScreen() {

        //do anything you want

    }

    function onLeaveFullScreen() {

        //do anything you want

    }

    function gofull() {

        game.scale.startFullScreen();

    }

    function update() {
        console.log(game.time.totalElapsedSeconds());
        var curTime = game.time.totalElapsedSeconds();
        apple.bringToTop();
        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( player.y < 250 ) {
            tree.bringToTop();
            apple.bringToTop();
        }
        else{
            player.bringToTop();
        }

        if ( apple.alive == true){
            if ( appleSpawnTime+3 < curTime  && appleOnTree == 0 ){
                appleOnTree = 1;
                console.log("Apple ready to fling!");
            }
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            if ( apple_count > 0 ){
                randX = Math.floor(Math.random()*(650-600+1)+600);
                randY = Math.floor(Math.random()*(190-90+1)+90);

                console.log("Apple is clear of horse, spawned apple.");
                apple = game.add.sprite(randX, randY, 'apple');
                var appleOnTree = 1;
                var appleSpawnTime = game.time.totalElapsedSeconds();
                console.log(appleSpawnTime);
                game.physics.arcade.enable(apple);
                game.physics.arcade.enableBody(apple);
                apple.body.collideWorldBounds = true;
                game.physics.arcade.collide(player, apple);
                game.physics.arcade.collide(ocean, apple);
            }//apple_count isnt 0
            else {
                console.log("apple count is now zero!");
                game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                game.physics.destroy();
            }//apple count is 0
        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

function render () {

    if (game.scale.isFullScreen)
    {
        game.debug.text('ESC to leave fullscreen', (game.width/2)-140, 60);
    }
    else
    {
        game.debug.text('Click / Tap to go fullscreen', (game.width/2)-140, 16);
    }

}
};
});<commit_msg>Set this up when the first apple spawns<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.5 - Developed by d4rkd0s & d3mn5pwn ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.CANVAS, '', { preload: preload, create: create, update: update, render: render });
    function preload() {
        //setting up starting vars
        apple_count = 1;
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('tree', 'assets/images/tree.png');
        game.load.image('sun', 'assets/images/sun.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects

        apple = game.add.sprite(100, 200, 'apple');
        appleOnTree = 0;
        // Stretch to fill
        game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        tree = game.add.sprite(450, 30, 'tree');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //add horse
        sun = game.add.sprite(80, 20, 'sun');

        //add player
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;

    game.scale.enterFullScreen.add(onEnterFullScreen, this);
    game.scale.leaveFullScreen.add(onLeaveFullScreen, this);

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

    //prime that apple
    apple.kill();
    }//create

    function onEnterFullScreen() {

        //do anything you want

    }

    function onLeaveFullScreen() {

        //do anything you want

    }

    function gofull() {

        game.scale.startFullScreen();

    }

    function update() {
        console.log(game.time.totalElapsedSeconds());
        var curTime = game.time.totalElapsedSeconds();
        apple.bringToTop();
        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( player.y < 250 ) {
            tree.bringToTop();
            apple.bringToTop();
        }
        else{
            player.bringToTop();
        }

        if ( apple.alive == true){
            if ( appleSpawnTime+3 < curTime  && appleOnTree == 0 ){
                appleOnTree = 1;
                console.log("Apple ready to fling!");
            }
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            if ( apple_count > 0 ){
                randX = Math.floor(Math.random()*(650-600+1)+600);
                randY = Math.floor(Math.random()*(190-90+1)+90);

                console.log("Apple is clear of horse, spawned apple.");
                apple = game.add.sprite(randX, randY, 'apple');
                var appleOnTree = 1;
                var appleSpawnTime = game.time.totalElapsedSeconds();
                console.log(appleSpawnTime);
                game.physics.arcade.enable(apple);
                game.physics.arcade.enableBody(apple);
                apple.body.collideWorldBounds = true;
                game.physics.arcade.collide(player, apple);
                game.physics.arcade.collide(ocean, apple);
            }//apple_count isnt 0
            else {
                console.log("apple count is now zero!");
                game.debug.text('Retry? (Refresh the page)', (game.width/2)-140, game.height/2);
                game.physics.destroy();
            }//apple count is 0
        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

function render () {

    if (game.scale.isFullScreen)
    {
        game.debug.text('ESC to leave fullscreen', (game.width/2)-140, 60);
    }
    else
    {
        game.debug.text('Click / Tap to go fullscreen', (game.width/2)-140, 16);
    }

}
};
});<|endoftext|>


<commit_before>module.exports = function Game(hash, client) {
  this.deck = [];
  this.board = [];
  this.players = [new Player(client), null, null, null, null, null, null, null];
  this.hash = hash;
  this.puzzled = [];
  for (var i = 0; i < 61; i++) {
    this.deck.push( new Card(i) );
  }
  shuffle(this.deck);
  for (var i = 0; i < 12; i++) {
    this.board.push(this.deck.pop());
  }

  this.getActivePlayers = function() {
    return this.players.filter( function(player) { return player !== null; });
  }

  this.numPlayers = function() {
    return this.getActivePlayers().length;
  }

  this.firstAvailablePlayerSlot = function() {
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] === null) return i;
    }
    return 0;
  }

  this.getPlayerIdx = function(client) {
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] !== null &&
          this.players[i].client.sessionId === client.sessionId)
        return i;
    }
    return -1;
  }

  this.playerScores = function() {
    ret = {};
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] !== null) ret[i] = this.players[i].score;
    }
    return ret;
  }

  this.registerClient = function(client) {
    if (this.numPlayers() >= this.players.length) return false;
    if (this.players.every( function(player) {
      return (player === null || player.client.sessionId !== client.sesionId);
    })) {
      var playerIdx = this.firstAvailablePlayerSlot();
      this.broadcast({action: 'join', player: playerIdx});
      this.players[playerIdx] = new Player(client);
    }
    return true;
  }

  this.unregisterClient = function(client, gameOver) {
    var playerIdx = this.getPlayerIdx(client);
    this.players[playerIdx] = null;
    this.broadcast({action: 'leave', player: playerIdx});
    var that = this;
    setTimeout( function delayGameover() {
      if (that.numPlayers() === 0) gameOver();
    }, 5000);
  }

  this.broadcast = function(message) {
    this.players.forEach( function(player) {
      if (player !== null) player.client.send(message);
    });
  }

  this.message = function(client, message) {
    if (!message.action) return;
    var player = this.getPlayerIdx(client);
    if (player === -1) return;
    if (message.action === 'init') {
      client.send({
          action: 'init'
        , board: this.board
        , players: this.playerScores()
        , you: player
      });
      return;
    }
    if (message.action === 'take') {
      if (this.checkSet(message.selected)) {
        console.log('take set succeed');
        var update = {};
        if (this.board.length <= 12 && this.deck.length > 0) {
            message.selected.forEach( function(val) {
              var c = this.deck.pop();
              update[val] = c;
              this.board[val] = c;
            }, this );
        } else {
          var lastRow = this.board.length - 3;
          var lastReplace = this.board.length - 1;
          message.selected.sort( function reverse(a, b) { return b - a; } );
          message.selected.forEach( function(val) {
            if (val >= lastRow) {
              update[val] = false;
            } else {
              while (message.selected.indexOf(lastReplace) != -1)
                lastReplace--;
              update[val] = lastReplace--;
              this.board[val] = this.board[update[val]];
            }
          }, this);
          this.board.splice(lastRow, 3);
        }
        this.players[player].score += 3;
        var playerUpdate = {};
        playerUpdate[player] = this.players[player].score;
        this.puzzled = [];
        this.broadcast({
            action: 'taken'
          , update: update
          , player: player
          , players: playerUpdate
        });

        if (this.deck.length === 0 && !this.checkSetExistence()) {
          var message = {
              action: 'win'
            , player: this.players.reduce(function(prev, cur, idx, arr) {
                if (cur === null) return prev;
                if (prev === null || cur.score > arr[prev].score) return idx;
                return prev;
              }, null)
          };
          var that = this;
          setTimeout(function() { that.broadcast(message); }, 2000);
        }
      } else {
        console.log('take set failed');
      }
      return;
    }

    if (message.action === 'hint') {
      if (this.puzzled.indexOf(player) != -1) return;
      this.puzzled.push(player);
      this.broadcast({
          action: 'puzzled'
        , player: player
      });
      var that = this;
      setTimeout(function() {
        if (that.puzzled.length < Math.ceil(that.numPlayers() * 0.51)) return;
        var setExists = that.checkSetExistence();
        if (setExists) {
          that.broadcast({
              action: 'hint'
            , card: setExists[Math.floor(Math.random()*3)]
          });
        } else if (that.deck.length > 0) {
          var newCards = [];
          for (var i = 0; i < 3; i++) newCards.push(that.deck.pop());
          that.board = that.board.concat(newCards);
          that.broadcast({
              action: 'add'
            , cards: newCards
          });
        }
        that.puzzled = [];
      }, 1000);
    }
  }

  this.checkSetExistence = function() {
    if (this.board.length < 3) return false;
    for (var i = 0; i < this.board.length - 2; i++) {
    for (var j = i + 1; j < this.board.length - 1; j++) {
    for (var k = j + 1; k < this.board.length; k++) {
      if (this.verifySet(this.board[i],this.board[j],this.board[k]])) return [i,j,k];
    }}}
    return false;
  }

  this.checkSet = function(indexes) {
    indexes = indexes.unique();
    if (indexes.length != 3) return false;
    if (!indexes.every( function valid(index) {
      return (index >= 0 && index < this.board.length);
    }, this)) {
      return false;
    }
    return this.verifySet(this.board[indexes[0]], this.board[indexes[1]], this.board[indexes[2]]);
  }

  // hardcoding and unrolling all this for speed, possibly premature optimization
  this.verifySet = function(c0, c1, c2) {
    var s = c0.number + c1.number + c2.number;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.color + c1.color + c2.color;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.shape + c1.shape + c2.shape;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.shading + c1.shading + c2.shading;
    if (s != 0 && s != 3 && s != 6) return false;
    return true;
  }
}

function Card(idx) {
  this.number = idx % 3;
  idx = Math.floor(idx / 3);
  this.color = idx % 3;
  idx = Math.floor(idx / 3);
  this.shape = idx % 3;
  idx = Math.floor(idx / 3);
  this.shading = idx % 3;
}

function Player(client) {
  this.client = client;
  this.score = 0;
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]
function shuffle(v){
    for(var j, x, i = v.length;
      i;
      j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x)
    ;
    return v;
};

// **************************************************************************
// Copyright 2007 - 2009 Tavs Dokkedahl
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************

// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };<commit_msg>oops, typo<commit_after>module.exports = function Game(hash, client) {
  this.deck = [];
  this.board = [];
  this.players = [new Player(client), null, null, null, null, null, null, null];
  this.hash = hash;
  this.puzzled = [];
  for (var i = 0; i < 61; i++) {
    this.deck.push( new Card(i) );
  }
  shuffle(this.deck);
  for (var i = 0; i < 12; i++) {
    this.board.push(this.deck.pop());
  }

  this.getActivePlayers = function() {
    return this.players.filter( function(player) { return player !== null; });
  }

  this.numPlayers = function() {
    return this.getActivePlayers().length;
  }

  this.firstAvailablePlayerSlot = function() {
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] === null) return i;
    }
    return 0;
  }

  this.getPlayerIdx = function(client) {
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] !== null &&
          this.players[i].client.sessionId === client.sessionId)
        return i;
    }
    return -1;
  }

  this.playerScores = function() {
    ret = {};
    for (var i = 0; i < this.players.length; i++) {
      if (this.players[i] !== null) ret[i] = this.players[i].score;
    }
    return ret;
  }

  this.registerClient = function(client) {
    if (this.numPlayers() >= this.players.length) return false;
    if (this.players.every( function(player) {
      return (player === null || player.client.sessionId !== client.sesionId);
    })) {
      var playerIdx = this.firstAvailablePlayerSlot();
      this.broadcast({action: 'join', player: playerIdx});
      this.players[playerIdx] = new Player(client);
    }
    return true;
  }

  this.unregisterClient = function(client, gameOver) {
    var playerIdx = this.getPlayerIdx(client);
    this.players[playerIdx] = null;
    this.broadcast({action: 'leave', player: playerIdx});
    var that = this;
    setTimeout( function delayGameover() {
      if (that.numPlayers() === 0) gameOver();
    }, 5000);
  }

  this.broadcast = function(message) {
    this.players.forEach( function(player) {
      if (player !== null) player.client.send(message);
    });
  }

  this.message = function(client, message) {
    if (!message.action) return;
    var player = this.getPlayerIdx(client);
    if (player === -1) return;
    if (message.action === 'init') {
      client.send({
          action: 'init'
        , board: this.board
        , players: this.playerScores()
        , you: player
      });
      return;
    }
    if (message.action === 'take') {
      if (this.checkSet(message.selected)) {
        console.log('take set succeed');
        var update = {};
        if (this.board.length <= 12 && this.deck.length > 0) {
            message.selected.forEach( function(val) {
              var c = this.deck.pop();
              update[val] = c;
              this.board[val] = c;
            }, this );
        } else {
          var lastRow = this.board.length - 3;
          var lastReplace = this.board.length - 1;
          message.selected.sort( function reverse(a, b) { return b - a; } );
          message.selected.forEach( function(val) {
            if (val >= lastRow) {
              update[val] = false;
            } else {
              while (message.selected.indexOf(lastReplace) != -1)
                lastReplace--;
              update[val] = lastReplace--;
              this.board[val] = this.board[update[val]];
            }
          }, this);
          this.board.splice(lastRow, 3);
        }
        this.players[player].score += 3;
        var playerUpdate = {};
        playerUpdate[player] = this.players[player].score;
        this.puzzled = [];
        this.broadcast({
            action: 'taken'
          , update: update
          , player: player
          , players: playerUpdate
        });

        if (this.deck.length === 0 && !this.checkSetExistence()) {
          var message = {
              action: 'win'
            , player: this.players.reduce(function(prev, cur, idx, arr) {
                if (cur === null) return prev;
                if (prev === null || cur.score > arr[prev].score) return idx;
                return prev;
              }, null)
          };
          var that = this;
          setTimeout(function() { that.broadcast(message); }, 2000);
        }
      } else {
        console.log('take set failed');
      }
      return;
    }

    if (message.action === 'hint') {
      if (this.puzzled.indexOf(player) != -1) return;
      this.puzzled.push(player);
      this.broadcast({
          action: 'puzzled'
        , player: player
      });
      var that = this;
      setTimeout(function() {
        if (that.puzzled.length < Math.ceil(that.numPlayers() * 0.51)) return;
        var setExists = that.checkSetExistence();
        if (setExists) {
          that.broadcast({
              action: 'hint'
            , card: setExists[Math.floor(Math.random()*3)]
          });
        } else if (that.deck.length > 0) {
          var newCards = [];
          for (var i = 0; i < 3; i++) newCards.push(that.deck.pop());
          that.board = that.board.concat(newCards);
          that.broadcast({
              action: 'add'
            , cards: newCards
          });
        }
        that.puzzled = [];
      }, 1000);
    }
  }

  this.checkSetExistence = function() {
    if (this.board.length < 3) return false;
    for (var i = 0; i < this.board.length - 2; i++) {
    for (var j = i + 1; j < this.board.length - 1; j++) {
    for (var k = j + 1; k < this.board.length; k++) {
      if (this.verifySet(this.board[i],this.board[j],this.board[k])) return [i,j,k];
    }}}
    return false;
  }

  this.checkSet = function(indexes) {
    indexes = indexes.unique();
    if (indexes.length != 3) return false;
    if (!indexes.every( function valid(index) {
      return (index >= 0 && index < this.board.length);
    }, this)) {
      return false;
    }
    return this.verifySet(this.board[indexes[0]], this.board[indexes[1]], this.board[indexes[2]]);
  }

  // hardcoding and unrolling all this for speed, possibly premature optimization
  this.verifySet = function(c0, c1, c2) {
    var s = c0.number + c1.number + c2.number;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.color + c1.color + c2.color;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.shape + c1.shape + c2.shape;
    if (s != 0 && s != 3 && s != 6) return false;
    s = c0.shading + c1.shading + c2.shading;
    if (s != 0 && s != 3 && s != 6) return false;
    return true;
  }
}

function Card(idx) {
  this.number = idx % 3;
  idx = Math.floor(idx / 3);
  this.color = idx % 3;
  idx = Math.floor(idx / 3);
  this.shape = idx % 3;
  idx = Math.floor(idx / 3);
  this.shading = idx % 3;
}

function Player(client) {
  this.client = client;
  this.score = 0;
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]
function shuffle(v){
    for(var j, x, i = v.length;
      i;
      j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x)
    ;
    return v;
};

// **************************************************************************
// Copyright 2007 - 2009 Tavs Dokkedahl
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************

// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };<|endoftext|>


<commit_before>var m = require('mori');
var set = require('./setLogic.js');

exports.getInitialState = function() {
    var deck = set.makeDeck();
    var dealt = m.take(12, deck);
    var undealt = m.drop(12, deck);
    var gameState = {'dealt': dealt, 'undealt': undealt};
    return gameState;
}

function deal(n, gameState) {
    //TODO
    return gameState;
}
<commit_msg>Make gameState.dealt a JS object (not Mori)<commit_after>var m = require('mori');
var set = require('./setLogic.js');

exports.getInitialState = function() {
    var deck = set.makeDeck();
    var dealt = m.take(12, deck);
    var undealt = m.drop(12, deck);
    var gameState = {'dealt': m.toJs(dealt), 'undealt': undealt};
    return gameState;
}

function deal(n, gameState) {
    //TODO
    return gameState;
}
<|endoftext|>


<commit_before>'use strict';

//arrays to hold data
var animalsArray = ['imgs/animals/alligator.jpg', 'imgs/animals/bear.png', 'imgs/animals/cat.jpg', 'imgs/animals/chicken.jpg', 'imgs/animals/cow.jpg', 'imgs/animals/deer.jpg', 'imgs/animals/dog.jpg', 'imgs/animals/eagle.jpg', 'imgs/animals/elephant.jpg', 'imgs/animals/flamingo.jpg', 'imgs/animals/giraffe.jpg', 'imgs/animals/gorilla.jpg', 'imgs/animals/hippo.jpg', 'imgs/animals/horse.jpg', 'imgs/animals/lion.jpg', 'imgs/animals/lizard.jpg', 'imgs/animals/mouse.jpg', 'imgs/animals/parrot.jpg', 'imgs/animals/pig.jpg', 'imgs/animals/sheep.jpg', 'imgs/animals/sloth.jpg', 'imgs/animals/snake.jpg', 'imgs/animals/tiger.jpg', 'imgs/animals/turtle.jpg'];

var cardsArray = ['imgs/cards/10clubs.jpg', 'imgs/cards/10hearts.jpg', 'imgs/cards/acehearts.jpg', 'imgs/cards/acespades.jpg', 'imgs/cards/jackdiamonds.jpg', 'imgs/cards/jackspades.jpg', 'imgs/cards/joker1.jpg', 'imgs/cards/joker2.png', 'imgs/cards/kinghearts.jpg', 'imgs/cards/kingspades.jpg', 'imgs/cards/queenhearts.jpg', 'imgs/cards/queenspades.jpg', 'imgs/cards/10spades.png', 'imgs/cards/10diamonds.png', 'imgs/cards/jackhearts.png', 'imgs/cards/jackclubs.png', 'imgs/cards/queendiamonds.jpg', 'imgs/cards/queenclubs.jpg', 'imgs/cards/kingdiamonds.png', 'imgs/cards/kingclubs.png', 'imgs/cards/aceclubs.png', 'imgs/cards/acediamonds.png', 'imgs/cards/joker3.jpg', 'imgs/cards/joker4.jpg' ];

var moviesArray = ['imgs/posters/alien.jpg', 'imgs/posters/avengers.jpg', 'imgs/posters/backtothefuture.jpg', 'imgs/posters/bladerunner.jpg', 'imgs/posters/darkknight.jpg', 'imgs/posters/deadpool.jpg', 'imgs/posters/findingnemo.jpg', 'imgs/posters/forceawakens.jpg', 'imgs/posters/ghostbuster.jpg', 'imgs/posters/greatoutdoors.jpg', 'imgs/posters/hackers.jpg', 'imgs/posters/hotfuzz.jpg', 'imgs/posters/indianajones.jpg', 'imgs/posters/jaws.jpg', 'imgs/posters/johnwick.jpg', 'imgs/posters/jurassicpark.jpg', 'imgs/posters/martian.jpg', 'imgs/posters/meangirls.jpg', 'imgs/posters/notebook.jpg', 'imgs/posters/rocky.jpg', 'imgs/posters/silenceofthelambs.jpg', 'imgs/posters/startrek.jpg', 'imgs/posters/starwars.jpg'];

var cardDictionary = {
  animals: animalsArray,
  cards: cardsArray,
  movies: moviesArray,
};

// function to parse from local storage and grab level
function getGameParam(){
  level = JSON.parse(localStorage.getItem('current_player'));
  level1 = level.level;
  key1 = level.cardset;
}
getGameParam();

console.log(level);
console.log(level1);
// function getArray(){
//   if (level1 === 'easy'){
//     imageArray = imageArrayEasy;
//   } else if (level1 === 'medium') {
//     imageArray = imageArrayMedium;
//   }else{
//     imageArray = imageArrayHard;
//   };
// }
//getArray();
// Variables to capture game level
var level;
var level1;
var key1;
var imageArray = [];
var altImage = 'imgs/back.png';
// counts correct pairs
var countCorrect = 0;
// counts total clicks
var countTotal = 0;
// selects game table
var picSelector = document.getElementById('game_table');
// creates array which clicked choices will be stored
var choiceArray = [];
// creates array to prevent the same image from being chosen
var choiceIndexArray = [];
// creates array to house correctly answered pairs
var correctPairs = [];
// allows for flipping of cards
var firstChoice = null;
// allows for disabling clicking during timeOut function
var selecting = false;
// holds the current player object
var playerObject;

var shuffledArray;

// function to parse from local storage and grab level
function getGameParam(){
  level = JSON.parse(localStorage.getItem('current_player'));
  level1 = level.level;
  key1 = level.cardset;
};

function shuffleArray(array){
  for (var i = array.length - 1; i > 0; i--){
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  };
  return array;
};

function grabItems(array, difficulty) {
  var itemsNeeded = 0;
  if (difficulty === 'easy') {
    itemsNeeded = 3;
  } else if (difficulty === 'medium') {
    itemsNeeded = 6;
  } else {
    itemsNeeded = 12;
  };
  for (var i = 0; i < itemsNeeded; i++) {
    imageArray.push(array[i]);
    imageArray.push(array[i]);
  };
};

function buildTable(){
  var iA = 0;
  var table = document.getElementById('game_table');
  var tRow;
  var tData;
  var image;
  for (var r = 0; r < (imageArray.length / 6); r++){
    tRow = document.createElement('tr');
    for (var c = 0; c < 6; c++){
      tData = document.createElement('td');
      image = document.createElement('img');
      image.setAttribute('faceup', imageArray[iA]);
      image.setAttribute('facedown', altImage);
      image.setAttribute('src', altImage);
      image.setAttribute('index', iA);
      iA += 1;
      tData.appendChild(image);
      tRow.appendChild(tData);
    };
    table.appendChild(tRow);
  };
};

function clickHandler(event){
  //getting attributes the clicked image
  var choiceIndex = event.target.getAttribute('index');
  var faceUp = event.target.getAttribute('faceup');
  var faceDown  = event.target.getAttribute('facedown');
  //stops from selecting image after 2 wrong clicks
  if (selecting){
    return;
  };
  //prevents a null image
  if (faceUp === null){
    return;
  };
  countTotal += 1;
  //beginning flip of clicked photo
  event.target.setAttribute('src', faceUp);
  event.target.setAttribute('class', 'flipfront');
  choiceIndexArray.push(choiceIndex);
  //if statements made to determine what will happen upon clicking of photo
  //comparing clicked images
  if (choiceIndexArray[0] !== choiceIndexArray[1]) {
    choiceArray.push(faceUp);
    //comparing if clicked choice is already matched in order to
    //prevent the same correct choices to be clicked again
    if (correctPairs.indexOf(choiceArray[0]) === -1 && correctPairs.indexOf(choiceArray[1]) === -1) {
      //determining the first clicked choice and enabling it to switch
      //back if the second choice is wrong
      if (!firstChoice){
        firstChoice = event.target;
      };
      //script after two choices are made
      if(choiceArray.length === 2){
        //script if choices are MATCHING
        if(choiceArray[0] === choiceArray[1]){
          pushCctPairs();
          //script after all correct choices are made
          if (countCorrect === (imageArray.length / 2)) {
            //timeout to allow seeing the final choice
            setTimeout(finished, 500);
          }
          //what will happen if choices are NOT MATCHING
        } else {
          choiceNotMatching(event, faceDown);
        };
      };
    //else if choice has already been matched
    } else {
      alert('Please make another choice.');
      choiceArray = [];
      firstChoice.setAttribute('src', faceDown);
      firstChoice = null;
    };
  //else if same card is picked twice
  } else {
    setTimeout(function(){flipCards(event, faceDown);}, 0),
    alert('please click a separate card, start over');
    choiceArray = [];
    choiceIndexArray = [];
  };
};

//function to flip cards and allow for setTimout
function flipCards(event, faceDown) {
  selecting = false;
  event.target.setAttribute('src', faceDown);
  event.target.setAttribute('class', 'flipback');
  firstChoice.setAttribute('src', faceDown);
  firstChoice.setAttribute('class', 'flipback');
  firstChoice = null;
  event.target.disable = false;
};

function pushCctPairs() {
  correctPairs.push(choiceArray[0]);
  choiceArray = [];
  choiceIndexArray = [];
  countCorrect += 1;
  firstChoice = null;
};

function finished(){
  playerObject = updatePlayerInfo(countTotal);
  pullPushHighScoreArray(playerObject);
  alert('Congratulations! You solved the game in ' + countTotal + ' clicks!');
  window.location = 'about-info.html';
};

function choiceNotMatching(event, faceDown) {
  selecting = true;
  setTimeout(function(){flipCards(event, faceDown);}, 1000);
  choiceArray = [];
  choiceIndexArray = [];
};

function pullPushHighScoreArray(object) {
  var jsonArray;
  var updatedArray;
  var newArray;
  if (localStorage.getItem('high_score_array')) {
    jsonArray = JSON.parse(localStorage.getItem('high_score_array'));
    jsonArray.push(object);
    updatedArray = JSON.stringify(jsonArray);
    localStorage.setItem('high_score_array', updatedArray);
  } else {
    newArray = JSON.stringify([object]);
    localStorage.setItem('high_score_array', newArray);
  };
};

function updatePlayerInfo(countTotal) {
  var playerObject;
  var returnPlayer;
  playerObject = JSON.parse(localStorage.getItem('current_player'));
  playerObject.score = countTotal;
  returnPlayer = JSON.stringify(playerObject);
  localStorage.setItem('current_player', returnPlayer);
  return playerObject;
};

//main

getGameParam();
shuffledArray = shuffleArray(cardDictionary[key1]);
grabItems(shuffledArray, level1);
imageArray = shuffleArray(imageArray);
buildTable();
picSelector.addEventListener('click', clickHandler);
<commit_msg>did best to fix javascript on branch<commit_after>'use strict';

//arrays to hold data
var animalsArray = ['imgs/animals/alligator.jpg', 'imgs/animals/bear.png', 'imgs/animals/cat.jpg', 'imgs/animals/chicken.jpg', 'imgs/animals/cow.jpg', 'imgs/animals/deer.jpg', 'imgs/animals/dog.jpg', 'imgs/animals/eagle.jpg', 'imgs/animals/elephant.jpg', 'imgs/animals/flamingo.jpg', 'imgs/animals/giraffe.jpg', 'imgs/animals/gorilla.jpg', 'imgs/animals/hippo.jpg', 'imgs/animals/horse.jpg', 'imgs/animals/lion.jpg', 'imgs/animals/lizard.jpg', 'imgs/animals/mouse.jpg', 'imgs/animals/parrot.jpg', 'imgs/animals/pig.jpg', 'imgs/animals/sheep.jpg', 'imgs/animals/sloth.jpg', 'imgs/animals/snake.jpg', 'imgs/animals/tiger.jpg', 'imgs/animals/turtle.jpg'];

var cardsArray = ['imgs/cards/10clubs.jpg', 'imgs/cards/10hearts.jpg', 'imgs/cards/acehearts.jpg', 'imgs/cards/acespades.jpg', 'imgs/cards/jackdiamonds.jpg', 'imgs/cards/jackspades.jpg', 'imgs/cards/joker1.jpg', 'imgs/cards/joker2.png', 'imgs/cards/kinghearts.jpg', 'imgs/cards/kingspades.jpg', 'imgs/cards/queenhearts.jpg', 'imgs/cards/queenspades.jpg', 'imgs/cards/10spades.png', 'imgs/cards/10diamonds.png', 'imgs/cards/jackhearts.png', 'imgs/cards/jackclubs.png', 'imgs/cards/queendiamonds.jpg', 'imgs/cards/queenclubs.jpg', 'imgs/cards/kingdiamonds.png', 'imgs/cards/kingclubs.png', 'imgs/cards/aceclubs.png', 'imgs/cards/acediamonds.png', 'imgs/cards/joker3.jpg', 'imgs/cards/joker4.jpg' ];

var moviesArray = ['imgs/posters/alien.jpg', 'imgs/posters/avengers.jpg', 'imgs/posters/backtothefuture.jpg', 'imgs/posters/bladerunner.jpg', 'imgs/posters/darkknight.jpg', 'imgs/posters/deadpool.jpg', 'imgs/posters/findingnemo.jpg', 'imgs/posters/forceawakens.jpg', 'imgs/posters/ghostbuster.jpg', 'imgs/posters/greatoutdoors.jpg', 'imgs/posters/hackers.jpg', 'imgs/posters/hotfuzz.jpg', 'imgs/posters/indianajones.jpg', 'imgs/posters/jaws.jpg', 'imgs/posters/johnwick.jpg', 'imgs/posters/jurassicpark.jpg', 'imgs/posters/martian.jpg', 'imgs/posters/meangirls.jpg', 'imgs/posters/notebook.jpg', 'imgs/posters/rocky.jpg', 'imgs/posters/silenceofthelambs.jpg', 'imgs/posters/startrek.jpg', 'imgs/posters/starwars.jpg'];

var cardDictionary = {
  animals: animalsArray,
  cards: cardsArray,
  movies: moviesArray,
};

// Variables to capture game level
var level;
var level1;
var key1;
var imageArray = [];
var altImage = 'imgs/back.png';
// counts correct pairs
var countCorrect = 0;
// counts total clicks
var countTotal = 0;
// selects game table
var picSelector = document.getElementById('game_table');
// creates array which clicked choices will be stored
var choiceArray = [];
// creates array to prevent the same image from being chosen
var choiceIndexArray = [];
// creates array to house correctly answered pairs
var correctPairs = [];
// allows for flipping of cards
var firstChoice = null;
// allows for disabling clicking during timeOut function
var selecting = false;
// holds the current player object
var playerObject;

var shuffledArray;

// function to parse from local storage and grab level
function getGameParam(){
  level = JSON.parse(localStorage.getItem('current_player'));
  level1 = level.level;
  key1 = level.cardset;
};

function shuffleArray(array){
  for (var i = array.length - 1; i > 0; i--){
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  };
  return array;
};

function grabItems(array, difficulty) {
  var itemsNeeded = 0;
  if (difficulty === 'easy') {
    itemsNeeded = 3;
  } else if (difficulty === 'medium') {
    itemsNeeded = 6;
  } else {
    itemsNeeded = 12;
  };
  for (var i = 0; i < itemsNeeded; i++) {
    imageArray.push(array[i]);
    imageArray.push(array[i]);
  };
};

function buildTable(){
  var iA = 0;
  var table = document.getElementById('game_table');
  var tRow;
  var tData;
  var image;
  for (var r = 0; r < (imageArray.length / 6); r++){
    tRow = document.createElement('tr');
    for (var c = 0; c < 6; c++){
      tData = document.createElement('td');
      image = document.createElement('img');
      image.setAttribute('faceup', imageArray[iA]);
      image.setAttribute('facedown', altImage);
      image.setAttribute('src', altImage);
      image.setAttribute('index', iA);
      iA += 1;
      tData.appendChild(image);
      tRow.appendChild(tData);
    };
    table.appendChild(tRow);
  };
};

function clickHandler(event){
  //getting attributes the clicked image
  var choiceIndex = event.target.getAttribute('index');
  var faceUp = event.target.getAttribute('faceup');
  var faceDown  = event.target.getAttribute('facedown');
  //stops from selecting image after 2 wrong clicks
  if (selecting){
    return;
  };
  //prevents a null image
  if (faceUp === null){
    return;
  };
  countTotal += 1;
  //beginning flip of clicked photo
  event.target.setAttribute('src', faceUp);
  event.target.setAttribute('class', 'flipfront');
  choiceIndexArray.push(choiceIndex);
  //if statements made to determine what will happen upon clicking of photo
  //comparing clicked images
  if (choiceIndexArray[0] !== choiceIndexArray[1]) {
    console.log(choiceIndexArray);
    choiceArray.push(faceUp);
    //comparing if clicked choice is already matched in order to
    //prevent the same correct choices to be clicked again
    if (correctPairs.indexOf(choiceArray[0]) === -1 && correctPairs.indexOf(choiceArray[1]) === -1) {
      //determining the first clicked choice and enabling it to switch
      //back if the second choice is wrong
      if (!firstChoice){
        firstChoice = event.target;
      };
      //script after two choices are made
      if(choiceArray.length === 2){
        //script if choices are MATCHING
        if(choiceArray[0] === choiceArray[1]){
          pushCctPairs();
          //script after all correct choices are made
          if (countCorrect === (imageArray.length / 2)) {
            //timeout to allow seeing the final choice
            setTimeout(finished, 500);
          }
          //what will happen if choices are NOT MATCHING
        } else {
          selecting = true;
          choiceNotMatching(event, faceDown);
        };
      };
    //else if choice has already been matched
    } else {
      alert('Please make another choice.');
      choiceArray = [];
      choiceIndexArray = [];
      firstChoice.setAttribute('src', faceDown);
      firstChoice.setAttribute('class', 'flipback');
      firstChoice = null;
    };
  //else if same card is picked twice
  } else {
    selecting = false;
    setTimeout(function(){flipCards(event, faceDown);}, 0),
    alert('please click a separate card, start over');
    choiceArray = [];
    choiceIndexArray = [];
  };
};

//function to flip cards and allow for setTimout
function flipCards(event, faceDown) {
  selecting = false;
  event.target.setAttribute('src', faceDown);
  event.target.setAttribute('class', 'flipback');
  firstChoice.setAttribute('src', faceDown);
  firstChoice.setAttribute('class', 'flipback');
  firstChoice = null;
  event.target.disable = false;
};

function pushCctPairs() {
  correctPairs.push(choiceArray[0]);
  choiceArray = [];
  choiceIndexArray = [];
  countCorrect += 1;
  firstChoice = null;
};

function finished(){
  playerObject = updatePlayerInfo(countTotal);
  pullPushHighScoreArray(playerObject);
  alert('Congratulations! You solved the game in ' + countTotal + ' clicks!');
  window.location = 'about-info.html';
};

function choiceNotMatching(event, faceDown) {
  selecting = true;
  setTimeout(function(){flipCards(event, faceDown);}, 1000);
  choiceArray = [];
  choiceIndexArray = [];
};

function pullPushHighScoreArray(object) {
  var jsonArray;
  var updatedArray;
  var newArray;
  if (localStorage.getItem('high_score_array')) {
    jsonArray = JSON.parse(localStorage.getItem('high_score_array'));
    jsonArray.push(object);
    updatedArray = JSON.stringify(jsonArray);
    localStorage.setItem('high_score_array', updatedArray);
  } else {
    newArray = JSON.stringify([object]);
    localStorage.setItem('high_score_array', newArray);
  };
};

function updatePlayerInfo(countTotal) {
  var playerObject;
  var returnPlayer;
  playerObject = JSON.parse(localStorage.getItem('current_player'));
  playerObject.score = countTotal;
  returnPlayer = JSON.stringify(playerObject);
  localStorage.setItem('current_player', returnPlayer);
  return playerObject;
};

//main

getGameParam();
shuffledArray = shuffleArray(cardDictionary[key1]);
grabItems(shuffledArray, level1);
imageArray = shuffleArray(imageArray);
buildTable();
picSelector.addEventListener('click', clickHandler);
<|endoftext|>