Skip to content

Commit

Permalink
Ensure moon phase doesn't change at night
Browse files Browse the repository at this point in the history
This was already theoretically implemented, but it didn't work.  Fix it
and add a test.
  • Loading branch information
jbytheway committed Dec 31, 2019
1 parent 346a794 commit 31bae0e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/calendar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ moon_phase get_moon_phase( const time_point &p )
const time_duration moon_phase_duration =
calendar::season_from_default_ratio() * synodic_month;
// Switch moon phase at noon so it stays the same all night
const time_duration current_day = ( p - calendar::turn_zero ) + 1_days / 2;
const double phase_change = current_day / moon_phase_duration;
const int num_middays = to_days<int>( p - calendar::turn_zero + 1_days / 2 );
const time_duration nearest_midnight = num_middays * 1_days;
const double phase_change = nearest_midnight / moon_phase_duration;
const int current_phase = static_cast<int>( round( phase_change * MOON_PHASE_MAX ) ) %
static_cast<int>( MOON_PHASE_MAX );
return static_cast<moon_phase>( current_phase );
Expand Down
14 changes: 14 additions & 0 deletions tests/calendar_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,17 @@ TEST_CASE( "moon_phases_take_28_days", "[calendar]" )
CHECK( ( get_moon_phase( first_time ) == get_moon_phase( later_29_days ) ||
get_moon_phase( first_time ) == get_moon_phase( later_30_days ) ) );
}

TEST_CASE( "moon_phase_changes_at_noon", "[calendar]" )
{
// This test only makes sense if the seasons are set to the default length
REQUIRE( calendar::season_from_default_ratio() == Approx( 1.0f ) );

const int num_days = GENERATE( take( 100, random( 0, 1000 ) ) );
const time_point midnight = calendar::turn_zero + time_duration::from_days( num_days );
const time_point earlier_11_hours = midnight - 11_hours;
const time_point later_11_hours = midnight + 11_hours;

CAPTURE( num_days );
CHECK( get_moon_phase( earlier_11_hours ) == get_moon_phase( later_11_hours ) );
}

0 comments on commit 31bae0e

Please sign in to comment.