I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}
Related
This might be less difficult than I'm making it out to be, but I'm trying to make a Discord.JS bot command, that will take however many arguments I have. For example: !randomize 1,2,3,4,5,6,7,8,9,10
And the bot would respond with something like: "I have chosen: 4,2,7,3,9!" Any help?
Current attempt: Not exactly sure what I'm doing.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}`
`bot.on('message', async msg => {
if(msg.content === "!add") {
//message.member.user.tag
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var user = args[1];
//if(!args[1]) return msg.channel.send("Please specify an argument!");
if(nameList.includes(user)) {
msg.reply("You're already on the list.")
} else {
nameList.push(args[1]);
msg.channel.send(`${args[1]} has been added to the list!\n Current List:` + nameList);
}
}
if(msg.content === "!bonus") {
if(nameList.length === 0) {
msg.reply("Either the list is empty, or I'm not in the mood!");
} else {
shuffleArray(nameList);
var chosenOne = nameList.pop();
nameList = [];
msg.reply(chosenOne + ' has been chosen! Good luck!');
}
}
if(msg.content === "!list") {
if(nameList.length === 0) {
msg.channel.send("Either the list is empty, or I'm not in the mood!");
} else {
msg.channel.send('The current list:' + nameList);
}
});```
Here's some simple steps to select 5 random elements from an array...
Construct an array of possible selections. In this example I've used names for the first 10 letters of the alphabet. In your code, it'll be the command arguments or predefined nameList.
Make a new array to hold the elements picked.
At some point before #3, you should check to make sure the pool the user has provided is large enough to make 5 selections (Array.length).
Use a for loop to execute the next code multiple times.
Generate a random number representing the index of a selected element (Math.random(), Math.floor()/double NOT bitwise operator).
Push the selection into the array.
Remove the chosen element from the original pool (Array.splice()).
Return the results.
const pool = ['Albert', 'Bob', 'Charlie', 'David', 'Edward', 'Francis', 'George', 'Horacio', 'Ivan', 'Jim'];
const selected = [];
for (let i = 0; i < 5; i++) {
const num = ~~(Math.random() * pool.length);
selected.push(pool[num]);
pool.splice(num, 1);
}
console.log(`I have chosen: ${selected.join(', ')}`);
Take this example and manipulate it within your code to suit your purpose.
i wrote a code that should take a value from a cell and than convert it to the string and than into the array. its working fine. I can see the value of arr in Logs as an array with the input of the cell. For example, in the cell are " dog, cat " and tha arr value in Logs is [dog, cat].
But after i create this array, i would like to make a loop on it. And than i become in Logs, that arr is undefined. Can somebody help me please? im working on it for 2 days :(
Here is my code:
function animal (s,z){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange("SM");
var columnNumber = getColumnNumberOfSM(s);
var rowNumber = getRowNumberOfSM(z);
var colAction = columnNumber + 1;
var action = sheet.getRange(rowNumber, colAction, 1, 1).getValues();
var bar = action.toString();
var arr = [{}];
arr = bar.split(", ");
//return arr; // returns an array [dog, cat]
var foo = arr; // underfined
for (var i = 0; i <= foo.length; ++i) {
if (foo[i] == "dog") {
Logger.log(upload());
}
}
}
now i edit my code and its working fine,but only with "dog" but not with "cat"
function animal(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var action = sheet.getRange("C3").getValue();
var bar = action.toString();
var arr = bar.split(", ");
for (var i = 0; i <= arr.length; ++i) {
if (arr[i] == "dog") { // works
Logger.log(upload());
}
if (arr[i] == "cat") { // doesn't work
Logger.log(upload());
}
}
}
You don't need to initiate arr as blank you can directly initialize it as a result to split method , also one point I didn't get is why do you need to assign arr to foo? You can directly iterate through arr.length and perform the required operation.
Here's my working snippet.
var parts = path.split(",");
for (var i = 0; i < parts.length; i++) {
if (parts[i] == 'dog'){
Logger.log(parts[i]);
}
}
I have two code snippets . which one is better.
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
texts.reverse();
for(var index:int=0; index < texts.length; index++) {
trace(texts[index]);
}
Or
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
for( var index:int = texts.length; --index;) {
trace(texts[index]);
}
In former we have reverse operation and then print it and in latter we start from the length and start printing the array. The goal is to traverse the array from last.
I wrote a script which evaluates time elapsed between for loops. After running the application numerous of times, it appears that the 2nd for loop is fastest.
Averaging: 4.168000000000001 | 4.163000000000002 seconds respectively for 100 iterations of each for loop.
The script is as follows:
import flash.events.Event;
var _t:int = getTimer();
var dt:Number;
var started:Boolean = false;
var iteration:int = 0;
var timer1:Number = 0;
var timer2:Number = 0;
var numberOfIterations = 100;
var texts1:Array = new Array(1,2,3,4,5,6,7,8,9,10);
var texts2:Array = new Array(1,2,3,4,5,6,7,8,9,10);
texts2.reverse();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
addEventListener(Event.EXIT_FRAME, onExitFrame);
function onEnterFrame(e:Event):void {
var t:int = getTimer();
dt = (t - _t) * 0.001;
_t = t;
iteration++;
// small FLA load buffer
if(iteration == 50 && !started)
{
iteration = 0;
started = true;
}
}
function onExitFrame(e:Event):void {
if(started)
{
if(iteration < numberOfIterations)
{
for(var index:int=0; index < texts1.length; index++) {}
timer2 += dt;
trace("Time Elapsed Alg 2: " + (timer2));
}
else
{
for( var index:int = texts2.length; --index;) {}
timer1 += dt;
trace("Time Elapsed Alg 1: " + (timer1));
}
if(iteration == ((numberOfIterations*2)-1))
{
trace("________________________________________");
trace("FINAL: " + timer1 + " | " + timer2);
removeEventListener(Event.EXIT_FRAME, onExitFrame);
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
}
I am interested to see what others get using the following script, as it seems reliable on my PC as if I switch the for loop positions, the results still indicate that the fastest is:
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
for( var index:int = texts.length; --index;) {
trace(texts[index]);
}
The first one doesn't trace the last item in the array ie 1
The second one does.
So I say the second is better.
I'm curious though - what's the correct way to code the first one so that it traces all the items in the array?
In AS3 :
I've got a long text in an array.
var myHugeArray:Array = ["I love Apple
I have an Iphone
I eat a Banana
I'm John
I sell a computer
I sell an Apple
I love rock
I sell a car"];
How can I do to search a specifics words ? (like : show me sentences with the word "apple") --> output : "I love Apple" and "I sell an Apple"
Thanks,
EDIT
Here's what I did so far :
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE,completeHandler2);
function completeHandler2(event:Event):void{
loader5.removeEventListener(Event.COMPLETE,completeHandler2);
trace("Données envoyées");
feedbackText.text = "Données envoyées";
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE, complete);
}
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
feedbackText.text = "complete";
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
showList();
}
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
listItem.text = item.title;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
bar();
}
function bar(){
var arr: Array ;
searchBar.type = TextFieldType.INPUT;
var suggested:Array = new Array();
var textfields:Array = new Array();
searchBar.addEventListener(Event.CHANGE, suggest);
arr = str.split(",");
trace(arr);
function suggest(e:Event):void
{
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
for (var j:int = 0; j < arr.length; j++)
{
if (arr[j].indexOf(searchBar.text.toLowerCase()) != -1)
{
var term:TextField = new TextField();
term.width = 360;
term.height = 24;
term.x = 18;
term.y = (24 * suggested.length) + 135;
term.border = true;
term.borderColor = 0x353535;
term.background = true;
term.backgroundColor = 0xFF9900;
term.textColor = 0x4C311D;
term.defaultTextFormat = format;
addChild(term);
suggested.push(arr[j]);
term.text = arr[j];
}
}
function showList():void {
list.visible = true;
}
function showDetails(item:Object):void {
titleTxt.htmlText = item.title;
detailsTxt.htmlText = "<U>prix:</U> " + item.prix + " xpf"+ "\n\n<U>Description:</U> " + "\n"+item.theDescription + "\n"+"\n\n<U>Contact:</U> " + item.mail+ "\n"+item.phone;
}
So, my AS3 code go search for PHP variable with loader5.
All the items found by the php are put in an Array (products).
And a list of all the products is created. (createListItem).
If I click on an item, it show me some details (price, description..etc). It's the function showDetails();
Know I've created a searchBar (autocomplete).
An array is created (arr) that split the string (str).
Then it does what it does to search through the array.
Problems :
1/ Weirdly, not all the words are displayed in my searchBar. Some words are working, other not.
2/ How can I do to call the function showDetails() when the user click on the suggest term ? (term.addEventListener(MouseEvent.CLICK, showDetails)); doesn't work as the terms is not item.title. ShowDetails is showing details of item.title. (so how can I say that term = item.title ?)
3/ Do you see a way simpler than that ?
Your myHugeArray is just string, so split() it with \n', you got the
ret array for example, then find the one contains the word you search, like "apple", using indexof() in each string
You need to split the string into an array then search each item
check this out
https://stackoverflow.com/a/34842518/3623547
I have been using this java code to call a random html page from a list of 49 on a set timer (or upon page refresh). I would like to convert it so that a cookie - or something else - saves the pages that have already been shown so that upon refresh the user always receives a new page, until the list is finished, at which point the cookie is emptied/deleted.
I found this code for a cookie image array. Could I use it with this? A variant of this also appears here. Apologies, my coding is pretty poor. Any advice appreciated:
<script type="text/javascript">
var sites = [
"name1.html",
"name2.html",
"name3.html",
"name...etc.html",
"name49.html",
]
$(document).ready(function() {
newPage();
});
function newPage()
{
setTimeout(newPage, 60000);
var min = 0;
var max = 48;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
$('#target').attr('src',sites[num]);
}
</script>
var numSites = 49;
var seen = new Array(numSites);
$(document).ready(function() {
var cookie = unescape(getCookie("seen"));
seen = cookie ? cookie.split(',') : seen;
setTimeout(gotoNext, 60000);
});
function gotoNext() {
var num = getRandom();
var count = 0;
while (seen[num] == 1) {
num++;
if (num >= numSites) {
num = 0;
count++;
if (count > 1) {
resetSeen();
num = getRandom();
}
}
}
seen[num] = 1;
setCookie("seen", escape(seen.join(',')), 365);
window.location = "name" + num + ".html";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length, c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function resetSeen() {
for (var i=0; i<numSites; i++) {
seen[i] = "";
}
}
function getRandom() {
return Math.ceil(Math.random() * numSites);
}
It looks like you're using jQuery so I'll recommend using a jquery plugin for managing cookies much more neatly.
Copy & paste the contents of this URL to a new js file on your server and include it after the jquery file: https://raw.githubusercontent.com/carhartl/jquery-cookie/master/jquery.cookie.js
Or you could possibly use the get/set cookie functions from the other answer you mention.
The main thing to remember is that the cookie is stored as a string so you'll be join()ing and split()ing the array.
The other thing to note is that because we want a random item from the items we haven't visited yet it's more efficient to keep track of those rather than the ones we have visited.
What this means is we always choose a random item from what's left instead of looping over everything and checking each time if we've been there already as that would get very inefficient.
var sites = [ 'name1.html', 'name2.html', 'name3.html', ...etc... ],
unvisited = sites.slice(0); // .slice(0) clones the array
// if the cookie has a value then make it into the unvisited array
if ( $.cookie( 'unvisited' ) )
unvisited = $.cookie( 'unvisited' ).split( ',' );
$(document).ready(function() {
newPage();
});
function newPage() {
setTimeout( newPage, 60000 );
// check if the unvisited array needs resetting
if ( unvisited.length == 0 ) {
unvisited = sites.slice(0);
$.removeCookie( 'unvisited' );
}
// get a new index from the unvisited array
var num = Math.floor( Math.random() * unvisited.length );
// remove the item from the array and save the cookie
var site = unvisited.splice( num, 1 )[ 0 ];
// save the unvisited array minus the site we just spliced out
$.cookie( 'unvisited', unvisited.join( ',' ) );
$( '#target' ).attr( 'src', site );
}