package { import flash.display.Sprite; import flash.display.Shape; import…
- User
package { import flash.display.Sprite; import flash.display.Shape; import flash.events.Event;
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 function ProgressBar() { init(); }
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):void { progress = value; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } } } } почему прогресс бар движется сам, не зависимо от того сколько скачало, класс скачивания 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;
public class ZIPResourceLoader { 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 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 onDownloadComplete(event:ProgressEvent):void { var percent:Number = event.bytesLoaded / event.bytesTotal; progressBar.setProgress(percent); 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 progress bar moves independently of the download progress because the
onUpdatefunction in the class is continuously increasing the variable by 0.01 every frame. This causes the progress bar to gradually fill up even if the download progress has not reached that point yet. - User
а это случаем не в main.as добавлять надо ?
- Assistant
No, you do not need to add the modifications in the
Main.asfile. The modifications need to be made in theZIPResourceLoaderandProgressBarclasses themselves.In your application's
Main.asfile, you can create an instance of theProgressBarclass and an instance of theZIPResourceLoaderclass. Then, you can add theProgressBarinstance to the stage and pass it as a parameter to theZIPResourceLoaderconstructor.Here's an example of how you can update your
Main.asfile to instantiate theProgressBarandZIPResourceLoaderclasses:package { import flash.display.Sprite; import ProgressBar; import ZIPResourceLoader; public class Main extends Sprite { private var progressBar:ProgressBar; private var resourceLoader:ZIPResourceLoader; public function Main() { progressBar = new ProgressBar(); addChild(progressBar); resourceLoader = new ZIPResourceLoader(progressBar); } } } - User
C:\Users\Alexander\Desktop\project\Preloader\src\ProgressBar.as(20): col: 19 Error: Call to a possibly undefined method addEventListener through a reference with static type Class. ZIPResourceLoader.addEventListener(ZIPResourceLoader.PROGRESS_UPDATE, onProgressUpdate); ошибка
- Assistant
The error message you're seeing is because you're trying to call the
addEventListenermethod on theZIPResourceLoaderclass itself, which is a static reference to the class. However,addEventListeneris an instance method and should be called on an instance of theZIPResourceLoaderclass.To fix this error, you need to create an instance of the
ZIPResourceLoaderclass and then call theaddEventListenermethod on that instance. Here's an example of how you can update yourProgressBarclass:public class ProgressBar extends Sprite { // ... public function ProgressBar() { // ... init(); } public function setResourceLoader(resourceLoader:ZIPResourceLoader):void { resourceLoader.addEventListener(ZIPResourceLoader.PROGRESS_UPDATE, onProgressUpdate); } // ... } - User
все равно прогресс бар идет произвольно, не зависимо скачивается или нет
- Assistant
- User
public function setProgress(value:Number):void { progress = value; if (progress < 0) { progress = 0; } else if (progress > 1) { progress = 1; } } может дело в этом
- Assistant
Yes, the issue might be in the
setProgress()function of theProgressBarclass.In the current implementation, the
setProgress()function updates theprogressvariable based on the provided value, but it also limits the value to a range between 0 and 1. However, if thevalueparameter is obtained from the download progress (which could potentially exceed 1), limiting it to 1 will prevent the progress bar from reflecting the complete download progress.To resolve this issue, you can modify the
setProgress()function to remove the limit on theprogressvalue, or you can add an additional parameter to specify the maximum value for the progress bar. Here's an example:public function setProgress(value:Number, maxValue:Number = 1):void { progress = value; if (progress < 0) { progress = 0; } else if (progress > maxValue) { progress = maxValue; } updateProgressBar(); }With this modification, you can pass the maximum value of the progress bar (the expected total download progress) to the function when you call it. This ensures that the progress bar will accurately represent the download progress up to the provided maximum value.
- User
не помогло, все равно не показывается сколько скачалось, просто идет вперед и все, не зависимо сколько скачалось
- Assistant
I apologize for the confusion. It seems that I'm missing some crucial details about your implementation.
To clarify, the
ProgressBarclass itself does not have any knowledge of the download progress unless it is explicitly provided with the progress information. In the provided code, theProgressBarclass has asetProgress()function that allows you to manually set the progress value. However, it seems that this function is not being called with the actual download progress from theZIPResourceLoaderclass.To make the progress bar update based on the actual download progress, you need to modify the
ZIPResourceLoaderclass to dispatch progress events that contain the relevant information. Then, you can listen for these progress events in the `