Skip to content

Commit

Permalink
refactor and improve algo
Browse files Browse the repository at this point in the history
  • Loading branch information
danielchalmers committed Jul 17, 2024
1 parent 530d51d commit 63da7bc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 23 deletions.
8 changes: 4 additions & 4 deletions DesktopClock.Tests/PixelShifterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public void ShiftX_ShouldNotExceedMaxTotalShift(int shiftAmount, int maxTotalShi
{
var shifter = new PixelShifter
{
ShiftAmount = shiftAmount,
MaxTotalShift = maxTotalShift,
PixelsPerShift = shiftAmount,
MaxPixelOffset = maxTotalShift,
};

double totalShiftX = 0;
Expand All @@ -37,8 +37,8 @@ public void ShiftY_ShouldNotExceedMaxTotalShift(int shiftAmount, int maxTotalShi
{
var shifter = new PixelShifter
{
ShiftAmount = shiftAmount,
MaxTotalShift = maxTotalShift,
PixelsPerShift = shiftAmount,
MaxPixelOffset = maxTotalShift,
};

double totalShiftY = 0;
Expand Down
46 changes: 27 additions & 19 deletions DesktopClock/Utilities/PixelShifter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,46 @@ public class PixelShifter
/// <summary>
/// The number of pixels that will be shifted each time.
/// </summary>
public int ShiftAmount { get; set; } = 2;
public int PixelsPerShift { get; set; } = 1;

/// <summary>
/// The maximum amount of drift that can occur in each direction.
/// </summary>
public int MaxTotalShift { get; set; } = 4;
public int MaxPixelOffset { get; set; } = 4;

public double ShiftX()
{
var shift = _random.Next(-ShiftAmount, ShiftAmount + 1);
var newTotalShiftX = _totalShiftX + shift;

if (Math.Abs(newTotalShiftX) <= MaxTotalShift)
{
_totalShiftX = newTotalShiftX;
return shift;
}

return 0;
double pixelsToMoveBy = GetRandomShift();
pixelsToMoveBy = GetFinalShiftAmount(_totalShiftX, pixelsToMoveBy, MaxPixelOffset);
_totalShiftX += pixelsToMoveBy;
return pixelsToMoveBy;
}

public double ShiftY()
{
var shift = _random.Next(-ShiftAmount, ShiftAmount + 1);
var newTotalShiftY = _totalShiftY + shift;
double pixelsToMoveBy = GetRandomShift();
pixelsToMoveBy = GetFinalShiftAmount(_totalShiftY, pixelsToMoveBy, MaxPixelOffset);
_totalShiftY += pixelsToMoveBy;
return pixelsToMoveBy;
}

private int GetRandomShift() => _random.Next(-PixelsPerShift, PixelsPerShift + 1);

if (Math.Abs(newTotalShiftY) <= MaxTotalShift)
private double GetFinalShiftAmount(double current, double offset, double max)
{
var newTotal = current + offset;

if (newTotal > max)
{
_totalShiftY = newTotalShiftY;
return shift;
return max - current;
}
else if (newTotal < -max)
{
return -max - current;
}
else
{
return offset;
}

return 0;
}
}

0 comments on commit 63da7bc

Please sign in to comment.