- Сообщений: 727
- Спасибо получено: 124
Скрипт касается лимита инвентаря.Помогите улучшить
Во-первых, там синтаксические ошибки, из-за которых игра вообще не должна запуститься.
Во-вторых, "if @items[item_id] = SynItemMax::Max_item[item_id]" - это ещё что такое? Присваивание вместо оператора сравнения, да ещё и в условии.
В-третьих, ещё один бред в "else".
Короче говоря, что-то ты странный какой-то скрипт привёл. Я думаю ты сам там что-то намутил и потом сюда выложил. И даже банально на ошибки не проверил.
Ещё один момент. Из твоего сообщения совершенно не понятно, что тебе нужно. То ли чтобы вещи в сундуках оставались при превышении лимита, то ли чтобы сообщение показывалось, то ли ещё что-то. Короче говоря, чётко и ясно объясняй - что нужно. Чтобы сразу было понятно.
И пользуйся тегом code.
→ → ↓ ↑ Y
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
Здесь ты не совсем прав. Такая конструкция допустима, я уже об этом писал. В развернутом видел эта строка будет выглядеть так:Во-вторых, "if @items[item_id] = SynItemMax::Max_item[item_id]" - это ещё что такое? Присваивание вместо оператора сравнения, да ещё и в условии.
@items[item_id] = SynItemMax::Max_item[item_id]
if (@items[item_id] != nil && @items[item_id] != false)
Другое дело, что в нашем случае это не подходит и должен стоять именно оператор сравнения: ==
Тут все просто - аффтор копипастил блоки своего скрипта и делал это донельзя криво. Даже end'ы кое-гдн остались.В-третьих, ещё один бред в "else".
Maximus
Ошибок там конечно... Лучше бы ты сам скрипт написал, а не чужой какой пользовался... Да и не удобен он будет в использовании... Впрочем, ладно. Скрипт я исправил, теперь будет работать (протестил на предметах даже!). Теперь собственно, касательно самой работы.
Сундук у тебя должен выглядить примерно так:
Две страницы. Обе "on action button / по нажатию кнопки". На второй в качестве условия указываешь "Local Switch - A / Личный переключатель A". На первой вставляешь события:
"Change Item(Armor, Weapon...) / Изменить количество предметов (Доспехов, оружия)": выдаешь нужный предмет.
Далее создаешь условие "Conditional Branch / Условие": в качестве условия выбираешь "Switch / Переключатель" - Номер 276 - Это зарезервированный этим скриптом переключатель, что еще раз говорит о криворукости автора, не используй его в своей игре кроме сундуков. Поставь галочку на создание ветки "else".
В действиях до else вызываешь "Change local switch / Переключить личный переключатель" - выбираешь A. Можешь вывести сообщение "Show Message / Показать сообщение": "Поздравляю! Вы нашли кокосы!"
В действиях после else (до end) Выводишь сообщение "Show Message / Показать сообщение": "Количество кокосов в вашем инвентаре уже достигло максимума! Приходите позже!"
Вот собственно и все. Добавлю, что данный скрипт жутко неудобен и, по сути, бесполезен. Больше возни с ним, чем пользы. А если ты выдаешь несколько предметов, то скрипт еще и попортит игроку нервы. Так что пользовать его я не рекомендую. Масамунэ - он все равно уникален. А если какого-то предмета уже накопилось 99, то я сомневаюсь, что они уже кончатся до самого конца игры. Можно использовать, для расширения или уменьшения количества предметов... но тогда убери из кода переключатель. Короче - скрипт на 2'йку с натягом.
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Сообщений: 727
- Спасибо получено: 124
Нет ты.Здесь ты не совсем прав.
Кроме этого, мог бы ещё пару минусов заметить.
Первое. По достижении максимума в какой-либо вещи невозможно будет взять любую другую вещь из сундука. Ибо блокирующий свитч всего один.
Второе. Если проверять его в игре на торговце, то получится что можно покупать сверх лимита, хотя и в инвентаре будет лежать только установленный максимум. Очевидно, что требует переработки и Shop_Processing.
Третье. Проверка на максимум вещей - фуфло. Возьмём например пули. Максимум в инвентаре - 100. У нас в кармане - 99. В сундуке - 50. Этот скрипт положит одну пулю нам в карман, а 49 выбросит на ветер. По условию, поставленному автором такого тоже происходить не должно.
Скрипт убогий до невозможности. Поэтому я от автора и добиваюсь - чего ему надо-то. По хорошему тут вообще другой подход нужен.
→ → ↓ ↑ Y
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Agckuu_Coceg
-
- Не в сети
- Живу я здесь
-
- Простой Гинтокист с огромной внутренней ленью.
- Сообщений: 1549
- Спасибо получено: 329
Я конечно, не сильно соображаю, как это можно сделать, но попробую пошерудить в нём. Если кто ещё захочет обработать, ссылку я даю.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
Извини, но ты слишком бурно отреагировал на это, и мне показалось, что тебе претит сама мысль о присваивании в условии, тогда, как иногда это в несколько раз ускоряет работу скрипта, а в случае с циклами, попрой, и вовсе единственный вариант (ибо перед if'ом можно задать переменную, а перед циклом, если она изменяется внутри него - нет[не поможет]).Нет ты.
Синтаксически правильная конструкция ещё ни о чём не говорит. Речь шла о логической ошибке использования присваивания в условии. Что должно было иметься в виду это и так ясно. По крайней мере мне и тебе.
Я и заметил, о чем и написал:Кроме этого, мог бы ещё пару минусов заметить.
Первое. По достижении максимума в какой-либо вещи невозможно будет взять любую другую вещь из сундука. Ибо блокирующий свитч всего один.
А если ты выдаешь несколько предметов, то скрипт еще и попортит игроку нервы.
Мимо. Существует множество способов получить предметы - трофеи с монстров, торговцы, кастомные системы крафта и прочее. Здесь обсуждались сундуки. о них и речь.Второе. Если проверять его в игре на торговце, то получится что можно покупать сверх лимита, хотя и в инвентаре будет лежать только установленный максимум. Очевидно, что требует переработки и Shop_Processing.
Да, ты прав. Этого не заметил.Третье. Проверка на максимум вещей - фуфло. Возьмём например пули. Максимум в инвентаре - 100. У нас в кармане - 99. В сундуке - 50. Этот скрипт положит одну пулю нам в карман, а 49 выбросит на ветер. По условию, поставленному автором такого тоже происходить не должно.
Agckuu_Coceg
В следующий раз давай, пожалуйста, сам скрипт...
Вот и он, кстати:
Скрипт поглядел. Выглядит довольно надежным... но мне не нравится. Аффтор мог бы снизойти до пробелов - отсутпы еще никого не убили. Да и слишком много лишнего кода. Вот только... он просто управляет максимумом предметов в инвентаре. Включая магазинные и трофейные... Замечательно... Но оставлять предметы в сундуке он и не думает.
P.S. А идея с сундуками взята на заметку. Будет свободное время - обязательно реализую! Если коротко, то уже давно хочу сделать скриптовые шаблоны событий. Типы будут указываться в первом комментарии. Там же, наверное, и параметры. По части этого примера, будет класс - Chest. У него будет свой инвентарь, на манер Game_Party... может наследником сделать?.. В общем, если действительно хочется полноценных сундуков из которых можно брать до определенного предмета в красивом окошке - копайте в эту сторону. А пляски с бубном вокруг стандартных классов не принесут ничего хорошего.
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Рад что на этом форуме есть ребята которые шарят в RGSS. Ну так ближе к делу.
Попробую объяснить более конкретно. Хотя основную суть вы уже поняли!
Что я хочу:
1. Да речь идёт о сундуках. Я заметил что, если делать сундуки на свитчах и вэрибалах, то при достижении лимита вмещаемости Вашего инвентаря, свитч перелистывает страницу эвента на пустой лист. А шмотки с первого листа эвента соответственно исчезают. Пример: У Вас в сундуке лежит ключь, для открытия двери, игрок - жадынй лутер. Собирает нужный и не нужный хлам. Инвентарь достиг лимита. Получается так, что игрок берёт ключь и ключик исчезает. Игрок вынужден загружать LOAD. Или вообще начинать сначало! Только из за того что игроку не пройти дальше, не открыть дверь. Тоесть по сути, я предложил один из методов закрытия этого глюка через теже свитчи!
2. Конечно, хотелось бы иметь красивое окошечко, с вещами в нём, при открытии сундучка или трупа. И конечно же было бы здорово иметь систему вмещаемости инвентаря, похожую как в Diablo или Fallout.
Вообщем-то, я нашёл один из вариантов создания такой системы на Varibal и Common Events. Очень легко.
1. Создаёшь вещь, называешь её "ВЕС" например.
2. Создаешь для каждой вещи conditinl branch c словием "IF "название вещьи" in invetary = change item discrase "Вес"." Таким оброзом криэтится шмотка ВЕС у в инвентаре.
3. Устанавливаеи лимит. Создаём CONTROL VARIBL где ставим Varible = ВЕС in Inventary.
4. Создаём проверку лимита. Conditional Branch IF Varible == ВЕС >= 100 Switch 02 Запереть сундук On. Таким оброзом шмотки из сундуков сохряняются, за счёт того что сундук заперается, за счёт свитча.
Вот собственно моя идея! Есть у Вас идеи по решению этой проблемы выкладывайте. Я скажу так, что идея скрипта возможно уникальна. Я не в одной игре на Мэйкере такого не видел. Возмодно только Baldurs Gate.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
1. Игрок берет предмет.
2. Идет проверка заполнен ли инвентарь.
3. Если заполнен, то идет проверка предмет был в сундуке(или любом обьекте по типу сундука) или же нет(тоесть, просто лежал на земле или получен от нпц/oбъекта).
4. Если инвентарь заполнен, а предмет был в сундуке, то он там и остается.
5. Если инвентарь заполнен, а предмет был получен другим способом(см. выше) то он падает на землю в том месте где стоит ГГ.
Сомневаюсь что на условиях такое можно сделать, а если и можно, то гемора будет предостаточно. А вот на RGSS я думаю можно.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
Можно, только есть одно "но". В RPG Maker 1 слой для событий. Ну и что будет, если игрок получил предмет стоя на каком-нибудь событии? Скажем, на том же сундуке? :dry: Можно, конечно, сделать 2ой слой событий, специально для тех ивентов, что подгружаются не с карты, а создаются во время работы, вот только... легче написать нормальные сундуки.Я себе это по другому представлял:
1. Игрок берет предмет.
2. Идет проверка заполнен ли инвентарь.
3. Если заполнен, то идет проверка предмет был в сундуке(или любом обьекте по типу сундука) или же нет(тоесть, просто лежал на земле или получен от нпц/oбъекта).
4. Если инвентарь заполнен, а предмет был в сундуке, то он там и остается.
5. Если инвентарь заполнен, а предмет был получен другим способом(см. выше) то он падает на землю в том месте где стоит ГГ.
Сомневаюсь что на условиях такое можно сделать, а если и можно, то гемора будет предостаточно. А вот на RGSS я думаю можно.
Maximus писал(а):
Хм, а что за систему инвентаря ты используешь? Дело все в том, что дефолтная система безразмерна и инвентарь может содержать абсолютно все предметы в игре в размере 99 штук. Так что единственной причиной, по которой ключ может "исчезнуть" из сундука - если у игрока уже 99 ключей.1. Да речь идёт о сундуках. Я заметил что, если делать сундуки на свитчах и вэрибалах, то при достижении лимита вмещаемости Вашего инвентаря, свитч перелистывает страницу эвента на пустой лист. А шмотки с первого листа эвента соответственно исчезают. Пример: У Вас в сундуке лежит ключь, для открытия двери, игрок - жадынй лутер. Собирает нужный и не нужный хлам. Инвентарь достиг лимита. Получается так, что игрок берёт ключь и ключик исчезает. Игрок вынужден загружать LOAD. Или вообще начинать сначало! Только из за того что игроку не пройти дальше, не открыть дверь. Тоесть по сути, я предложил один из методов закрытия этого глюка через теже свитчи!
Что касается веса и инвентаря... JRPG не очень то приспоболены для этого, да и дополнительные параметры придется вводить. В PRGMakerVX, например, есть поле Note, в которое их можно вбить. В XP - нету. Следовательно, либо модуль, либо внешние базы... либо новый мейкер...
P.S. Касательно шаблонов: делается это, примерно так...
В маповском интерпретаторе создаем проверку на первое действие. Если комментарий - парсим его на предмет искомого имени шаблона. Например - [Box]. Если находим - переключаем на соответствующий метод (пишем сами), который согласно последующим действиям, создаст новый объект класса RPG::Box(пишем сами) и запишет его в хэш с сылкой на карту, координаты и имя события, если такого еще нет. Далее при проверке карты будем учитывать этот хэш, а при сохранении-загрузки - сохранять и его... Вот... Если кто понял - можете попробовать реализовать. У меня времени нет.
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Можно, только есть одно "но". В RPG Maker 1 слой для событий. Ну и что будет, если игрок получил предмет стоя на каком-нибудь событии? Скажем, на том же сундуке? Можно, конечно, сделать 2ой слой событий, специально для тех ивентов, что подгружаются не с карты, а создаются во время работы, вот только... легче написать нормальные сундуки.
Как на счетдополнительного условия, если ГГ стоит на событии предмет дропнется в ближайшую свободную клетку. (Не думаю, что карта может быть без свободных клеток, да и маловероятна ситуация получения больше 2х-3х предметов от нпц/объекта одновременно.)
Кстати вспомни Балдурсгейт(если играл конечно), там лут лежащий в одной точке учитывался потипу сундука. И когда ты открывал меню, то видел список предметов которые лежали в этой куче.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
Вот на Game Maker - сколько угодно. Но не здесь. Ну, вот пример - сундук в укромном уголке, перед ним игрок, а сзади 3 из его комманды. А рядом стена с оградой и за ней - свободные клетки. А добираться до них через весь город. Ну и куда дропнется итем? И как это логически объяснить? А после перехода с карты он исчезнет. Надо сохранять. А если их много? Надо сохранять все содержимое. А значит мы возвращаемся к вышеозначенным шаблонным сундукам.
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Что не позволяет использовать эту систему в моём проекте.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Agckuu_Coceg
-
- Не в сети
- Живу я здесь
-
- Простой Гинтокист с огромной внутренней ленью.
- Сообщений: 1549
- Спасибо получено: 329
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Equilibrium Keeper, а может тебе не стоит писать сундучки с нуля, вот поковряй этот уже готовый. Я посмотрел демку, помойму круть. Ну не идеал конечно!
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Agckuu_Coceg
-
- Не в сети
- Живу я здесь
-
- Простой Гинтокист с огромной внутренней ленью.
- Сообщений: 1549
- Спасибо получено: 329
Agckuu_Coceg, где ты такой скрипт нарыл? Он по сути своей, то что нужно. Кстати я почему-то не нашёл ничего по добного на буржуйских сайтах. Спасибо тебе огромное, поковыряю.
Профессия поисковика скриптов обязывает рыскать по всем местам...
А нашёл я его на Хаосе, форуме Близзарда. Там порой хорошие скрипты встречаются, я тебе скажу. Только региться не вздумай, а то там такая анти-спамерская хрень стоит, что они потом тебя не допустят на сайт. А скрипты можно и за просто так брать. Ссылку я давал в теме с базами скриптов, но если тебе надо, вот, держи.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Maximus писал(а):
Agckuu_Coceg, где ты такой скрипт нарыл? Он по сути своей, то что нужно. Кстати я почему-то не нашёл ничего по добного на буржуйских сайтах. Спасибо тебе огромное, поковыряю.
Профессия поисковика скриптов обязывает рыскать по всем местам...
А нашёл я его на Хаосе, форуме Близзарда. Там порой хорошие скрипты встречаются, я тебе скажу. Только региться не вздумай, а то там такая анти-спамерская хрень стоит, что они потом тебя не допустят на сайт. А скрипты можно и за просто так брать. Ссылку я давал в теме с базами скриптов, но если тебе надо, вот, держи.
Agckuu_Coceg, плюс один, тебе ещё раз! И спасибо огромное!
Я думаю тему можно закрыть, до того момента пока Equilibrium не накатает вышеупомянутые "Шаблонные сундучки" и не выложет их на обсуждение. Всем участникам БОЛЬШОЕ СПАСИБО!
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Equilibrium Keeper
-
- Не в сети
- Захожу иногда
-
- Скриптер
- Сообщений: 119
- Спасибо получено: 3
P.S. Блин, просил же - выкладывайте скрипты, а не ссылки на демки... -_-
Истина там, во тьме, и во тьме ты иди - мыслящий бродит во тьме.
В себя самого загляни, открой свою дорогу в Ничто.
В Ничто ты войди, во тьму, и пойми:
Пока ты во тьме, не может она быть Ничем - ведь там ты.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
- Agckuu_Coceg
-
- Не в сети
- Живу я здесь
-
- Простой Гинтокист с огромной внутренней ленью.
- Сообщений: 1549
- Спасибо получено: 329
# Alisha's Storage Containers
#
# by DerVVulfman
# version 1.0
# 07-23-2009
# RGSS / RMXP - Involves Rewrites
#==============================================================================
# INTRODUCTION:
#
# This system allows you to create re-usable chests and other forms of con-
# tainers on your map. Rather than just finding a chest to get your loot,
# you can return to the chest and put stuff back in for later. You can put
# items, weapons, armor and even gold into these storage containers which
# you can retrieve later.
#
#
# INSTALLATION INSTRUCTIONS:
#
# Please remember that this system allows you to use script calls to change
# Place below Scene_Debug and above Main to use. Please note that this sys-
# tem does rewrite the 'read_save_data' method in Scene_Load, though it is
# merely a single line of code.
#
# Should be easy to spot.

#
#
# HOW TO USE:
#
# This system doesn't make the actual container events on your map, so you
# still have to use the map editor to draw your chests, bookshelves, safes,
# barrels, or whatever.
#
# After you make your map, including these chests or whatnot, you insert a
# comment into your desired map event containers. This comment is a single
# line of text (or even just one word) that matches the CONTAINER_KEY value
# in the configuration section. By default, this is set to 'container'. It
# is this comment that helps to trigger your container menu.
#
# Once you add the CONTAINER_KEY value, you also take note or change the
# name of your container's map event name. Typically, it is something like
# 'EV003', but you will likely wish to change it to something fairly recog-
# nizable. This 'new event name' will identify the exact contents of the
# storage container in this system, and the related CONTAINERS array.
#
# ____________________________________________ Please note that the con-
# | tainer's 'new event name'
# | Name: must be unique. It is not
# | [ EV-MyContainer-12 ] advised to have 2 map con-
# | ______ tainers sharing the same
# | | |
name unless you want them
# | | 1 | 2 | to use the same array.
# | | |_____|____________________________
# | | List of Event
Could be fun though.# | | ______________
# | | -Conditions
|| Put stuff in one chest and
# | | | || pick it up in the other.
#
#
#
# THE CONFIGURABLES:
#
# Actually, this isn't so hard.
#
# CONTAINER_KEY:
# ==============
# The first value in the configuration section is the CONTAINER_KEY. It is
# part of the trigger mechanism that lets the system know that this event
# can store your items. Whatever you have this value set must be an exact
# match to the text in your event's comment. For simplicity, I merely have
# it set to 'container'.
#
# CONTAINER_INPUT:
# ================
# When you finally trigger a container (be it barrel or chest), you will
# see a split screen. On the left is your current party's list of goods,
# while the right side lists the items in the container. Now while the
# select, cancel and arrow keys are already in use, I needed another key to
# switch between target windows. Hence, the CONTAINER_INPUT feature. By
# default, this is set to Input::A which is also the 'shift' button, but
# it can be changed to suit your tastes.
#
#
# CONTAINERS:
# ===========
# The final piece of the system. This is a complex array that creates each
# and every container array used in your game. Each container array must
# have a unique name, and any container 'event' in your game map(s) must
# have a name that corresponds to the name of an array in CONTAINERS.
#
# The syntax for the CONTAINERS array is as follows:
#
# CONTAINERS = [ container_array, container_array,.... container_array ]
#
# And each of these 'container_array' values is in itself another array with
# it's own syntax... as follows:
#
# [ 'container', [ itemlist ] ]
#
# The 'container' is a text string that matches the name of the map event
# to become a storage container. So, if you have a map event named chest2,
# then the text string in your container array would also be 'chest2'.
#
# When you finally trigger a container (be it barrel or chest), you will
# Now, the itemlist inside the braces [] is a list of items, weapons and
# even gold. that your container hold whtn the game starts. The information
# you enter uses a form of shortcuts to identify the type of goods, the ID
# number of the goods, and the quantity thereof. An example of an itemlist
# is presented below:
#
# [ 'i2201', 'w201', 'g2332', 'a102', 'i104' ]
#
# As you can tell, every item within this itemlist is a string. This is
# so you can use a simple and memorable series of prefixes in the itemlist.
# The first character for each item string identifies whether the item is a
# weapon, armor or whatever. As such, the following four prefixes are used:
#
# i = item * w = weapon * a = armor * g = gold
#
# Now, all items, with the exception of gold, follow the same rudimentary
# rules:
#
# --Items Coding--
# Following the prefix, the text includes the ID number of your item, wea-
# pon or armor. This ID number can be from 1 digit to 3 digits long. The
# 3 digit limit is the imposed limit set by the RMXP editor.
#
# After the ID number of your item, you follow it up with a two-digit entry
# which indicates the quantity of that item. While the number of digits for
# the ID number is flexible, the number indicating the quantity is not. You
# must use two characters to represent the quantity.
#
# As such, creating an entry for three bronze swords would be as follows:
#
# 'w103' .... ' w (for weapon) 1 (for the 1st ID) 03 (for 3 quantity) '.
#
# --Gold Coding--
# Slightly different, but easier to follow is the coding for gold stored in
# your array. It's merely the 'g' prefix followed by a range of numbers
# from 1 to 7 digits long (as set by the limits in RPGMaker XP).
#
# Just to let you know, it is pointless to have 'two' gold entries in a
# single itemlist. So an entry like this is kind of useless:
#
# [ 'i2201', 'g2001', 'g432' ]
#
# The system will not combine the two 'gold' entries, but will opt to use
# the last entry instead. In this case, 432 in gold will be in this chest.
#
# --Empty Coding--
# The system will not combine the two 'gold' entries, but will opt to use
# What? You thought you HAD to have something in every container as the
# game starts? Fat chance. You can have barrels that are dead empty. All
# you have to do is have 'nothing' in the braces. Yep, just don't give it
# a list of items, as this example shows:
#
# [ 'sample_container', [] ]
#
# And that's all there is to it.
#
#
#
# COMPATABILITY:
#
# Designed for use with RPGMakerXP, this system rewrites the read_save_data
# method ing Scene_Load, but it is a common rewrite found in many scripts.
# And I identified the... hehehe... lone line of code, for anyone who would
# need to edit anything.
#
#
# NOTES:
#
# Why didn't anyone make this until now???
#
#
# TERMS AND CONDITIONS:
#
# Free for use, even in commercial games. However, this is an exclusive to
# the 'House Slashers' run by DerVVulfman, Kalier and Mea, and an exclusive
# to the 'RMVXPUniverse' forum owned by PK8 (formerly Punk, Punkid89), and
# run with Olivia and DerVVulfman. It is not for display or distribution
# on any other site or forum.
#
#==============================================================================
#======================================================================
# ** CONFIGURATION ** #
#======================================================================
# Container Comment Key
CONTAINER_KEY = 'container'
# Container Window Switch Key
CONTAINER_INPUT = Input::A
# Storage Containers Array
#
# Name Item Array...
# ======= ==================
CONTAINERS = [
],
],
]
]
#==============================================================================
# ** Game_Party
#
# This class handles the party. It includes information on amount of gold
# and items. Refer to "$game_party" for the instance of this class.
#==============================================================================
class Game_Party
#
# * Public Instance Variables
#
attr_accessor :gold # amount of gold
attr_accessor :items # number of items
attr_accessor :weapons # number of weapons
attr_accessor :armors # number of armor pieces
#
# * Initial Party Setup
#
alias setup_me setup_starting_members
def setup_starting_members
setup_me
# Setup Game Containers at game start
$game_containers.setup
end
end
#==============================================================================
# ** Game_Event
#
# This class deals with events. It handles functions including event page
# switching via condition determinants, and running parallel process events.
# It's used within the Game_Map class.
#==============================================================================
class Game_Event < Game_Character
#
# * Obtain name
#
def name
return @event.nil? ? '' : @event.name
end
#
# * Obtain container trigger value
#
def container_trigger
container_flag = false
# Checks to see if display text
unless @list.nil?
for i in 0...@list.size
if @list.code == 108
container_flag = true if @list.parameters.include?(CONTAINER_KEY)
end
end
end
return container_flag
end
end
#==============================================================================
# ** Game_Player
#
# This class handles the player. Its functions include event starting
# determinants and map scrolling. Refer to "$game_player" for the one
# instance of this class.
#==============================================================================
class Game_Player < Game_Character
#
# * Frame Update
#
alias container_update update
def update
# Original Call
container_update
if Input.trigger?(Input::C)
container_check
end
end
#
# * Detect container
#
def container_check
# Calculate front event coordinates
new_x = @x + (@direction == 6 ? 1 : @direction == 4 ? -1 : 0)
new_y = @y + (@direction == 2 ? 1 : @direction == 8 ? -1 : 0)
# All event loops
for event in $game_map.events.values
# If event coordinates and triggers are consistent
if event.x == new_x and event.y == new_y
# Obtain event name if properly triggered
ev_name = event.name if event.container_trigger == true
end
end
# Test if standing on event
if ev_name == nil
# All event loops
for event in $game_map.events.values
# If event coordinates and triggers are consistent
if event.x == @x and event.y == @y
# Obtain event name if properly triggered
ev_name = event.name if event.container_trigger == true
end
end
end
# Sort through containers for matching event ID
for i in 0..$game_containers.data.size-1
# Switch to Container Screen
$scene = Scene_Container.new(i) if $game_containers.data[0] == ev_name
end
end
end
#==============================================================================
# ** Game_Containers
#
# This class handles the container array. Refer to "$game_containers" for each
# instance of this class.
#==============================================================================
class Game_Containers
attr_accessor :data
attr_accessor :tempgold
#
# * Object Initialization
#
def initialize
@data = []
@tempgold = 0
end
#
# * Get Actor
# actor_id : actor ID
#
def setup
for i in 0..(CONTAINERS.size).to_i-1
@data.push(CONTAINERS)
end
end
end
$game_containers = Game_Containers.new
#==============================================================================
# ** Window_PartyItems
#
# This window displays items in possession on the item and battle screens.
#==============================================================================
class Window_PartyItems < Window_Selectable
#
# * Public Instance Variables
#
attr_accessor :data # list of party items
#
# * Object Initialization
#
def initialize
super(0, 0, 320, 416)
@column_max = 1
refresh
self.index = 0
end
#
# * Get Item
#
def item
return @data[self.index]
end
#
# * Get Item Qty
#
def item_qty
item = @data[self.index]
case item
when RPG::Item ; return $game_party.item_number(item.id)
when RPG::Weapon ; return $game_party.weapon_number(item.id)
when RPG::Armor ; return $game_party.armor_number(item.id)
end
end
#
# * Refresh
#
def refresh
if self.contents != nil
self.contents.dispose
self.contents = nil
end
@data = []
# Add item
for i in 1...$data_items.size
@data.push($data_items) if $game_party.item_number(i) > 0
end
for i in 1...$data_weapons.size
@data.push($data_weapons) if $game_party.weapon_number(i) > 0
end
for i in 1...$data_armors.size
@data.push($data_armors) if $game_party.armor_number(i) > 0
end
# If item count is not 0, make a bit map and draw all items
@item_max = @data.size
if @item_max > 0
self.contents = Bitmap.new(width - 32, row_max * 32)
for i in 0...@item_max
draw_item(i)
end
end
end
#
# * Draw Item
# index : item number
#
def draw_item(index)
item = @data[index]
case item
when RPG::Item
number = $game_party.item_number(item.id)
when RPG::Weapon
number = $game_party.weapon_number(item.id)
when RPG::Armor
number = $game_party.armor_number(item.id)
end
if item.is_a?(RPG::Item) and
$game_party.item_can_use?(item.id)
self.contents.font.color = normal_color
else
self.contents.font.color = disabled_color
end
x = 4 + index
y = index * 32
rect = Rect.new(x, y, self.width / @column_max - 32, 32)
self.contents.fill_rect(rect, Color.new(0, 0, 0, 0))
bitmap = RPG::Cache.icon(item.icon_name)
opacity = self.contents.font.color == normal_color ? 255 : 128
self.contents.blt(x, y + 4, bitmap, Rect.new(0, 0, 24, 24), opacity)
self.contents.draw_text(x + 28, y, 212, 32, item.name, 0)
self.contents.draw_text(x + 240, y, 16, 32, ":", 1)
self.contents.draw_text(x + 256, y, 24, 32, number.to_s, 2)
end
end
#==============================================================================
# ** Window_Container
#
# This window displays items in storage containers found on the map.
#==============================================================================
class Window_Container < Window_Selectable
attr_accessor :data
#
# * Object Initialization
#
def initialize(container_number)
super(320, 0, 320, 416)
@column_max = 1
@container_number = container_number
refresh
self.index = 0
end
#
# * Get Item
#
def item
return @data[self.index][0]
end
#
# * Get Item Qty
#
def item_qty
return @data[self.index][1].to_i
end
#
# * Refresh
#
def refresh
if self.contents != nil
self.contents.dispose
self.contents = nil
end
@data = []
# Add item
newdata = []
newdata = $game_containers.data[@container_number][1]
unless newdata == []
for i in 0..$game_containers.data[@container_number][1].size-1
itemname = newdata
item_size = itemname.size-1
item_type = itemname.slice(0, 1)
item_number = itemname.slice(1,item_size-2).to_i
item_quantity = itemname.slice(item_size-1,2)
case item_type
when 'a' ; @data.push([$data_armors[item_number], item_quantity])
when 'i' ; @data.push([$data_items[item_number], item_quantity])
when 'w' ; @data.push([$data_weapons[item_number], item_quantity])
end
end
end
# If item count is not 0, make a bit map and draw all items
@item_max = @data.size
if @item_max > 0
self.contents = Bitmap.new(width - 32, row_max * 32)
for i in 0...@item_max
draw_item(i)
end
end
end
#
# * Draw Item
# index : item number
#
def draw_item(index)
# Retrieve item and Qty
item = @data[index][0]
number = @data[index][1]
self.contents.font.color = normal_color
x = 4 + index
y = index * 32
rect = Rect.new(x, y, self.width / @column_max - 32, 32)
self.contents.fill_rect(rect, Color.new(0, 0, 0, 0))
bitmap = RPG::Cache.icon(item.icon_name)
opacity = self.contents.font.color == normal_color ? 255 : 128
self.contents.blt(x, y + 4, bitmap, Rect.new(0, 0, 24, 24), opacity)
self.contents.draw_text(x + 28, y, 212, 32, item.name, 0)
self.contents.draw_text(x + 240, y, 16, 32, ":", 1)
self.contents.draw_text(x + 256, y, 24, 32, number.to_s, 2)
end
end
#==============================================================================
# ** Window_Party_Gold
#
# This window displays amount of gold.
#==============================================================================
class Window_Party_Gold < Window_Selectable
#
# * Object Initialization
#
def initialize
super(0, 416, 320, 64)
self.contents = Bitmap.new(width - 32, height - 32)
self.index = 0
refresh
end
#
# * Refresh
#
def refresh
self.contents.clear
cx = contents.text_size($data_system.words.gold).width
self.contents.font.color = normal_color
self.contents.draw_text(4, 0, 260-cx-2, 32, $game_party.gold.to_s, 2)
self.contents.font.color = system_color
self.contents.draw_text(264-cx, 0, cx, 32, $data_system.words.gold, 2)
end
end
#==============================================================================
# ** Window_Container_Gold
#
# This window displays amount of gold in a container.
#==============================================================================
class Window_Container_Gold < Window_Selectable
#
# * Object Initialization
#
def initialize(container_number)
super(320, 416, 320, 64)
self.contents = Bitmap.new(width - 32, height - 32)
self.index = 0
@container_number = container_number
refresh
end
#
# * Refresh
#
def refresh
# Add item
newdata = []
newdata = $game_containers.data[@container_number][1]
unless newdata == []
for i in 0..$game_containers.data[@container_number][1].size-1
itemname = newdata
item_size = itemname.size-1
item_type = itemname.slice(0, 1)
item_number = itemname.slice(1,item_size)
if item_type == 'g'
$game_containers.tempgold = item_number.to_i
end
end
end
self.contents.clear
cx = contents.text_size($data_system.words.gold).width
self.contents.font.color = normal_color
self.contents.draw_text(4, 0, 260-cx-2, 32, $game_containers.tempgold.to_s, 2)
self.contents.font.color = system_color
self.contents.draw_text(264-cx, 0, cx, 32, $data_system.words.gold, 2)
end
end
#==============================================================================
# ** Scene_Save
#
# This class performs save screen processing.
#==============================================================================
class Scene_Save < Scene_File
#
# * Write Save Data
# file : write file object (opened)
#
alias container_write_save_data write_save_data
def write_save_data(file)
container_write_save_data(file)
Marshal.dump($game_containers, file)
end
end
#==============================================================================
# ** Scene_Load
#
# This class performs load screen processing.
#==============================================================================
class Scene_Load < Scene_File
#
# * Read Save Data
# file : file object for reading (opened)
#
def read_save_data(file)
# Read character data for drawing save file
characters = Marshal.load(file)
# Read frame count for measuring play time
Graphics.frame_count = Marshal.load(file)
# Read each type of game object
$game_system = Marshal.load(file)
$game_switches = Marshal.load(file)
$game_variables = Marshal.load(file)
$game_self_switches = Marshal.load(file)
$game_screen = Marshal.load(file)
$game_actors = Marshal.load(file)
$game_party = Marshal.load(file)
$game_troop = Marshal.load(file)
$game_map = Marshal.load(file)
$game_player = Marshal.load(file)
# Here's the one stupid edit, guys
$game_containers = Marshal.load(file)
# If magic number is different from when saving
# (if editing was added with editor)
if $game_system.magic_number != $data_system.magic_number
# Load map
$game_map.setup($game_map.map_id)
$game_player.center($game_player.x, $game_player.y)
end
# Refresh party members
$game_party.refresh
end
end
#==============================================================================
# ** Scene_Container
#
# This class performs container screen processing.
#==============================================================================
class Scene_Container
#
# * Object Initialization
# container_index : container
#
def initialize(container_index = 0)
@container_index = container_index
end
#
# * Main Processing
#
def main
# Make help window, item window
@change = @qty1 = @qty2 = 0
$game_containers.tempgold = 0
@item_window = Window_PartyItems.new
@item2_window = Window_Container.new(@container_index)
@gold_window = Window_Party_Gold.new
@gold2_window = Window_Container_Gold.new(@container_index)
# Toggle between windows
@item_window.active = true
@item2_window.active = false
@gold_window.active = false
@gold2_window.active = false
# Execute transition
Graphics.transition
# Main loop
loop do
# Update game screen
Graphics.update
# Update input information
Input.update
# Frame update
update
# Abort loop if screen is changed
break if $scene != self
end
# Prepare for transition
Graphics.freeze
# Dispose of windows
@item_window.dispose
@item2_window.dispose
@gold_window.dispose
@gold2_window.dispose
end
#
# * Frame Update
#
def update
# Update windows
@item_window.update
@item2_window.update
@gold_window.update
@gold2_window.update
# As long as Quantity Changer is off
if @change == 0
# If item window is active: call update_item
if @item_window.active
update_item
return
end
# If item window is active: call update_item
if @item2_window.active
update_item2
return
end
# If item window is active: call update_item
if @gold_window.active
update_gold
return
end
# If item window is active: call update_item
if @gold2_window.active
update_gold2
return
end
# Otherwise, while quantity changer is active
else
update_quantity
end
end
#
# * Frame Update (when item window is active)
#
def update_item
# If B button was pressed
if Input.trigger?(Input::
# Play cancel SE
$game_system.se_play($data_system.cancel_se)
# Switch to map screen
$scene = Scene_Map.new
return
end
# If A button was pressed
if Input.trigger?(CONTAINER_INPUT)
# Toggle between windows
@item2_window.active = true
@item_window.active = false
@gold_window.active = false
@gold2_window.active = false
end
# If C button was pressed
if Input.trigger?(Input::C)
# If no item is present
if @item_window.item == nil
# Play buzzer SE
$game_system.se_play($data_system.buzzer_se)
else
# Play decision SE
$game_system.se_play($data_system.decision_se)
# Get currently selected data on the item window
@item_window.active = false
@item2_window.active = false
@gold_window.active = false
@gold2_window.active = false
@item = @item_window.item
@change = 1
# Setup Quantities
@qty1 = 0
@qty1 = @item_window.item_qty if @item_window.item_qty != nil
setup_quantity
end
end
end
#
# * Frame Update (when 2nd item window is active)
#
def update_item2
# If B button was pressed
if Input.trigger?(Input::
# Play cancel SE
$game_system.se_play($data_system.cancel_se)
# Switch to map screen
$scene = Scene_Map.new
return
end
# If A button was pressed
if Input.trigger?(CONTAINER_INPUT)
# Toggle between windows
@item2_window.active = false
@item_window.active = false
@gold_window.active = true
@gold2_window.active = false
end
# If C button was pressed
if Input.trigger?(Input::C)
if @item2_window.data.size == 0
# Play buzzer SE
$game_system.se_play($data_system.buzzer_se)
else
# Play decision SE
$game_system.se_play($data_system.decision_se)
# Get currently selected data on the item window
@item = @item2_window.item
@item_window.active = false
@item2_window.active = false
@gold_window.active = false
@gold2_window.active = false
@change = 2
# Setup Quantities
@qty2 = 0
@qty2 = @item2_window.item_qty if @item2_window.item_qty != nil
setup_quantity
end
end
end
#
# * Frame Update (when gold window is active)
#
def update_gold
# If B button was pressed
if Input.trigger?(Input::
# Play cancel SE
$game_system.se_play($data_system.cancel_se)
# Switch to map screen
$scene = Scene_Map.new
return
end
# If A button was pressed
if Input.trigger?(CONTAINER_INPUT)
# Toggle between windows
@item2_window.active = false
@item_window.active = false
@gold_window.active = false
@gold2_window.active = true
end
# If C button was pressed
if Input.trigger?(Input::C)
# Play decision SE
$game_system.se_play($data_system.decision_se)
# Get currently selected data on the item window
@item_window.active = false
@item2_window.active = false
@gold_window.active = false
@gold2_window.active = false
@item = @item_window.item
@change = 3
end
end
#
# * Frame Update (when item window is active)
#
def update_gold2
# If B button was pressed
if Input.trigger?(Input::
# Play cancel SE
$game_system.se_play($data_system.cancel_se)
# Switch to map screen
$scene = Scene_Map.new
return
end
# If A button was pressed
if Input.trigger?(CONTAINER_INPUT)
# Toggle between windows
@item2_window.active = false
@item_window.active = true
@gold_window.active = false
@gold2_window.active = false
end
# If C button was pressed
if Input.trigger?(Input::C)
# Play decision SE
$game_system.se_play($data_system.decision_se)
# Get currently selected data on the item window
@item_window.active = false
@item2_window.active = false
@gold_window.active = false
@gold2_window.active = false
@item = @item_window.item
@change = 4
end
end
#
# * Frame Update (when qty window is active)
#
def update_quantity
# If B button was pressed
if Input.trigger?(Input::
$game_system.se_play($data_system.cancel_se)
case @change
when 1 ; @item_window.active = true
when 2 ; @item2_window.active = true
when 3 ; @gold_window.active = true
when 4 ; @gold2_window.active = true
end
@change = 0
return
end
# If a gold click
if @change > 2
if Input.repeat?(Input::LEFT)
if $game_party.gold < 9999999 && $game_containers.tempgold > 0
$game_system.se_play($data_system.cursor_se)
process_gold(1)
else
$game_system.se_play($data_system.buzzer_se)
end
end
# If the right directional button was pressed
if Input.repeat?(Input::RIGHT)
if $game_containers.tempgold < 9999999 && $game_party.gold > 0
$game_system.se_play($data_system.cursor_se)
process_gold(-1)
else
$game_system.se_play($data_system.buzzer_se)
end
end
# Otherwise...
else
# Reset click
click_dir = 0
# If the left directional button was pressed
if Input.repeat?(Input::LEFT)
if @qty1 < 99 && @qty2 > 0
$game_system.se_play($data_system.cursor_se)
click_dir = 1
else
$game_system.se_play($data_system.buzzer_se)
end
end
# If the right directional button was pressed
if Input.repeat?(Input::RIGHT)
if @qty2 < 99 && @qty1 > 0
$game_system.se_play($data_system.cursor_se)
click_dir = -1
else
$game_system.se_play($data_system.buzzer_se)
end
end
# Perform Item Change on Click
unless click_dir == 0
# Locate item in chest
container_location = locate_container_item
# Process Party and Chest arrays
process_party_item(click_dir)
process_container_item(click_dir, container_location)
# Update the windows
@item_window.update
@item2_window.update
@item_window.refresh
@item2_window.refresh
# Break from list if Party Item is empty
if @qty1 == 0 && @change == 1
@item_window.active = true
@change = 0
end
if @qty1 == 0 && @change == 2
@item2_window.active = true
@change = 0
end
end
end
end
#
# * Setup target quantity
#
def setup_quantity
location = nil
data = []
data = $game_containers.data[@container_index][1]
case @change
when 1 # Original - Party, find chest
location = locate_container_item
@qty2 = 0
unless location == nil
itemname = data[location]
item_size = itemname.size-1
@qty2 = itemname.slice(item_size-1,2).to_i
end
when 2 # Original - Chest, find the party item
@qty1 = 0
case @item
when RPG::Item
@qty1 = $game_party.item_number(@item.id)
when RPG::Weapon
@qty1 = $game_party.weapon_number(@item.id)
when RPG::Armor
@qty1 = $game_party.armor_number(@item.id)
end
end
end
#
# * Locate container item position
#
def locate_container_item
returnval = nil
data = []
data = $game_containers.data[@container_index][1]
case @item
when RPG::Item ; testval1 = 'i'
when RPG::Weapon ; testval1 = 'w'
when RPG::Armor ; testval1 = 'a'
end
testval2 = @item.id
testval3 = testval1 + testval2.to_s
for i in 0..data.size-1
itemname = data
item_size = itemname.size-1
item_test = itemname.slice(0,item_size-1)
returnval = i if item_test == testval3
end
return returnval
end
#
# * Process (Add/Remove) items from party list
#
def process_party_item(click_dir)
@qty1 = 0
case @item
when RPG::Item
@qty1 = $game_party.item_number(@item.id) + click_dir
$game_party.items[@item.id] =
[[$game_party.item_number(@item.id) + click_dir, 0].max, 99].min
when RPG::Weapon
@qty1 = $game_party.weapon_number(@item.id) + click_dir
$game_party.weapons[@item.id] =
[[$game_party.weapon_number(@item.id) + click_dir, 0].max, 99].min
when RPG::Armor
@qty1 = $game_party.armor_number(@item.id) + click_dir
$game_party.armors[@item.id] =
[[$game_party.armor_number(@item.id) + click_dir, 0].max, 99].min
end
end
#
# * Process (Add/Remove) items in a container
#
def process_gold(click_dir)
# Alter basic gold value
$game_party.gold += click_dir
# Add item
newdata = []
newdata = $game_containers.data[@container_index][1]
test_found = false
for i in 0..$game_containers.data[@container_index][1].size-1
itemname = newdata
item_size = itemname.size-1
item_type = itemname.slice(0, 1)
item_number = itemname.slice(1,item_size)
if item_type == 'g'
test_found = true
$game_containers.tempgold = item_number.to_i
$game_containers.tempgold -= click_dir
item_number = $game_containers.tempgold.to_s
end
itemname = item_type+item_number
newdata = itemname
end
if test_found != true
newdata.push('g1')
end
# Refresh gold windows
@gold_window.update
@gold2_window.update
@gold_window.refresh
@gold2_window.refresh
end
#
# * Process (Add/Remove) items in a container
#
def process_container_item(click_dir, location)
data = []
data = $game_containers.data[@container_index][1]
if location == nil
# Gotta be adding a new value
case @item
when RPG::Item ; testval1 = 'i'
when RPG::Weapon ; testval1 = 'w'
when RPG::Armor ; testval1 = 'a'
end
testval2 = @item.id
testval3 = testval1 + testval2.to_s + '01'
data.push(testval3)
else
itemname = data[location]
item_size = itemname.size-1
item_type = itemname.slice(0, 1)
item_number = itemname.slice(1,item_size-2)
item_quantity = itemname.slice(item_size-1,2).to_i
item_quantity -= click_dir
@qty2 = item_quantity
itemname = item_type + item_number + sprintf("%02d", item_quantity)
itemname = nil if item_quantity == 0
data[location] = itemname
$game_containers.data[@container_index][1] = data.compact
end
# Bread from list if chest quantity is zero
if item_quantity == 0
@item2_window.active = true
@change = 0
@qty1 = 0
if location == data.size - 1
@item2_window.index = location - 1
end
end
end
end
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
