andykenobi's Forum Posts

  • I use number 1 just in case in the future I have to put an "if" or "else" statement it will be easier. So go with number 1 so in case you want to make changes to code, its very easy.

    Me too, but, do u think this can be make a code be slow and heavy?

  • Hello there!

    I'm always making games in construct 2 and i like to make a function with a single blank event inside, becouse i can minimize a function to see better all the codes and every function that i have. I want to know if this is a bad thing to do or not.

    Example:

  • Can i play a read file? I see that the api can do it.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • I have 3 singles sprites in a single family:

    Sprite1,

    Sprite2,

    Sprite.

    I want to click in a single sprite on the layout, example: i clicked in Sprite1. I want to clone him! I want to spawn another Sprite 1, but i clicked on the family... How do i spawn in a object?

    I did this:

    And it doest work! It's creating a random instance object of family... i want just create the object i have clicked!

  • I think GetLastValue can work better with two formats:

    > GetLastValue: ["Fernando Santorini","20","Curitiba"]
    
    *easy use with tokenat.
    [/code:1irzpeul]
    
    [code:1irzpeul]
    *ExportToC2Array: {"c2array":true,"size":[3,1,1],"data":[[["Fernando Santorini"]],[["20"]],[["Curitiba"]]]}
    
    or
    *C2Array
    *GetC2ArrayFormat
    *I don't know lol
    [/code:1irzpeul]
    

    Good idea! I will see later about it! Thanks.

  • Look for 'PlayLive'.

    edittime.js

    > function GetPluginSettings() {
        return {
            "name": "Sweet", // as appears in 'insert object' dialog, can be changed as long as "id" stays the same
            "id": "Sweet", // this is used to identify this plugin and is saved to the project; never change it
            "version": "1.0", // (float in x.y format) Plugin version - C2 shows compatibility warnings based on this
            "description": "A BEAUTIFUL REPLACEMENT FOR JAVASCRIPT'S 'ALERT'",
            "author": "Andrews Vinícius",
            "help url": "htpps://andrewsarts.com.br",
            "category": "Addon", // Prefer to re-use existing categories, but you can set anything here
            "type": "object", // either "world" (appears in layout and is drawn), else "object"
            "rotatable": true, // only used when "type" is "world".  Enables an angle property on the object.
            "flags": pf_singleglobal, // uncomment lines to enable flags...
            "dependency": "sweetalert2.min.css;sweetalert2.min.js;es6-promise.js"
                //	| pf_singleglobal		// exists project-wide, e.g. mouse, keyboard.  "type" must be "object".
                //	| pf_texture			// object has a single texture (e.g. tiled background)
                //	| pf_position_aces		// compare/set/get x, y...
                //	| pf_size_aces			// compare/set/get width, height...
                //	| pf_angle_aces			// compare/set/get angle (recommended that "rotatable" be set to true)
                //	| pf_appearance_aces	// compare/set/get visible, opacity...
                //	| pf_tiling				// adjusts image editor features to better suit tiled images (e.g. tiled background)
                //	| pf_animations			// enables the animations system.  See 'Sprite' for usage
                //	| pf_zorder_aces		// move to top, bottom, layer...
                //  | pf_nosize				// prevent resizing in the editor
                //	| pf_effects			// allow WebGL shader effects to be added
                //  | pf_predraw			// set for any plugin which draws and is not a sprite (i.e. does not simply draw
                // a single non-tiling image the size of the object) - required for effects to work properly
        };
    };
    
    ////////////////////////////////////////
    // Parameter types:
    // AddNumberParam(label, description [, initial_string = "0"])			// a number
    // AddStringParam(label, description [, initial_string = "\"\""])		// a string
    // AddAnyTypeParam(label, description [, initial_string = "0"])			// accepts either a number or string
    // AddCmpParam(label, description)										// combo with equal, not equal, less, etc.
    // AddComboParamOption(text)											// (repeat before "AddComboParam" to add combo items)
    // AddComboParam(label, description [, initial_selection = 0])			// a dropdown list parameter
    // AddObjectParam(label, description)									// a button to click and pick an object type
    // AddLayerParam(label, description)									// accepts either a layer number or name (string)
    // AddLayoutParam(label, description)									// a dropdown list with all project layouts
    // AddKeybParam(label, description)										// a button to click and press a key (returns a VK)
    // AddAnimationParam(label, description)								// a string intended to specify an animation name
    // AddAudioFileParam(label, description)								// a dropdown list with all imported project audio files
    
    ////////////////////////////////////////
    // Conditions
    
    // AddCondition(id,					// any positive integer to uniquely identify this condition
    //				flags,				// (see docs) cf_none, cf_trigger, cf_fake_trigger, cf_static, cf_not_invertible,
    //									// cf_deprecated, cf_incompatible_with_triggers, cf_looping
    //				list_name,			// appears in event wizard list
    //				category,			// category in event wizard list
    //				display_str,		// as appears in event sheet - use {0}, {1} for parameters and also <b></b>, <i></i>
    //				description,		// appears in event wizard dialog when selected
    //				script_name);		// corresponding runtime function name
    
    // example
    // AddNumberParam("Number", "Enter a number to test if positive.");
    // AddCondition(0, cf_none, "Is number positive", "My category", "{0} is positive", "Description for my condition!", "MyCondition");
    
    AddStringParam("Tag", "A tag, which can be anything you like, to distinguish between different alert requests.", "\"\"");
    AddCondition(0, cf_trigger, "On alert confim", "Trigger", "On alert confim {0}", "Callback to execute when the confirm alert button is clicked.", "OnAlertConfirm");
    
    AddStringParam("Tag", "A tag, which can be anything you like, to distinguish between different alert requests.", "\"\"");
    AddCondition(1, cf_trigger, "On alert cancel", "Trigger", "On alert cancel {0}", "Callback to execute when the cancel alert button is clicked.", "OnAlertCancel");
    
    AddCondition(2, cf_trigger, "On alert close", "Trigger", "On alert close", "Callback to execute when the alert was closed.", "OnAlertClose");
    
    ////////////////////////////////////////
    // Actions
    
    // AddAction(id,				// any positive integer to uniquely identify this action
    //			 flags,				// (see docs) af_none, af_deprecated
    //			 list_name,			// appears in event wizard list
    //			 category,			// category in event wizard list
    //			 display_str,		// as appears in event sheet - use {0}, {1} for parameters and also <b></b>, <i></i>
    //			 description,		// appears in event wizard dialog when selected
    //			 script_name);		// corresponding runtime function name
    
    // example
    // AddStringParam("Message", "Enter a string to alert.");
    // AddAction(0, af_none, "Alert", "My category", "Alert {0}", "Description for my action!", "MyAction");
    
    AddStringParam("Title", "Enter the string title.");
    AddStringParam("Message", "Enter the string message.");
    AddComboParamOption("Normal");
    AddComboParamOption("Success");
    AddComboParamOption("Error");
    AddComboParamOption("Warning");
    AddComboParamOption("Info");
    AddComboParamOption("Question");
    AddComboParam("Message type", "The message type.", [initial_selection = 0])
    AddStringParam("Button confirm text", "Enter the confirm button string message.");
    AddAction(0, cf_none, "Alert message", "Alert", "Alert message: {0} {1}", "A title with a text under.", "AlertMessage");
    
    AddStringParam("Title", "Enter the string title.");
    AddStringParam("Message", "Enter the string message.");
    AddStringParam("Image URL", "Enter the string message.");
    AddStringParam("Button confirm Text", "Enter the confirm button string message.");
    AddAction(1, cf_none, "Image alert", "Alert", "Image alert message: {0} {1}", "A message with a custom image icon.", "ImageAlert");
    
    AddStringParam("Tag", "A tag, which can be anything you like, to distinguish between different alert requests.", "\"\"");
    AddStringParam("Title", "Enter the string title.");
    AddStringParam("Message", "Enter the string message.");
    AddComboParamOption("Normal");
    AddComboParamOption("Success");
    AddComboParamOption("Error");
    AddComboParamOption("Warning");
    AddComboParamOption("Info");
    AddComboParamOption("Question");
    AddComboParam("Message type", "The message type.", [initial_selection = 0])
    AddStringParam("Button confirm text", "Enter the confirm button string message.");
    AddStringParam("Button cancel text", "Enter the cancel button string message.");
    AddAction(2, cf_none, "Confirm alert", "Alert", "Confirm alert message: {0}", "A warning message, with a function attached to the 'Confirm'-button...", "ConfirmAlert");
    
    AddStringParam("Tag", "A tag, which can be anything you like, to distinguish between different alert requests.", "\"\"");
    AddStringParam("Title", "Enter the string title.");
    AddStringParam("Message", "Enter the string message.");
    AddComboParamOption("Normal");
    AddComboParamOption("Success");
    AddComboParamOption("Error");
    AddComboParamOption("Warning");
    AddComboParamOption("Info");
    AddComboParamOption("Question");
    AddComboParam("Message type", "The message type.", [initial_selection = 0])
    AddStringParam("Button confirm text", "Enter the confirm button string message.");
    AddStringParam("Button cancel text", "Enter the cancel button string message.");
    AddStringParam("Input error Message", "Enter the input error string message. Leave it blank if can be a empty input.");
    AddAction(3, cf_none, "Input alert", "Alert", "Input alert message: {0}", "A replacement for the 'prompt' function.", "InputAlert");
    
    // PlayLive
    AddStringParam("Tag", "A tag, which can be anything you like, to distinguish between different alert requests.", "\"\"");
    AddComboParamOption("Normal");
    AddComboParamOption("Success");
    AddComboParamOption("Error");
    AddComboParamOption("Warning");
    AddComboParamOption("Info");
    AddComboParamOption("Question");
    AddComboParam("Message type", "The message type.", [initial_selection = 0]);
    AddStringParam("Title", "Enter the string title.");
    AddStringParam("Confirm text", "Enter the confirm button string message.");
    AddStringParam("Cancel text", "Enter the cancel button string message. Leave it blank if do not want to cancel button.");
    AddStringParam("Error message", "Enter the input error string message. Leave it blank if can be a empty input.");
    AddVariadicParams("Input {n}", "A input to add for the alert call.");
    AddComboParamOption("false");
    AddComboParamOption("true");
    AddComboParam("Allow escape key", "If set to false, the user can't dismiss the modal by pressing the Escape key.", [initial_selection = 1]);
    AddComboParamOption("false");
    AddComboParamOption("true");
    AddComboParam("Allow outside click", "If set to false, the user can't dismiss the modal by clicking outside it.", [initial_selection = 1]);
    AddAction(4, cf_none, "Alert [multiple inputs]", "Alert", "<b>[multiple]</b> Alert(<i>{2}</i>)", "A replacement for the 'prompt' function.", "Multiple");
    
    ////////////////////////////////////////
    // Expressions
    
    // AddExpression(id,			// any positive integer to uniquely identify this expression
    //				 flags,			// (see docs) ef_none, ef_deprecated, ef_return_number, ef_return_string,
    //								// ef_return_any, ef_variadic_parameters (one return flag must be specified)
    //				 list_name,		// currently ignored, but set as if appeared in event wizard
    //				 category,		// category in expressions panel
    //				 exp_name,		// the expression name after the dot, e.g. "foo" for "myobject.foo" - also the runtime function name
    //				 description);	// description in expressions panel
    
    // example
    // AddExpression(0, ef_return_number, "Leet expression", "My category", "MyExpression", "Return the number 1337.");
    AddExpression(0, ef_return_string, "GetLastValue", "Alert", "GetLastValue", "Get a last input alert message text.");
    
    ////////////////////////////////////////
    ACESDone();
    
    ////////////////////////////////////////
    // Array of property grid properties for this plugin
    // new cr.Property(ept_integer,		name,	initial_value,	description)		// an integer value
    // new cr.Property(ept_float,		name,	initial_value,	description)		// a float value
    // new cr.Property(ept_text,		name,	initial_value,	description)		// a string
    // new cr.Property(ept_color,		name,	initial_value,	description)		// a color dropdown
    // new cr.Property(ept_font,		name,	"Arial,-16", 	description)		// a font with the given face name and size
    // new cr.Property(ept_combo,		name,	"Item 1",		description, "Item 1|Item 2|Item 3")	// a dropdown list (initial_value is string of initially selected item)
    // new cr.Property(ept_link,		name,	link_text,		description, "firstonly")		// has no associated value; simply calls "OnPropertyChanged" on click
    
    var property_list = [
    >     // new cr.Property(ept_integer, 	"My property",		77,		"An example property.")
    > ];
    
    // Called by IDE when a new object type is to be created
    function CreateIDEObjectType() {
        return new IDEObjectType();
    }
    
    // Class representing an object type in the IDE
    function IDEObjectType() {
        assert2(this instanceof arguments.callee, "Constructor called as a function");
    }
    
    // Called by IDE when a new object instance of this type is to be created
    IDEObjectType.prototype.CreateInstance = function(instance) {
        return new IDEInstance(instance);
    }
    
    // Class representing an individual instance of an object in the IDE
    function IDEInstance(instance, type) {
        assert2(this instanceof arguments.callee, "Constructor called as a function");
    
        // Save the constructor parameters
        this.instance = instance;
        this.type = type;
    
        // Set the default property values from the property table
        this.properties = {};
    
        for (var i = 0; i < property_list.length; i++)
            this.properties[property_list[i].name] = property_list[i].initial_value;
    
        // Plugin-specific variables
        // this.myValue = 0...
    }
    
    // Called when inserted via Insert Object Dialog for the first time
    IDEInstance.prototype.OnInserted = function() {}
    
    // Called when double clicked in layout
    IDEInstance.prototype.OnDoubleClicked = function() {}
    
    // Called after a property has been changed in the properties bar
    IDEInstance.prototype.OnPropertyChanged = function(property_name) {}
    
    // For rendered objects to load fonts or textures
    IDEInstance.prototype.OnRendererInit = function(renderer) {}
    
    // Called to draw self in the editor if a layout object
    IDEInstance.prototype.Draw = function(renderer) {}
    
    // For rendered objects to release fonts or textures
    IDEInstance.prototype.OnRendererReleased = function(renderer) {}
    [/code:1i92xix9]
    
    [b]runtime.js[/b]
    [code:1i92xix9]
    // ECMAScript 5 strict mode
    "use strict";
    
    assert2(cr, "cr namespace not created");
    assert2(cr.plugins_, "cr.plugins_ not created");
    
    /////////////////////////////////////
    // Plugin class
    // *** CHANGE THE PLUGIN ID HERE *** - must match the "id" property in edittime.js
    //          vvvvvvvv
    cr.plugins_.Sweet = function(runtime) {
        this.runtime = runtime;
    };
    
    (function() {
        /////////////////////////////////////
        // *** CHANGE THE PLUGIN ID HERE *** - must match the "id" property in edittime.js
        //                            vvvvvvvv
        var pluginProto = cr.plugins_.Sweet.prototype;
    
        /////////////////////////////////////
        // Object type class
        pluginProto.Type = function(plugin) {
            this.plugin = plugin;
            this.runtime = plugin.runtime;
        };
    
        var typeProto = pluginProto.Type.prototype;
    
        // called on startup for each object type
        typeProto.onCreate = function() {};
    
        /////////////////////////////////////
        // Instance class
        pluginProto.Instance = function(type) {
            this.type = type;
            this.runtime = type.runtime;
            this.tag = "";
            this.lastValue = "";
            // any other properties you need, e.g...
            // this.myValue = 0;
        };
    
        var instanceProto = pluginProto.Instance.prototype;
    
        // called whenever an instance is created
        instanceProto.onCreate = function() {
            // note the object is sealed after this call; ensure any properties you'll ever need are set on the object
            // e.g...
            // this.myValue = 0;
        };
    
        // called whenever an instance is destroyed
        // note the runtime may keep the object after this call for recycling; be sure
        // to release/recycle/reset any references to other objects in this function.
        instanceProto.onDestroy = function() {};
    
        // called when saving the full state of the game
        instanceProto.saveToJSON = function() {
            // return a Javascript object containing information about your object's state
            // note you MUST use double-quote syntax (e.g. "property": value) to prevent
            // Closure Compiler renaming and breaking the save format
            return {
                // e.g.
                //"myValue": this.myValue
            };
        };
    
        // called when loading the full state of the game
        instanceProto.loadFromJSON = function(o) {
            // load from the state previously saved by saveToJSON
            // 'o' provides the same object that you saved, e.g.
            // this.myValue = o["myValue"];
            // note you MUST use double-quote syntax (e.g. o["property"]) to prevent
            // Closure Compiler renaming and breaking the save format
        };
    
        // only called if a layout object - draw to a canvas 2D context
        instanceProto.draw = function(ctx) {};
    
        // only called if a layout object in WebGL mode - draw to the WebGL context
        // 'glw' is not a WebGL context, it's a wrapper - you can find its methods in GLWrap.js in the install
        // directory or just copy what other plugins do.
        instanceProto.drawGL = function(glw) {};
    
        //////////////////////////////////////
        // Conditions
        function Cnds() {};
    
        Cnds.prototype.OnAlertConfirm = function(tag_) {
            return cr.equals_nocase(tag_, this.tag);
        };
    
        Cnds.prototype.OnAlertCancel = function(tag_) {
            return cr.equals_nocase(tag_, this.tag);
        };
    
        Cnds.prototype.OnAlertClose = function() {
            return true;
        };
    
        pluginProto.cnds = new Cnds();
    
        //////////////////////////////////////
        // Actions
        function Acts() {};
    
        function GetType(type) {
            switch (type) {
                case 0:
                    return "";
                case 1:
                    return "success";
                case 2:
                    return "error";
                case 3:
                    return "warning";
                case 4:
                    return "info";
                case 5:
                    return "question";
            }
        }
    
        Acts.prototype.AlertMessage = function(title, text, type, btnConfirmText) {
            var self = this;
            var msgType = GetType(type);
    
            if (btnConfirmText == "") {
                btnConfirmText = "OK";
            }
            swal({
                title: title,
                text: text,
                type: msgType,
                confirmButtonColor: '#3085d6',
                confirmButtonText: btnConfirmText
            }).then(function() {
                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertClose, self);
            });
        };
    
        Acts.prototype.ImageAlert = function(title, text, customImageUrl, btnConfirmText) {
            var self = this;
    
            if (btnConfirmText == "") {
                btnConfirmText = "OK";
            }
    
            swal({
                title: title,
                text: text,
                imageUrl: customImageUrl,
                confirmButtonColor: '#3085d6',
                confirmButtonText: btnConfirmText
            }).then(function() {
                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertClose, self);
            });
        };
    
        Acts.prototype.ConfirmAlert = function(tag, title, text, type, btnConfirmText, btnCancelText) {
            var self = this;
            var msgType = GetType(type);
            var showCancel = true;
    
            if (btnConfirmText == "") {
                btnConfirmText = "OK";
            }
            if (btnCancelText == "") {
                //btnCancelText = "CANCEL";
                showCancel = false;
            }
    
            swal({
                title: title,
                text: text,
                type: msgType,
                showCancelButton: showCancel,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: btnConfirmText,
                cancelButtonText: btnCancelText,
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger',
                buttonsStyling: true
            }).then(function() {
                self.tag = tag;
                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertConfirm, self);
            }, function(dismiss) {
                // dismiss can be 'cancel', 'overlay', 'close', 'timer'
                if (dismiss === 'cancel') {
                    self.tag = tag;
                    self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertCancel, self);
                }
            });
        };
    
        Acts.prototype.InputAlert = function(tag, title, text, type, btnConfirmText, btnCancelText, errorMessage) {
            this.tag = tag;
            var self = this;
            var msgType = GetType(type);
            var showCancel = true;
            
            if (btnConfirmText == "") {
                btnConfirmText = "Ok";
            }
            if (btnCancelText == "") {
                //btnCancelText = "CANCEL";
                showCancel = false;
            }
            var cancelBtn = true;
            var messageNull = errorMessage;
            var confirmClose = false;
            if (errorMessage == "") {
                messageNull = "";
                confirmClose = true;
            }
            // if (btnCancelText == "") {
            //     cancelBtn = false;
            // }
    
            swal({
                title: title,
                text: text,
                type: msgType,
                input: 'text',
                showCancelButton: showCancel,
                inputValidator: function(value) {
                    return new Promise(function(resolve, reject) {
                        if (value) {
                            resolve();
                        } else {
                            if (errorMessage != "") {
                                reject(errorMessage);
                            } else {
                                self.lastValue = "";
                                self.tag = tag;
                                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertConfirm, self);
                                swal.close();
                            }
                        }
                    });
                }
            }).then(function(result) {
                self.lastValue = result;
                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertConfirm, self);
            }, function(dismiss) {
                // dismiss can be 'cancel', 'overlay', 'close', 'timer'
                if (dismiss === 'cancel') {
                    self.tag = tag;
                    self.lastValue = "";
                    self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertCancel, self);
                }
            })
        };
    
        // PlayLive
        Acts.prototype.Multiple = function(tag_, type_, title_, confirm_, cancel_, error_, params_, allow_escapekey_, allow_outsideclick_) {
            var self = this;
            var input = "";
    
            for (var i = 0; i < params_.length; i++) {
    			input += "<input id='swal-input" + i + "' class='swal2-input' placeholder='" + params_[i] + "' autofocus>";
    		};
    
            swal({
                type: GetType(type_),
                title: title_,
                html: input,
                confirmButtonText: (confirm_) ? confirm_ : "OK",
                cancelButtonText: cancel_,
                showCancelButton: (cancel_),
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger',
                buttonsStyling: true,
                allowEscapeKey: allow_escapekey_,
                allowOutsideClick: allow_outsideclick_,
                preConfirm: function() {
    				return new Promise(function(resolve, reject) {
    					var array = [];
    					for (var i = 0; i < params_.length; i++) {
    						if ($('#swal-input' + i).val() != '')
    							array[i] = $("#swal-input" + i).val();
    						else {
    							if (error_ != "") {
    	                            $('#swal-input' + i).focus();
    	                            reject(error_);
    	                            return;
    							} else
    								array[i] = "";
    						};
    					};
    					resolve(array);
    				});
    			}
            }).then(function(result) {
                self.tag = tag_;
                self.lastValue = JSON.stringify(result);
                self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertConfirm, self);
            }, function(dismiss) {
                // dismiss can be 'cancel', 'overlay', 'close', 'timer'
                //if (dismiss === 'cancel') {
                    self.tag = tag_;
                    self.lastValue = "";
                    self.runtime.trigger(cr.plugins_.Sweet.prototype.cnds.OnAlertCancel, self);
                //}
            });
        };
    
        pluginProto.acts = new Acts();
    
        //////////////////////////////////////
        // Expressions
        function Exps() {};
    
        // the example expression
        Exps.prototype.MyExpression = function(ret) // 'ret' must always be the first parameter - always return the expression's result through it!
        {
            ret.set_int(1337); // return our value
            // ret.set_float(0.5);			// for returning floats
            // ret.set_string("Hello");		// for ef_return_string
            // ret.set_any("woo");			// for ef_return_any, accepts either a number or string
        };
    
        // ... other expressions here ...
    
        Exps.prototype.GetLastValue = function(ret)
        {
            ret.set_string(this.lastValue);
        };
    
        pluginProto.exps = new Exps();
    
    }());
    [/code:1i92xix9]
    
    [b]sweetalert2.min.js[/b] [i]*mini error in 'allowEscapeKey'.[/i]
    [code:1i92xix9]
    !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Sweetalert2=t()}(this,function(){"use strict";function e(){if(void 0===arguments[0])return console.error("SweetAlert2 expects at least 1 attribute!"),!1;var e=c({},j);switch(typeof arguments[0]){case"string":e.title=arguments[0],e.text=arguments[1]||"",e.type=arguments[2]||"";break;case"object":c(e,arguments[0]),e.extraParams=arguments[0].extraParams,"email"===e.input&&null===e.inputValidator&&(e.inputValidator=function(e){return new Promise(function(t,n){var o=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;o.test(e)?t():n("Invalid email address")})});break;default:return console.error('SweetAlert2: Unexpected type of argument! Expected "string" or "object", got '+typeof arguments[0]),!1}K(e);var n=f();return new Promise(function(o,r){function a(t,n){for(var o=b(e.focusCancel),i=0;i<o.length;i++){t+=n,t===o.length?t=0:-1===t&&(t=o.length-1);var r=o[t];if(L(r))return r.focus()}}function l(n){var o=n||window.event,i=o.keyCode||o.which;if(-1!==[9,13,32,27].indexOf(i)){for(var l=o.target||o.srcElement,c=b(e.focusCancel),s=-1,u=0;u<c.length;u++)if(l===c[u]){s=u;break}9===i?(o.shiftKey?a(s,-1):a(s,1),V(o)):13===i||32===i?-1===s&&(e.focusCancel?O(P,o):O(M,o)):27===i&&e.allowEscapeKey===!0|e.allowEscapeKey===1&&(t.closeModal(e.onClose),r("esc"))}}e.timer&&(n.timeout=setTimeout(function(){t.closeModal(e.onClose),r("timer")},e.timer));var c=function(){switch(e.input){case"select":return x(n,i.select);case"radio":return n.querySelector("."+i.radio+" input:checked")||n.querySelector("."+i.radio+" input:first-child");case"checkbox":return n.querySelector("#"+i.checkbox);case"textarea":return x(n,i.textarea);default:return x(n,i.input)}},u=function(){var t=c();switch(e.input){case"checkbox":return t.checked?1:0;case"radio":return t.checked?t.value:null;case"file":return t.files.length?t.files[0]:null;default:return e.inputAutoTrim?t.value.trim():t.value}};e.input&&setTimeout(function(){var e=c();e&&w(e)},0);var p,f=function(n){e.showLoaderOnConfirm&&t.showLoading(),e.preConfirm?e.preConfirm(n,e.extraParams).then(function(i){t.closeModal(e.onClose),o(i||n)},function(e){t.hideLoading(),e&&t.showValidationError(e)}):(t.closeModal(e.onClose),o(n))},g=function(n){var o=n||window.event,i=o.target||o.srcElement,a=v(),l=h(),c=a===i||a.contains(i),d=l===i||l.contains(i);switch(o.type){case"mouseover":case"mouseup":e.buttonsStyling&&(c?a.style.backgroundColor=s(e.confirmButtonColor,-.1):d&&(l.style.backgroundColor=s(e.cancelButtonColor,-.1)));break;case"mouseout":e.buttonsStyling&&(c?a.style.backgroundColor=e.confirmButtonColor:d&&(l.style.backgroundColor=e.cancelButtonColor));break;case"mousedown":e.buttonsStyling&&(c?a.style.backgroundColor=s(e.confirmButtonColor,-.2):d&&(l.style.backgroundColor=s(e.cancelButtonColor,-.2)));break;case"click":if(c&&t.isVisible())if(e.input){var p=u();e.inputValidator?(t.disableInput(),e.inputValidator(p,e.extraParams).then(function(){t.enableInput(),f(p)},function(e){t.enableInput(),e&&t.showValidationError(e)})):f(p)}else f(!0);else d&&t.isVisible()&&(t.closeModal(e.onClose),r("cancel"))}},q=n.querySelectorAll("button");for(p=0;p<q.length;p++)q[p].onclick=g,q[p].onmouseover=g,q[p].onmouseout=g,q[p].onmousedown=g;y().onclick=function(){t.closeModal(e.onClose),r("close")},m().onclick=function(){e.allowOutsideClick&&(t.closeModal(e.onClose),r("overlay"))};var M=v(),P=h();e.reverseButtons?M.parentNode.insertBefore(P,M):M.parentNode.insertBefore(M,P),d.previousWindowKeyDown=window.onkeydown,window.onkeydown=l,e.buttonsStyling&&(M.style.borderLeftColor=e.confirmButtonColor,M.style.borderRightColor=e.confirmButtonColor),t.showLoading=t.enableLoading=function(){C(M,"loading"),C(n,"loading"),M.disabled=!0,P.disabled=!0},t.hideLoading=t.disableLoading=function(){k(M,"loading"),k(n,"loading"),M.disabled=!1,P.disabled=!1},t.enableButtons=function(){M.disabled=!1,P.disabled=!1},t.disableButtons=function(){M.disabled=!0,P.disabled=!0},t.enableConfirmButton=function(){M.disabled=!1},t.disableConfirmButton=function(){M.disabled=!0},t.enableInput=function(){var e=c();if("radio"===e.type)for(var t=e.parentNode.parentNode,n=t.querySelectorAll("input"),o=0;o<n.length;o++)n[o].disabled=!1;else e.disabled=!1},t.disableInput=function(){var e=c();if("radio"===e.type)for(var t=e.parentNode.parentNode,n=t.querySelectorAll("input"),o=0;o<n.length;o++)n[o].disabled=!0;else e.disabled=!0},t.showValidationError=function(e){var t=n.querySelector("."+i.validationerror);t.innerHTML=e,S(t);var o=c();w(o),C(o,"error")},t.resetValidationError=function(){var e=n.querySelector("."+i.validationerror);B(e);var t=c();t&&k(t,"error")},t.enableButtons(),t.hideLoading(),t.resetValidationError();var T,N=["input","select","radio","checkbox","textarea"];for(p=0;p<N.length;p++){var H=i[N[p]];for(T=x(n,H);T.attributes.length>0;)T.removeAttribute(T.attributes[0].name);for(var D in e.inputAttributes)T.setAttribute(D,e.inputAttributes[D]);T.className=H,e.inputClass&&C(T,e.inputClass),A(T)}var I;switch(e.input){case"text":case"email":case"password":case"file":T=x(n,i.input),T.value=e.inputValue,T.placeholder=e.inputPlaceholder,T.type=e.input,E(T);break;case"select":var j=x(n,i.select);if(j.innerHTML="",e.inputPlaceholder){var K=document.createElement("option");K.innerHTML=e.inputPlaceholder,K.value="",K.disabled=!0,K.selected=!0,j.appendChild(K)}I=function(t){for(var n in t){var o=document.createElement("option");o.value=n,o.innerHTML=t[n],e.inputValue===n&&(o.selected=!0),j.appendChild(o)}E(j),j.focus()};break;case"radio":var z=x(n,i.radio);z.innerHTML="",I=function(t){for(var n in t){var o=1,r=document.createElement("input"),a=document.createElement("label"),l=document.createElement("span");r.type="radio",r.name=i.radio,r.value=n,r.id=i.radio+"-"+o++,e.inputValue===n&&(r.checked=!0),l.innerHTML=t[n],a.appendChild(r),a.appendChild(l),a["for"]=r.id,z.appendChild(a)}E(z);var c=z.querySelectorAll("input");c.length&&c[0].focus()};break;case"checkbox":var R=x(n,i.checkbox),Z=n.querySelector("#"+i.checkbox);Z.value=1,Z.checked=Boolean(e.inputValue);var $=R.getElementsByTagName("span");$.length&&R.removeChild($[0]),$=document.createElement("span"),$.innerHTML=e.inputPlaceholder,R.appendChild($),E(R);break;case"textarea":var F=x(n,i.textarea);F.value=e.inputValue,F.placeholder=e.inputPlaceholder,E(F);break;case null:break;default:console.error('SweetAlert2: Unexpected type of input! Expected "text" or "email" or "password", "select", "checkbox", "textarea" or "file", got "'+e.input+'"')}"select"!==e.input&&"radio"!==e.input||(e.inputOptions instanceof Promise?(t.showLoading(),e.inputOptions.then(function(e){t.hideLoading(),I(e)})):"object"==typeof e.inputOptions?I(e.inputOptions):console.error("SweetAlert2: Unexpected type of inputOptions! Expected object or Promise, got "+typeof e.inputOptions)),W(),U(e.animation,e.onOpen),a(-1,1)})}function t(){var n=arguments,o=f();return null===o&&(t.init(),o=f()),t.isVisible()&&t.close(),e.apply(this,n)}var n="swal2-",o=function(e){var t={};for(var o in e)t[e[o]]=n+e[o];return t},i=o(["container","modal","overlay","close","content","spacer","confirm","cancel","icon","image","input","select","radio","checkbox","textarea","validationerror"]),r=o(["success","warning","info","question","error"]),a={title:"",text:"",html:"",type:null,customClass:"",animation:!0,allowOutsideClick:!0,allowEscapeKey:!0,showConfirmButton:!0,showCancelButton:!1,preConfirm:null,confirmButtonText:"OK",confirmButtonColor:"#3085d6",confirmButtonClass:null,cancelButtonText:"Cancel",cancelButtonColor:"#aaa",cancelButtonClass:null,buttonsStyling:!0,reverseButtons:!1,focusCancel:!1,showCloseButton:!1,showLoaderOnConfirm:!1,imageUrl:null,imageWidth:null,imageHeight:null,imageClass:null,timer:null,width:500,padding:20,background:"#fff",input:null,inputPlaceholder:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputClass:null,inputAttributes:{},inputValidator:null,onOpen:null,onClose:null},l='<div class="'+i.overlay+'" tabIndex="-1"></div><div class="'+i.modal+'" style="display: none" tabIndex="-1"><div class="'+i.icon+" "+r.error+'"><span class="x-mark"><span class="line left"></span><span class="line right"></span></span></div><div class="'+i.icon+" "+r.question+'">?</div><div class="'+i.icon+" "+r.warning+'">!</div><div class="'+i.icon+" "+r.info+'">i</div><div class="'+i.icon+" "+r.success+'"><span class="line tip"></span> <span class="line long"></span><div class="placeholder"></div> <div class="fix"></div></div><img class="'+i.image+'"><h2></h2><div class="'+i.content+'"></div><input class="'+i.input+'"><select class="'+i.select+'"></select><div class="'+i.radio+'"></div><label for="'+i.checkbox+'" class="'+i.checkbox+'"><input type="checkbox" id="'+i.checkbox+'"></label><textarea class="'+i.textarea+'"></textarea><div class="'+i.validationerror+'"></div><hr class="'+i.spacer+'"><button class="'+i.confirm+'">OK</button><button class="'+i.cancel+'">Cancel</button><span class="'+i.close+'">&times;</span></div>',c=function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},s=function(e,t){e=String(e).replace(/[^0-9a-f]/gi,""),e.length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),t=t||0;for(var n="#",o=0;3>o;o++){var i=parseInt(e.substr(2*o,2),16);i=Math.round(Math.min(Math.max(0,i+i*t),255)).toString(16),n+=("00"+i).substr(i.length)}return n},u=function(e){return"function"==typeof e},d={previousWindowKeyDown:null,previousActiveElement:null},p=function(e){return document.querySelector("."+e)},f=function(){return p(i.modal)},m=function(){return p(i.overlay)},v=function(){return p(i.confirm)},h=function(){return p(i.cancel)},y=function(){return p(i.close)},b=function(e){var t=[v(),h()];return e&&t.reverse(),t.concat(Array.prototype.slice.call(f().querySelectorAll("button:not([class^="+n+"]), input:not([type=hidden]), textarea, select")))},g=function(e,t){return e.classList.contains(t)},w=function(e){e.focus();var t=e.value;e.value="",e.value=t},C=function(e,t){if(e&&t){var n=t.split(/\s+/);n.forEach(function(t){e.classList.add(t)})}},k=function(e,t){if(e&&t){var n=t.split(/\s+/);n.forEach(function(t){e.classList.remove(t)})}},x=function(e,t){for(var n=0;n<e.childNodes.length;n++)if(g(e.childNodes[n],t))return e.childNodes[n]},E=function(e){e.style.opacity="",e.style.display="block"},S=function(e){if(e&&!e.length)return E(e);for(var t=0;t<e.length;++t)E(e[t])},A=function(e){e.style.opacity="",e.style.display="none"},B=function(e){if(e&&!e.length)return A(e);for(var t=0;t<e.length;++t)A(e[t])},L=function(e){return e.offsetWidth||e.offsetHeight||e.getClientRects().length},q=function(e,t){e.style.removeProperty?e.style.removeProperty(t):e.style.removeAttribute(t)},M=function(e){var t=e.style.display;e.style.left="-9999px",e.style.display="block";var n=e.clientHeight;return e.style.left="",e.style.display=t,"-"+parseInt(n/2,10)+"px"},P=function(e,t){if(+e.style.opacity<1){t=t||16,e.style.opacity=0,e.style.display="block";var n=+new Date,o=function(){var i=+e.style.opacity+(new Date-n)/100;e.style.opacity=i>1?1:i,n=+new Date,+e.style.opacity<1&&setTimeout(o,t)};o()}},T=function(e,t){if(+e.style.opacity>0){t=t||16;var n=e.style.opacity,o=+new Date,i=function(){var r=new Date-o,a=+e.style.opacity-r/(100*n);e.style.opacity=a,o=+new Date,+e.style.opacity>0?setTimeout(i,t):A(e)};i()}},O=function(e){if("function"==typeof MouseEvent){var t=new MouseEvent("click",{view:window,bubbles:!1,cancelable:!0});e.dispatchEvent(t)}else if(document.createEvent){var n=document.createEvent("MouseEvents");n.initEvent("click",!1,!1),e.dispatchEvent(n)}else document.createEventObject?e.fireEvent("onclick"):"function"==typeof e.onclick&&e.onclick()},V=function(e){"function"==typeof e.stopPropagation?(e.stopPropagation(),e.preventDefault()):window.event&&window.event.hasOwnProperty("cancelBubble")&&(window.event.cancelBubble=!0)},N=function(){var e=document.createElement("div"),t={WebkitAnimation:"webkitAnimationEnd",OAnimation:"oAnimationEnd oanimationend",msAnimation:"MSAnimationEnd",animation:"animationend"};for(var n in t)if(t.hasOwnProperty(n)&&void 0!==e.style[n])return t[n];return!1}(),H=function(){var e=f();window.onkeydown=d.previousWindowKeyDown,d.previousActiveElement&&d.previousActiveElement.focus&&d.previousActiveElement.focus(),clearTimeout(e.timeout)},D=function(e){var t=n+"mediaquery-"+Math.random().toString(36).substring(2,7),o=document.getElementsByTagName("head")[0],i=document.createElement("style");return i.type="text/css",i.id=t,i.innerHTML=e,o.appendChild(i),t},I=function(e){if(!e)return!1;var t=document.getElementsByTagName("head")[0],n=document.getElementById(e);n&&t.removeChild(n)},j=c({},a),K=function(e){var t=f();for(var n in e)a.hasOwnProperty(n)||"extraParams"===n||console.warn('SweetAlert2: Unknown parameter "'+n+'"');e.width=e.width.toString();var o,l=e.width.match(/^(\d+)(px|%)?$/);if(l?(o="px",l[2]&&(o=l[2]),l=parseInt(l[1],10),t.style.width=l+o,t.style.marginLeft=-l/2+o):console.warn('SweetAlert2: Invalid width parameter, usage examples: "400px", "50%", or just 500 which equals to "500px"'),t.style.padding=e.padding+"px",t.style.background=e.background,"px"===o){var c=5,s=l+l*(c/100)*2,u=D("@media screen and (max-width: "+s+"px) {."+i.modal+" {width: auto !important;left: "+c+"% !important;right: "+c+"% !important;margin-left: 0 !important;}}");t.setAttribute("data-mediaquery-id",u)}var d=t.querySelector("h2"),p=t.querySelector("."+i.content),m=v(),y=h(),b=t.querySelector("."+i.spacer),g=t.querySelector("."+i.close);if(d.innerHTML=e.title.split("\n").join("<br>"),e.text||e.html){if("object"==typeof e.html)if(p.innerHTML="",0 in e.html)for(var w=0;w in e.html;w++)p.appendChild(e.html[w]);else p.appendChild(e.html);else p.innerHTML=e.html||e.text.split("\n").join("<br>");S(p)}else B(p);if(e.showCloseButton?S(g):B(g),t.className=i.modal,e.customClass&&C(t,e.customClass),B(t.querySelectorAll("."+i.icon)),e.type){var x=!1;for(var E in r)if(e.type===E){x=!0;break}if(!x)return console.error("SweetAlert2: Unknown alert type: "+e.type),!1;var A=t.querySelector("."+i.icon+"."+r[e.type]);switch(S(A),e.type){case"success":C(A,"animate"),C(A.querySelector(".tip"),"animate-success-tip"),C(A.querySelector(".long"),"animate-success-long");break;case"error":C(A,"animate-error-icon"),C(A.querySelector(".x-mark"),"animate-x-mark");break;case"warning":C(A,"pulse-warning")}}var L=t.querySelector("."+i.image);e.imageUrl?(L.setAttribute("src",e.imageUrl),S(L),e.imageWidth?L.setAttribute("width",e.imageWidth):L.removeAttribute("width"),e.imageHeight?L.setAttribute("height",e.imageHeight):L.removeAttribute("height"),L.className=i.image,e.imageClass&&C(L,e.imageClass)):B(L),e.showCancelButton?y.style.display="inline-block":B(y),e.showConfirmButton?q(m,"display"):B(m),e.showConfirmButton||e.showCancelButton?S(b):B(b),m.innerHTML=e.confirmButtonText,y.innerHTML=e.cancelButtonText,e.buttonsStyling&&(m.style.backgroundColor=e.confirmButtonColor,y.style.backgroundColor=e.cancelButtonColor),m.className=i.confirm,C(m,e.confirmButtonClass),y.className=i.cancel,C(y,e.cancelButtonClass),e.buttonsStyling?(C(m,"styled"),C(y,"styled")):(k(m,"styled"),k(y,"styled"),m.style.backgroundColor=m.style.borderLeftColor=m.style.borderRightColor="",y.style.backgroundColor=y.style.borderLeftColor=y.style.borderRightColor=""),e.animation===!0?k(t,"no-animation"):C(t,"no-animation")},U=function(e,t){var n=f();e?(P(m(),10),C(n,"show-swal2"),k(n,"hide-swal2")):S(m()),S(n),d.previousActiveElement=document.activeElement,null!==t&&"function"==typeof t&&t.call(this,n)},W=function(){var e=f();null!==e&&(e.style.marginTop=M(e))};return t.isVisible=function(){var e=f();return L(e)},t.queue=function(e,n){var o;return n&&(o={fork:function(e){n=e,this.next=e[0]},repeatCurrent:function(){n.unshift(this.current),this.next=this.current},insert:function(e){n.unshift(e),this.next=this.state},terminate:function(){n=[],this.next=""}}),new Promise(function(i,r){!function a(l,c){var s=null;u(e)?n&&n.length>0?(o.current=n[0],o.next=n.length>1?n[1]:"",o.alertNumber=l,n.shift(),s=e(o)):s=e(l):l<e.length&&(s=e[l]),s?t(s).then(function(){a(l+1,c)},function(e){r(e)}):i()}(0)})},t.close=t.closeModal=function(e){var t=f();k(t,"show-swal2"),C(t,"hide-swal2");var n=t.querySelector("."+i.icon+"."+r.success);k(n,"animate"),k(n.querySelector(".tip"),"animate-success-tip"),k(n.querySelector(".long"),"animate-success-long");var o=t.querySelector("."+i.icon+"."+r.error);k(o,"animate-error-icon"),k(o.querySelector(".x-mark"),"animate-x-mark");var a=t.querySelector("."+i.icon+"."+r.warning);k(a,"pulse-warning"),H();var l=t.getAttribute("data-mediaquery-id");N&&!g(t,"no-animation")?t.addEventListener(N,function c(){t.removeEventListener(N,c),g(t,"hide-swal2")&&(A(t),T(m(),0)),I(l)}):(A(t),A(m()),I(l)),null!==e&&"function"==typeof e&&e.call(this,t)},t.clickConfirm=function(){v().click()},t.clickCancel=function(){h().click()},t.init=function(){if("undefined"==typeof document)return void console.log("SweetAlert2 requires document to initialize");if(!document.getElementsByClassName(i.container).length){var e=document.createElement("div");e.className=i.container,e.innerHTML=l,document.body.appendChild(e);var n=f(),o=x(n,i.input),r=x(n,i.select),a=n.querySelector("#"+i.checkbox),c=x(n,i.textarea),s=x(n,i.image);o.oninput=function(){t.resetValidationError()},o.onkeyup=function(e){e.stopPropagation(),13===e.keyCode&&t.clickConfirm()},r.onchange=function(){t.resetValidationError()},a.onchange=function(){t.resetValidationError()},c.oninput=function(){t.resetValidationError()},s.onload=s.onerror=W,window.addEventListener("resize",W,!1)}},t.setDefaults=function(e){if(!e)throw new Error("userParams is required");if("object"!=typeof e)throw new Error("userParams has to be a object");c(j,e)},t.resetDefaults=function(){j=c({},a)},t.version="4.2.4",window.sweetAlert=window.swal=t,function(){"complete"===document.readyState||"interactive"===document.readyState&&document.body?t.init():document.addEventListener("DOMContentLoaded",function e(){document.removeEventListener("DOMContentLoaded",e,!1),t.init()},!1)}(),"function"==typeof Promise?Promise.prototype.done=Promise.prototype.done||function(){return this["catch"](function(){})}:console.warn("SweetAlert2: Please inlude Promise polyfill BEFORE including sweetalert2.js if IE10+ support needed."),t});
    [/code:1i92xix9]
    

    Thanks for the help. I use somethings that you made, i like it! I hope you like this plugin in this new version!

  • It is really what I was looking for! Thanks for sharing!

    I need multiples inputs, so I ended up adding, you could check and perhaps implement the "multiples inputs"?

    Thank you again! Excellent plugin!

    Hey, it's good to know that u like it. Yes i can. If i have some minutes today i will increment it!

  • I always give text objects some little more extra space for issues like those.

    Here's an example.

    Hum, i got it, but i need to be the exactly same size at run time...

  • I'm making a game for desktop and mobile and i have a text box, but i have some issue.

    The font size is not equals in mobile and desktop... just look at the example:

    Example1

    Example2

    If you look the word: RESPOSTA in the second example was cutted... how do i fix it?

  • Thanks. it works on mobile but the problem is that the keybord cover a part of the box...

    Have you solution to change the position of the box ?

    Hum, okay, i will see what i can do to fix it!

  • I made a plugin for a sweet alert in Construct 2.

    I hope you like it!

    [quote:2hjlthnv]

    V.2.1

    Add a new function: GetLastValueAt(index) - Now you can get a last value from the multiple input by an index.

    Name: SweetAlert2

    Version: 2.1

    Description: Add sweet alert to show in desktop or mobile.

    Tested: PC.

    Link: Plugin and Example

    [quote:2hjlthnv]

    V.2.0

    Change some structures.

    Change some things:

    ADD

    • Tags.
    • Multiple inputs alert.

    REMOVE

    • Remove input alert. If you want to use one input, use multiple with one input.

    Name: SweetAlert2

    Version: 2.0

    Description: Add sweet alert to show in desktop or mobile.

    Tested: PC.

    Link: Plugin and Example

  • Not working in Android

    I used in my Android... hum... Where did you test? Browser or PhoneGap?

  • woah what complications, how about this:

    x = Min + (random() * ((Max - Min) + 1))

    1st problem = minimum is 280, maximum 420.

    same thing applies to the 2nd problem, your minimum is -100, while your maximum is 0.

    same formula applies. - gives you a random number between your max and min, now if you want percentage of that number in your range you just apply this:

    perc = (x /(max+min))*100

    Hey, perfect! Thank you!

  • You always want a number between 0 and 1, and 0 to be the starting point, so add 100. That gives you 0 to 100. Divide by 100 to get the factor (0to1). Do your math, multiply by 100, then subtract 100 again, to move everything back into range.

    Thanks

  • Subtract 120, so the range is 0 to 280. 280 is your divisor, so the coordinate X, minus 120 divided by 280 is the factor (0 to 1). Or, the factor multiplied by 280 plus 120 gives you X. (Remember, you don't actually work in percentages. You want a factor from 0 to 1, where the percentage is just the factor times 100).

    Humm cool. i will use, but when i want:

    -100 = 0%

    0 = 100%

    what do i do?