Jump to content

  • Log In with Google      Sign In   
  • Create Account

Pure virtual function use case question


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 ShereModulus   Members   -  Reputation: 113

Like
1Likes
Like

Posted 24 March 2013 - 09:26 AM

Hi, I'm writing a Pong clone and sort of learning C++ at the same time. In the game I have one paddle controlled by the computer and one by the user, but for now I have just one Paddle class.


 

class Paddle
{
public:
    Paddle();
    Paddle(Position p);
    void setPosition(Position p);
    void moveUp();
    void moveDown();
    void moveTowardGoal(int goal);
    Position getPosition() const;
 
protected:
    int xpos;
    int ypos;
    int vel;
};
 

 

Now I want the moveUp/moveDown methods to move the paddle different distances depending if it's the AI paddle or the user paddle, so I was going to create two child classes, AIPaddle and UserPaddle. However, I am not going to be using polymorphism, as I need to be able to call the moveTowardGoal method, which would only be in the AIPaddle child class. My question is, since the moveUp/moveDown functions are in both child classes (with different implementations), is it "best practice" to declare them in the base class as pure virtual even if polymorphism isn't happening? Or should I just define separate moveUp/moveDown functions in each child class? I doubt it makes any difference performance- or conceptual-wise in this simple case, but as I said I'm trying to learn the C++ way of thinking about things so I'll have a blueprint if something more complex happens in the future.

 



Sponsor:

#2 Paradigm Shifter   Crossbones+   -  Reputation: 5434

Like
1Likes
Like

Posted 24 March 2013 - 09:33 AM

I don't like it.

 

If your move distance is different for different kinds of paddles I would make it a member of the class initialised in the constructor (and make it const if it is only initialised by the constructor and not changed after construction).

 

I would have an external class to update the position, the player paddle gets user input to move it and the AI paddle calls moveTowardGoal with a reference to the Paddle instance. You don't want to place your key input or AI logic in the Paddle class at all.

 

EDIT: So you probably want a boolen in the paddle as well whether it is a player paddle or not (maybe having the skill level of the AI instead of just a boolean, with skill level 0 being human controlled).

 

You can also use that to change the human paddle to AI control at run time (which you couldn't do with inheritance).


Edited by Paradigm Shifter, 24 March 2013 - 09:35 AM.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#3 ShereModulus   Members   -  Reputation: 113

Like
0Likes
Like

Posted 24 March 2013 - 09:52 AM

Thank you, that's a lot simpler than what I was about to do! smile.png Sometimes I can't see the forest because of the trees.


Edited by ShereModulus, 24 March 2013 - 09:54 AM.


#4 Lightness1024   Members   -  Reputation: 739

Like
0Likes
Like

Posted 26 March 2013 - 08:49 AM

it is maybe too generic at your level, but when inheritance comes to mind, before deciding to design it, there is a tool named "liskov substitution principle" (https://en.wikipedia.org/wiki/Liskov_substitution_principle) that helps.

pure virtuality in C++ is a way to design a strong contract. in practice it just says the functions must be overriden (re-implemented) in the base classes. you must already know that. Also note that it doesn't mean that a pure virtual method has no body. it can have one, just never defined on the same line that the declaration. (must use deported definition)



#5 Paradigm Shifter   Crossbones+   -  Reputation: 5434

Like
0Likes
Like

Posted 26 March 2013 - 09:07 AM

You can define a pure virtual function wherever you want... you still have to override it of course. It just means you can call the base class implementation if you want to.


"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#6 NightCreature83   Crossbones+   -  Reputation: 3032

Like
0Likes
Like

Posted 26 March 2013 - 10:22 AM

I wouldnt use a boolean to Identify whether the paddle is an AI paddle or not as you can do this with variables in the code itself just keep two variables around one that is player controlled and one that is AI controlled.

 

I would replace your moveUP and moveDown functions with a single move function that takes a the inputstate as a parameter, I would remove the moveTowardsGoal as well and stick that in an AI controller. With these changes the AI controller can then get the position of it's paddle to the towardsGoal calculation and decide what it's inputstate should look like that it then feeds to the the AI paddle move function. This way your AI usage of the paddle is the same as that of a human player which is nice as that means your application flow is the same for both.

 

Just as a side note as soon as you add a virtual function to a class, make the destructor of that class virtual as well to avoid problems once you start inheriting from that class.


Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#7 Paradigm Shifter   Crossbones+   -  Reputation: 5434

Like
0Likes
Like

Posted 26 March 2013 - 10:51 AM

What if you want 2 human players? 2 AI players? Also you can have one paddle AI controlled and then enable a human to jump in and take control with a member variable.

 

Another option is to have a an abstract Controller member pointer which is the base class for HumanController, AIController which is responsible for the update.


Edited by Paradigm Shifter, 26 March 2013 - 10:52 AM.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#8 NightCreature83   Crossbones+   -  Reputation: 3032

Like
0Likes
Like

Posted 26 March 2013 - 12:00 PM

The point is that you do not need that member variable and even with my solution that is easy to fix instead of passing it through the AI controller you pass it the actual input that comes from pad two problem solved. If you have a list for each of the human and AI players you move it from one list to the other. The boolean in the paddle class makes it encode state that it doesn't need to do it's job and as such shouldn't be part of that class.

Edited by NightCreature83, 26 March 2013 - 12:06 PM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#9 ApochPiQ   Moderators   -  Reputation: 16397

Like
2Likes
Like

Posted 31 March 2013 - 12:36 AM

Ugh.

 

Loose coupling for the win: a paddle should not point to its controller, but rather vice versa. Not all paddles need to have controllers, but all controllers need to have a paddle. Code accordingly.

 

Also, single responsibility is important.

 

 

This is what I would write:

class Paddle
{
public:
    void Move(int velocity)
    {
        CurPosition += velocity;
    }
 
    int GetPosition() const
    {
        return CurPosition;
    }
 
private:
    int CurPosition;
};
 
class Controller
{
public:
    virtual ~Controller() { }
 
    virtual void MovePaddle(Paddle& p) = 0;
};
 
class HumanController : public Controller
{
public:
    virtual void MovePaddle(Paddle& p) override
    {
        // Read input state
        p.Move(inputvelocity);   
    }
};
 
class AIController : public Controller
{
public:
    AIController(const PositionedObject& t, int maxspeed)
        : TargetObject(t),
          MaxSpeed(maxspeed)
    { }
 
    virtual void MovePaddle(Paddle& p) override
    {
        int targetpos = TargetObject.GetPosition().GetY();
        int unclampedvelocity = targetpos - p.GetPosition();
        int clampedvelocity;
 
        if(std::abs(unclampedvelocity) > MaxSpeed)
            clampedvelocity = (unclampedvelocity > 0) ? MaxSpeed : -MaxSpeed;
        else
            clampedvelocity = unclampedvelocity;
 
        p.Move(clampedvelocity);
    }
 
private:
    const PositionedObject& TargetObject;
    const int MaxSpeed;
};

 

 

Representing paddles and moving them are separate concerns. They should not be crammed into the same class (single responsibility). No variable, function, or class should have more than one reason to exist.

 

Extending the idea of moving a paddle around should be a matter of following the interface contract, not modifying the code of paddles as you would with the boolean flag solution (open/closed rule). In this approach, I can add an infinite number of means of moving paddles without changing any code - just adding new code. This is as it should be.

 

In building my paddle controller, I take care to obey Liskov substitution - which has already been mentioned. In a nutshell: if I expect a Base object but I'm handed a Derived object, I should never know the difference. Moreover, that Derived might actually be a Derived2 and I should not need to care.

 

Interface segregation is also important: never bundle logic that is unrelated. (The OP's solution runs afoul of this.) The AI paddle is the only thing that relies on knowing the ball's position, or has any notion of a "target" position, so don't pollute other code with those ideas.

 

Dependency inversion is also relevant here. Note that I made the AI controller talk about a positioned object, not a ball. In brief: never depend on implementations. Depend on abstract contracts and interfaces. If I want the AI paddle to follow something besides the ball, I just give it a different object! If the implementation of the ball changes, it won't break the AI, and so on.

 

 

For those following along at home: these are the SOLID design principles, and well worth learning about.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS