package { import flash.display.Sprite; import flash.display.Shape; import…
- User
package { import flash.display.Sprite; import flash.display.Shape; import flash.events.Event; import zip.ZIPResourceLoader; import flash.events.ProgressEvent;
public class ProgressBar extends Sprite { private var progressBar:Shape; private var backgroundBar:Shape; private var progress:Number; private var maxWidth:Number; private var maxHeight:Number; public var resourceLoader:ZIPResourceLoader;
public function ProgressBar() { init(); }
public function setResourceLoader(resourceLoader:ZIPResourceLoader):void { resourceLoader.addEventListener(ZIPResourceLoader.PROGRESS_UPDATE, onProgressUpdate); } public function onProgressUpdate(event:ProgressEvent):void { progress = event.bytesLoaded / event.bytesTotal; updateProgressBar(); }private function init():void { maxWidth = 200; maxHeight = 20; progress = 0;
backgroundBar = new Shape(); backgroundBar.graphics.beginFill(0xCCCCCC); backgroundBar.graphics.drawRect(0, 0, maxWidth, maxHeight); backgroundBar.graphics.endFill();
progressBar = new Shape();
addChild(backgroundBar); addChild(progressBar);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); }
private function onAddedToStage(event:Event):void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); addEventListener(Event.ENTER_FRAME, onUpdate); }
private function onRemovedFromStage(event:Event):void { removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); removeEventListener(Event.ENTER_FRAME, onUpdate); }
private function onUpdate(event:Event):void { progress += 0.01; // Увеличьте прогресс на 0.01 каждый фрейм if (progress > 1) progress = 1; // Убедитесь, что прогресс не превышает 1 updateProgressBar(); }
private function updateProgressBar():void { progressBar.graphics.clear(); progressBar.graphics.beginFill(0x0000FF); progressBar.graphics.drawRect(0, 0, maxWidth * progress, maxHeight); progressBar.graphics.endFill(); }
public function setProgress(value:Number, maxValue:Number = 1):void { progress = value; if (progress < 0) { progress = 0; } else if (progress > maxValue) { progress = maxValue; } updateProgressBar(); } } } прогресс все равно не показывается сколько скачалось, просто идет вперед и все, не зависимо сколько скачалось, вот класс загрузки package zip { import flash.events.Event; import flash.events.IOErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.URLRequest; import flash.net.URLLoaderDataFormat; import flash.net.URLRequestMethod; import flash.net.URLLoader; import flash.net.URLStream; import flash.net.URLVariables; import flash.utils.ByteArray; import deng.fzip.FZip; import flash.events.ProgressEvent; import deng.fzip.FZipFile; import flash.events.EventDispatcher; import flash.events.ProgressEvent;
public class ZIPResourceLoader extends EventDispatcher { public var resourcesURL:String = "https://redagereborn.ru/resources.zip"; public var versionURL:String = "https://redagereborn.ru/version.txt"; public var localFilePath:String = File.applicationStorageDirectory.nativePath + File.separator + "resources.zip"; public var versionFile:File = new File(File.applicationStorageDirectory.nativePath + File.separator + "version.txt"); public var zipLoader:URLLoader = new URLLoader(); private var progressBar:ProgressBar; public static const PROGRESS_UPDATE:String = "progressUpdate"; public function ZIPResourceLoader(progressBar:ProgressBar) { this.progressBar = progressBar; zipLoader.dataFormat = URLLoaderDataFormat.TEXT; zipLoader.addEventListener(Event.COMPLETE, onVersionLoaded); zipLoader.addEventListener(IOErrorEvent.IO_ERROR, onVersionLoadError); zipLoader.load(new URLRequest(versionURL)); } public function onVersionLoaded(event:Event):void { var remoteVersion:Number = Number(zipLoader.data); var versionLoader:URLLoader = new URLLoader(); versionLoader.dataFormat = URLLoaderDataFormat.TEXT; versionLoader.addEventListener(Event.COMPLETE, onLocalVersionLoaded); versionLoader.addEventListener(IOErrorEvent.IO_ERROR, onLocalVersionLoadError); versionLoader.load(new URLRequest(versionFile.nativePath)); function onLocalVersionLoaded(event:Event):void { var localVersion:Number = Number(versionLoader.data); if (localVersion != remoteVersion) { startDownloadProcess(); } else { Alert.showMessage("Local version is up to date"); // Пропущен код для распаковки архива } } function onLocalVersionLoadError(event:IOErrorEvent):void { // Создаем новый файл version.txt и записываем в него пустую строку var fileStream:FileStream = new FileStream(); fileStream.open(versionFile, FileMode.WRITE); fileStream.writeUTFBytes(""); fileStream.close(); // Запускаем процесс загрузки и распаковки архива startDownloadProcess(); } } private function startDownloadProcess():void { Alert.showMessage("Downloading resources.zip"); var downloadStream:URLStream = new URLStream(); downloadStream.addEventListener(Event.COMPLETE, onDownloadComplete); downloadStream.addEventListener(IOErrorEvent.IO_ERROR, onDownloadError); downloadStream.load(new URLRequest(resourcesURL)); } public function onVersionLoadError(event:IOErrorEvent):void { Alert.showMessage("Failed to load version.txt"); } private function updateLocalVersion(remoteVersion:Number):void { var fileStream:FileStream = new FileStream(); fileStream.open(versionFile, FileMode.WRITE); fileStream.writeUTFBytes(remoteVersion.toString()); fileStream.close(); } public function onProgressUpdate(event:ProgressEvent):void { var percent:Number = event.bytesLoaded / event.bytesTotal; progressBar.setProgress(percent); } public function onDownloadComplete(event:ProgressEvent):void { var percent:Number = event.bytesLoaded / event.bytesTotal; dispatchEvent(new ProgressEvent(PROGRESS_UPDATE, false, false, percent, 1)); var downloadStream:URLStream = event.target as URLStream; var fileBytes:ByteArray = new ByteArray(); downloadStream.readBytes(fileBytes); var fileStream:FileStream = new FileStream(); fileStream.open(new File(localFilePath), FileMode.WRITE); fileStream.writeBytes(fileBytes, 0, fileBytes.length); fileStream.close(); //Alert.showMessage("Downloaded resources.zip"); var remoteVersion:Number = Number(zipLoader.data); // Получаем удаленную версию файла updateLocalVersion(remoteVersion); // Обновляем локальную версию файла extractLocalArchive(); } public function onDownloadError(event:IOErrorEvent):void { Alert.showMessage("Failed to download resources.zip"); } public function extractLocalArchive():void { var resourcesFolder:File = new File(File.applicationStorageDirectory.nativePath + File.separator + "cache/resources"); if (resourcesFolder.exists && resourcesFolder.isDirectory) { resourcesFolder.deleteDirectory(true); // Удаление папки “resources” с ее содержимым } var zipFile:FZip = new FZip(); zipFile.addEventListener(Event.COMPLETE, onZipExtracted); zipFile.load(new URLRequest(localFilePath)); } public function onZipExtracted(event:Event):void { var zipFile:FZip = event.target as FZip; try { for (var i:int = 0; i < zipFile.getFileCount(); i++) { var zipEntry:FZipFile = zipFile.getFileAt(i); var targetFilePath:String = File.applicationStorageDirectory.nativePath + File.separator + "cache/resources" + File.separator + zipEntry.filename; var targetFile:File = new File(targetFilePath); if (zipEntry.filename.charAt(zipEntry.filename.length - 1) == "/") { targetFile.createDirectory(); } else { var targetFileStream:FileStream = new FileStream(); targetFileStream.open(targetFile, FileMode.WRITE); targetFileStream.writeBytes(zipEntry.content); targetFileStream.close(); } } // Закрываем архив zipFile.close(); // Удаляем архив var file:File = new File(localFilePath); file.deleteFile(); Alert.showMessage("Extracted successfully!"); } catch (error:Error) { Alert.showMessage("Failed to extract resources.zip: " + error.message + " (" + error.errorID + ")"); } } private function versionIsUpToDate(version:Number):Boolean { if (versionFile.exists) { var fileStream:FileStream = new FileStream(); fileStream.open(versionFile, FileMode.READ); var localVersion:Number = Number(fileStream.readUTFBytes(fileStream.bytesAvailable)); fileStream.close(); return version == localVersion; // Возвращает true, если версии совпадают. } return false; } } - Assistant
The issue you are facing is that the progress is not being updated in the ProgressBar class. To fix this issue, you need to dispatch the progress event from the ZIPResourceLoader class and listen to it in the ProgressBar class. Here are the steps to update the progress in the ProgressBar class:
-
In the ZIPResourceLoader class, add the following line before dispatching the progress event in the onDownloadComplete method:
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, event.bytesLoaded, event.bytesTotal)); -
In the ProgressBar class, modify the onProgressUpdate method to take two parameters: bytesLoaded and bytesTotal:
public function onProgressUpdate(bytesLoaded:Number, bytesTotal:Number):void { progress = bytesLoaded / bytesTotal; updateProgressBar(); } -
In the ProgressBar class, update the setResourceLoader method to register to the new progress event instead of the ZIPResourceLoader.PROGRESS_UPDATE event:
-
- User
C:\Users\Alexander\Desktop\project\Preloader\src\zip\ZIPResourceLoader.as(94): col: 8 Error: Access of undefined property progress. progress = bytesLoaded / bytesTotal;
- Assistant
Apologies for the confusion. It seems that the
progressproperty is not defined in the ProgressBar class. To fix this error, follow these steps:- In the ProgressBar class, add a private variable
bytesLoadedand another private variablebytesTotal:
private var bytesLoaded:Number; private var bytesTotal:Number;- Update the onProgressUpdate method in the ProgressBar class to assign the values of
bytesLoadedandbytesTotalreceived from the progress event:
public function onProgressUpdate(event:ProgressEvent):void { bytesLoaded = event.bytesLoaded; bytesTotal = event.bytesTotal; progress = bytesLoaded / bytesTotal; updateProgressBar(); } - In the ProgressBar class, add a private variable
- User
прогресс бар перестал вообще идти
- Assistant
I apologize for the confusion. It appears that there might be an issue with the implementation of the progress bar. Let's review the code and make some modifications to ensure it functions correctly.
In the ProgressBar class, update the onUpdate method to use the progress value passed from the resource loader:
private function onUpdate(event:Event):void { updateProgressBar(); }Next, modify the updateProgressBar method to use the progress value from the resource loader:
private function updateProgressBar():void { progressBar.graphics.clear(); progressBar.graphics.beginFill(0x0000FF); progressBar.graphics.drawRect(0, 0, maxWidth * progress, maxHeight); progressBar.graphics.endFill(); }Make sure you insert these code changes in the ProgressBar class. This will ensure that the progress bar updates correctly based on the progress value received from the resource loader.
Additionally, double-check that you have correctly set the resource loader in the ProgressBar instance by calling the setResourceLoader method. For example:
- User
теперь прогресс бар двигается но произвольно, не зависимо от того сколько скачалось
- Assistant
I apologize for the confusion. It seems that the progress value in the ProgressBar class is not being updated correctly. To fix this issue, follow these steps:
-
In the ProgressBar class, remove the onUpdate method that increments the progress by 0.01 in each frame.
-
Update the setProgress method in the ProgressBar class to accept the progress value directly:
public function setProgress(value:Number, maxValue:Number = 1):void { progress = value / maxValue; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } updateProgressBar(); }- In the ZIPResourceLoader class, modify the onDownloadComplete method to dispatch the progress event with the proper values:
public function onDownloadComplete(event:ProgressEvent):void { var percent:Number = event.bytesLoaded / event.bytesTotal; dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, event.bytesLoaded, event.bytesTotal)); // Rest of the code... } -
- User
onProgressUpdate это где ZIPResourceLoader тут или в proggersbar ?
- Assistant
I apologize for the confusion. The
onProgressUpdatemethod should be implemented in the ProgressBar class, not in the ZIPResourceLoader class. Here are the correct steps to implement theonProgressUpdatemethod in the ProgressBar class:-
In the ProgressBar class, remove the
onProgressUpdatemethod that was previously added. -
Update the
setResourceLoadermethod in the ProgressBar class to listen to theProgressEvent.PROGRESSevent and call theonProgressUpdatemethod:
public function setResourceLoader(resourceLoader:ZIPResourceLoader):void { resourceLoader.addEventListener(ProgressEvent.PROGRESS, onProgressUpdate); }- Implement the
onProgressUpdatemethod in the ProgressBar class to update the progress bar based on the bytesLoaded and bytesTotal values received from the progress event:
public function onProgressUpdate(event:ProgressEvent):void { progress = event.bytesLoaded / event.bytesTotal; updateProgressBar(); } -
- User
ничего не поменялось
- Assistant
I apologize for the confusion. To address the issue, let's make sure we update the
ProgressBarclass correctly.- Modify the
setResourceLoadermethod in theProgressBarclass as follows:
public function setResourceLoader(resourceLoader:ZIPResourceLoader):void { resourceLoader.addEventListener(ProgressEvent.PROGRESS, onProgressUpdate); }- Update the
onProgressUpdatemethod in theProgressBarclass to accept the progress event and update the progress bar:
public function onProgressUpdate(event:ProgressEvent):void { progress = event.bytesLoaded / event.bytesTotal; updateProgressBar(); }-
Remove the
onUpdatemethod from theProgressBarclass.
- Modify the
- User
зачем ты мне выдаешь одно и тоже, не работает это
- Assistant
I apologize for any confusion. To further assist you, please provide the updated code for both the
ZIPResourceLoaderclass and theProgressBarclass. This will allow me to review the code and determine the specific issue causing the progress bar to not update correctly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.