查看: 4011|回复: 5

[有事请教] 判断某文件是否存在,用条件分歧的脚本怎么写?

[复制链接]
梦石
8
星屑
3963
在线时间
397 小时
注册时间
2017-10-11
回帖
114
发表于 2020-6-28 03:15:31 | 显示全部楼层 |阅读模式

加入我们,或者,欢迎回来。

您需要 登录 才可以下载或查看,没有账号?注册会员

×
例如,判断某个文件名的图片是否存在,存在则显示,不存在则跳过。
梦石
0
星屑
7801
在线时间
683 小时
注册时间
2012-7-29
回帖
172
发表于 2020-6-28 05:23:21 | 显示全部楼层
我可能会用这段代码来实现判断文件是否存在:
[pre lang="javascript"]require('fs').existsSync('img/animations/Absorb.png');[/pre]
但是对于1楼所描述,遇到不存在的图片就跳过的效果,我认为另一个方法实现得更加简便。方法是让显示图片命令遇到不存在的图片时不报错。

要实现图片缺失却不报错,可以试试下面这个插件:
来源:https://raw.githubusercontent.com/triacontane/RPGMakerMV/master/ThroughFailedToLoad.js
插件本体[pre lang="javascript"]//=============================================================================
// ThroughFailedToLoad.js
// ----------------------------------------------------------------------------
// Copyright (c) 2015-2017 Triacontane
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 2.3.1 2017/10/30 アニメーション画像に対するエラーが無視が無効になっていた問題を修正
// 2.3.0 2017/10/29 音声ファイルと画像ファイルのいずれかのみ無視する機能を追加
// 2.2.0 2017/06/18 本体v1.5.0で機能しなくなる問題を修正
// 2.1.1 2017/03/11 通常版1.3.5でエラーになる問題を修正
// 2.1.0 2017/03/11 本体v1.3.5(コミュニティ版)で機能しなくなる問題を修正
// 2.0.0 2016/08/05 本体v1.3.0対応(1.2.0では使えなくなります)
// 1.0.0 2016/06/25 初版
// ----------------------------------------------------------------------------
// [Blog]   : https://triacontane.blogspot.jp/
// [Twitter]: https://twitter.com/triacontane/
// [GitHub] : https://github.com/triacontane/
//=============================================================================

/*:
* @plugindesc Through Failed to load
* @author triacontane
*
* @param InvalidIfTest
* @desc Not through if test play.
* @default true
* @type boolean
*
* @param InvalidIfWeb
* @desc Not through if Web mode.
* @default false
* @type boolean
*
* @param ThroughType
* @desc 無視する素材の種別です。
* @default 3
* @type select
* @option Audio Only
* @value 1
* @option Image Only
* @value 2
* @option All
* @value 3
*
* @help Through error of Failed to load.
* Image not found, Audio not found.
*
* This plugin is released under the MIT License.
*/
/*:ja
* @plugindesc ロード失敗エラーのすり抜けプラグイン
* @author トリアコンタン
*
* @param テストプレー時無効
* @desc テストプレー時は本プラグインの機能が無効になります。
* @default true
* @type boolean
*
* @param Web版で無効
* @desc Web版実行時は本プラグインの機能が無効になります。
* @default false
* @type boolean
*
* @param 無視種別
* @desc 無視する素材の種別です。
* @default 3
* @type select
* @option 音声のみ
* @value 1
* @option 画像のみ
* @value 2
* @option 全て
* @value 3
*
* @help 存在しない画像、音声素材が指定された場合に発生するエラーを無視します。
* 音声の場合は何も再生されず、画像の場合は空の透明画像がセットされます。
*
* エラーログは通常通り出力されます。
*
* 本体v1.5.0より正式に実装されたロード失敗時に3回までリロードする機能については
* 当プラグインの機能と競合するため、無効化されます。
*
* フォント、データベースまたはプラグインで追加されたファイルの読み込みに
* 失敗した場合は、通常通りエラーが発生します。
*
* このプラグインにはプラグインコマンドはありません。
*
* 利用規約:
*  作者に無断で改変、再配布が可能で、利用形態(商用、18禁利用等)
*  についても制限はありません。
*  このプラグインはもうあなたのものです。
*/

(function() {
    'use strict';
    var pluginName = 'ThroughFailedToLoad';

    var getParamOther = function(paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames];
            if (name) return name;
        }
        return null;
    };

    var getParamBoolean = function(paramNames) {
        var value = (getParamOther(paramNames) || '').toUpperCase();
        return value === 'ON' || value === 'TRUE';
    };

    var getParamNumber = function(paramNames, min, max) {
        var value = getParamOther(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(value) || 0).clamp(min, max);
    };

    //=============================================================================
    // パラメータの取得と整形
    //=============================================================================
    var paramInvalidIfTest = getParamBoolean(['InvalidIfTest', 'テストプレー時無効']);
    var paramInvalidIfWeb  = getParamBoolean(['InvalidIfWeb', 'Web版で無効']);
    var paramThroughType   = getParamNumber(['ThroughType', '無視種別'], 1, 3);

    //=============================================================================
    // プラグイン無効条件の判定
    //=============================================================================
    if (paramInvalidIfTest && Utils.isOptionValid('test')) {
        return;
    } else if (paramInvalidIfWeb && !Utils.isNwjs()) {
        return;
    }

    if (paramThroughType !== 1) {
        //=============================================================================
        // Bitmap
        //  エラー発生用のフラグをキャンセルします。
        //=============================================================================
        var _Bitmap_isReady = Bitmap.prototype.isReady;
        Bitmap.prototype.isReady = function() {
            if (this.isError()) {
                this.eraseError();
            }
            return _Bitmap_isReady.apply(this, arguments);
        };

        var _Bitmap_decode = Bitmap.prototype.decode;
        Bitmap.prototype.decode = function(){
            _Bitmap_decode.apply(this, arguments);
            if (this._loadingState === 'requesting') {
                this._image.addEventListener('error', this._onError.bind(this));
            }
        };

        Bitmap.prototype.eraseError = function() {
            this._hasError     = false;
            this._isLoading    = false;
            this._loadingState = 'loaded';
        };

        //=============================================================================
        // Graphics
        //  エラーイベントを登録します。
        //=============================================================================
        var _Graphics__playVideo = Graphics._playVideo;
        Graphics._playVideo      = function(src) {
            _Graphics__playVideo.apply(this, arguments);
            this._video.onerror = this._videoLoader || this._onVideoError.bind(this);
        };
    }

    if (paramThroughType !== 2) {
        //=============================================================================
        // AudioManager
        //  エラーチェック処理を無視します。
        //=============================================================================
        AudioManager.checkErrors = function() {};
    }

    if (typeof ResourceHandler !== 'undefined') {
        //=============================================================================
        // ResourceHandler
        //  リトライ機能の仕様を変更します。
        //=============================================================================
        var _ResourceHandler_createLoader = ResourceHandler.createLoader;
        ResourceHandler.createLoader = function(url, retryMethod, resignMethod, retryInterval) {
            return this.isNeedLoader(url) ? _ResourceHandler_createLoader.apply(this, arguments) : null;
        };

        ResourceHandler.isNeedLoader = function(url) {
            if (paramThroughType === 1 && !url.match(/^audio\//)) {
                return true;
            } else if (paramThroughType === 2 && (!url.match(/^img\//) && !url.match(/^movie\//))) {
                return true;
            } else {
                return false;
            }
        };
    }
})();

[/pre]

这样一来,就可以在事件执行内容中随心所欲地显示图片,遇到不存在的图片也不会报错了。这个方法省去了写条件分歧的工作量。

评分

参与人数 1赞 +1 收起 理由
CCD0645 + 1 认可答案

查看全部评分

回复

使用道具 举报

老黄鸡

梦石
4
星屑
45733
在线时间
7952 小时
注册时间
2009-7-6
回帖
13338

MZ评测员RM创作大赛01组委会开拓者贵宾

发表于 2020-6-28 08:40:42 | 显示全部楼层
给bitmap加一坨函数

[pre lang="javascript"]Bitmap.prototype.setErrorListener = function(listner) {
        if (!this.isError() && this._image) {
                this._image.removeEventListener('error', this._errorListener);
                this._image.addEventListener('error', this._errorListener = listner);
        } else {
                listner(this);
        }
};[/pre]

测试
[pre lang="javascript"]var callback = function() {
  console.log('8存在');
};
var bitmap = ImageManager.loadPicture("test");
bitmap.setErrorListener(callback.bind(this));[/pre]

当然,这个方法是异步的,不一定能立刻获得结果
所以一般加一个addLoadListener来确认是否成功
RGDirect - DirectX驱动的RGSS,点我了解.
(排满,暂停)RM全系列成套系统定制请联系QQ1213237796
不接受对其他插件维护的委托
回复

使用道具 举报

梦石
0
星屑
1343
在线时间
153 小时
注册时间
2020-4-26
回帖
146
发表于 2020-6-28 08:46:10 | 显示全部楼层
但以遊戲開發的角度,什麼情況會出現,圖片資源存在的不肯定呢?會用到,你就會放,他就該在
因為fs是node.js的模組,打包的方式不支援就不能用

点评

同意,不如研究检查文件完整性的方案来得实在。不过也许楼主是想做ARG游戏,让玩家去改文件名,改对了才显示。这就需要判断文件存在与否了。  发表于 2020-6-28 12:23
回复

使用道具 举报

梦石
2
星屑
2676
在线时间
204 小时
注册时间
2020-5-21
回帖
116

RM创作大赛01参赛者

发表于 2020-6-28 09:44:44 | 显示全部楼层
耶,收藏
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部