Hello and thank you so much for your time.
I'm trying to build a quiz for my students, where the start button will go to a random frame out of 7. Then on the landing frame, question appears and the answer is selected via radiobutton then submitted via another button which goes to the next random question. This needs to happen 5 times so it will pick 5 questions randomly out of 7 and not repeating any previous question. If anyone can point me to right direction, it'll be much appreciated.
//Start Button - AS3 Frame #8157
startBtn.addEventListener(MouseEvent.CLICK, startQuiz);
function startQuiz(event:MouseEvent):void{
}
//Submit Button with score count - AS3 Frame #8158
var count:Number = 0;
var mygroup1:RadioButtonGroup = new RadioButtonGroup("group1");
q1a1.group = q1a2.group = q1a3.group = q1a4.group = q1a5.group = mygroup1;
b1.addEventListener(MouseEvent.CLICK, quizHandler1)
function quizHandler1(event:MouseEvent):void{
if(mygroup1.selection.label=="B) 12") {
count = count + 20;
scoreresult.text = (count).toString();
var number_array:Array = [8158,8159,8160,8161,8162,8163,8164 ];
var final_array:Array = [];
var count_selected:int = 5;
var i:int;
for(i = 0; i < count_selected; i++)
{
if(number_array.length == 0)
break;
else
final_array.push(number_array.splice(Math.floor(Math.random() * number_array.length), 1)[0]);
}
trace(final_array);
}
}
Since you don't want to repeat the same value, you need to know what values you've used already. There's a bunch of ways you could do this, but probably the most straight forward is to put all your values in an array, then remove a random value until the array is empty. Here's an example:
// create an array with all the frames you want to visit
var frames:Array = [0, 1, 2, 3, 4, 5, 6];
// when you want to pick one randomly, remove it using splice
var frame:int = frames.splice(Math.random() * frames.length, 1)[0];
// when the array is empty, you've visited every frame
if(frames.length == 0)
trace("all done!");
Here's the docs on splice(): http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#splice%28%29
Related
I copy some code and want to use it but I don't understand. this code is about How to randomly swap shapes' positions in specific locations. anyone can explain in simple how this code works?
function randomSort(a:*, b:*):Number
{
if (Math.random() < 0.5) return -1;
else return 1;
}
// Push 12 positions as new Point() in an array.
var positions:Array = [ new Point(12, 42), new Point(43, 56), new Point(43,87) ]; // ...add 12 positions
var mcs:Array = [mc1, mc2, mc3]; // ...add 12 mcs
positions.sort(randomSort);
// link randomized position to MovieClips:
for (var i:int = 0, l:int = positions.length; i < l, i++ ) {
var mc:MovieClip = mcs[i];
var point:Point = positions[i];
mc.x = point.x;
mc.y = point.y;
}
There are two lists: MovieClips and Points. The provided script randomizes one of the lists, so each MovieClip get a random Point out of the given ones.
The idea of random-sorting could be confusing a bit. The Array.sort() method is intended to organize Array's elements on given criteria, but if you give a random-based criteria instead, the elements are mixed with no predefined order.
The other (and probably more understandable) way to do the thing is to match a fixed MovieClip to a random Point, then remove matched pair from the respective lists, then proceed until there are items left.
var P:Array = [new Point(12, 42), new Point(43, 56), new Point(43,87)];
var M:Array = [mc1, mc2, mc3];
// Do while there are items to process.
while (M.length)
{
// Get the last MovieClip and remove it from the list.
var aMC:MovieClip = M.pop();
// Produce a random Point.
var anIndex:int = Math.random() * P.length;
var aPo:Point = P[anIndex];
// Remove the selected Point from its list.
P.splice(anIndex, 1);
// Move the selected MovieClip to the selected Point coordinates.
aMC.x = aPo.x;
aMC.y = aPo.y;
}
When my random word appears the user has to memorise it and click the correct corresponding image to it. I'm trying to write the code that runs if the user selects the right image. I have paired my words and images in my array. I'm just unsure as how to go about calling this function.
This is what I've attempted so far, but this isn't working. I'm new to actionscript3 so excuse the lack of knowledge as I am trying to teach myself.
All help greatly appreciated!!
This is one way you can do this:
See code comments
basket.visible = false;
//------ Home Button ------\\
backhome1btn.addEventListener(MouseEvent.CLICK, goback1Click);
function goback1Click(event:MouseEvent):void{
gotoAndStop("homepage");
}
//-------------------
var score:int = 0;
var items:Array = new Array(); //store all food items in array
var wordsToShow:Array = new Array(); //store all words to show in array - this is the array that will keep track of which has been asked (or rather not asked yet)
//to reduce redundant code, call this with each food item (below)
function initFoodItem(item:MovieClip, word:String):void {
item.word = word; //forget the array, just store the word on the image as a dynamic property
item.addEventListener(MouseEvent.CLICK, foodClicked);
items.push(item); //add to array
wordsToShow.push(item); //add to array
item.visible = false;
}
initFoodItem(oc, "Orange Juice");
initFoodItem(sand, "Sandwich");
//...repeat for all other food items
//now randmize the words to show array:
wordsToShow.sort(function(a,b):int {
return(Math.random() > .5) ? 1 : -1;
});
var curAnswer:MovieClip; //a var to store the current correct answer
//this does the next question per se
function displayWord():void {
if(wordsToShow.length < 1){
//they've all been asked
gotoAndPlay("gameoverpage");
return;
}
curAnswer = wordsToShow.pop(); //assigns the last item in the array to the cur asnwer, and pop also removes that item from the array (so it won't get asked again)
randomword.text = curAnswer.word; //assign the text to the word value of this item
randomword.visible = true;
remember.visible = true;
}
remember.addEventListener(MouseEvent.CLICK, readyClick);
//when you click your ready button
function readyClick(e:MouseEvent):void {
//we have an array of all items, let's loop through it and change them all to be visible
for (var i:int = 0; i < items.length; i++) {
//items[i].alpha = 1; //alpha values are 0 - 1 in AS3
items[i].visible = true; //use visible instead of alpha if just toggling visibility, it's more efficient
}
randomword.visible = false;
remember.visible = false;
bask.visible = true;
notepape.visible = false;
//! another reason to use visible instead of alpha = 0, is alpha = 0 items will still be clickable! visible = false items cannot be clicked.
}
function foodClicked(e:MouseEvent):void {
if (e.currentTarget == curAnswer) {
//if the current target (the item clicked) is the same item as what we stored in curAnswer, you answered correctly, so do this:
score += 10; //or however much you get for answering correctly
gotoAndStop("listpage"); //not sure what this does?
displayWord();
}else {
//wrong
gotoAndStop("gameoverpage");
}
}
I am creating a FlashCS4 Application that is in the style of a quiz. The questions are stored in a seperate text file and are called into the program through as3. This all works fine, however I am wondering how to randomise this data, but to make sure that the same question is not pulled twice.
For example, at the moment when I navigate to the questions page, I can display each part of the question (answer a,b,c,d + the question itself) and then this can be proceeded through 10times.
What I am trying to do is make these 10questions be randomly generated from the (27?) questions that I have in the text file.
import flash.geom.Transform;
import flash.geom.ColorTransform;
import fl.motion.Color;
var glowFilter:GlowFilter = new GlowFilter(0x000000, 1, 2, 2, 10, 3)
var questionNumber:int = 0;
var totalCorrect:int = 0;
var selectedAnswer:String;
var checkAnswer:String;
var correctAnswer:String;
var questionCount:int = 0;
var numberOfQuestions:int = 10;
txt_loggedin_Question.text = (userName);
//Displays the Question Number which is called in from XML
txt_QuestionNumber.text = ("Question #"+questions[questionNumber].ref +" of"+numberOfQuestions);
function CheckAnswer() {
if (selectedAnswer == correctAnswer){
totalCorrect = totalCorrect + 1;
trace("Correct");
}else{
totalCorrect = totalCorrect;
trace("incorrect");
}
questionNumber = questionNumber + 1;
questionCount = questionCount + 1;
//Random questions set up new variable questioncount
if (questionCount == numberOfQuestions){
trace("we are at 10");
gotoAndStop (1, "Result");
//STOP RUN NEXT SCENE
}else{
setUpQuestions()
}
There is a fair bit of code missing, but I am hoping that this covers the essentials, the file is called on a seperate page,
var questions:Array = [ ];
var request:URLRequest = new URLRequest("1.txt");
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void
{
// loader data - the questions.txt file
var data:String = event.target.data;
// split data by newline for each question
var lines:Array = data.split("\n");
// for every line
for each (var line:String in lines)
{
// split line by "||" delimiter
var question:Array = line.split("||");
// add the question to the questions array:
questions.push({ref: question[0],
question: question[1],
answerA: question[2],
answerB: question[3],
answerC: question[4],
answerD: question[5],
answerE: question[6],
correct: question[7],
answer: question[8],
type: question[9],
file: question[10]});
}
}
All of this works but the only thing I am struggling with is to randomly generate the questions from within the text file each time that the scene is loaded. Sorry for the long winded question.
Thanks for reading.
Here are the steps you need to do:
Get your list of questions as an array called "orderedQuestions".
Create a second empty array called "shuffledQuestions".
Create while loop:
while(orderedQuestions.length > 0){
shuffledQuestions.push(orderedQuestions.splice(Math.floor(Math.random()*orderedQuestions.length),1));
}
The loop removes one question at random from the sorted list and adds it to the shuffled list. When done your sorted list will be empty and the shuffledQuestions will have all of the questions added in a random order.
I've created a score system in my flash Quiz game where the faster you answer a question, the more points you get. At the moment however my tracer shows 'NAN' when I run my game. Can anybody see why this is?
var score:int = 0;
var count:int = 0;
var mTimer:Timer;
mTimer = new Timer(100, 70);
function processScore():void {
var count:int = mTimer.currentCount;
var score:int = score + (700 - (count * 10));
trace("score registered");
}
trace(aUserAnswers[numLoops] + " " + returnedNumber);
if(aUserAnswers[numLoops] == returnedNumber){
processScore();
}
returnedNumber is when a button is clicked, if the number matches that which is in the array, the question is correct.
Thank you
You're redeclaring count and score inside processScore(). That makes them local variables to the function, unrelated to the previous declared variables of the same name. This means that their values are lost when the function finishes and the previous variables are unchanged. I'm guessing that at some point you divide something by one of them and since you'll always be dividing by zero you get NAN.
I want to show some dynamic text and that is read from a php file within xml. Here in swf player i just set three button. Two button for text and one button for images. This all are working fine but the swf background covered by the white background. Here is the normal view and some of this code snippet
normal view image http://outshinebd.com/sm/Flash/normal_view.png http://outshinebd.com/sm/Flash/normal_view.png
Code :
btnItem.addEventListener(MouseEvent.CLICK, showItem);
//btnItem.addEventListener(Event:event, showItem);
function showItem(event:Event):void
{
imgLoader.alpha =0;
textLoader.alpha=0;
imgLoader3.alpha=0;
imgLoader4.alpha=0;
imgLoader5.alpha=0;
imgLoader2.alpha=0;
var itemLoader:URLLoader = new URLLoader();
itemLoader.load(new URLRequest("http://localhost/sm/flash/productdata"));
itemLoader.addEventListener(Event.COMPLETE , onItemLoad);
function onItemLoad(e:Event):void
{
var myLoader:XML = new XML(e.target.data);
xmlList = myLoader.children();
//this values array will hold all of the values we need to paginate
var values:Array = new Array();
//defining the 'i' variable so we can use it multiple times in for loops
var i:int;
for(i = 0; i < xmlList.length(); i++){
//textLoader.text = xmlList[i].elements("productname");
values[i] = xmlList[i].elements("productname");
}
//the current page we're on
var page:int = 1;
//the limit of values we need per page
var limit:int = 1;
//the current row that we're working on
var row:int = 0;
//The total pages that we have
var totalPages:int = Math.ceil(values.length/limit);
function createValues():void{
//this will always limit the amount to the limit variable
//but, "i" will act as a marker for which part of the values
//array that we're going to use
for(i=(page-1)*limit;i<page*limit;i++){
//checks if there actually is a value where "i" is
//otherwise we'll get some undefined movieclips
if(i < values.length){
var newValue:UILoader = new UILoader();
//sets the coordinates based on the row
newValue.x = 5;
newValue.y = 5+newValue.height*row;
//sets this guys value to the correct part of the array
textLoader.text = values[i];
//changing this guys name so we can reference it later
newValue.name = 'value'+row;
//adds the mc to stage
addChild(newValue);
//move onto the next row
row ++;
}
}
//then we reset the rows so we can use the variable again
row=0;
}
//function to remove the mc's
function removeValues():void{
//this loop will run once for each mc on stage
for(i=0;i<limit;i++){
//get the object in the current row and kill it!
removeChild(getChildByName('value'+i));
}
}
//next page and previous page functions
function prevPage(event:MouseEvent):void{
//checking if the current page isn't too low
if(page > 1){
//take away all of the objects so we can make new ones
removeValues();
page --;
createValues();
//then update the page text
//updateString();
}
}
function nextPage(event:MouseEvent):void{
//checking if the current page isn't too high
if(page < totalPages){
removeValues();
page ++;
createValues();
//updateString();
}
}
//then we place the movieclips onto the stage
createValues();
//adding listeners to the buttons
btnPrev.addEventListener(MouseEvent.CLICK, prevPage);
btnNext.addEventListener(MouseEvent.CLICK, nextPage);
}
}
And the view after clicking the button
after clicking image http://outshinebd.com/sm/Flash/after_click.png http://outshinebd.com/sm/Flash/after_click.png
I'm stacked with in the last two days. Please give me a solution.
It seems that you are using an input TextField or a TextTield with a border and a background, just turn them off:
textLoader.border=textLoader.background=false;