All files ShiftPosition.ts

85.71% Statements 18/21
68.75% Branches 11/16
100% Functions 6/6
85.71% Lines 18/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70        1x           1x         22944x 22944x       120407x       5601x       11228x       26x     26x     26x                 68804x 68804x 68804x 68804x   26x     26x         26x         68778x        
/**
 * @author Timo Lehnertz
 */
import { BoardPosition } from "./BoardPosition";
import { Heading, HeadingHelper } from "./Heading";
import { Vec2 } from "./Vec2";
 
/**
 * Immutable ShiftPosition class representing a unique way of shifting on a board
 */
export class ShiftPosition {
  public readonly heading: Heading; // the direction from wich the shift will start
  public readonly index: number; // from left to right or top to bottom
 
  public constructor(heading: Heading, index: number) {
    this.heading = heading;
    this.index = index;
  }
 
  public get shiftVector(): Vec2 {
    return new HeadingHelper(this.heading).vec2.multiply(-1);
  }
 
  public static create(instance: ShiftPosition): ShiftPosition {
    return new ShiftPosition(instance.heading, instance.index);
  }
 
  public equals(other: ShiftPosition): boolean {
    return this.heading === other.heading && this.index === other.index;
  }
 
  private static checkOverflow(position: number, size: number): number {
    Iif (position < 0) {
      return size - 1;
    }
    Iif (position >= size) {
      return 0;
    }
    return position;
  }
 
  public shiftPlayer(
    playerPosition: BoardPosition,
    width: number,
    height: number
  ): BoardPosition {
    const isXAxis =
      this.heading === Heading.EAST || this.heading === Heading.WEST;
    const playerAxis = isXAxis ? playerPosition.y : playerPosition.x;
    const shiftAxis = this.index * 2 + 1;
    if (playerAxis === shiftAxis) {
      const increment =
        this.heading === Heading.NORTH || this.heading === Heading.WEST
          ? 1
          : -1;
      Iif (isXAxis) {
        return playerPosition.setX(
          ShiftPosition.checkOverflow(playerPosition.x + increment, width)
        );
      } else {
        return playerPosition.setY(
          ShiftPosition.checkOverflow(playerPosition.y + increment, height)
        );
      }
    } else {
      return playerPosition;
    }
  }
}