mardi 30 juin 2015

How to change one object into another object?

This is mostly a question about code design. What you see here is a very condense version of the original code.

An example of the code is:

player.rest();

Which makes the player sleep.

There is a bunch more like, walk, run, talk etc which all work great. The one that is a problem is polymorph. That changes the player from a human object to another object. The solution I came up with is this:

class main
  {
      var human:Human = new Human;
      var alien:Alien = new Alien;
      var cow:Cow = new Cow;
      var player = human;

      enterframe loop{
       //other code 
       if (player does something)
       player.polymorph = "alien";

       switch (player.polymorph)
       {
         case "alien":
         player = alien;
         break;
         case "cow":
         player = cow;
         break;
         //etc
       }
       player.update();
     }
  }

I want something that looks like this:

  class main 
    {
      var human:Human = new Human;
      var alien:Alien = new Alien;
      var player = human;

      enterframe loop
      {
       player.polymorph(alien);
      }
    }

I know my original solution is the wrong way to go about things as it encourages spaghetti code. But how would I do it differently? I don't mind a whole rewrite, but need like a example to help push me in the right direction. I hope this makes sense and thanks for the help.

If the second one can work, what would the polymorph function look like?

I thought of making a class called player and changing what that extends, but to my knowledge that can't be done? Plus I would like to change the character to something already in game rather than a new object.

Aucun commentaire:

Enregistrer un commentaire