Add support for named colors

E.g., in `mix blue and red`.
master
Ben Moon 2016-07-05 12:03:59 +01:00
parent 5707700a7c
commit 09d622130e
2 changed files with 18 additions and 5 deletions

View File

@ -5,6 +5,7 @@ use strict;
use warnings;
use List::Util qw(first);
use Color::Library;
use Color::RGB::Util qw(
mix_2_rgb_colors
rand_rgb_color
@ -17,8 +18,17 @@ zci is_cached => 0;
triggers any => 'color', 'colour';
triggers start => 'mix';
#####################
# Color Constants #
#####################
my %colors = map { $_ => '#' . lc Color::Library->color($_)->hex }
Color::Library->WWW->names;
my @color_names = sort keys %colors;
my $color_name_re = '(?:' . (join '|', @color_names) . ')';
my $scolor = 'colou?r';
my $color_re = '#?\p{XDigit}{6}';
my $color_re = "(?:$color_name_re|#?\\p{XDigit}{6})";
#############
# Helpers #
@ -26,6 +36,7 @@ my $color_re = '#?\p{XDigit}{6}';
sub normalize_color {
my $color = shift;
return $colors{$color} if exists $colors{$color};
return $color if $color =~ /^#/;
return "#$color";
}

View File

@ -68,7 +68,7 @@ sub build_test { test_zci(build_structured_answer(@_)) }
# Test Cases #
################
my $tc_mix_white_black = build_test('mix',
my $tc_mix_black_white = build_test('mix',
input_colors => ['#000000', '#ffffff'],
result_color => '#7f7f7f',
);
@ -81,11 +81,13 @@ ddg_goodie_test(
# Using 'colour'
'random colour' => build_test('random'),
# Mixing colors
'mix 000000 ffffff' => $tc_mix_white_black,
'mix 000000 ffffff' => $tc_mix_black_white,
# # With leading '#'
'mix #000000 #ffffff' => $tc_mix_white_black,
'mix #000000 #ffffff' => $tc_mix_black_white,
# # 'and'
'mix 000000 and ffffff' => $tc_mix_white_black,
'mix 000000 and ffffff' => $tc_mix_black_white,
# # Using names
'mix black and white' => $tc_mix_black_white,
# Invalid queries
'color' => undef,
'color ffffff' => undef,