Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

package { import flash.display.Sprite; import flash.display.Loader; import…

  1. User

    package { import flash.display.Sprite; import flash.display.Loader; import flash.text.TextField; import flash.events.Event; import flash.display.StageAlign; import flash.events.KeyboardEvent; import flash.desktop.NativeApplication; import flash.events.InvokeEvent; import flash.display.StageDisplayState; import flash.ui.Keyboard; import flash.geom.Rectangle; import flash.display.Screen; import flash.system.LoaderContext; import flash.system.ApplicationDomain; import flash.events.IOErrorEvent; import flash.net.URLVariables; import flash.net.URLRequest;

    public class GameLoader extends Sprite 
    {
    
        private var loader:Loader;
        private var locale:String;
        public var log:TextField;
        private var fullScreen:Boolean;
    
        public function GameLoader()
        {
            if (stage)
            {
                this.init();
            }
            else
            {
                addEventListener(Event.ADDED_TO_STAGE, this.init);
            };
        }
    
        private function init(e:Event=null):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, this.init);
            stage.align = StageAlign.TOP_LEFT;
            stage.frameRate = 60;
            stage.nativeWindow.maximize();
            stage.addEventListener(KeyboardEvent.KEY_DOWN, this.onKey);
            this.setCenterPosition();
            this.log = new TextField();
            this.log.x = 15;
            this.log.y = 15;
            this.log.width = 520;
            this.log.height = 370;
            this.log.background = true;
            this.logEvent("aaa");
            try
            {
                NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, this.onInvoke);
            }
            catch(e:Error)
            {
                logEvent(e.getStackTrace());
                throw (e);
            };
        }
    
        private function onKey(e:KeyboardEvent):void
        {
            switch (e.keyCode)
            {
                case Keyboard.F11:
                    this.fullScreen = (!(this.fullScreen));
                    if (this.fullScreen)
                    {
                        stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
                    }
                    else
                    {
                        stage.displayState = StageDisplayState.NORMAL;
                    };
                    break;
            };
        }
    
        private function setCenterPosition():void
        {
            var appBounds:Rectangle = stage.nativeWindow.bounds;
            var screen:Screen = Screen.getScreensForRectangle(appBounds)[0];
            stage.nativeWindow.x = ((screen.bounds.width - stage.nativeWindow.width) / 2);
            stage.nativeWindow.y = ((screen.bounds.height - stage.nativeWindow.height) / 2);
        }
    
        private function onInvoke(event:*):void
        {
            if (event.arguments.length > 0)
            {
                this.logEvent(("Arguments: " + event.arguments.toString()));
                this.locale = event.arguments[0];
            };
            var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
            this.loader = new Loader();
            this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onComplete);
            this.loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void
            {
            });
            var flashvars:URLVariables = new URLVariables();
            flashvars["locale"] = this.locale;
            flashvars["rnd"] = Math.random();
            var urlReq:URLRequest = new URLRequest("battles.swf");
            urlReq.data = flashvars;
            this.loader.load(urlReq, context);
        }
    
        public function logEvent(entry:String):void
        {
            this.log.appendText((entry + "\n"));
            trace(entry);
        }
    
        private function onComplete(e:Event):void
        {
            this.loader.removeEventListener(Event.COMPLETE, this.onComplete);
            var mainClass:Class = Class(this.loader.contentLoaderInfo.applicationDomain.getDefinition("Game"));
            var obj:* = new (mainClass)();
            obj.SUPER(stage);
            addChild(obj);
        }
    
    
    }
    

    }//package как сделать чтобы в onInvoke flashvars["locale"] = this.locale; читал файл game.properties с его параметром locale=RU в директории он находится applicationStorageDirectory

  2. Assistant

    Для того чтобы прочитать файл game.properties из директории applicationStorageDirectory, вам потребуется использовать класс File, FileMode и FileStream.

    Вот пример метода, который читает файл и возвращает значение параметра "locale":

    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.errors.IOError;
    
    private function readGameProperties():String
    {
        var file:File = File.applicationStorageDirectory.resolvePath("game.properties");
        var fileStream:FileStream = new FileStream();
        var gameProperties:String = "";
    
        try
        {
            fileStream.open(file, FileMode.READ);
            gameProperties = fileStream.readUTFBytes(fileStream.bytesAvailable);
            fileStream.close();
    
            // Разбить game.properties на строки и найти строку с параметром "locale"
            var lines:Array = gameProperties.split("\r\n"); // В Windows используется символ возврата каретки (\r\n)
            for each(var line:String in lines)
            {
                if(line.indexOf("locale=") == 0)
                {
                    return line.substring(7); // Возвращает значение после "locale="
                }
            }
        }
        catch(e:IOError)
        {
            trace("Ошибка при чтении game.properties:", e);
        }
    
        return ""; // Если параметр "locale" не найден или возникла ошибка при чтении файла
    }
    

    Вызовите этот метод внутри метода onInvoke перед установкой значения locale:

    this.locale = readGameProperties();
    

    Теперь переменная locale будет содержать значение параметра "locale" из файла game.properties.

  3. User

    а почему когда я меняю в property файле ru на en язык не меняется

  4. Assistant

    Если вы хотите, чтобы изменения в файле game.properties отразились в языке, вы должны считать файл game.properties каждый раз, когда пользователь открывает вашу игру. В противном случае, значение переменной locale будет установлено только один раз при запуске игры.

    Чтобы обновить значение переменной locale при каждом запуске игры, вы можете модифицировать метод onInvoke следующим образом:

    private function onInvoke(event:*):void
    {
        var gamePropertiesLocale:String = readGameProperties();
        if (gamePropertiesLocale != "")
        {
            this.locale = gamePropertiesLocale;
        }
        else
        {
            if (event.arguments.length > 0)
            {
                this.locale = event.arguments[0];
            }
        }
        // остальной код метода...
    }
    

    Таким образом, значение переменной locale будет проверяться наличие файла game.properties при каждом запуске игры. Если файл найден и содержит параметр "locale", то значение переменной будет обновлено согласно файлу. В противном случае, будет использовано значение из командной строки.

    Убедитесь, что файл game.properties находится в правильной директории (applicationStorageDirectory) и содержит нужные значения для параметра "locale".

  5. User

    ты можешь сделать чтобы оно просто читало locale= из property файла, и не зависимо что стоит после = ru или en

  6. Assistant

    Определение значения после символа "=" в строке файла game.properties является задачей простой обработки строки. Вот пример метода, который считывает файл game.properties и возвращает значение параметра "locale":

    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.errors.IOError;
    
    private function readGameProperties():String
    {
        var file:File = File.applicationStorageDirectory.resolvePath("game.properties");
        var fileStream:FileStream = new FileStream();
        var gameProperties:String = "";
    
        try
        {
            fileStream.open(file, FileMode.READ);
            gameProperties = fileStream.readUTFBytes(fileStream.bytesAvailable);
            fileStream.close();
    
            // Разбить game.properties на строки и найти строку с параметром "locale"
            var lines:Array = gameProperties.split("\r\n"); // В Windows используется символ возврата каретки (\r\n)
            for each(var line:String in lines)
            {
                if(line.indexOf("locale=") == 0)
                {
                    return line.substr(7); // Возвращает значение после "locale="
                }
            }
        }
        catch(e:IOError)
        {
            trace("Ошибка при чтении game.properties:", e);
        }
    
        return ""; // Если параметр "locale" не найден или возникла ошибка при чтении файла
    }
    

    Вы можете вызвать этот метод внутри метода onInvoke перед установкой значения locale:

    this.locale = readGameProperties();
    

    Теперь переменная locale будет содержать значение параметра "locale" из файла game.properties, независимо от того, что стоит после символа "=".