Submit Your Article


 
RPG Maker

Welcome Guest ( Log In | Register )


  Games Resources RPG Maker VX RPG Maker XP Scripts Tutorials Downloads

 
Reply to this topicStart new topic
> [Scripting][Series]The Scripter’s Journey Series, 6. Welcome to Classes!
The Law G14
post Aug 7 2012, 05:51 AM
Post #1


Scripter FTW
Group Icon

Group: Local Mod
Posts: 1,346
Type: Scripter
RM Skill: Skilled
Rev Points: 5




The Scripter’s Journey Series

6. Welcome to Classes!


Table of Contents
I. Solidifying your Learning! Object-Oriented Programming, Revisited!
II. All about Classes!
III. Classes and Variables!
IV. Classes and Methods!
V. Initialization!
VI. Super…Inheritance!
VII. Conclusion!


Solidifying your Learning! Object-Oriented Programming, Revisited!
So up this point, we’ve been learning some really foundational type stuff, and that’s how it’s supposed to be! Let’s review what we know: we understand our work environment (the editor) and what it means to program, we understand the basics of variables, we know how to control the flow, we can manipulate arrays and hashes, and we can effectively use methods. Now so far, there have been a couple tutorials where we haven’t fully expanded on the given topic (like variables and methods). This is because I wanted to provide all the very foundational stuff before we move onto what I have continually been saying: Object-Oriented Programming. Now that we’ve reached this point, I can fully expand on any topic from the past that has some deeper connection with classes and OOP (Object Oriented Programming). Let’s go over again, what OOP is. Essentially, everything is an object or data structure in a figurative sense and a literal sense. In the figurative sense, it can be relatable to real life objects. A “book”, for example, is an object because it has certain properties (variables) and behavior (methods) that make it a book. In the literal sense, like we said in the last tutorial, everything is derived from the Class, “Object”. Now you may be thinking, “What’s the difference between a Class and an Object?” Well, let’s get into the meat of this tutorial, shall we?!


All about Classes!
To answer the above question, you can think of classes as the guidelines of an object of that type. For example, if you create the class “book”, this allows you to create objects of the type “book” (these objects are called “instances” as we’ll discuss in a second). In programming, you can say “type” to refer to what class the object is from. For example, the number “1” is of the Integer type. This is why we can literally say everything is of an Object type because everything derives from the Object class (we’ll go into inheritance and deriving in a few sections from now).

Now that we understand the difference, let’s move on. First, let’s go over a term called instance or instance of a class. An instance basically is what I just explained in the paragraph before this. Every time a new “object” is created of a certain class, its politically correct name is “instance” or “instance of that class type” because each instance has different properties and behavior than other instances of the class. How, do you make an instance of a class?

CODE
kong = Monkey.new
kong.bananas_owned = 4
print kong.bananas_owned
donkey_kong = Monkey.new
donkey_kong.bananas_owned = 5
print donkey_kong.bananas_owned


The very first think to note is the new keyword. This keyword basically allows you to make an instance (remember instance just means a new object created of that class) of a certain class. In this case, the name of our class is “Monkey” so every time you want to make a new object of the Monkey type or a new instance of the Monkey type, you simply create a variable and set it equal to this “new” instance of the class specified. Furthermore, in this code, we see the importance of “instances” as they allow each object of a certain class or type to have different properties (in this case, bananas owned).

So, now that we made our own instances of the Monkey class, you’re wondering “well, man, I get how to make an instance of a certain class…but how do I make a class!” Simple, the basic class structure is as follows:

CODE
class Monkey
attr_accessor :bananas_owned
attr_reader    :age

def initialize
@bananas_owned = 0
@age = 4
end

def find_food
return @age - @bananas_owned
end

end


DO NOT PANIC. I know you probably don’t get anything in that sample code, but that’s why we’re doing this tutorial. The only thing you should get out of this is that to establish that you’re making a class; you use the “class” keyword. Furthermore, always make sure you class names are capitalized and they make sense! So, now we’re going to get deeper into this tutorial and expand upon this code by learning object properties (variables), object behavior (methods), how to construct and call them, and the process of initialization and inheritance!


Classes and Variables!
Back in Lesson 2, we talked about the “accepted values” a variable can take. I said “These are the major types of values accepted for variables to refer to” when I was talking about Integers, Floats, etc. and then said “There is another type of value that can be referred to and those are class objects (but we’ll get more into that when we discuss classes)”. Well, time to shatter that paradigm, there is no difference between those “major types” and “class objects”, they’re all instances of a certain class. Integers are instances of the Integer class and monkeys are instances of the Monkey class. Variables can refer to any sort of instance of a class! (And of course they can refer to expressions as well like “1 + 1” which is why people just say variables refer to values because this includes class instances and expressions so I’ll be saying “value” even though you know what I mean in the specific situation). So with that established, we now that most of the time, a variable’s value will be an instance of a class object!

Now, variables can be used in a class to give that class certain properties. We discussed in Lesson 2 the different types of values (which we just pretty much combined it all together), but now we need to discuss the different types of variables! Each variable type has a different scope which is like how long a variable can live before it “dies”. Variables, with the smallest scope are called Local Variables and are usually variables defined in methods or in small blocks of code:

CODE
def find_food
new_banana = Banana.new
# fun fun fun
return
# new_banana is destroyed or “dies” and erased from memory
end


or

CODE
if one > 1
new_banana = Banana.new
# fun fun fun
# new_banana is destroyed or “dies” and erased from memory
end


Next, let’s go over Global Variables or variables that can be used anywhere in a program (or in our case, RPG Maker). They have the largest scope out of any variable, but are also the most dangerous variables since they can be accessed from anywhere and they might accidently be changed. To create a global variable, you simple prefix the variable name with a dollar sign ($). Examples of global variables in RPG Maker include the game variables:

CODE
$game_variables = Game_Variables.new


Good tip to know is to keep your amount of global variables to a bare minimum as the larger the scope of a variable, the more dangerous it is to deal with.

Now, we just went over variables that aren’t necessarily dependant on classes, so now we’ll go on to learn the two types of variables that are based on classes and their construction. First, let’s understand Instance Variables. If you remember our definition of “instance” or “instance of a class” it was basically every unique object created of a specific class, meaning they have different properties and behaviors. Well, instance variables are variables that can be uniquely changed for each instance of the class. For example, in the Monkey class we made earlier, @bananas_owned was an instance variable because each instance of the Monkey class had it’s own different value for @bananas_owned. To create an instance variable in its simplest form, you simply write a “@” sign before the variable name. Moreover, the scope of instance variables is larger than that of local variables as they can be used anywhere in the class or by the class, but they can’t be used everywhere in the program like global variables. Now I won’t get into the “attr_accessor” lines yet, first, let’s just understand what I mean by “in” and “by”.

CODE
class Donkey
def initialize
@legs = 4
end
def how_many_legs
print @legs
end
end


First of all, we can clearly see that I prefixed the variable name with a “@” sign making it an instance variable. I then proved that the scope of instance variables works anywhere inside a class. A local variable would have been erased from memory after the initialize method was done, however, since this is an instance variable, it could be used anywhere, including inside the “how_many_legs” method.

Now when I say “by” the class, that means instances of the class can use the variable. It would be done like this:

CODE
donkey = Donkey.new
Donkey.legs = 5


Now this looks all fine, BUT we would get an error if we tested this. This is because we haven’t specified the “by” part of our instance variable (if it can be used, read, and changed by instances of the class) and this is where the Attribute Accessors come into play. These handy tools allow us to specify how instance variables can be accessed “by” instances of a class.

attr_accessor = allows a specific attribute/property/variable to be read and written by any instance of a class.
attr_reader = allows a specific attribute/property/variable to be read by any instance of a class.
attr_writer = allows a specific attribute/property/variable to be written by any instance of a class.

So let’s put it all together:

CODE
class Donkey
attr_accessor :legs
attr_reader :friends
def initialize
@legs = 4
@friends = 5
end
def how_many_legs
print @legs
end
end
donkey = Donkey.new
Donkey.legs = 5 # This works because legs can be “written” like in this case, or read
Donkey.friends = 4  # Would receive an error because friends can only be “read” not “written”
print Donkey.friends # Works because friends can be “read” not written”


So, there you have it, that’s how you can change how instances of a class can manage instance variables. Instance Variables’ scope is anywhere in a class as well as how far your attribute accessors allow your instance variable to be manipulated by instances of the class. Now you also may be wondering “Why should I use writer and reader when accessor does both?!” Well, sometimes it’s good to “protect” your object’s attributes and properties. Like I said earlier, having a very large scope can be dangerous.

Finally, the colon sign ( : ) before the variable name and after the attribute accessor term creates something called a Symbol. But that’s out of the scope of this tutorial and is something that will be discussed later, just know that to use attribute accessors, simply do:

attribute_accessor + : + variable_name
Example: attr_reader :friends

Alright, well that took a while to explain thoroughly, but we’re not done yet! Next, we have Class Variables Don’t worry too much about this type of variable, it’s rarely used, and I mean rarely. Class Variables can be used anywhere in a class, and all instances of an object share this same variable. So if one instance changes this variable, it changes for every other instance. You make class variables by prefixing it with two “@” symbols.

CODE
@@number_of_donkeys = 4


Finally, we have our last type of variable. This one is not deeply connected to classes like instance variables and class variables, but it is important to know. It’s whose value is fixed. I’m talking about constants. Constants are made through a capital first letter, and I usually make all the letters capital just to make it more noticeable. Moreover, if you try to change a constant’s value, you’ll get a warning, but your game won’t crash.

CODE
CONSTANT = 5



Classes and Methods!
Now we learned about all the different types of variables and how they can relate to classes as attributes. Now, let’s go over the “behavior” aspect which is methods! Methods are more simple, there are only two concepts we need to elaborate on this section. We need to revisit method activation and we need to learn about singleton methods.

Now, recall back all the way to the beginning of this tutorial where I first constructed a class and told you not to panic. Let’s look at the method defined in that class:

CODE
def find_food
return @age - @bananas_owned
end


Simple enough, it’s just a normal method like we’ve discussed in the last tutorial. Now, what’s different though is that this is a method defined in a class, so it’s called an “instance method”. You can activate it like how we did in the previous tutorial only within the class. For example:

CODE
class Monkey
attr_accessor :bananas_owned
attr_reader    :age

def initialize
@bananas_owned = 0
@age = 4
@food = find_food
end

def find_food
return @age - @bananas_owned
end

end


(Remember last tutorial we discussed how by using “return” you can treat a method like a variable value as it returns an “expression” that a variable can refer to). In this case, method activation is like how we discussed last time, you simple name the method when you want to call it:

CODE
@food = find_food


The find_food method will be called and it will return a value to the @food instance variable. Now this is the normal method activation we know, and when it comes to classes, this method activation only works like this when you’re inside the class. Now, when it comes to using it outside the class, any method can be used on an instance of that class, you don’t need attribute accessors like variables. However, the method activation is a bit different, but still pretty simple:

CODE
monkey = Monkey.new
monkey.find_food


All you have to do is add a period to the instance of the class and then the name of the method, much like accessing variables of an instance.

Next, let’s move on to Class Methods (Singleton Methods). Class methods are like Class Variables in that they don’t belong to one specific instance of a class, but the class in general. This is a semi-practical example of how to make it and what it can be used for:

CODE
class Monkey
attr_reader :species
def Monkey.species_name(name)
@species = name
end
end
print Monkey.species_name


First, notice how to construct the method, instead of just saying the name of what you want the method to be, you have put the class name before it “Monkey.species_name”. Then you go on to make the method like normal. To call the method, you would again place the class name in front, and then add the method name! To see a real example in RGSS, go to the help file and in the Index go to “File”. It’s filled with class methods!


Initialization!
In some of the code samples I’ve been providing throughout this tutorial, I’ve been using a common method called “initialize”. Why? Let me explain. Go to your help file and go to Object, go all the way down until you see “initialize”. Now read it!

If you had no clue what you just read, let me explain, basically, every time you do something like:

CODE
monkey = Monkey.new


The initialize method for the Monkey class is immediately called because the system sees the “new” method. The default initialize method defined in Object is to do nothing as it assumes that the class will make its own method of how to “build” or “construct” a newly created object. So if you don’t have the initialize method it won’t hurt you, it’s just that the initialize method is great place to setup your new objects and you’ll always be using them when you start to make real scripts. Now, the last part in that help file says arguments passed to the new method will be passed to the initialize method! What does this mean?

CODE
class Monkey
def initialize(age, weight)
@age = age
@weight = weight
end
end
monkey = Monkey.new(4, 100)


See how that works? The initialize method, like any other method, can have parameters so when you create a new instance of the class, you can supply those parameters with arguments. If you’re familiar with other programming languages, this is also known as a constructor because you’re constructing your objects right at its beginning. Once you create the object in this case, age and weight are set based on the arguments. You can really get creative with initialize methods, just check them out in your script editor, you can find an initialize method nearly on every page!


Super…Inheritance!
Alright, last thing to cover for this chapter: Inheritance! What is inheritance? Basically…it’s like if your class had a child. This child gains all the methods and properties of its parent class. Remember we talked a little bit about this last tutorial and that’s why everything is literally an “Object”? Because everything inherits from the Object class! So, how do we explicitly define inheritance and what can we do with it? Here’s an example!

CODE
class Monkey
attr_reader :age
attr_reader :weight
def initialize(age, weight)
@age = age
@weight = weight
end
def gain_weight(increase)
@weight += increase
end
end

class Chimpanzee < Monkey
attr_reader :fingers
def initialize(age, weight, fingers)
super(age, weight)
@fingers = fingers
end
end
monkey = Chimpanzee.new(3, 45, 5)
monkey.gain_weight(5)
print monkey.age
print monkey.weight
print monkey.fingers


Again, DO NOT PANIC. Most of this you should understand, just take it line by line. The first class (The Monkey Class) you should understand very easily, we already understand all the components of this. Now the real new stuff starts when we introduce the Chimpanzee class. We use the less than operator ( < ) to denote that our class is a “child of” or “inheriting” from another class, in this case, the Monkey class. Now remember, everything gets inherited, so that means we already have the attribute readers of weight and age here too, but we add another one just for fun, called fingers. Next, we move on to the initialize method which has three parameters. After that we see a new keyword called “super”. Super is essentially a way to call the initialize method of the parent class. So you could think of that super line as this:

CODE
Monkey.new(age, weight)


But don’t write it this way, you must use the “super” keyword. Anyway, we take the first two arguments received in the initialize method for the Chimpanzee class, and we put them for arguments in the super keyword so that we can set the age and weight of our chimpanzee. Then we set our new instance variables (fingers) like normal. After that, we put these classes to the test. We initialize our monkey (chimpanzee) to be 3 years old, 45 pounds, and have 5 fingers. Low and behold, we are able to use a method defined in the Monkey class on our Chimpanzee object! Thanks to inheritance we can safely increase our little chimpanzee’s weight. We then go on to print all the properties of our chimpanzee proving that age and weight were also inherited. Wooo…that took a while lol, if you still don’t understand, feel free to ask questions!


Conclusion
Alrightly, now how about that! You can now officially say you’ve learned classes and the basic principles of OOP! Just to recap, in this tutorial you learned we reviewed the basic fundamentals of OOP, we learned about classes, their connection with variables and methods (properties and behaviors), initialization, and the super keyword with inheritance! Please, if you have any concerns regarding this tutorial (like something that wasn’t clear or a question) or if you just feel like commenting, don’t be afraid to post! Next time I’ll cook up something interesting for you guys, until then, practice, practice, practice!

The order of how these tutorials will progress: http://www.rpgrevolution.com/forums/index....showtopic=54953

~Law


__________________________

To put in sig, copy this link:
CODE
[url="http://www.rpgrevolution.com/forums/index.php?showtopic=51540"][img]http://img40.imageshack.us/img40/6504/conceptthelawbanner.png[/img][/url]


Sig Stuff


"When you first come, no one knows you. When help them out, they all know you. When you leave, they all love you. When you come back, they've already forgotten you." -- copy into your sig if you think this quote speaks true!

If you are one of the very few teenagers that know what real rap is and don't blindly listen to the hate statements (rap is crap), then put this in your sig. I say this in the name of Common, Mos Def, Lupe Fiasco, 2Pac, Nas, Talib Kweli, Eminem, and many others. -Exiled One

My Project Thread: Gai's Hunters


Go to the top of the page
 
+Quote Post
   

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 19th May 2013 - 12:59 PM
RPG RPG Revolution is an Privacy Policy and Legal
eXTReMe Tracker