I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).
The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.
For these methods the condition is based on an integer level that equals the level the player is in.
Example code
private void SetBackgrounds()
{
if (level == 5)
{
gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);
}
else if (level == 10)
{
gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);
}
else if (level == 15)
{
gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);
}
}
The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.
For instance a level looks like this.
if(level == 1) {
levelDisplay.Text = "LEVEL 1";
timer = new Timer();
timer.Interval = 2000; /// DIFFERENT
timer.Enabled = true;
timer.Elapsed += Level1; /// DIFFERENT
timer.Start();
}
///LEVEL 2
if (level == 2)
{
levelDisplay.Text = "LEVEL 2";
timer = new Timer();
timer.Interval = 2000; /// DIFFERENT
timer.Enabled = true;
timer.Elapsed += Level2; /// DIFFERENT
timer.Start();
}
Is there a way to make this code less DRY? Input is appreciated.
Aucun commentaire:
Enregistrer un commentaire