Flexible Coding

From GMpedia.org Wiki

Jump to: navigation, search
This article (or section) may need to be wikified to meet GMpedia's quality standards.
Please help improve this article, especially its categories, and wiki-links.

This tutorial works with...

Game Maker

Unless you're a programmer, the chances are you've never heard of the phrase "Hard Coding", or perhaps you've heard or read it but didn't have a clue as to what it meant!

But is it relevant here? Does it have anything to do with Game Maker?

In fact it's relevant wherever there is a programming language, like Basic or GML, but what actually is Hard coding?

"Hard coding is when your code is not flexible when other changes are made."

[edit] Examples

Confused? Let me show you a couple of examples:

Let's say you made a game where 10 objects are created on the right hand side of the screen throughout your game, the screen is 640 pixels wide by 480 pixels high, the objects are 32 x 32 pixels and you created the objects like so:instance_create(x,y,object1), instance_create(x,y,object2), instance_create(x,y,object3)... etc...

Because you want it on the right, then x would be 640 (the width of the screen), but you also need to take the width of the sprite into consideration (32 pixels), so we need to subtract 32 from 640 and this will leave 608, so you'll get:

instance_create(608,y,object1)
instance_create(608,y,object2)
instance_create(608,y,object3)
...
...

which will create your objects on the right-hand side, but what happens if you change the width of the screen? Or the width of one of the objects? Because you've hard coded (or put an absolute value (608) ) in x, you'd have to go through your code changing those 10 values. What happens if you then don't like the changes you've made and decide to change something again? Back you go through your code...

As you can see, because you've made a slight change in one place, you'll need to go through your entire program changing other values, therefore hard coding is not recommended for certain things, it would be much better to have something like this:

instance_create(room_width - sprite_width,y,object1)
instance_create(room_width - sprite_width,y,object2)
instance_create(room_width - sprite_width,y,object3)
...
...

or even:

rightside = room_width - sprite_width
instance_create(rightside,y,object1)
instance_create(rightside,y,object2)
instance_create(rightside,y,object3)
...
...

So, no matter the width of the screen, or the width of the sprite (object), you'll never need to change the code as room_width - sprite_width will automatically position the object when changes are made!

This article was originally found at the Game Maker Knowledge Base, contributed by nickydude.
See the talk page for details
Personal tools