Skip to content

Commit

Permalink
some more improvements
Browse files Browse the repository at this point in the history
- usage help
- support for multiple words
- strip non-scorable chars from input
  • Loading branch information
gooh committed Oct 20, 2016
1 parent 9f30f0a commit 459974f
Showing 1 changed file with 47 additions and 8 deletions.
55 changes: 47 additions & 8 deletions src/Plugins/Scrabble.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

class Scrabble extends BasePlugin
{
const USAGE = "Usage: `!!scrabble [words to calculate score for]`";

const SCORES = [
'en' => [
1 => 'EAIONRTLSU',
Expand All @@ -28,33 +30,70 @@ public function __construct(ChatClient $chatClient)
$this->chatClient = $chatClient;
}

public function getDescription(): string
{
return 'Calculates the Scrabble score for the given input';
}

public function scrabble(Command $command): Promise
{
if (!$command->hasParameters()) {
return new Success();
if ($command->hasParameters() === false) {
return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
}

return $this->chatClient->postReply(
$command,
$this->calculateScore(implode($command->getParameters()))
$this->formatScores(
$this->calculateScores(
$this->getScorableWords(
$command->getParameters()
)
)
)
);
}

private function getScorableWords(array $words): array
{
$chars = preg_quote(implode(static::SCORES['en']), '~');
$words = preg_replace("~[^$chars]~i", '', $words);
// @todo remove any non-dictionary words

return array_filter($words, 'strlen');
}

public function getDescription(): string
private function calculateScores(array $words): array
{
return 'Calculates the Scrabble score for the given input';
$scores = [];
foreach ($words as $word) {
$scores[$word] = $this->calculateScore($word);
}

return $scores;
}

private function calculateScore(string $input): string
private function calculateScore(string $word): string
{
$sum = 0;
foreach ($input as $char) {
$char = preg_quote($char, '~');
for ($i = 0; $i < strlen($word); $i++) {
$char = preg_quote($word[$i], '~');
$sum += key(preg_grep("~$char~i", static::SCORES['en']));
}

return $sum;
}

private function formatScores(array $scores): string
{
$total = 0;
$result = '';
foreach ($scores as $word => $score) {
$result .= "$word = $score, ";
$total += $score;
}
return $result .= "TOTAL SCORE = $total";
}

/**
* @return PluginCommandEndpoint[]
*/
Expand Down

0 comments on commit 459974f

Please sign in to comment.