13.07.2015 Views

29 The Power of Inheritance and Polymorphism

29 The Power of Inheritance and Polymorphism

29 The Power of Inheritance and Polymorphism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Finalising the clases 1035<strong>The</strong> algorithm has to chose the best sequence <strong>of</strong> integer points, for examplechoosing point (2, 1) rather than (2, 2) <strong>and</strong> (8, 4) rather than (8, 3) or (8, 5). <strong>The</strong>algorithm works by calculating the error associated with different points (shown bythe vertical lines in Figure <strong>29</strong>.5). <strong>The</strong> correct y value for say x=8 can be calculated;the errors <strong>of</strong> taking y = 3, or 4, or 5 are easy to calculate <strong>and</strong> the best approximationis chosen. When the squares traversed have been identified, they can be checked todetermine that they are not blocked by walls <strong>and</strong>, if clear, added to the path array.<strong>The</strong> algorithm is easiest to implement using two separate versions for the caseswhere the change in x is larger or the change in y is larger. A pseudo-code outlinefor the algorithm for where the change in x is larger is as follows:Dungeon::ClearSemiHorizontal(Pt p1, Pt p2, int max,Pt path[])ychange = difference in y values <strong>of</strong> two pointsxchange = difference in x values <strong>of</strong> two pointsif(xchange > max)return faildeltax = if x increasing then 1 else -1deltay = if y increasing then 1 else -1slope = change in y divided by change in xerror = slope*deltaxcurrent point = p1for i < abs(xchange) doif(error*deltay>0.5)current point y += deltayerror -= deltayerror += slope*deltaxcurrent point x += deltaxif(current point not accessible) return failpath[i] = current pointif(current point equal p2) return successi++return failPick best next pointCheck accessibilityAdd to pathClass PtIt is worth introducing a simple class to represent coordinates because many <strong>of</strong> thefunctions need coordinates as arguments, <strong>and</strong> there are also several places in thecode where it is necessary to compare the coordinates <strong>of</strong> different objects. Adeclaration for class Pt is:class Pt {public:Pt(int x = 0, int y = 0);int X() const;int Y() const;void SetPt(int newx, int newy);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!