• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ShereModulus

Pure virtual function use case question

8 posts in this topic

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.

 

1

Share this post


Link to post
Share on other sites

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
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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)

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

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 [i]moving them[/i] 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 [i]changing[/i] 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]I should never know the difference[/i]. 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.

2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0