AS3 Air High Score Help

Hello everyone, i just came here to ask how to add a high score feature in as3 for android and ios. I want it to display on the main menu of the game. Heres my main file (game.as). I am wondering how i would implement it into that? (as you can see i have tried but failed...) please point me in the right direction on this one I want it to display in a dynamic text field called "bestScore" in a movieclip called "HighScore" the instance name of HighScore is bestScore so idk lol. Im new to as3... My score is in a movieclip called "Score" and the dynamic text field is "scoreDisplay" and the instance name is "gameScore" If that helps. Heres my game.as:
[as]
package
          import flash.display.MovieClip;
          import flash.utils.Timer;
          import flash.events.TimerEvent;
          import flash.ui.Mouse;
          import flash.events.KeyboardEvent;
          import flash.ui.Keyboard;
          import flash.events.Event;
          import flash.media.SoundChannel;
          import flash.net.SharedObject;
          public class Game extends MovieClip
                    static var ship:MovieClip;
                    static var healthMeter:HealthMeter;
                    static var score:Score;
                    static var highScore:HighScore;
                    static var enemyShipTimer:Timer;
                    static var gameOverMenu:GameOverMenu;
                    static var startMenu:StartMenu;
                    static var startButton:StartButton;
                    static var pauseButton:PauseButton;
                    static var playButton:PlayButton;
                    static var mainMenuButton:MainMenuButton;
                    public var currentValue:Number;
                    public var sharedObject:SharedObject;
                    public function Game()
                              Key.initialize(stage);
                              ship = new Ship();
                              healthMeter = new HealthMeter();
                              var score:Score = new Score();
                              var highScore:HighScore = new HighScore();
                              addChild(score);
                              addChild(highScore);
                              gameScore.visible = false;
                              bestScore.visible = true;
                              healthMeter.x = 2.5;
                              healthMeter.y = 576;
                              gameOverMenu = new GameOverMenu();
                              gameOverMenu.x = 217;
                              gameOverMenu.y = 244;
                              addChild(gameOverMenu);
                              gameOverMenu.visible = false;
                              gameOverMenu.playAgainButton.addEventListener("mouseDown", newGame);
                              startMenu = new StartMenu();
                              mainMenuButton = new MainMenuButton();
                              startButton = new StartButton();
                              startMenu.x = 151;
                              startMenu.y = 111;
                              startButton.x = 93;
                              startButton.y = 426;
                              mainMenuButton.x = 656;
                              mainMenuButton.y = 483;
                              addChild(mainMenuButton);
                              mainMenuButton.visible = false;
                              stage.addChildAt(startMenu, 0);
                              addChild(startButton);
                              startMenu.visible = true;
                              startButton.visible = true;
                              startMenu.visible = true;
                              startButton.addEventListener("mouseDown", newGame);
                              mainMenuButton.addEventListener("mouseDown", mainMenu);
                              pauseButton = new PauseButton();
                              pauseButton.x = 896;
                              pauseButton.y = 63;
                              pauseButton.addEventListener("mouseDown", PauseGame);
                              playButton = new PlayButton();
                              playButton.x = 896;
                              playButton.y = 63;
                              addChild(playButton);
                              playButton.visible = false;
                              playButton.addEventListener("mouseDown", PlayGame);
                    static function gameOver()
                              mainMenuButton.visible = true;
                              healthMeter.visible = false;
                              pauseButton.visible = false;
                              gameOverMenu.visible = true;
                              enemyShipTimer.stop();
                              for (var i in EnemyShip.list)
                                        EnemyShip.list[i].kill();
                              ship.takeDamage(-ship.maxHealth);
                    function newGame(e:Event)
                              addEventListener(Event.DEACTIVATE, PauseGame);
                              bestScore.visible = false;
                              gameScore.visible = true;
                              addChild(pauseButton);
                              addChild(healthMeter);
                              addChild(mainMenuButton);
                              enemyShipTimer = new Timer(750);
                              enemyShipTimer.addEventListener("timer", sendEnemy);
                              addChild(ship);
                              healthMeter.visible = true;
                              startMenu.visible = false;
                              mainMenuButton.visible = false;
                              startButton.visible = false;
                              healthMeter.visible = true;
                              pauseButton.visible = true;
                              playButton.visible = false;
                              gameOverMenu.visible = false;
                              ship.visible = true;
                              ship.x = 367;
                              ship.y = 542;
                              enemyShipTimer.start();
                              currentValue = 0;
                              updateDisplay();
                    function mainMenu(e:Event)
                              removeEventListener(Event.DEACTIVATE, PauseGame);
                              bestScore.visible = true;
                              gameScore.visible = false;
                              removeChild(mainMenuButton);
                              removeChild(ship);
                              healthMeter.visible = false;
                              startMenu.visible = true;
                              mainMenuButton.visible = false;
                              startButton.visible = true;
                              healthMeter.visible = false;
                              pauseButton.visible = false;
                              playButton.visible = false;
                              ship.takeDamage(ship.maxHealth);
                              gameOverMenu.visible = false;
                    function PauseGame(e:Event)
                              enemyShipTimer.removeEventListener("timer", sendEnemy);
                              stage.frameRate = 0;//
                              pauseButton.visible = false;
                              playButton.visible = true;
                    function PlayGame(e:Event)
                              enemyShipTimer.addEventListener("timer", sendEnemy);
                              stage.frameRate = 30;//
                              pauseButton.visible = true;
                              playButton.visible = false;
                    public function Counter()
                              reset();
                    function sendEnemy(e:Event)
                              var enemy = new EnemyShip();
                              stage.addChildAt(enemy, 0);
                              addToValue(1);
                    function addToValue( amountToAdd:Number ):void
                              currentValue = currentValue + amountToAdd;
                              updateDisplay();
                    function setValue( amount:Number ):void
                              currentValue = amount;
                              updateDisplay();
                    function reset():void
                              currentValue = 0;
                              updateDisplay();
                    function updateDisplay():void
                              gameScore.scoreDisplay.text = currentValue.toString();
                    function getFinalScore():Number
                              return gameScore.currentValue;
                    public function GameOverScreen()
                              sharedObject = SharedObject.getLocal("natdScores");
                    public function setFinalScore( scoreValue:Number ):void
                              gameScore.text = scoreValue.toString();
                              if (sharedObject.data.bestScore == null)
                                        sharedObject.data.bestScore = scoreValue;
                              else if ( scoreValue > sharedObject.data.bestScore )
                                        sharedObject.data.bestScore = scoreValue;
                              bestScore.text = sharedObject.data.bestScore.toString();
                              sharedObject.flush();
[/as]
Thanks in advance
-Ben

hello again, i added that code to the updatedisplay function with the currentValue.toString(); because putting a number there would achieve nothing here, and it works, but it doesnt save the highest score. whatever score is the last score it puts it there, becoming like a last score than a high score feature. heres my game.as again with your help
[as]
package
          import flash.display.MovieClip;
          import flash.utils.Timer;
          import flash.events.TimerEvent;
          import flash.ui.Mouse;
          import flash.events.KeyboardEvent;
          import flash.ui.Keyboard;
          import flash.events.Event;
          import flash.media.SoundChannel;
          import flash.net.SharedObject;
          import flash.text.TextField;
          public class Game extends MovieClip
                    static var ship:MovieClip;
                    static var healthMeter:HealthMeter;
                    static var score:Score;
                    static var highScore:HighScore;
                    static var enemyShipTimer:Timer;
                    static var gameOverMenu:GameOverMenu;
                    static var startMenu:StartMenu;
                    static var startButton:StartButton;
                    static var pauseButton:PauseButton;
                    static var playButton:PlayButton;
                    static var mainMenuButton:MainMenuButton;
                    public var currentValue:Number;
                    public var sharedObject:SharedObject;
                    public function Game()
                              Key.initialize(stage);
                              ship = new Ship();
                              healthMeter = new HealthMeter();
                              var score:Score = new Score();
                              var highScore:HighScore = new HighScore();
                              addChild(score);
                              addChild(highScore);
                              gameScore.visible = false;
                              bestScore.visible = true;
                              healthMeter.x = 2.5;
                              healthMeter.y = 576;
                              gameOverMenu = new GameOverMenu();
                              gameOverMenu.x = 217;
                              gameOverMenu.y = 244;
                              addChild(gameOverMenu);
                              gameOverMenu.visible = false;
                              gameOverMenu.playAgainButton.addEventListener("mouseDown", newGame);
                              startMenu = new StartMenu();
                              mainMenuButton = new MainMenuButton();
                              startButton = new StartButton();
                              startMenu.x = 151;
                              startMenu.y = 111;
                              startButton.x = 93;
                              startButton.y = 426;
                              mainMenuButton.x = 656;
                              mainMenuButton.y = 483;
                              addChild(mainMenuButton);
                              mainMenuButton.visible = false;
                              stage.addChildAt(startMenu, 0);
                              addChild(startButton);
                              startMenu.visible = true;
                              startButton.visible = true;
                              startMenu.visible = true;
                              startButton.addEventListener("mouseDown", newGame);
                              mainMenuButton.addEventListener("mouseDown", mainMenu);
                              pauseButton = new PauseButton();
                              pauseButton.x = 896;
                              pauseButton.y = 63;
                              pauseButton.addEventListener("mouseDown", PauseGame);
                              playButton = new PlayButton();
                              playButton.x = 896;
                              playButton.y = 63;
                              addChild(playButton);
                              playButton.visible = false;
                              playButton.addEventListener("mouseDown", PlayGame);
                    static function gameOver()
                              mainMenuButton.visible = true;
                              healthMeter.visible = false;
                              pauseButton.visible = false;
                              gameOverMenu.visible = true;
                              enemyShipTimer.stop();
                              for (var i in EnemyShip.list)
                                        EnemyShip.list[i].kill();
                              ship.takeDamage(-ship.maxHealth);
                    function newGame(e:Event)
                              addEventListener(Event.DEACTIVATE, PauseGame);
                              bestScore.visible = false;
                              gameScore.visible = true;
                              addChild(pauseButton);
                              addChild(healthMeter);
                              addChild(mainMenuButton);
                              enemyShipTimer = new Timer(750);
                              enemyShipTimer.addEventListener("timer", sendEnemy);
                              addChild(ship);
                              healthMeter.visible = true;
                              startMenu.visible = false;
                              mainMenuButton.visible = false;
                              startButton.visible = false;
                              healthMeter.visible = true;
                              pauseButton.visible = true;
                              playButton.visible = false;
                              gameOverMenu.visible = false;
                              ship.visible = true;
                              ship.x = 367;
                              ship.y = 542;
                              enemyShipTimer.start();
                              currentValue = 0;
                              updateDisplay();
                    function mainMenu(e:Event)
                              removeEventListener(Event.DEACTIVATE, PauseGame);
                              bestScore.visible = true;
                              gameScore.visible = false;
                              removeChild(mainMenuButton);
                              removeChild(ship);
                              healthMeter.visible = false;
                              startMenu.visible = true;
                              mainMenuButton.visible = false;
                              startButton.visible = true;
                              healthMeter.visible = false;
                              pauseButton.visible = false;
                              playButton.visible = false;
                              ship.takeDamage(ship.maxHealth);
                              gameOverMenu.visible = false;
                    function PauseGame(e:Event)
                              enemyShipTimer.removeEventListener("timer", sendEnemy);
                              stage.frameRate = 0;//
                              pauseButton.visible = false;
                              playButton.visible = true;
                    function PlayGame(e:Event)
                              enemyShipTimer.addEventListener("timer", sendEnemy);
                              stage.frameRate = 30;//
                              pauseButton.visible = true;
                              playButton.visible = false;
                    public function Counter()
                              reset();
                    function sendEnemy(e:Event)
                              var enemy = new EnemyShip();
                              stage.addChildAt(enemy, 0);
                              addToValue(1);
                    function addToValue( amountToAdd:Number ):void
                              currentValue = currentValue + amountToAdd;
                              updateDisplay();
                    function setValue( amount:Number ):void
                              currentValue = amount;
                              updateDisplay();
                    function reset():void
                              currentValue = 0;
                              updateDisplay();
                    public function updateDisplay():void
                              TextField(gameScore.getChildByName("scoreDisplay")).text = currentValue.toString();
                              TextField(bestScore.getChildByName("bestScore")).text = currentValue.toString();
                    function getFinalScore()
                              return gameScore.currentValue;
                    public function GameOverScreen()
                              sharedObject = SharedObject.getLocal("natdScores");
                    public function setFinalScore( scoreValue:Number ):void
                              gameScore.text = scoreValue.toString();
                              if (sharedObject.data.bestScore == null)
                                        sharedObject.data.bestScore = scoreValue;
                              else if ( scoreValue > sharedObject.data.bestScore )
                                        sharedObject.data.bestScore = scoreValue;
                              bestScore.text = sharedObject.data.bestScore.toString();
                              sharedObject.flush();
[/as]

Similar Messages

  • Help with online high scores

    I'm working on a marathon runner game ( http://www.locopuyo.com/MarathonRunnerBeta1.zip ) just for the fun of it. What I am wondering is what the best way to make a high scores list would be.
    I have mySQL on my server, I don't know if that is the best way to do it though.
    I don't know at all how to connect files on the internet with java.
    I was thinking it might be easier if I just had a plain html web site that I could edit in my java program using ftp, but I don't know how to do that and dont' even know if it is possible.
    Any help would be much appretiated.

    since you have MySQL on your server, I'm going to go ahead and assume you have PHP installed also. If so, you can do the highscore work in PHP and just have the game query that script. Basically (if you know anything about PHP and web queries in general) you just query the URL of the PHP script with a few GETVARS. In the simplest (and most easily hacked) way is something like:
    http://yourserver.com/game/highscore.php?action=submit&name=bob&score=5000highscore.php (your script) would then use MySQL to store the data of the GETVARS ($action,$name, and $score).
    All you need in Java to query this script is the URL class.
    URL url = new URL("http://yourserver.com/game/highscore.php?action=submit&name=bob&score=5000");
    url.openConnection(); // this is where it is queriedhighscore.php is where you need to do your database work. If you don't know anything about PHP or if this sounds too easily hacked, you might look into connecting to MySQL via JDBC (see tutorial)
    If I find the time I can make a simple template for you to build off of

  • I bought a new Iphone 4s and when I sync my apps over I lost all of my high scores. How can I get back my high scores as I do not want to start all over on some of the games

    I bought the new Iphone 4s. I backed up my old 3gs on Itunes store before trading in my old Iphone. I sync my new phone and I have all of my apps but non of the high scores. For example I played all of the angry birds and had three stars on all levels. Now I have the app on my Iphone but I am back no levels completed. How do I fix this problem. My Itunes store is on a PC running Windows 7

    Under the answer you want to mark as correct you should see a box that says Correct with a green symbol to the left and a box with Helpful with an orange star to the left. Click on the one you want.
    And thanks for thinking about that, it is appreciated.

  • [AS3 AIR] 2880x2880 Size Limit, Camera, Filter, CameraRoll Issues & Finger Friendly Components

    AS3 AIR ANDROID
    I started playing with this Adobe AIR for Adroid by building an app that would let the user take a picture using the mobile device's native camera app.  Then, I'm applying filter effects to make the image look cool.  Then, I'm allowing the user to save the image back to the camera roll.
    Here are some questions that I have:
    KEEPING UP WITH CURRENT TECHNOLOGY
    Are we limited to the 2880x2880 stage size limit?  Although, this dimension does yield 8+megapixels, it's not in the ratio that most camera sensors are built (widescreen).  Plus, you can bet that newer cameras will have even higher dimensions.  Will this be updated to keep up with current technology requirements?
    IMPORTING & MANIPULATING CAMERA DATA
    Code
    var bmpData:BitmapData = new BitmapData($loader.width, $loader.height);
    bmpData.draw(DisplayObject($loader));
    bmp = new Bitmap(bmpData);
    bmp.width = Capabilities.screenResolutionX;
    bmp.height = Capabilities.screenResolutionY;
    if (CameraRoll.supportsAddBitmapData) {
        var cameraRoll:CameraRoll = new CameraRoll();              
        cameraRoll.addEventListener(ErrorEvent.ERROR, onCrError);
        cameraRoll.addEventListener(Event.COMPLETE, onCrComplete);
        var savedBmpData:BitmapData = new BitmapData (bmp.width, bmp.height);
        savedBmpData.draw(DisplayObject(bmp));
        cameraRoll.addBitmapData(savedBmpData);
    } else {
        trace("~" + "Camera Roll not supported for this device.");
    addChild(bmp);
    When you capture an image using the mobile device's camera app, you have to use the Loader object.
    So, here, I am doing just that with these steps:
    First, I'm creating a BitmapData object and sizing it the same as the camera image.
    Pass the camera image into the BitmapData object.
    Create a Bitmap object and pass in the BitmapData.
    Resize it to fit on the stage.
    Check for Camera Roll and then create a savedBmpData BitmapData object at the size of the screen.
    Pass in the bmp.
    Save it to the Camera Roll.
    The problem is that when the image is displayed on the phone, it shows THE ENTIRE (uncropped) image.  However, the image that is saved to the phone is only the top 800x480 corner of the image.  What is wrong?  How do we save an image to the Camera Roll that is larger than the display area of the phone.  It seems like the only way to save the entire camera image is to resize it to fit the stage and then capture the stage into a bitmapData object.
    FILTERS
    If you apply any filters to the bitmapData object, the filter effects will display on the phone, but if the image is saved to the Camera Roll, then all the filters are lost and it only saves the original (unfiltered) image.
    FINGER FRIENDLY UI COMPONENTS
    Do they exist?
    ADDITIONAL NOTES
    The max image size that can be saved is 2039x2039 pixels on the HTC Evo.  Anything bigger than this resulted in a CameraRoll Error #1 (which there is no documentation for what that means ANYWHERE on the web).

  • Flash Game High Scores Board

    Hello everyone,
    I know this is a subject that gets covered a lot as i have found a ton of tutorials that show a million dfferent ways to create a high scores board on a flash game.  So i decided to go out on a limb and pick a tutorial out to try.  Well I have now tried 3 different ones and have yet to get a working high scores board with my game.
    http://www.flashkit.com/tutorials/Games/How_to_c-Nick_Kuh-771/index.php
    That is the link to the most recent attempts to creat my high scores board.  When i finished everything the way the tutorial said it seemed like everything would work and then it just didnt.  After spending oh about 40 plus hours trying to make a high scores board i am getting very frustrated.  My game is scripted in AS2 and i have access to mysql and can set up unlimited databases.
    Can anyone please help me by sending an easy to follow tutorial that will work with AS2?  I would just like any kind of help right now as I feel ALL of my valid ideas have been ehausted.  Thanks in advance to anyone that can help!
    kapelskic

    Okay not a problem.
    This is my code on the very first frame of the game that initializes the the highscores.php script
    command = "init";
    _root.loadVariables("highscores.php?"+int(Math.random()*100000), "POST");
    This is the code that I have on a submit button, next to the input text box where the user enters their name for the scoreboard.
    on (release) {
    if(name ne ""){
    command = "update";
    _root.loadVariables("highscores.php?"+int(Math.random()*100000), "POST");
    gotoAndStop ("highScores");
    In every place the code says _root. I have also tried this. and neither of them work.  I have also tried a million other things.  So far the game plays through, goes to the game over screen where it asks for a user name and tells them their score.  Then once they press submit the game goes to the highScores screen but the name and score are not there.  The high scores screen cosists of 2 dynamic text fields one named "players" and one named "scores".  I hope this helps because I spent another 5 or so hours after my initial posts trying more tutorials with still no luck.  (the problem i am having is that i am new to flash, however not to PHP)
    kapelskic

  • Keeping a high score

    I'm not sure whether to put this topic here or on the game section, so forgive me if it's not supposed to be here. Just like the title says, I'd like to keep simply one high score. I'd like to write it into a file (along with the name of the person who holds the high score). I simply do not know what to do, I will post what I have so far (it's just a piece of a bigger class):
    public void openFile(){
              BufferedReader file;
              try
                   file = new BufferedReader (new FileReader ("data.dat"));
              catch (FileNotFoundException e)
                   System.out.println("File not found.");
              try
                   int highCombo = file.read();
                   if(MovingBar.p1Hits > highCombo && MovingBar.p1Hits > MovingBar.p2Hits){
                        JOptionPane.showMessageDialog(null, "Congratulations! Player 1 has beat the high score of " + highCombo + " hits with " + MovingBar.p1Hits + " hits!", "Congratulations!", JOptionPane.PLAIN_MESSAGE);
                        String name = JOptionPane.showInputDialog("Enter your name:");
                   if(MovingBar.p2Hits > highCombo && MovingBar.p2Hits > MovingBar.p1Hits){
                        JOptionPane.showMessageDialog(null, "Congratulations! Player 2 has beat the high score of " + highCombo + " hits with " + MovingBar.p2Hits + " hits!", "Congratulations!", JOptionPane.PLAIN_MESSAGE);
                        String name = JOptionPane.showInputDialog("Enter your name:");
         }I know there are a lot of random pieces of info, but more importantly, MovingBar.p#Hits is a variable in another class which I want to keep as a high score if it is one. highCombo is the current high score (hopefully read from the file data.dat which is simply a text file). I pretty much scrounged this code up from random places so I really dunno exactly what I'm doing. Also, I realize that I'm missing something from the last "try" statement and I don't know what to put. I'm sorry if this is confusing and amateur, but I really need some help. Thanks in advanced.

    Hi
    Create one class that want to be Serializable and implements the Serializable interface on it, then you can serialize the Whole object at once..........
    // Write to disk with FileOutputStream
    FileOutputStream f_out = new
         FileOutputStream("myobject.data");
    // Write object with ObjectOutputStream
    ObjectOutputStream obj_out = new
         ObjectOutputStream (f_out);
    // Write object out to disk
    obj_out.writeObject ( myObject )
    // Read from disk using FileInputStream
    FileInputStream f_in = new
         FileInputStream("myobject.data");
    // Read object using ObjectInputStream
    ObjectInputStream obj_in =
         new ObjectInputStream (f_in);
    // Read an object
    Object obj = obj_in.readObject();
    Regards
    Vinoth

  • High Score with Applets

    Well, I'm currently in a 'gaming club' at my high school. We are a small group of about 10-12 people that enjoy playing and designing games. Recent accomplishments consist of Battleship, Snake, Airhockey, and a few other minor 3D games.
    As of late, we wanted to take it to the next level. We'd like to put these games on a website in applet-form for everyone to enjoy and comment on. To do this, we'd like to implement a high score count to see who is the best at these games. However, when we tried to do this we ran into a security error. Aparently applets can't write to files. Is there any way around this? Any help would be greatly appriciated. Much thanks.
    - Sange

    Set up a php database. You can communicate between it and your Applet. That's how I do it on GameLizard.com

  • Use html ad banner in as3 AIR

    I am wanting to use an HTML ad banner in my AS3 Air for Android project, here is the html code:
    <a href="http://tracking.raftika.com/aff_c?offer_id=1106&aff_id=1708&file_id=12132&file_id=12166" target="_blank"><img src="https://media.go2speed.org/brand/files/raftika/1106/320x50_150k_ArchersVsCerberus_GEN_EN.g if" width="320" height="50" border="0" /></a><img src="http://tracking.raftika.com/aff_i?offer_id=1106&file_id=12166&aff_id=1708&file_id=12132" width="1" height="1" />
    I would need it to have a certain height and width on my app. Thanks, any and all help is appreciated.

    Unfortunately, that is not an option, as I am using this banner for an ad network( http://raftika.com). The banner is a GIF image. Is there no way to embed HTML in AIR?

  • High scores table without name repeat

    Hello there,
    I have some code which fills a high scores table.. we've decided to give away a prize to the top ten people in the high scores table.. the problem is that people are playing repeatedly and fillnig the high scores table with their name, this makes it unfair to other players as they can't manage to get onto the table !!
    Is there a way I can modify my code to ignore the same name should it appear and skip to the next non repeated name(pseudo) and score ??
    My text boxes are called pseudo1 - pseudo10 and score1 - score10
    Many thanks in advance for your help below is my code :-
    for (var p:uint = 1; p <= 10; p++) {
              var currentPseudo:String = "pseudo" + p;
              var currentScore:String = "score" + p;
              if (event.target.data["pseudo" + p]) {
                   highScoresPage[currentPseudo].appendText(event.target.data["pseudo"+p]);
              if (event.target.data["score" + p]) {
                   highScoresPage[currentScore].appendText(event.target.data["score"+p] + " points"/*/1000 + "s"*/);
              } else {
                   highScoresPage[currentPseudo].appendText(" \n");
                   highScoresPage[currentScore].appendText(" \n");

    I find using Dictionary class for filtering unique names very useful. The code below shows that. Note how array is sorted in descending order:
    var scores:Array = [];
    scores.push( { name: "Peter Smith", score: 32 } );
    scores.push( { name: "Amanda Smith", score: 112 } );
    scores.push( { name: "Peter Smith", score: 23 } );
    scores.push( { name: "Jerry Pak", score: 45 } );
    scores.push( { name: "Peter Smith", score: 80 } );
    scores.push( { name: "Martin", score: 78 } );
    scores.push( { name: "Andrei", score: 99 } );
    scores.push( { name: "Andrei", score: 65 } );
    scores.push( { name: "Martin", score: 76 } );
    scores.push( { name: "Amanda", score: 10 } );
    scores.push( { name: "Peter Smith", score: 73 } );
    // this sorting assures that only highest score for the same name will be presented
    // default sort is ascending
    scores.sortOn("score", Array.NUMERIC);
    var uniquePlayers:Dictionary = new Dictionary();
    // this creates unqie entries
    for each(var obj:Object in scores) {
         // each element is entered only once
         uniquePlayers[obj.name] = obj;
    // reset array
    scores = [];
    // populate with unique names
    for (var key:String in uniquePlayers) {
         scores.push(uniquePlayers[key]);
    scores.sortOn("score", Array.NUMERIC | Array.DESCENDING);
    for each(obj in scores) {
         trace(obj.name, obj.score);

  • IPhone High Score Data File/Sort Oddities

    Hello all.
    I am working on an iPhone game which is nearly complete but I am having trouble with the following high score sort/write code. I am aiming to keep up to 10 scores, sorted from highest to lowest obviously.
    The code creates a new data file with the current score added as first entry if there is no existing data file (and this works), or it creates a data file with the current score as first entry if a data file exists but is empty for some reason (and this works as well), or it adds the current score to a data file of existing scores if it is within the top ten or there are less than ten entries (this is where it gets odd).
    If there is one existing score in the data file, the current score is added and sorted properly. If there are two scores in the data file, the application crashes BUT the data file shows the current score was correctly added and sorted to the existing scores. If there are three existing scores, the application crashes and the data file remains unchanged.
    I have been over the logic many times and tried many different variations of the logic structure to no avail. I suspect it is something simple but I've been staring at it too long to see. Any ideas?
    If there is a better way to display the code/formatting on the forum, please let me know. It doesn't look pretty this way and there must be a way to make it more readable here. I tried to manually format it some to help. The code follows (score variable is brought in from another class but works properly in my tests). At the end I have repeated an isolated snippet of the code where I think the problem occurs.
    *CODE START:*
    int i, ii;
    struct highscoreentry {
    NSString *name;
    int highScore;
    struct highscoreentry structArray(10);
    FILE *fin = fopen("highscore.dat", "rb");
    if (fin != NULL) { //if the data file exists proceed here
    for (i = 0; i < 10; i++) {
    if (fscanf(fin, "%s %d\n", structArray(i).name, &structArray(i).highScore) != EOF) { //if data exists for this iteration proceed
    ii = i; //ii will be the last entry of existing data
    for (i = ii; i > -1; i--) { //will begin at last entry and work up the list of scores to sort
    if (score > structArray(i).highScore) { //if current score is higher than recoded score, recorded score moves down 1 place
    structArray(i + 1) = structArray(i);
    structArray(i).name = (NSString *)"JESSE";
    structArray(i).highScore = score;
    if (i == ii && ii < 9) //if there are less than 10 entries we will add another for our new entry
    ii = ii + 1;
    else if (score < structArray(i).highScore && i == ii) { //if current score is less than last recorded score it becomes new last entry
    structArray(i + 1).name = (NSString *)"JESSE";
    structArray(i + 1).highScore = score;
    if (ii < 9)
    ii = ii + 1;
    fclose(fin);
    if (fin == NULL) { //if the data file does not exist prepare data for new file
    ii = 0; //will be used to limit write iterations to this single new entry
    structArray(0).name = (NSString *)"JESSE";
    structArray(0).highScore = score;
    FILE *fout;
    fout = fopen("highscore.dat", "wb"); //should create/rewrite data file from scratch
    for (i = 0; i <= ii; i++) {
    fprintf(fout, "%s %d\n", structArray(i).name, structArray(i).highScore);
    fclose(fout);
    *CODE END*
    As far as I can tell by commenting out different portions of the code, the problem appears to be somewhere in here:
    *CODE START:*
    if (fin != NULL) { //if the data file exists proceed here
    for (i = 0; i < 10; i++) {
    if (fscanf(fin, "%s %d\n", structArray(i).name, &structArray(i).highScore) != EOF) { //if data exists for this iteration proceed
    *CODE END*
    ...but it baffles me that this works with one structure in the data file, crashes with two structures in the data file but correctly processes/sorts them and writes the file properly, and crashes with three structures in the data file without doing any additional work.
    Jesse Widener
    www.artandstructure.com

    Actually I've found online material to be adequately, and sometimes more than adequately, elucidating in learning the language. When I decided to take a stab at this I spent about 40 hours of my spare time the first week reading 2 or 3 different "takes" on the C/C++/Objective C language in addition to Apple's docs on their implementation along with the iPhone SDK. As I mentioned, I've thus far found the language quite clear and concise. I began my application the second week and this is the first time in 7 weeks of coding where I've felt the need to ask assistance. Every other problem I've solved, leaving no errors, warnings or leaks in my software and accomplishing every task I've set to this point.
    I find reading several different "takes" on a subject helps fill out an understanding from different perspectives. In this case, one perspective might lead the reader to believe or misunderstand the full use/context of a particular syntax, while reading from multiple sources can show the same syntax used in different contexts, broadening the understanding of its use, and that understanding can be user further to interpolate uses in a variety of situations.
    I am new to C/C++/Objective C and the iPhone SDK, but I am not new to programming. It may have been some time (other than hand-coding my website the last few years) and my language experience may be limited to BASIC, HTML, PHP and Javascript, but from my view learning a new language is relatively easy once you know one...even if it is BASIC. The general logic structure remains the same. The overall software design concept remans essentially the same. Both are going to use variables, arrays, subroutines, memory allocation/management, input and output of data, runtime logic, etc. I am 80-90% sure I know exactly how I want to attack a coding problem every time...I just need to know how to "say it in C".
    I don't remember when I first started coding, but I know by age 7 I wrote a karaoke style "Happy Birthday" for my great aunt with music playing through a Commodore 16 via "beeps" figuring the particular vibrations per second of the speaker (the hertz values) and durations for each note in time and pitch perfectly along with "lyrics" printed to screen with the music. To me, learning C is like learning a new foreign language. I took 2 years of French in high school and had to study at it but aced it nonetheless. I then opted to take Spanish but after a semester I opted to stop because the pacing was too slow. Learning Spanish after learning French was a piece of cake. They are in the same general language family and the syntax construction is very similar. I only needed the raw data of the words to fit to the rules I already knew. I didn't need to learn the same rules a second time.
    The C/Objective C language seems no more complicated than it need be, which is to say it seems simple in doing what it needs to do and I am impressed with that simplicity thus far. I am also impressed with Apple's implementation with regard to the iPhone. Being able to provide music via 4-5 lines of code using AVAudioPlayer is transcendental compared to "beeping" every note monophonically.
    Apple's explanations are very clear and concise. It is just, sometimes their examples are sparse or too narrow in scope to get a rounded context. However, their docs are very good and there is a wealth of information here on the net. My biggest complaint with Apple's docs really stems from the fact they seem to want to shove Interface Builder at everything and provide the code to do so but leave the reader stranded if the reader would rather stay within XCode exclusively and do more programmatically rather than leave that much "behind the curtain" work to Interface Builder...but it is a minor complaint.
    On pointers...I do understand the use of pointers, perhaps not to the nth degree as I am just starting out, but the concept makes sense to me. I understand they are not "content" but a memory address location of the "content". I also understand why pointing to a location which is undefined or unprotected is damaging to whatever may be in that location already and to the data being pointed since it can be inadvertently overwritten my some other memory using item.
    {quote}No. The (i < 9) condition is critical. Writing to structArray[10] will crash, since structArray[9] is the end of the array. In practice such a crash might not happen right away, though. If our program's data allocation actually ended at the end of the array, the crash would be immediate. But what usually happens when we write past the end of an array is that the beginning of some other data is overwritten.{quote}
    I need to slap my forehead on this one. I know better than that. I don't know why I missed that. Too many late nights I suppose.
    {quote}(NSString*) is called a type cast in that context.{quote}
    Yes, which is why I used it to deal with the incompatible type error I thought I had at that point, but I shouldn't have assumed by appeasing the compiler I was necessarily solving the problem.
    {quote} The best I can do for now is to caution that an enquiring mind, like all virtues, can be taken too far. I think it's important to compromise and copy good models sometimes. This isn't just to avoid reinventing the wheel. Sometimes it's good to remember we only have a limited time on Earth.{quote}
    Agreed...and I don't expect to understand every nuance the first time around. I expect to at least understand how each successful line of code works in its context, but I imagine some processes will take a few times through before it "clicks" how it works in a greater context than its own, and I am all right with that. I also understand deadlines are deadlines whether they be software development or otherwise and a broad eye needs to be kept to remaining on the track forward.
    Anyway, off to my day job.
    Thank you again...I began reading up on NSDictionary and NSUserDefaults last night. Will post soon.
    Jesse Widener
    www.artandstructure.com

  • AS3 AIR accessing Android expansion file

    Hello, I have AS3/AIR application for deploying on Google Play. The app has an expansion file attached to it. Expansion file is named "main.1000000.air.com.mycompany.myapp12.obb" and it is downloaded along with the app properly.
    The problem is I cannot access the file with any way I tried, like:
    File.applicationStorageDirectory.resolvePath('Android/obb/main.1000000.air.com.mycompany.myapp12.obb');
    File.applicationStorageDirectory.resolvePath('/Android/obb/main.1000000.air.com.mycompany.myapp12.obb');
    File.applicationStorageDirectory.resolvePath('main.1000000.air.com.mycompany.myapp12.obb');
    File.applicationStorageDirectory.resolvePath('/main.1000000.air.com.mycompany.myapp12.obb');
    or simillar, and I cannot access the file even when the path while developing on Windows seems to be right. When deployed, I just got the "not found" error in my catch block with the supplied File url property: "app-storage:/Android/obb/main.1000000.air.com.mycompany.myapp12.obb". I have been looking for the solution and trying various approaches for several days, but I am stucked. Please help. Developed on ASUS EEE PAD.

    I have same problem on my Nexus 7(2012) Android Lillipop
    The Aplication can't see the obb file after install - it can find it only after device system reload
    but I can see it on such directorys
    storage/sdcard0/Android/obb/
    storage/emulated/legacy/Android/obb/
    storage/emulated/0/Android/obb/
    so why aplication can't find it ?

  • High Score Security

    Hi I recently made a game(dosen't really matter what kind) in which the user gets a score and saves the score to my high score table.
    I do this by connecting to a .php page and passing the score and name variables on to it. (www.random.com/blablabla.php?name=bla&score=676) The page then opens the mySQL table and saves the high scores. THe page is opened from within the applet and the user dosen't see the page opening.
    The problem I am having is security, and i'm trying to make it so that nobody can access that php page from their browser and input whatever score they want and what not. THis was brought to my attention by my friend who put images(none rude) and hyperlinks allover my high score page. He was nice enough to tell me so now I am trying to fix it.
    THe first steps I took were to not package the source code with the jar(which he downloaded and extracted). But even then I could decompile the class file and search the file for ".php" and easily know what url to type into the browser to input any score for my game. I then tried using an obfuscator, ProGuard, which didn't help me much. It only renamed all the classes and variables, but the String I open for the high score I still very easily visible. Also from other people I got the general opinion that they(obfuscators) aren't much good as they only make it slightly harder to people to get the information, not make it impossible.
    Basically what I want to do is to make it as hard as possible for people(namely my friend...) to find out the page which saves the high scores, and type it into their browsers so they can input whatever high score they want. Obfusticating didn't help much and now I am running out of ideas. I was thinking about:
    Making sure the thing that oppened the page is an applet, but I'm not sure how to do this. This would be my ideal solution as I am not too worried about people who would go out of their way to make an applet with the same name as mine just to "hack" my high scores which aren't even worth hacking. But how would I go about doing this?

    You could do this using a client/server system comminicating using sockets, rather than simply a HTML request sent from the client. This way the client could be required to provide some validation before the server accepts score updates from it.
    The trick is to decide how the validation is done; you need to be able to differentiate between genuine clients and a client your friend has decompiled and changed so he can cheat.
    Remember that your friend can see exactly how the client works, but cannot see how the server works. Maybe you could send a copy of the client class object to the server and then the server could checksum it?

  • High Score Table: Writing a Simple Text File with Flash and PHP

    I am having a problem getting Flash to work with PHP as I need Flash to read and write to a text file on a server to store simple name/score data for a games hi score table. I can read from the text file into Flash easily enough but also need to write to the file when a new high score is reached, so I need to use PHP to do that. I can send the data from flash to the php file via POST but so far it is not working. The PHP file is confirmed as working as I added an echo to the file which displayed a message so I  could check that the server was running PHP - the files were also uploaded to a remote server so I  could test them properly. Flash code is as follows:
    //php filewriter
    var myLV = new LoadVars();
    function sendData() {
    //sets up variable 'hsdata' to send to php
    myLV.hsdata = myText;
    myLV.send("hiscores.php");
    I believe this sends the variable 'myText' to the php file as a variable called 'hsdata' which I want the php file to write into a text file. The mytext variable is just a long string that has all the scores and names in the hiscore. OK, XML would be better way of doing this but for speed I just want to get basic functionality working, so storing a simple text sting is adequate for now. The PHP code that reads the Flash 'hsdata' variable and writes it to the text file 'scores.txt' follows:
    <?php
    //assigns to variable the data POSTed from flash
    $flashdata = $_POST["hsdata"];
    //file handler opens file and erases all contents with w arg
    $fh = fopen("scores.txt","w");
    //adds data to file
    fwrite ($fh,$flashdata);
    //closes file
    fclose ($fh);
    echo 'php file is working';
    ?>
    Any help with this would be greatly appreciated - once I can get php to write simple text files I should be ok. Thanks.

    Thanks for your help.
    I have got Flash working to a certain extent with PHP using loadVars but have been unable to get flash to receive a variable declared in PHP. Here's my Flash code:
    var outLV = new LoadVars();
    var inLV = new LoadVars();
    function sendData() {
    outLV.hsdata = "Hello from Flash";
    outLV.sendAndLoad("http://www.mysite.com/hiscores/test23.php",inLV,"post");
    inLV.onLoad = function(success) {
    if (success) {
      //sets dynamic text box to show variable sent from php
      statusTxt.text = phpmess;
    } else {
      statusTxt.text = "No Data Received";
    This works ok and the inLV.onLoad function reports that it is receiving data but does not display the variable received from PHP. The PHP file is like this:
    <?php
    $mytxt =$_POST['hsdata'];
    $myfile = "test23.txt";
    $fh = fopen($myfile,'w');
    //adds data to file
    fwrite($fh, $mytxt);
    //closes file
    fclose ($fh);
    $mess = "hello there from php";
    echo ("&phpmess=$mess&");
    ?>
    The PHP file is correctly receiving the hsdata from flash and writing it to a text file, but there seems to be a problem with the final part of the code which is intended to send a variable called 'phpmess' back to Flash, this is the string "hello there from php". How do I set up Flash and PHP so that PHP can send a variable back to Flash using echo? Really have tried everything but am totally baffled. Online tutorials have given numerous different syntax configurations for how the PHP file should be written which has really confused me - any help would be greatly appreciated.

  • High Scores

    Hi can anyone help please -
    I'm currently making a game for an assignment, which is
    pretty much finished however I have to include a score recording
    system which will record name, score and number of hits for the top
    10 players. The scores should be held in an external text file . I
    was wondering if anyone could explain a simple way to do this, i
    know i should use getpref and setpref to create and load the text
    file, and also use some sort of list. If i use a property list i
    can have a property 'name' and its value 'score' but how would i
    add a third element, the hits. Alternatively if i use a linear
    list, one for each of name, hits and score, how would i link them
    and sort them so that the correct name hits and score display
    together. Also i should probably mention that the game currently
    has name, hits and score held in global variables.
    If anyone could point me in the right direction that would be
    great, I'd really like to understand how to get this working first
    instead of just the usual trial and error.
    thanks
    Mark

    The general tool for reading and writing text files is the
    fileIO xtra,
    implementing it involves some learning curve.
    The easy way to store user settings like high scores is the
    setPref,
    getPref functions which store text in a predefined location
    and works
    with shockwave, unlike fileIO xtra.
    The larger effort might be involved in getting the scores
    from the
    stored text version back to whatever variables scheme you
    store them in.
    value(somestring) converts a text representation of a number
    back to an
    integer or float.
    you can even store list variables as text
    x = [["bob", 123], ["Jim", 567], ["Sally", 778]]
    savePref "scoreFile", string(x)
    -- retrieved with
    x = value(getPref("scoreFile"))

  • Online high score list

    Hi guys,
    I was wondering how I could implement a high score list into a java applet game i wrote. The logic isnt what im worried about, its writing to a file that is on a server that i dont own. It's my school's webspace...do i have access to do this?
    If I dont have access, how would I do this, there are tons of online games with high score lists, so how do they do it?
    Appreciate the help,
    Brian

    Only you would know if you have the permission to do this!. BTW you cannot write to a file from an Applet unless it is signed.
    What I would do if I wanted to do this is, Create a webpage that has access to write to a file or database, then inside my applet use a HttpURLConnection to call this webpage with the paramaters passed along the query line:
    http://www.yourHost.com/TopScores?name=Gary&score=12345

Maybe you are looking for

  • "Show Bookmarks" in 6.1.2 no longer shows visual of webpages bookmarked. Can I get it back like before the update?

    Show Bookmarks has changed with the last update I recently did. I really like the visual panel of the urls and a slide bar to select a bookmark with the description of the url, and the date I bookmarked. It's all gone in 6.1.2. I look at my old MacBo

  • Photoshop CS4 Is Not Showing all Formats/Extensions when saving. [was: Please Help]

    My Adobe Photoshop Cs4 Is Not Showing all Formats/Extensions. when i edit a picture and wants to save in .png or .bmp or in any other format ... there is no .png In the Save As List, There are only Some Extenstions in that list like Jpeg-Psd-Tif etc.

  • VPN - FireWall : do i need to keep port open ?

    hi, when i try to turn off AFP port in the firewall settings, i can't connect to the AFP server anymore even when i have a VPN session open. i was under the impression that connections going trough the VPN would not need to have their ports open in t

  • Help needed in Billing

    Hi, For particular rate category i have defined 3 Rate Types 1)KWH : Register 2)KW :Register 3)SVCH :Facts Then I defined 3 Rates 1)Rate-KWH  : Register Permissble to valuate the KWH COnsumption 2)Rate-KW  : Register Permissble to valuate the KW Dema

  • Safari install on v9.2

    Will Safari work on v9.2 and if so, what version Safari s/b installed? What may I expect in terms of performance. Thank you very much for your help!!!