Actionscript Take Input and compare to an Int - string

I'm trying to take an input from the user using an Input Text field, this data is a number. I want the user to input the correct number (in this case 1) and then print out yay.
However, i can't get it to work. Any help is much appreciated.
I assume the issue is to do with comparing an int and a string, but honestly im not sure anymore.
import flash.events.MouseEvent;
import flash.text.TextField;
var dayVar:String = dayInput.text;
var dayNum:Number = Number(dayVar);
stop();
button3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void
{
if(dayNum == 1) {
trace("yay");
} else {
trace("nay");
}
}

You will have to update your dayVal and/or dayNum after user has given input. So in this minimal case you can simply:
function mouseDownHandler3(event:MouseEvent):void{
if(Number(dayInput.text)==1) {
trace("yay");
} else {
trace("nay");
}
}
Other possibilites would be listening Event.CHANGE for the text input, or KeyboardEvent to update your variables, but in this case the MouseEvent handler does the job easier.

You can use restriction property for text field input like this:
dayInput.restrict = "0-9";
This should omit to type only digits.

Related

How to write a string regix in typescript take 'href' value?

I need to take 'href'(tag link location value) value from following pattern html text. need some expert help to do it using typescript
String Text one
"<html><body>docker_command.txt </body></html>"
String Text Two
"<html><body>https://www.facebook.com/ </body></html>"
Something like this?
const a = '"<html><body>docker_command.txt </body></html>"';
const b = '"<html><body>https://www.facebook.com/ </body></html>"';
function getHref(html: string): string|null {
if (!html) {
return null;
}
return html.match(/ href=("|')([^'"]*?)('|")/i)[2];
}
console.log(getHref(a));
console.log(getHref(b));

Angular 5 custom pipe

I am new to Angular and facing this issue.
I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.
This is my code:
my-component.ts
this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
var convert = String.fromCharCode(chars1[k]); // convert into base64
this.imgIn = this.imgIn + convert;
}
this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);
Has anyone else experienced this, please help me?
I highly suggest you to take a look at the docs, it's really easy to understand and gives you a good amount of information that you might need to create your custom pipe, Here's the link to the official docs: Angular - Pipes
If your snippet of code already does what you want, then moving to a custom pipe is pretty straight forward. You just need to bind your array of decimal and use a pipe that converts it exactly like you do now. Something like:
Pipe:
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({
name: 'base64'
})
export class Base64Pipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any,){
let imgIn="";
for (var k = 0; k < value.length; k++) {
var convert = String.fromCharCode(value[k]); // convert into base64
imgIn += convert;
}
let base64Url =this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + imgIn);
return base64Url;
}
}
And you'd use it like so: [src]="yourDecimalCodeArray | base64"
Here's a Stackblitz to illustrate.
Keep in mind that using this.sanitizer.bypassSecurityTrustResourceUrl mean you have to bind safely (Safe value must use [property]=binding after bypass security with DomSanitizer).
Hope this helps.

If statements not working with JSON array

I have a JSON file of 2 discord client IDs `{
{
"premium": [
"a random string of numbers that is a client id",
"a random string of numbers that is a client id"
]
}
I have tried to access these client IDs to do things in the program using a for loop + if statement:
for(i in premium.premium){
if(premium.premium[i] === msg.author.id){
//do some stuff
}else{
//do some stuff
When the program is ran, it runs the for loop and goes to the else first and runs the code in there (not supposed to happen), then runs the code in the if twice. But there are only 2 client IDs and the for loop has ran 3 times, and the first time it runs it goes instantly to the else even though the person who sent the message has their client ID in the JSON file.
How can I fix this? Any help is greatly appreciated.
You may want to add a return statement within your for loop. Otherwise, the loop will continue running until a condition has been met, or it has nothing else to loop over. See the documentation on for loops here.
For example, here it is without return statements:
const json = {
"premium": [
"aaa-1",
"bbb-1"
]
}
for (i in json.premium) {
if (json.premium[i] === "aaa-1") {
console.log("this is aaa-1!!!!")
} else {
console.log("this is not what you're looking for-1...")
}
}
And here it is with return statements:
const json = {
"premium": [
"aaa-2",
"bbb-2"
]
}
function loopOverJson() {
for (i in json.premium) {
if (json.premium[i] === "aaa-2") {
console.log("this is aaa-2!!!!")
return
} else {
console.log("this is not what you're looking for-2...")
return
}
}
}
loopOverJson()
Note: without wrapping the above in a function, the console will show: "Syntax Error: Illegal return statement."
for(i in premium.premium){
if(premium.premium[i] === msg.author.id){
//do some stuff
} else{
//do some stuff
}
}
1) It will loop through all your premium.premium entries. If there are 3 entries it will execute three times. You could use a break statement if you want to exit the loop once a match is found.
2) You should check the type of your msg.author.id. Since you are using the strict comparison operator === it will evaluate to false if your msg.author.id is an integer since you are comparing to a string (based on your provided json).
Use implicit casting: if (premium.premium[i] == msg.author.id)
Use explicit casting: if (premium.premium[i] === String(msg.author.id))
The really fun and easy way to solve problems like this is to use the built-in Array methods like map, reduce or filter. Then you don't have to worry about your iterator values.
eg.
const doSomethingAuthorRelated = (el) => console.log(el, 'whoohoo!');
const authors = premiums
.filter((el) => el === msg.author.id)
.map(doSomethingAuthorRelated);
As John Lonowski points out in the comment link, using for ... in for JavaScript arrays is not reliable, because its designed to iterate over Object properties, so you can't be really sure what its iterating on, unless you've clearly defined the data and are working in an environment where you know no other library has mucked with the Array object.

PHP-like string parsing

I'm writing a mini-console of sorts and I'm trying to figure out how to extract things from a link. For example, in PHP this is a request variable
so:
http://somelink.com/somephp.php?variable1=10&variable2=20
Then PHP figures out the url parameters and assigns them to a variable.
How would I parse something like this in Swift?
So, given the string I'd want to take: variable1=10 and variable2=20 etc, is there a simple way to do this? I tried googling around but didn't really know what I was searching for.
I have a really horrible hacky way of doing this but it's not really extendable.
You’d be wanting NSURLComponents:
import Foundation
let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)
components?.queryItems?.first?.name // Optional("variable1")
components?.queryItems?.first?.value // Optional("10")
You might find it helpful to add a subscript operator for the query items:
extension NSURLComponents {
subscript(queryItemName: String) -> String? {
// of course, if you do this a lot,
// cache it in a dictionary instead
for item in self.queryItems ?? [] {
if item.name == queryItemName {
return item.value
}
}
return nil
}
}
if let components = NSURLComponents(string: urlStr) {
components["variable1"] ?? "No value"
}

Cocos2dx 3.4 - manipulating user input

I am working on a breakout-type game using Cocos2dx.
I need to make a highscore table. After the game is finished, I'd like to display a page, where player types his username into text field.
I don't know how to add the user input into variable, so I can manipulate it later (mainly saving along with score to display it on the selected scene).
What is the simplest way of doing so?
Approach One:
If you just need to handle keyboard as key-event, It's as easy as these below lines of code:
HelloWorld::init()
{
...
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_UP_ARROW: /*Jump maybe*/ break;
case EventKeyboard::KeyCode::KEY_DOWN_ARROW: /*Crouch maybe*/ break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: /*Move Right maybe*/ break;
case EventKeyboard::KeyCode::KEY_LEFT_ARROW: /*Move Left maybe*/ break;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
...
return true;
}
I think it's clear enough not to need any extra description.
Approach Two: if you need an input box that user/player can enter string with keyboard and you get what is entered, I recommend to use TextField which is available in cocos2d v3 ( and with some difficulty in v2) and has a full functionality. You can create and initial one of them as:
auto textField = cocos2d::ui::TextField::create("hint: enter here","Arial" , 30);
textField->setTextHorizontalAlignment(cocos2d::TextHAlignment::CENTER);
textField->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
textField->setColor(Color3B(100,100,100));
textField->setMaxLength(10);
textField->setMaxLengthEnabled(true);
textField->setTouchAreaEnabled(true);
textField->setTouchSize(Size(200,400));
textField->setPosition(...);
textField->addEventListener(CC_CALLBACK_2(HelloWorld::textFieldEvent, this));
this->addChild(textField, 10);
You can get entered data any time with std::string enteredData= textField->getString();
You can also do something when user entering text with two event as :
void HelloWorld::textFieldEvent(Ref *pSender, cocos2d::ui::TextField::EventType type)
{
switch (type)
{
case cocos2d::ui::TextField::EventType::ATTACH_WITH_IME:
{
textField->setColor(Color3B::BLACK);
// or whatever elese
break;
}
case cocos2d::ui::TextField::EventType::DETACH_WITH_IME:
{
textField->setColor(Color3B(100,100,100));
// or whatever elese
break;
}
}
}
Enjoy !

Resources