Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Special Support - A great place to learn to Script

Everyone wants to learn to script, but no one really knows where to start. In my honest opinion, the best place to learn is just by reading the default scripts. I learned to script with the japanese RMXP, so I didn't have English comments at my disposal, so everyone of the new generation has that upperhand. Anyways, what I think the best thing to do to learn to script is read the default scripts, and understand each line.

So what I am offering here is support for anyone trying to learn to script. If there is a line of code you don't understand, ask me here. If there is something you want to know, like where in the script editor does something happen, ask here.
  • Ask about a certain line of code : What it means, does, etc.
  • Ask where the coding is for a certain function
PLEASE DO NOT ASK SOMETHING OTHER THAN EXISTING CODE, OR WHERE IN THE DEFAULT SCRIPTS TO FIND A CERTAIN BLOCK OF CODE. Your post will be deleted.

This is a Trial and Error topic. Hopefully, it can lead to more a use full FAQ for beginners.
 
Ok. Let me give you an example of what to ask here:

Example Question A":3gwdmloy said:
In Game_Actor, under def element_set, I am confused about this block
Code:
  #--------------------------------------------------------------------------
  # * Get Normal Attack Element
  #--------------------------------------------------------------------------
  def element_set
    weapon = $data_weapons[@weapon_id]
    return weapon != nil ? weapon.element_set : []
  end
More importantly:
Code:
    return weapon != nil ? weapon.element_set : []

What does that mean?

Glad you asked. That is one of my favorite tools in actions. It's really not an advanced tool, but can shorten lines pretty quickly.

Lets start from the beginning:
Code:
 weapon = $data_weapons[@weapon_id]
This line of code gets the RPG::Weapon data from the $data_weapons array, depending upon the @weapon_id (the current id of the equipped weapon) instance.

The next line, is what is called a Ternary Operator. Before we look at exactly what that line is doing, let me explain Ternary Operators...

Explanation of Ternary Operators By Seph":3gwdmloy said:
Ternary Operators are a C form of expression, that are mostly designed for simpler, smaller expressions, usually for returning data, setting a variable, or executing a single method.

Lets follow the flow of a simple expression, to get the TO form.
Code:
# We start with a simple, basic expression.
if a > 5
  b = 'Less Than'
else
  b = 'Greater or Equal to'
end

# Now, we can remove line breaks
if a > 5 ; b = 'Less Than' ; else b = 'Greater or Equal to' ; end

# Now in Ruby, we can switch on line expressions with a few keywords...
if a > 5 then b = 'Less Than' else b = 'Greater or Equal to' end

# Now, we can change those a few of those keywords and remove a few
# Remove the starting if, and final end
# change then to ?
# change else to :
a > 5 ? b = 'Less Than' : b = 'Greater or Equal to'

# Now, just think algebra in coding...
b = (a > 5 ? 'Less Than' : 'Greater or Equal to')

The format of a Ternary Expression is:
Code:
boolean-expression ? expr1 : expr2

If the boolean-expression is true, expr1 is returns/executed, otherwise epxr2 is returned/executed.

You can use this to return data (like in our method from Game_Actor), set variables (as in the example), call methods (place a method call in our expr's), etc.

Have fun!

Now that we have that under our belt, things are bit clearer.

Code:
return weapon != nil ? weapon.element_set : []

# is the same as

if weapon != nil
  return weapon.element_set
else
  return []
end

Further note on the method: If your actor has a weapon equipped, you will be attacking with your weapons element set in the database (an array). If you don't have an element set, you are sending an empty array.

Actual Help Request Thread":3gwdmloy said:
Also, could you please explain some of the syntaxes around the line
Code:
MapInput::Call_Common_Event.each do |input_button, common_event_id|
what does the || and the variables withing signify. does it mean run each key in the hash and check if it is being pressed and stores the values to each key in common_event_id?

(In reference to this code)

Code:
module MapInput
  Call_Common_Event = {Input::L => 4, Input::R => 2}
end

class Scene_Map
  alias_method :sephgubid_mapinputcallcommonevent_update, :update
  def update
    sephgubid_mapinputcallcommonevent_update
    return if $game_system.map_interpreter.running?
    MapInput::Call_Common_Event.each do |input_button, common_event_id|
      if Input.trigger?(input_button)
        $game_temp.common_event_id = common_event_id
        break
      end
    end
  end
end

Ok. This creates a loop function, passing through all the keys and values within a Hash. What you place between the | and | marks are your iterators. Now, the each function in the Hash class requires you have two of them, the first being the local variable name for you key within the loop, and the second being the local variable name for your value. You could do it with a for loop, or a million other ways.

Code:
MapInput::Call_Common_Event.each do |input_button, common_event_id|
  # code
end

# is the same as...

MapInput::Call_Common_Event.keys.each do |input_button|
  common_event_id = MapInput::Call_Common_Event[input_button]
  # code
end

# is the same as...

MapInput::Call_Common_Event.values.each do |common_event_id|
  input_button = MapInput::Call_Common_Event.index(common_event_id)
  # code
end

# is the same as...

for input_button in MapInput::Call_Common_Event.keys
  common_event_id = MapInput::Call_Common_Event[input_button]
  # cod
end

# and there's others, but I am lazy. Haha.

It's all a matter of preference on which loop you choose to go with. You can pass through the keys, values, or both at once.

Example where question":3gwdmloy said:
Where is all the number of items, weapons, armors held in the party, and how is it used?

First off, we will start in Game_Party. Under the def initialize method, we have this:
Code:
    # Create amount in possession hash for items, weapons, and armor
    @items = {}
    @weapons = {}
    @armors = {}

Now, with only this much information, we can't really say what they are planning on doing with this, so let's look a little further shall we... ;)

scrolls through Game_Party code...

WAIT A MINUTE!!!
Code:
  #--------------------------------------------------------------------------
  # * Get Number of Items Possessed
  #     item_id : item ID
  #--------------------------------------------------------------------------
  def item_number(item_id)
    # If quantity data is in the hash, use it. If not, return 0
    return @items.include?(item_id) ? @items[item_id] : 0
  end

Ok. So this is the method that reads the number of items held. Lets see, we pass the item_id to this method, and...
Code:
@items.include?(item_id) ? @items[item_id] : 0

The .include? method checks if an item_id has been added to our Hash (@items, as initialized in the initialize method). If it has the item_id, it returns the value. That means, that our key in the @items hash, is the item_id, and the value is the number owned. If no keys is found, it returns 0 (See explanation about Ternary Operators above if you don't understand the syntax behind this line).

As you can see
Code:
  #--------------------------------------------------------------------------
  # * Gain Items (or lose)
  #     item_id : item ID
  #     n       : quantity
  #--------------------------------------------------------------------------
  def gain_item(item_id, n)
    # Update quantity data in the hash.
    if item_id > 0
      @items[item_id] = [[item_number(item_id) + n, 0].max, 99].min
    end
  end

Here, we send the item_id, and number of the object to gain. We are setting the item_id in our @items Hash, and we are setting it with that funky looking expression on the right. The expression on the right side, is just two arrays, the major array returns the min value with the array. The minor array is within that array, and it returns the max number within itself. Which means, our item number will be

the biggest number in our minor array, but the smallest number in our major array.

The two numbers in our minor array are the number of items already owned (calling our item_number method from above), plus how every many items you are gaining (the second number passed in this method call). Our second number is just 0, which means we will never have less than this, because our minor array picks the biggest number.

The two numbers in our major array are the number that is returned in the minor array, and 99. Now, the major array returns the min number here, so if we have more than 99 of an object, it will cap it back to 99.


Summary:Items, Weapons and Armors all work the same way. Keys are the objects reference id (id to the $data_object array, such as item_id to $data_items) and values are the number owned.

(If you were wondering why I changed my narrative/tone throughout this explanation, it is to show you what should be going through your head when you don't know something. I took the position as the unknowing student, and the teacher)
 
The Sea King":37kzfibr said:
Question.
Do we have to start everything by:
def ....

and then end it?

Ok. In Ruby, we have quite a few keywords, that all mean something. The keyword def declares a method (A function, query or attribute of an Object). Its structured in the following manner:
PHP:
def your_method_name
  # your code here
end

You must have an end to end your methods. Certain keywords require the end keyword. This is why tabbing is so important: So you can keep the right number of end's.
PHP:
def your_method_name
  if some_boolean
    case something
    when x
      unless z > 0
        do_something
      else
        do_something_else
      end
    when y
      do_something_different
     end
  else
    do_something_crazy
  end
end

This is an example of how you should tab your programming.
 
Sailerius":2v7gft1d said:
Where are values such as an actor's level and exp stored? Basically, what I'm trying to do is create another value (skills like in D&D) which can be read in message boxes.

The quick answer:
Code:
$game_actors[actor_id].level
$game_actors[actor_id].exp

Actor data is stored in a "wrapper hash/array class", $game_actors. Now, each object in this class is a Game_Actor object. Each Game_Actor class has the two instances, @level, and @exp, both are readable.

So, here's the important parts.

Game_Actors:
Code:
#==============================================================================
# ** Game_Actors
#------------------------------------------------------------------------------
#  This class handles the actor array. Refer to "$game_actors" for each
#  instance of this class.
#==============================================================================

class Game_Actors
  #--------------------------------------------------------------------------
  # * Object Initialization
  #--------------------------------------------------------------------------
  def initialize
    @data = []
  end
  #--------------------------------------------------------------------------
  # * Get Actor
  #     actor_id : actor ID
  #--------------------------------------------------------------------------
  def [](actor_id)
    if actor_id > 999 or $data_actors[actor_id] == nil
      return nil
    end
    if @data[actor_id] == nil
      @data[actor_id] = Game_Actor.new(actor_id)
    end
    return @data[actor_id]
  end
end

So, everytime you access $game_actors#[], it either creates an actor and adds to the @data array as a new actor (at it's initial state), or returns the Game_Actor object in the @data array.

Then in Game_Actor, you can see:
Code:
#==============================================================================
# ** Game_Actor
#------------------------------------------------------------------------------
#  This class handles the actor. It's used within the Game_Actors class
#  ($game_actors) and refers to the Game_Party class ($game_party).
#==============================================================================

class Game_Actor < Game_Battler
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_reader   :level                    # level
  attr_reader   :exp                      # EXP

Here, you can see that the level and exp are readable in Game_Actor objects.

So, to get our actor data, we use:
Code:
$game_actors[actor_id]

From there, we just need to read our level and exp.
Code:
$game_actors[actor_id].exp
# or
$game_actors[actor_id].level




So, you are wanting to have this shown in Messages? Just use:
Code:
a = $game_actors[actor_id]
l = a.level
# or
e = a.exp
$game_variables[x] = l
# or
$game_variables[x] = e

Then just use the \v command.
 
where are the slide in windows methods stored in the sdk version 2.3?

Slide in windows = windows that aren't just shown on screen at once but are moved from beyond the borders of the screen to a specific point on the screen like x = 100, y = 0.
 
That's Trickster's Movable Module, in the MACL 2.1. Not really what this thread is for, but I am a nice guy. I won't get into details, but will tell you how to use it:

If you use the MACL 2.1+, for any window/sprite, call out:
Code:
your_window.move_x(x, speed)
# or
your_window.move_y(y, speed)
 
Where is the opacity for an event stored? That's a question that has been bothering me for some time, but didn't think of asking

Game_Character holds all the data the events. In Game_Character, there is an instance call @opacity. Sprite_Character reads this instance, and sets the sprite's opacity according to this value.

So if you wanted to change it, add this in Game_Character 1
Code:
  attr_accessor :opacity


Then just use:
Code:
$game_map.events[event_id].opacity = n

Sorry for not going in-depth on this explanation. I just woke up and can barely open my eyes. XD
 
Great, I get the idea now. But another question arises, this time about loops.

Here is how I've set up the loop:

Code:
    loop{
    $game_map.events[event_index].opacity -= 10
    @n += 1
      if @n = 25
        break 
      end
    }

The idea was to make the loop reduce the opacity with 10 each frame, but instead it instantly reduces it to 0. That wasn't how I had planned it. event_index is the event ID that will be changed.

Could you tell me what's wrong with it, and how to fix it?

Thanks
 
The thing is, it never breaks.

Your main problem is: if @n = 25

In boolean-expressions, you need to have the == operator.
Code:
    loop do
      $game_map.events[event_index].opacity -= 10
      @n += 1
      break if @n == 25
    end

That's how I would do it.
 
If I may, I'd like to ask a... "void-question".
It's just something the Translated RMXP Help File didn't explained very clearly for me:

What's the real function of the return?
 
If I may, I'd like to ask a... "void-question".
It's just something the Translated RMXP Help File didn't explained very clearly for me:

What's the real function of the return?


Return does a few things.

In query methods in object classes, return returns a value when a method is called. Like so:
Code:
def add_three_to(x)
  return x + 3
end

add_three_to(1) # => 4
add_three_to(4) # => 7

def is_greater_than_5?(n)
  return n > 5
end

is_greater_than_5?(3) #=> false
is_greater_than_5?(8) #=> true

We sometime use it to stop a block of code as well.
Code:
def refresh
  if $game_party.gold == @gold
    return
  end
  @gold = $game_party.gold
  # ...
end

When they gold value in $game_party is the same as the @gold instance in that class, the method is returned, and nothing after the return is executed.
 
return? mmm... it seems to let you get a result. When I use it as part of a def method inside an Interpreter class, it allows me to get a result, in this case it changes an expression I selected with a script call that lets me start a specific process defined in certain script(s). Does it have any other function?

This is something that confuses me a lot.
what is the difference between alias_method and just alias? How could anyone use them properly?
Code:
class Bitmap
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_accessor :blur_settings
  attr_accessor :anim_sprite_settings
  #--------------------------------------------------------------------------
  # * Class Variables
  #--------------------------------------------------------------------------
  class_accessor :default_blur_settings, :default_anim_sprite_settings
  #--------------------------------------------------------------------------
  # * Alias Listings
  #--------------------------------------------------------------------------
  [color=red]alias_method[/color] :seph_macl_bitmap_init, :initialize
  #-------------------------------------------------------------------------
  # * Object Initialization
  #-------------------------------------------------------------------------
  def initialize(*args)
    # Original Bitmap Initialization
    seph_macl_bitmap_init(*args)
    # Set Bitmap Settings
    @blur_settings        = @@default_blur_settings
    @anim_sprite_settings = @@default_anim_sprite_settings
  end
 ...
end
 
Like I said, return returns a value, or ends a block (or big block, like a method call).

what is the difference between alias_method and just alias? How could anyone use them properly?

Nothing, sorta.

alias is embedded into Ruby library. It's a hidden method we can never really get access to. However, alias_method is a method in the Module class. It probably looks just like this:
Code:
class Module
  def alias_method(new_method_name, old_method_name)
    alias new_method_name old_method_name
  end
end

However, I use it in all my scripts because I program with and for the SDK. The SDK has a log_alias method, that logs aliases. So we in the SDK, aliased the alias method, to call this SDK.log_alias method whenever the alias_method method was called. So instead of:
Code:
class X
  alias new old
  SDK.log_alias(X, new, old)
We just use the alias_method like you see above. We log aliases in the SDK to check for script conflicts, in the event a script over-writes a method. It took me a while, but I got it to work if you overwrote a method that was essential to another script, an error was raised.

Another reason is stack errors. Thanks to the wonderful F12, stack errors happen a lot in aliases, so once again, in the SDK, we used the alias_method to check and prevent stack errors.
 
We sometime use it to stop a block of code as well.
Code:
def refresh
  if $game_party.gold == @gold
    return
  end
  @gold = $game_party.gold
  # ...
end

When they gold value in $game_party is the same as the @gold instance in that class, the method is returned, and nothing after the return is executed.
Eah.. That was my doubt. :D
I was concerned especially about the alone returns.

So this, basically means:
"If the variable gold is equal to the party gold, stop the things here. If it is not, make the variable gold be the same as party gold.", right?

Thanks, thing I got it. :3
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top