Flash AS3 trivia game incorrect answer graphic needs to appear on stage in 3 locations - actionscript-3

I'm creating a trivia game in which a user answers a certain number of questions per round and if they get 3 wrong they fail the round. When a question is marked as incorrect an x is placed in a box from left to right, each x goes into a box in their own location.
I'm having trouble getting the x's to go to their location, based on the questions answered incorrectly.
Here is an image of the game image
Here is the code I'm using:
var questions:Array=['"I look like a dangling parsnip in this!" she cried. "I will never __________ these jeans!',
"Tell the freckled parrot to put his car in __________.",
"When purchasing a buttercream trowel, always choose one made of __________.",
"Everybody has a cracked snowflake. The question is, __________ one is yours? ",
"Standing at the dock, the loopy basket watched the cruise ship set __________ without him. ",];
var answers:Array=[ ["wear","where"], ["idle","idol"], ["steel","steal"] ,[ "which","witch"] ,[ "sail","sale"] ];
var qno=0;var rnd1; var rnd2;
tick.visible=false;cross1.visible=false;
var right_answers=0;var wrong_answers=0;
shade1.buttonMode = true;
shade1.useHandCursor = true;
shade2.buttonMode = true;
shade2.useHandCursor = true;
function change_question(){
if(tick.visible){right_answers++;}
if(cross1.visible){wrong_answers++;}
if(qno==questions.length){gotoAndPlay(60);}else{
tick.visible=false;cross1.visible=false;
rnd1=Math.ceil(Math.random()*3);
rnd2=Math.ceil(Math.random()*questions.length)-1;
q.text=questions[rnd2];
if(questions[rnd2]=="x"){change_question();}
questions[rnd2]="x";
enable_disable(1);
if(rnd1==1){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==2){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==3){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==4){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==5){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
}}
function enable_disable(a){
if(a==0){shade1.mouseEnabled=false;shade2.mouseEnabled=false;}
if(a==1){shade1.mouseEnabled=true;shade2.mouseEnabled=true;}}
change_question();
shade1.addEventListener(MouseEvent.CLICK, ButtonAction2);
shade2.addEventListener(MouseEvent.CLICK, ButtonAction3);
function ButtonAction2(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==1) {tick.visible=true;tick.y=shade1.y}else{cross1.visible=true;cross1.y=shade1.y}
//qno++;change_question();
}
function ButtonAction3(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==2){tick.visible=true;tick.y=shade2.y}else{cross1.visible=true;cross1.y=428.55}
//qno++;change_question();
}
Any help is much appreciated, please let me know if more information is needed. Thank you in advance.

Related

How can I put every sentence of a text in a row of a table next to its translation in a Google Document?

I want to put a text to be translated in a Google Doc so that every sentence is in its own row of a table. In each row of the next column is the corresponding, machine-translated sentence. Finally, there is a third blank column where I will write my own translation for each sentence.
Like so
What would some command line code look like for accessing the specific Google Doc, inserting a table, splitting the text on each sentence, and then writing each sentence to a row of the table?
I am aware of Google API, but I have struggled with authentication problems so far. If someone can sketch out a general outline of what my script should look like, hopefully I can fill in the details.
I am trying my best to meet Stack Overflow's post guidelines, so if the question is not a good one, I'm happy to reformulate it. My question is multi-part, so I prefer to ask the broader version first, before breaking it into smaller aspects.
Try this:
function translate() {
var doc = DocumentApp.openById('documentID');
var body = doc.getBody();
var str = "An elephant is the biggest living animal on land. It is quite huge in size. It is usually black or grey in colour. Elephants have four legs, a long trunk and two white tusks near their trunk. Apart from this, they have two big ears and a short tail. Elephants are vegetarian. They eat all kinds of plants especially bananas. They are quite social, intelligent and useful animals. They are used to carry logs of wood from one place to another. They are good swimmers.";
//Split paragraph into sentences.
var result = str.match( /[^\.!\?]+[\.!\?]+/g ).map(str => str.trim());;
var translated = [];
result.forEach(res => {
translated.push(LanguageApp.translate(res, 'en', 'es'));
})
var table = body.appendTable();
for(var i = 0; i <= result.length; i++){
var tr = table.appendTableRow();
if(i == 0){
tr.appendTableCell("Origin");
tr.appendTableCell("Translated");
tr.appendTableCell("");
}else{
tr.appendTableCell(result[i-1]);
tr.appendTableCell(translated[i-1]);
tr.appendTableCell("");
}
}
}
Output:
References:
translate(text, sourceLanguage, targetLanguage)
appendTableRow()
appendTableCell()

Sentence-count function not returning total count

So i've been trying to create a sentence-count function which will cycle through the following 'story':
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
And I realise the problem I'm having but I cannot find a way around this. Basically I want my code to return a the total sCount below but seeing as I've returned my sCount after my loop, it's only adding and returning the one count as a total:
const sentenceTotal = (word) => {
let sCount = 0;
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
return sCount;
};
// console.log(sentenceTotal(story)) returns '1'.
I've tried multiple ways around this, such as returning sentenceTotal(word) instead of sCount but console.log will just log the function name.
I can make it return the correct sCount total if I remove the function element of it, but that's not what I want.
I don't see any loop or iterator which would go through story to count the number of occurrences of ., ?, or !.
Having recently tackled "counting sentences" myself I know it is a non-trivial problem with many edge cases.
For a simple use-case though you can use split and a regular expression;
story.split(/[?!.]/).length
So you could wrap that in your function like so:
const sentenceTotal = (word) => {
return word.split(/[?.!]/).length
};
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
sentenceTotal(story)
=> 13
There a several strange things about you question so I'll do it in 3 steps :
First step : The syntax.
What you wrote is the assignement to a const of an anonymous variable. So what it does is :
Create a const name 'sentenceCount'
To this const, assign the anonymous function (words) => {...}
Now you have this : sentenceCount(words){...}
And that's all. Because what you wrote : ()=>{} is not the calling of a function, but the declaration of an anonym function, you should read this : https://www.w3schools.com/js/js_function_definition.asp
If you want a global total, you must have a global total variable(not constant) so that the total isn't lost. So :
let sCount = 0; //<-- have sCount as a global variable not a const
function isEndOfSentence(word) {
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
};
If you are forbidden from using a global variable (and it's best to not do so), then you have to register the total as a return of your function and store the total in the calling 'CountWords(sentence)' function.
function isEndOfSentence(words) {...}
callingFunction(){
//decalaration
let total;
//...inside your loop
total += isEndOfSentence(currentWord)
}
The algorithm
Can you provide more context as how you use you function ?
If your goal is to count the words until there is a delimiter to mark the end of a sentence, your function will not be of great usage .
As it is written, your function will only ever be able to return 0 or 1. As it does the following :
The function is called.
It create a var called sCount and set it to 0
It increment or not sCount
It return sCount so 1 or 0
It's basically a 'isEndOfSentence' function that would return a boolean. It's usage should be in an algorithm like :
// var totalSentence = 0
// for each word
// if(isEndOfSentence(word))
// totalSentence + totalSentence = 1
// endfor
Also this comes back to just counting the punctuation to count the number of sentence.
The quick and small solution
Also I tried specifically to keep the program in an algorithm explicit form since I guess that's what you're dealing with.
But I feel that you wanted to write something small and with as little characters as possible so for your information, there are faster way of doing this with a tool called regex and the native JS 'split(separator)' function of a string.
A regex is a description of a string that it can match to and when used can return those match. And it can be used in JS to split a string:
story.split(/[?!.]/) //<-- will return an array of the sentences of your story.
story.split(/[?!.]/).length //<-- will return the number of element of the array of the sentences of your story, so the sentence count
That does what you wanted but with one line of code. But If you want to be smart about you problem, remember that I said
Also this comes back to just counting the punctuation to count the number of sentence.
So we'll just do that right ?
story.match(/(\.\.\.)|[.?!]/g).length
Have fun here ;) : https://regexr.com/
I hope that helps you ! Good luck !

How to wait, then do something, in the GameScene

SKAction has waiting for duration abilities, for a period of time on a node. And seems to perform actions on nodes. Like moveTo, etc.
If I don't want that, rather I'd prefer to call functions within GameScene after a period of time, how do I do that with SpriteKit in the GameScene, not on a Sprite or other Node?
Are SKActions the way to do this? The only way to do this?
Yes. This question IS that ridiculously simple. I lack the heuristics and terminology to find an answer. Just keep looping around on how SKAction waits are calls on SKSprites for things like scale, rotation, etc, after time. Which isn't want I want/need.
Update:
Desired outcome, inside GameScene
doSetupStuff() // does some stuff...
waitForAWhile() // somehow wait, perhaps do somethings in here, while waiting
doSomethingElse() // does this after the waitForAWhile has waited
UPDATE 2:
What I think happens, again, inside didMove(to view...)
func wait(){
let timeToPause = SKAction.wait(forDuration: 3)
run(timeToPause)
}
let wontwait = SKAction.wait(forDuration: 3)
run(wontwait)
thisFunction(willnot: WAIT"it starts immediately")
wait()
thisFunction(forcedToWait: "for wait()'s nested action to complete")
UPDATE 3:
Found a way to get the delay without using SKActions. It's a little crude and brutal, but makes more sense to me than SKActions, so far:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
print("I waited ten seconds before printing this!")
}
An option, as you cited, is to manage this externally. The way I typically manage this sort of thing is to have an externally run update cycle. One that
To drive this updater, you could use either CADisplayLink (which is what I use right now with my OpenGL renderer) or a dispatch source timer (which I have used with my SpriteKit engine). When you use an updated, you want to calculate the delta time. The tick handler could look something like:
func tickHandler() {
let currTime = NSDate().timeIntervalSince1970
let dt = lastTime - currTime // lastTime is a data member of the class
// Call all updaters here, pretend "updater" is a known updater class
updater.update(dt)
}
And updater's update method would look something like:
func update(deltaTime:NSTimeInterval) {
// Do your magic
}
I typically have a main overall updater running independent of what people are calling scenes. Example usage would be something like having an attract mode like in old school arcade games. There they show title screen, sample game play, high scores, rinse and repeat. Scenes would be title, game play, high score. Here you can your main updater manage the time and coordinate the construction/destruction/switching of the scenes. Note this implies having an overall scene manager (which is actually quite handy to have).
For your case, you could use this updater to drive the GameScene updater. It's updater could look something like:
func update(deltaTime:NSTimeInterval) {
switch state {
case .SetupState:
// noop?
println("I'm in setup") // Shown just so you can see there is a setup state
case .WaitState:
waitTime += deltaTime
if waitTime >= kWaitTime {
// Do whats you gots to do
doSomethingElse()
state = .NextState
}
case .NextState:
// blah blah blah blah
}
}
So the flow to do this call path from your driver (CADisplayLink or dispatch source) would be something like:
tickHandler -> master updater -> game scene updater
Some will def find this is perhaps a little heavy handed. I, on the other hand, find this very helpful. While there is obviously some time management and the loss of being able to fire and forget, it can help provide more control for orchestrating pieces, as well as arbitrarily changing state without having to worry about killing already queued actions. There is also nothing that says you still cannot mix SKAction. When I did use SpriteKit, I did all my updating this way along with some dispatched items. I only used SKAction to update hierarchy. Keep in mind that I used my own animation and physics system. So at least for me I had a lot less dependency on SpriteKit (it effectively was just a renderer for me).
Note you have to have your own means to handle pause and coming to foreground where your timer will need to be resynced (you only need to worry about tickHandler). Breakpoints also will cause time jumps.
You can use below function
#define ANIM_TIME 2
SKAction *customACtion = [SKAction customActionWithDuration: ANIM_TIME actionBlock:^(SKNode *node, CGFloat elapsedTime) {
// Do Something Here
}];
Another way to make something happen after a certain period of time is to make use of the 'current time' parm passed to update(). The following code will spawn a boss at intervals ranging from 20 to 30 seconds.
In your property definitions:
var timeOfLastBoss: CFTimeInterval = -1 //Indicate no boss yet
var timePerBoss = CFTimeInterval()
.
.
.
didMoveToView() {
...
timePerBoss = CFTimeInterval(Int.random(20...30))
'''
}
.
.
.
func update(currentTime: CFTimeInterval) {
...
spawnBossForUpdate(currentTime)
...
}
'
'
'
func spawnBossForUpdate(currentTime : CFTimeInterval) {
if ( timeOfLastBoss == -1 ) {timeOfLastBoss = currentTime}
if (currentTime - timeOfLastBoss < timePerBoss) {return}
// Rest of 'spawnBoss code
self.timePerBoss = CFTimeInterval(Int.random(20...30))
self.timeOfLastBoss = currentTime
}
One way, using SKActions, in Swift 3.0, looks like this:
DEFINE: aPatientlyWaitingFunction() at the top level of
GameScene class.
To cause a delay to happen before calling the above function, inside
didMove(to view...)
three ways I've found to do this using Actions:
All three ways seem to accomplish the exact same thing:
let timeToWait: TimeInterval = 3 // is seconds in SKAction thinking time
let waitSomeTime = SKAction.wait(forDuration: timeToWait)
// 1st way __________________________________________
// with a completion handler, the function can be called after Action
run(waitSomeTime) {self.aPatientlyWaitingFunction()}
// 2nd way __________________________________________
// as a completion to be done after action, in the run invocation:
run(waitSomeTime, completion: aPatientlyWaitingFunction)
// 3rd way __________________________________________
// alternatively, as part of a sequence of actions...
// Create a sequence, by making a run action from waitSomeTime and...
let thenDoThis = SKAction.run(aPatientlyWaitingFunction)
// then activate sequence, which does one action, then the next
run(SKAction.sequence([waitSomeTime, thenDoThis]))
// OR... for something different ____________________
////////////////////////////////////////////////////////
DispatchQueue.main.asyncAfter(deadline: .now() + timeToWait) {
self.aPatientlyWaitingFunction()
print("DispatchQueue waited for 3 seconds")
}

how to connect a number variable to dynamic text in actionscript 3.0?

i know this might be simple but i have been searching everywhere for a fix but i just cannot find it!
i want to make something like a health #, so when you press whatever button the dynamic text # will go up or down. on my test project i have two layers, the first with the following code
var hp:Number = 100;
health.text = String hp;
hp being the variable, and health being the dynamic text. then i have the next layer with the button with:
function button(e:MouseEvent):void
{
hp -= 10;
}
without that second chunk of code, the dynamic text will appear, but once that is added it will disappear and the button is function-less.
how do i make this work??? once again sorry if this is a dumb question, i'm just very stumped.
The accepted answer is good, but I wanted to point out that your original code was actually very close to being correct, you just needed parenthesis:
health.text = String(hp);
For most objects String(object) and object.toString() has the same effect, except that object.toString() throws an error if object is null (which could be desirable or undesirable, depending on what you expect it to do).
This is not correct:
health.text = String hp;
use:
health.text = hp.toString();
and:
function button(e:MouseEvent):void
{
hp -= 10;
health.text = hp.toString();
}

New to ActionScript3, Making calculator and stuck

first time here on stackoverflow and first time scripting in flashCS6.
ill get down to it - the only lang ive done is html and a bit of css. I tried learning java, but gave up since i realised im making flash games so might as well just do AS3. Its pretty similar and not at all at the same time.
As my first original program (i did a tutorial of pong from a website before, got to know a bit about functions and event handlers[http://as3gametuts.com/2011/03/19/pong-1/]), im trying to create a calculator, and what want to know is how i can return the values from two input fields, put them into a logic calculator (say input a is 1 and input b is 2, and there are four functions, each attached to an event listener for the 4 mathematical operations, and i press addition so the calculator goes 2+1=3)
main question here, how do i get the outut text field to display the answer. In java i just used system.out.println(inputA + inputB).
Here i tried to do out.text = ( a + b) (where out is output , a is input and b is input 2)
Here is the code i have so far:
a is input 1, b is input 2
Out is output
and mul, add, sub and div are symbols containing dynamic test fields with instance names adn, sub, mul and div respectively. The symbol instances are the same as the test instances) Ex: i have a text field that says addition, its instance name is adn, then i convert it to a symbol and make its instance name adn as well.
a.text.restrict = "0-9";
b.text.restrict = "0-9";
mul.addEventListener(MouseEvent.CLICK, output);
adn.addEventListener(MouseEvent.CLICK, addition);
sub.addEventListener(MouseEvent.CLICK, subtraction);
div.addEventListener(MouseEvent.CLICK, division);
a.addEventListener(TextInput,input);
b.addEventListener(TextInput,input);
function output ():void
{
out.text=("test to see if output works")
}
function input (e:TextInput)
{
}
function multiplication (e:MouseEvent)
{
}
function addition (e:MouseEvent)
{
}
function subtraction (e:MouseEvent)
{
}
function division (e:MouseEvent)
{
}
thanks guys, and cheers! Also, ill appreciate if anyone can link me to a good video or text tutorial (series) for AS3 introduction. My main focus is to be making PC games and not apps, so keep that in mind.
Check This Out
Also, don't forget to convert value to string, that may be neccessary:
out.text = String(a + b);
Since a text field will give you the input typecast as a string you will need to type cast them to type Number or type int before you can do any kind of math function on them.
And if you want to create a more complex calculator I would suggest you read up on the Math class
function subtraction (e:MouseEvent)
{
var result:Number = Number(a.text) - Number(b.text)
out.text = String(result)
}