Search code examples
c++inheritancepolymorphismpositionbehavior

Polymorphism - using behavior class to compute new position for runner object


I'm creating a program that will simulate a race between various runners, using behavior classes to implement different types of runner movements.

To do this, an abstract MoveBehaviour class will be implemented, along with several other concrete sub-classes. One of these sub-classes is the JumpBehaviour class which keeps the runner in the same row and moves it forward by a random number between 1 and 8 of columns to the right.

I'm confused as to what I'm supposed to put in move() in the JumpBehaviour class. I know I would generate a random number using my Random.cc class, but I'm stumped on how to achieve the 'moves it forward by a random number between 1 and 8 of columns to the right.' The oldPos and newPos parameters confuse me as I'm not really sure what I'm supposed to do with them. I don't have a header file for JumpBehaviour, as I was told it was okay to keep the behavior class definitions in a single file, so I put it in MoveBehaviour.h

I would really appreciate any help or a push in the right direction. Additionally, I'm not sure if the move() function in MoveBehaviour should be left empty by default. I'm not sure what it's purpose is.

Position.cc

#include <iostream>
using namespace std;
#include <string>
#include "Position.h"

Position::Position(int i1, int i2) : row(i1), column(i2){
}

void Position::setRow(int r){
    row = r;
}

void Position::setColumn(int c){
    column = c;
}

JumpBehaviour.cc

#include <iostream>
using namespace std;
#include <string>
#include "MoveBehaviour.h"

void JumpBehaviour::move(Position& oldPos, Position& newPos, string& log) { 
    
} 

Random.cc

#include <iostream>
#include <cstdlib>

int random(int max){
    double r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) ); 
    return (int)(r * max);
} 

Solution

  • I'm confused as to what I'm supposed to put in move() in the JumpBehaviour class. I know I would generate a random number using my Random.cc class, but I'm stumped on how to achieve the 'moves it forward by a random number between 1 and 8 of columns to the right.' The oldPos and newPos parameters confuse me as I'm not really sure what I'm supposed to do with them.

    I think it's pretty clear: you generate a random number in the range of [1..8], and add it to oldPos to get a newPos:

    newPos.setColumn(oldPos.getColumn() + random(8));
    

    Those parameters are passed to your function by reference, so you can directly modify them. Since you shouldn't modify the old position, you should declare it const: const Position& oldPos

    You would need to fix your random function, as it now returns [0..max-1]. Don't mess with double, just use a % operator.