Monday, April 30, 2018

How to Organize Your Code

In order to maintain the organization of your code while creating a game, one way to do it is by making a "class". A class is basically a variable that stores the code to create the game object but has certain components of it replaced by a more variables. 

For example, variable CAR will store information on how to make the car. But the information for the color of the car is currently being held by R, G, and B. So, if we were to actually make the car now, we would have to call CAR not as a variable and place the information in the statement. Here's an example: 

var CAR = function(R, G, B) { 
color(R, G, B); 
Circle(); 
Circle(); 
Rect(); 
}; //This makes the  
CAR(255, 255, 0); //This makes a yellow car 
CAR(0, 0, 255); // This makes a blue car 

Open2Study mentioned that there are three steps to organizing your code. Modularity, composition, and encapsulation.  

Modularity is when the code for different objects are put into different categories. Of course, those different modules can still communicate or interact with each other. Meaning objects in one module probably has code to interact with objects in another category. 

 Composition is when an object is composed of different parts of code. This can simplify the code by making you to only need to make the code for each part of the object so you only need to edit that as you progress through the game instead making an entirely new game object. 

Encapsulation is kind of similar to modularity. In encapsulation, different objects are contained and protected from having any unwanted interactions with other objects. Encapsulated objects can still be interacted by other objects, but only if it's allowed in the code. Basically, encapsulation protects your objects from being interacted by anything else unless you want it to. 

In the programs I make, I usually use composition and modularity. For example, with my helicopter, I use different parts to form the helicopter. I use variables to hold the information of the location of it to allow me to make it move and I use composition to make the rotor spin without making the rest of the helicopter go with it. 

I also use modularity to create the different weapons, stats and UI on Holo-shooter 3. I separated the different weapons in different IF statements (Which I am using as modules), placed the different UI components on top of everything, and made the certain parts of the HUD move when you press the arrow keys to create the illusion of facing different directions. 

Remember, there are different methods to organize your code. And other methods will work better in different situations. 

No comments:

Post a Comment