Vous êtes sur la page 1sur 7

ABOUT VARIABLES

The first place to start with Object Oriented Programming (OOP) is variables. The
name suggests something that can vary. They are the foundation of OOP in a way, but
let's not get too technical just yet.

Variables are important because they give the programmer a placeholder for a value,
and give the program itself a place to store a value.

Most of us at least know a bit of algebra.


A = a2 is the formula to find the area of a square. The lowercase a (and
technically the uppercase) are variables in that equation. A clearer way to look at
it is this:
Area of a square = any side of the square mutiplied by itself.
What's my point?
No matter what square you're working with, that formula will give you the right
answer. As long as it's a square, not some stretch of the word. It's 'set it and
forget it'. Whoever made that formula doesn't have to tell anyone the area of any
square. It just requires you to input the value that represents the length of 1
side of the square.

In programs, tons of things will 'vary', so there are usually a lot of variables.

SETTING UP YOUR FIRST 'PLUGIN'

You can use any text editor to write JS. I use Sublime Text Editor. It's light,
fast, has some auto color coding for keywords in JS and is 'free'. Like Winrar
free. You don't have to pay, it will just ask you to sometimes. Been using it for
years.

To test out code with JavaScript, you need something to launch it. In this case, we
have RPG Maker MV. Inside of your project's folder, there is a folder called 'js'.
Inside of that, there is a folder called 'plugins'.
Inside of that folder is where you will save this document.

When you are saving, put .js after the file name, and in the dropdown menu, select
.js type file format.

Now, in the RPG Maker MV Editor, go to the Plugin Manager. Add your plugin to the
list. Make sure it is set to ON, and it will now load when your project launches.

Flip back to your .js document and, on line 1, write the following.

var exampleVariable = "Hello World";

Ctrl S to save your document, flip back to RPG Maker MV and launch your game.
Once it's launched, hit F8 on your keyboard. This will open the Console. You're
gonna spend a lot of time here, and it's gonna become your best friend.

In the console, type


exampleVariable
and hit Enter.
It will return the value "Hello World' and print it out on the console.

Congratulations, you made a variable. It holds the data you told it to, and can
return it once the program launches.
It's not all it can do though. It's a variable. It can change.
In the console, type
exampleVariable = 20;
and hit Enter.

You'll see the console return the number 20, and you'll understand why and when it
returns stuff later. For now, even though it's obvious that it worked, type
exampleVariable
and hit Enter.
You'll see it returns that value of the variable, which is now 20.

This exercise may seem pointless, and it's true that we haven't done anything
useful, but you now know how to define a variable, and give it a value. It's not a
whole lot more complicated than that.

WHY VARIABLES ARE NEEDED, AND WHEN

The last exercise doesn't show us why we need variables, but it's a difficult
question to flat out answer. Instead, consider this. You've no doubt used the
Control Variable event command in RPG Maker MV. Game Variables are pre-created
variables that RPG Maker lets you operate through Events. Even without scripting,
you can't really make a game without access to variables. Think about why. You
needed a value, and you didn't necessarily know what the value itself was at the
time.

Maybe you wanted to print a character's current HP to a text box. You don't know if
their HP is 100, 366, or 2952. You just know that whatever it is, you wanted to
print it out. (Interestingly enough, it already is in a variable, and soon you
won't need to use Event Commands to copy it into a Game Variable, you'll just know
where to find it).

It's hard to pin down any one reason for variables, but you'll see before long, if
you don't already, that you can't really live without them.

DECLARING AND OPERATING ON VARIABLES

Earlier, you declared and assigned a variable in your .js document. Declaring
basically means creating. If your scripting it into existince, you're declaring it.

Assigning is what happens when you use the = operator. An operator is any character
meant to interact with a variable. Here's a quick ereference.

Assignment and Mathematical Operators


Operator Name Usage
= Assignment Used to assign whatever is on the right side of it to the
variable on the left side of it
+ Addition Used to add the left and right sides of itself together (2 + 2)
- Subtraction Used to subtract left and right sides
/ Division Used to divide left and right sides
* Multiplication Used to multiply left and right sides
% Modulus Used to return the remainder of the division of left and right
sides (5 % 2 returns 1)

Operating on variables doesn't change the variable. Assigning does. The two can be
combined, but let's not get ahead of ourselves. First, let's back up.

Declaration
Go into your plugin document, and add a new variable. This time, we're just gonna
declare it. Type:
var myName;

Save the document, flip back over to the console and hit F5. This will restart the
game. If you do this with the game window instead of the console window, it may
restart without leaving the console open. Then you have to hit F8 again. May seem
minor, but trust me, you'll appreciate it.

Now the project has been reloaded. Any saved changes since the last time it
launched or was restarted will now be available.

In the console, type the name of the new variable we created


myName
and hit Enter.

You'll see the word 'undefined' returned to the console. This is what should
happen, because we only declared it.
However, we know it exists, and there's two ways to show you. First of all, type
something else into the console and hit enter. Like
myPetAcorn
and hit Enter.

You'll receive an error in red, that says whatever the name you typed is 'not
defined'. So that's one way we know that variable exists. Here's another way.
Begin to type the name of your variable. Type
myNa

and then stop. The window popping up with auto-complete suggestions is commonly
referred to as 'Intellisense'. From here on out, that's how I'll refer to it.
Notice how Intellisense pops up and has the variable listed in the window, and also
is trying to autocomplete the line you're typing.
If you hit the Tab key, it will complete the rest of the word it thinks you're
going for.
The fact that it's in the list for Intellisense at all means it exists.

This is important, because JavaScript is, by default, pretty lax about what you
have to do to declare a variable.

Above, when I said to type whatever into the console to return a 'not defined'
error, retype that into the console, but this time, assign it a value.
myPetAcorn = "Jerry";
and hit Enter

Then type the variable's name into the console and hit Enter. It returns "Jerry".
But you never used the keyword var�..so why did it work?

When a variable exists, typing it's name and assigning a value will change that
variables value.
When a variable doesn't exist, typing it's name and assigning a value will create a
new variable, and give it that value.

Without getting too confusing, just remember this. Never create a variable without
using a keyword (you'll learn others besides var later). It's not because it won't
work, it will. But it won't look any different than changing/assiginging a value to
an existing variable. There's a million reasons why you shouldn't do it. Just don't
do it, it's a good and very important practice.

Operating
Operating on variables happens all the time, often in tandem with assigning. In
games, they probably happen more often together than just operating alone. An
example of operating together would be adding 50 to a character's current HP.

An example of operating alone would subtracting an enemy's defense from a


character's attack to return a damage. (Even then, you'd be using that number to
assign the enemy's new HP after the result of the attack).

Go into your .js document, add a new variable and assign it a number. I'm going to
put
var apples = 10;
Save your doc, F5 to reload your game.
In the console, type the name of your new variable, followed by + 2
apples + 2
and hit Enter.

The result, in my case, is 12. You can imagine how the other operators work. I'm
sure there's no new concepts for you with the operations in the table above.

Assigning and Operating together

Often times with numbers, you'll want to change the number in a variable based off
of a mathematical calculation, not just a hard-coded number.
Examples are changing HP, Gold, Experience etc.
The math operators can be combined with the assignment operator like this
apples += 2;

If you type that in and hit enter, then type the name of your variable and hit
enter again, you'll see it's value has been changed.

apples -= 3
will change it's value to 3 less than whatever it has.

You can start to see how all of this would come together. A very unrealstic but
still not that far off example would be
playerHP -= (enemyAttack - playerDefense)

Of course, that's really simplified, doesn't use the true names of the properties
and so on, but that's the logic behind it. Variables, assignments and operators let
you make things like that possible. Inherently, some variables are meant to vary
more than others, but they can all be used to build formulas, like that formula for
the area of a square at the beginning of this lesson.

The player's HP and defense as well as the enemy's attack might be different at
different times, for different people playing the game. But that's fine. Thanks to
variables, you have a place to assign a value so that you can use it's name as a
placeholder in formulas or return data when needed.

You can write a formula that will work no matter what the values are that are given
to it.

Data Types
The last basic thing of note for variables is the data type. JavaScript has
virtually no default strictness for data type, although many prominent OOP
languages do. This has advantages and disadvantages. For now, lets talk about the
main types.

Numbers - Pretty obvious. One thing to note is that whole numbers without decimal
values are considered Integers, while values with decimals are considered Floats.

Boolean - A Boolean value is a true or false value. In RPG Maker MV, the best
example is the Game Switches accessed with the event command Control Switches. As
well as true or false, the numbers 1 and 0, respectively represent the same thing.
(0 also means false, 1 also means true)

String - A string is a set of literal characters, meant to actually be read by the


user, not treated as programming. An Actor's name, or a character's description,
anything that's not meant to be read by the computer as code, but rather as
meaningful output to a User is a String. String values must be surrounded by either
double or single quotes. e.g. var heroName = "Harold";

The data types aren't too complex to understand, but they're treated differently
for a reason, and are able to have different innate functionality as a result.
Mathematical operators behave differently on them, as well. If you try to add a
number and a boolean, you'll get a result, but maybe not what you'd expect. Since
one is a number and the other is a boolean, it will treat the boolean as 0 or 1
instead of false or true.

Because JavaScript isn't strict about data types, it often will allow you to
perform operations that you probably didn't mean to, and won't throw an error. You
have to be mindful if you don't want to create silly errors, or unexpected behavior
that might wind up being difficult to track down.

String Concatenation
To end this lesson, we'll cover string concatenation. Mathematical operators can
work on strings, but in a different way. Namely, the + addition operator will work
on strings. It will add whatever is on the right side of the operator to the
string.

Go back to your .js document, or go directly into the console and create two
variables. A string and a number. I'll use the following
var myString = "I can count to ";
var myNum = 10;

Then, in the console, I'll add them together


myString + myNum
and hit Enter.

The result will be "I can count to 10". This is called String Concatenation. We
concatenated a value together with a string. This also works with other strings.
var myOtherString = "whatever number I feel like.";
myString + myOtherString

The result of the above will be the string "I can count to whatever number I feel
like."
The result of string concatenation will always be string. Any number or boolean
added to a string will result in a string.

You can also use the addition/assignemtn operator


myString += myOtherString
to change the value of myString to the result of the two added together.

ACCESSING GAME VARIABLES THROGH SCRIPT

You know how to create your own variables, but how can you access the Game
Variables with script? RPG Maker MV has the Control Variables event command, but
sometimes you'll want to access them in your actual code.
In the console, type the following
$gameVariables.value(1)
and hit Enter
The result will be whatever is currently store in Game Variable 1. If you're on a
fresh project it will be 0.

To change a value, you use the following script call


$gameVarialbes.setValue(1, 200)
In parenthesis, the first value is the id of the variable, the second is the value
to assign it. The two are separated by a comma.

If you do that, and then retype the first script call to return the value, you'll
see it's changed to 200. Now, the $gameVariables object - that's what it actually
is, an object�more on that later - is actually not the most friendly call to use,
because it's not meant for script. It's the code used to make the Event Command
Control Variables work.

For example, we couldn't use the addition/assignment operator to add 100 to the
current value. We know right now it's 200, so adding 100 would make it 300. We know
that right now, but what if we needed to add 100 at a time that isn't necessarily
pre-determined. Like a potion that adds 100 to HP. We don't know exactly when the
player will use it. The HP won't necessarily be 200 when they do.

No sweat, right? Just add 100 to the current value.


$gameVariables.setValue(1, $gameVariables.value(1) + 100);

Um�on second thought, it's kind of ugly. It may not seem like a huge line to type,
but trust me, type it 10 different times and you'll hate it.
My own personal plugin actually contains a 'fix' for this. My plugin allows me to
type
vee.add(1, 100);
Don't type it, it won't work for you. My point is that some aspects of RPG Maker
are actually easier to handle with plain old events, unless you want to write some
of your own stuff like I did.

It's easy to start learning JS and want to do everything in code, but the truth is,
not everything is best that way, at least not as is. Pick your battles.

Using the Script Box in Control Variables Event Command


You may have noticed in some of the Event Commands, there is the option to select
Script. Even the last page of Event Commands has a Script command itself. This is
reserved for JavaScript, and from here on out you'll be able to use them.

In Control Variables, you can select script and input anything you would put on the
right side of the = assignment operator. For example, putting 25 will change the
value of the selected variable to 25. This is also how you can put strings inside
of Game Variables through Event Commands.

If you select the script box in the Control Variables commands and type "This is my
sentence", that's the value the Game Variable will get. Anything you could type as
an assignment for the variable can be typed there. For example (even though it's
pointless) you could type true or false, but it will change it to 1 or 0,
respectively. Remember from earlier, true is equal to 1, false is equal to 0;

Keep in mind, though�


Whatever operator is selected in the Operation section will be performed. Here's a
quick guide to the operation/script equivalents

Name RPG Maker JavaScript


Assignment Set =
Addition Add +
Subtraction Sub -
Multiplication Mul *
Division Div /
Modulus Mod %

So if you select Variable 0001, select Add, select Script and type
15

You are essentially writing

$gameVariables.value(1) + 15

If you select Variable 0020, select Set, select Script and type
"Pecan pie is superior to other kinds of pie.", you are essentially writing

$gameVariables.setValue(20, "Pecan pie is superior to other kinds of pie.");

Overall, using the Script box can give you the ability to quickly assign values you
otherwise couldn't to a variable, or even save multiple steps in
attaining/assigning a value.

I think for now that's it for variables. It's just the beginning, it doesn't paint
the big picture on it's own. But it's where everyone starts. Next up is Conditional
Logic, which is the true basis of how programming works.

Vous aimerez peut-être aussi