ICE nè....nếu rảnh thì làm ơn dịch dùm tui thứ này coi...cái thứ này là của RPG XP đó...hy vọng nó cũng có thể giúp ích cho nhóm...
Everything is an object
In Ruby, almost everything can be treated as an object. For example, the number 3 is actually an object, it has methods such as abs, size, to_s and more. Let's try this example:
CODE
p -2.abs #Outputs 2
As we remember, abs returns the absolute value of the number, in other words any negative signs are removed. We wrote an "abs" method earlier, but that method is actually useless. The "numbers" class (actually it's called Numeric class) includes a method called abs that returns the absolute value for us. All numbers are object of that numeric class. Think of it like this:
CODE
# FAKE EXAMPLE!! :P
class Numeric
def abs
# Does stuff to calculate the absolute value
return result
end
end
3 = Numeric.new()
3.abs
It's not really hard to understand. Keep in mind that we do NOT initialize numbers, in other words doing '3 = Numeric.new' would result in a syntax error, they are automatically initialized for us. One more thing to note is that you can use these methods on variables holding numbers (refering to numbers actually), which is what you'd do most of the time. Why? Because you do know that the absolute value of -1 is 1, but you can't be sure what the absolute value of unknown_variable_A is. Let's check some useful numeric methods:
abs
Returns the absolute value of the number (object)
to_s
Returns a string containing the number, useful for mixing numbers and strings without embedding numbers (using #{}). 'p "Hi No. " + 5.to_s' would output "Hi No. 5"
times
This is used for loops, it's better explained in an example:
CODE
3.times do
p \"Hi\"
end
It's similar to a for loop, it'd loop a number of times equal to the object's value.
Those 3 are enough for now, seeing how you'd rarely use them. Now let's see string objects, coming from the String class. The string methods are more useful and used more often than the numeric ones. Of course, you can use these methods on constant strings (Like "Hello") or variables holding strings. First a string example:
CODE
p \"Hi\".size # Outputs 2, number of characters in \"Hi\"
p \"small\".upcase # Outputs \"SMALL\"
p \"live\".reverse # Outputs \"evil\", which is \"live\" backwards
Cool, no? Let's check some interesting methods:
capitalize
Changes the first letter to uppercase and the other letters to lowercase, so "COW" becomes "Cow" and "hellO" becomes"Hello".
chop
Removes the last character. "Hello" becomes "Hell".
downcase
All uppercase characters are converted to lowercase ones, "PoKeMoN" becomes "pokemon"
gsub(pattern, replacement)
I won't explain patterns here since it's a very long topic. gsub replaces any occurrences of the pattern in the string with the replacement. Let's just say a pattern is some text in the string (it could be more than that), and we want to replace that text with something else. An example:
CODE
p\"I hate monkeys\".gsub(/hate/, \"like\")
# Outputs: I like monkeys
include?(string)
Returns true of the string includes the following string, false otherwise. For example "James is a communist".include? "communist' would return true.
reverse
Reverses the string. As in, the string is return backwards.
size
Returns number of characters in a string.
swapcase
Uppercase characters become lowercase characters and vice versa. "PoKeMoN" becomes "pOkEmOn".
to_i
Converts the string into a number. "345" will become the number 345, and"101 dogs" will become the number 101.
upcase
All lowercase characters are converted to uppercase ones, "PoKeMoN" becomes "POKEMON"
There are tons more, check Ruby's documentation for other methods (search for the String class).
The last thing to discuss is the Array class. All arrays are objects of that class. Array methods are very useful and used often in RGSS scripts. Some useful ones:
clear
Deletes all elements in the array
delete(item)
Deletes the specified item from array, note that you pass the item itself and not it's index (you pass 'h' if you want to delete item 'h')
delete_at(index)
Deletes the item with the given index.
include?(item)
Returns true if the given item exists within the array, returns false otherwise.
index(item)
Returns the index number of the item
pop
Removes the last element in the array and returns it. An example:
CODE
arr = [1,2,3,4,5]
p arr.pop # Outputs 5, the array now is [1,2,3,4]
push(elements)
Adds the given elements to the end of the array, you can pass more than one element
reverse
Reverses the order of elements in the array
shift
Removes the first element in the array and returns it, like pop. But all other items are shifted (if your array was [1,2,3] and you used shift, 1 will be removed and the index of the element 2 would be 0 (it'll become the first item in the array))
size
Returns the number of elements in the array
sort
Sorts the array, you can pass argument to it to specify the sorting order. I won't discuss that at the moment though (might do it later because it's used in RMXP's default scripts)
unshift(item)
Adds an item as the first item in the array, shifting all items up (The item with 0 index before the unshift will now have 1)
Whew, now we're done. For more information check the Ruby book (found on Ruby's site,
http://www.ruby-lang.org/book) for more information. You don't need to memorize any of these methods at the moment. You can just use them as a reference as we might run into them in future scripts.
Variable scope
A variable has a 'scope', a scope means an area where the variable is usable, once the program exits the area, the variable is deleted. Most variables we used thus far are called 'Local variables'. Their scope is limited to the block they are used in. Check this example:
CODE
if cow > 5
num = 12
end
p num # This will result in an error.
num is a local variable, it's scope is limited between 'if cow > 5' and 'end'. You can't use it outside the block. Now check this:
CODE
while me == true
x = 4
if cow > 5
p x
end
end
This works, because the if statement is inside the while, variable x scope is limited inside the while block, and the if and it's block are part of the while block.
We also have a type of variables called instance variables, they start with an 'at' @ sign. Instance variables are declared inside a class and can only be used by methods within the class. If you wish to use them outside the class you'll have to use 'attr_accessor' as we saw in the last tutorial. However, even with the accessor applied, you'll have to get their values using the object name. For example object.variable.
Another type of variables is the class variable, they start with two @@ signs (so a class variable would be like @@cow, @@moo, @@var). Class variables are shared within ALL objects of a class, so if one object change a class variable, the change will be reflected in all objects of that class. The last and most important type of variables to discuss is... Global variables. Global variables start with a $ sign. Their scope is global, meaning you can use them anywhere and that they store their values till the script is terminated. You can access global variables easily and they are very useful. So why not declare all my variables as global? This could lead to problems and can cause errors and would be considered bad design. Only use global variables when you really need them. RPG Maker XP declares some variables as global ones, and these variables are actually objects of the different classes that comes with RMXP. Most of the time these objects are used to get information from the database ($data_xxxx variables) or to get information about the current game ($game_xxx variables).
Namespaces
As your programs get bigger, some classes/methods/variables names might be used again, for example you might have an NPC class that handles Non-playable-characters in your game, and another class also named NPC that handles Ninja-Pink-Cows which are special types of items in your game. Moreover, both classes have a print method, for Non-Playable-Characters it prints their message text (Stuff they say to hero) but in the Ninja-Pink-Cows it prints each cow's name. Now you do this:
CODE
NPC example
example.print
This will result in an error, Ruby will not know which print method to call because there are two NPC methods. So, what should we do? Rename the Ninja-Pink-Cow class to NPC2? That'd work but in the real world programs get complicated and you add lots of classes and external files to your program, each defining it's own methods and classes. So it could become annoying. So, namespaces came to exist, namespaces define a place where your classes, methods and constants can be placed, when a class is in a name space the only way to access the class is to do Namespace::Class. In Ruby namespaces are called Modules, they are blocks that you can put your classes and methods within. An example:
CODE
module Cow
class NPC
#Ninja-Pink-Cow class stuff
end
end
module Person
class NPC
#Non-Playable-Character stuff
end
end
example1 = Cow::NPC.new()
example1.print # Outputs \"The cow's name is: Mooka\"
example2 = Person::NPC.new()
example2.print # Outputs \"Welcome to freedom town!\"
That's just a random example, another useful thing about namespaces (or modules) is that you can use them to organize similar classes and methods together, which is the way rmxp uses them with the RPG namespace. Don't worry a lot about namespaces and modules, just know that to use a class contained within a namespace you write: ModuleName::ClassName
RPG Maker XP global $data_xxxx variables
In the Scene_Title script, rmxp loads game info (as stored in the database) and store them in global variables and arrays called $data_xxxx, where xxxx is the name of the data. Here is a short list:
CODE
$data_actors = An array containing objects of class RPG::Actor, holds information about playable characters
$data_classes = An array containing objects of class RPG::Class, holds information about classes (As in warrior, mage, etc.)
$data_skills = An array containing objects of class RPG::Skill, holds information about skills
$data_items =An array containing objects of class RPG::Item, holds information about items
$data_weapons = An array containing objects of class RPG::Weapon, holds information about weapons
$data_armors = An array containing objects of class RPG::Armor, holds information about armors
$data_enemies = An array containing objects of class RPG::Enemy, holds information about enemies
$data_troops = An array containing objects of class RPG::Troop, holds information about enemy troops
$data_states = An array containing objects of class RPG::State, holds information about status effects
$data_animations = An array containing objects of class RPG::Animation, holds information about battle animations
$data_tilesets = An array containing objects of class RPG::Tileset, holds information about tilesets
$data_common_events = An array containing objects of class RPG::CommonEvent, holds information about common events
$data_system = An object of class RPG::System, holds various information such as switches, default sound effects, vocabulary, starting position, etc.
RPG Maker XP comes with built-in classes called RPG::Classname. These classes are contained in the RPG namespace (module). These classes describe information about database, these classes only include variables and no methods (exceptions are RPG::Sprite, RPG::Weather and RPG::Cache). Let's take $data_actor, an array containing objects of class RPG::Actor, this class has variables such as name (this actor's name), initial_level, character_name (actor's sprite filename), weapon_id (initial weapon's name), weapon_fix (is weapon fixed?) and more. $data_actor holds an array of RPG::Actors object, every object holds information about a specified actor (playable character). One thing to know about $data_xxx arrays in rmxp is that their index start with 1 and not 0, so the first actor info can be retrieved with $data_actors[1]. An example:
CODE
p $data_actors[1].name # Outputs first actor's name
p $data_actors[1].character_name # Outputs first actor's sprite filename
p $data_actors[1].battler_name # Outputs first actor's battle sprite name
p $data_actors[1].weapon_id # Outputs first actor's initial weapon ID (number)
p $data_actors[1].armor1_id # Outputs first actor's initial armor 1 ID (Shield)
p $data_actors[1].armor3_id # Outputs first actor's initial armor 3 ID (Head)
p $data_actors[2].name # Outputs second actor's name
You can actually change the values of these variables, enabling you to change things in the database such as the hero's name or the price of a weapon (a trading system would be easy to make that way), but most of the time you'll use these variables to get data. There are many things to get from data variables, I can't mention all of them here however so you'll have to check RMXP help file and find the reference for the RPG namespace classes. Here are some random examples:
CODE
p $data_skills[1].description # Outputs the descriptions of the first skill (in database)
p $data_item[3].icon_name # Outputs the icon file name of the third item
p $data_weapons[1].price # Outputs the price of the first weapon
p $data_armors[20].eva # Outputs the evasion gained from the 20th armor
p $data_enemies[2].gold # Outputs the gold obtained from the second enemy
p $data_tilesets[1].fog_zoom # Outputs the firt tileset's fog zoom value
One last thing to discuss is the $data_system variables, it's not an array but it holds several useful information. It mainly holds the stuff set in the system tab of the database, such as default sound effects, music, title screen, system gfx, starting position, starting party members, switches, variables, battle transition and more. It also holds an RPG::System::Words object that holds the default words for stuff such as "HP", "Level", "Str", etc. Some exampls:
CODE
p $data_system.title_name # Outputs the title screen filename
p $data_system.start_x # Outputs the starting x positon
p $data_system.words.gold # Outputs the database name given for gold (Gil or GP for example)
That's all for today, in the next lesson we'll discuss the $game_xxxx global variables that holds information regarding the currently running game (such as party members, party items, switches, variables, battle enemies, screen and more). We'll also discuss the Bitmap class. See you then~
CÒN Vài thứ đại loại như vậy nữa đó...nhưng ngay cả cái này tui còn chua hiểu nũa ...hi...hi...