java - Running different methods within an object depending on the 'type' of object -
i'm trying manage power-ups in game.
lets have 7 'platforms' in game , want randomly spawn power-up max of 1 per platform (this vertically scrolling 'infinite' type game).
so, have 5 different power-ups , (where powerup valid class) - '7' being passed constructor here number of sprites in individual objects (ie, batches of sprites) - 7 can place 1 on each platform , turn them on , off required (i have 'drawable' boolean array allows me individual sprites in batch).
powerup powerup1 = new powerup(7); powerup powerup2 = new powerup(7); powerup powerup3 = new powerup(7); powerup powerup4 = new powerup(7); powerup powerup5 = new powerup(7);
i add them list of objects drawn:
powerupslist.add(powerup1); //etc...
i can so:
(for int = 0; < powerupslist.size();i++){ if (powerupslist.get(i).hasbeencollected(); powerupslist.get(i).runpowerup(); //carry out specific code powerup if has been activated }
the issue have i'm, in effect creating 35 sprites (5 batches of 7) - more when add more powreups. only ever use maximum of 7 sprites @ once.
therefore, i'm trying this:
powerup = new powerup(7);
then, when spawn powerup, after getting it's type randomly- (so, powerup1 example), instead of turning relevant ones on within relevant batch, changing properties of specific sprite within batch. if platform number @ time of spawn 7, set frame 7th sprite in batch relevant 1 , want run code.
however, seem have use switch statement switch on objects enum before can run relevant logic.
switch (poweruptype){ case poweruptype.powerup1: {logicforpowerup1;break} case poweruptype.powerup2: {logicforpowerup2;break} //etc }
is there way can run logic cleanly depending on enum of object using batch of 7 sprites? can't seem find way , using switch, honestly, find messy.
you monkeying around enum so, assuming logicforpowerup1/logicforpowerup2 etc methods in class has switch statement
public class powerupuser { private poweruptype poweruptype; public powerupuser(poweruptype poweruptype) { this.poweruptype = poweruptype; } public void usepowerup() { // replaces switch statement poweruptype.execute(this); } private void logicforpowerup1() { } private void logicforpowerup2() { } private enum poweruptype { powerup1 { @override public void execute(powerupuser powerupuser) { powerupuser.logicforpowerup1(); } }, powerup2 { @override public void execute(powerupuser powerupuser) { powerupuser.logicforpowerup2(); } }; public abstract void execute(powerupuser powerupuser); } }
Comments
Post a Comment