In a lot of the games I've (tried) making in the past, I often run into the problem of the code getting really heavy on ugly mathematical code. This happens especially frequently in setting up user-interfaces such as choosing the positions of things on screen. Just to get an idea of what I mean, here is some code from the setup for the level selection screen in a recent project:
It gets really verbose, as you can probably tell. I try to mitigate it with descriptive variable names and detailed explanations of the purposes of constants such as
INITIAL_LEVEL_SELECT_Y_OFFSET, but then it becomes verbose just in a different way.
I considered making everything,
totalHeight, etc., constants, but to me it looked really weird to have 30+ constants attached to every class. I also tried using local variables with smaller names, such as
yOffset, but then it defeats the purpose of having descriptive variable names (as you can see I use
INITIAL_LEVEL_SELECT_Y_OFFSET anyways 5 lines after declaring
Another problem this causes is that some constants are used by multiple classes, but aren't really general enough to be included in some static "Constants" class. For example, the constructor for
INITIAL_LEVEL_SELECT_X_OFFSET, and the class in the picture above does the reverse and uses a constant defined in
I originally placed the constants according to "what they were most attached to" if that makes any sense. For example,
BUTTON_WIDTH makes most sense in the
LevelSelectButton class since it describes a level select button's width.
Another problem is that some of these constants refer to the width and height of images that haven't been loaded statically. For example,
LevelSelectButton.BUTTON_WIDTH is supposed to be the same as the width of the button sprite that class uses, but my current setup requires that the sprite for
LevelSelectButton be loaded in the constructor for that class (I can think of ways to remedy this based on my current system however).
Any tips on how to avoid these problems? More comments? More constants? Less constants? A static