Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Last active October 23, 2023 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgestephanis/c25486468a86d93ad66b70e1483b40a2 to your computer and use it in GitHub Desktop.
Save georgestephanis/c25486468a86d93ad66b70e1483b40a2 to your computer and use it in GitHub Desktop.
Implementation of Four Letters Word Game from BJ Homer's flash talk at Division Meetup
<?php
define( 'DICT_FILE', '/usr/share/dict/words' );
$allwords = file_get_contents( DICT_FILE );
$qty = preg_match_all( '/^\w{4}$/m', $allwords, $matches );
echo "\r\n\e[32mLoaded \e[37m{$qty}\e[32m four-letter words in from \e[37m" . DICT_FILE . "\e[32m ...\r\n\e[0m";
$fourletter = $matches[0];
// Build our frequency chart ...
$frequency = array_count_values(
str_split(
strtolower(
implode(
'',
$fourletter
)
)
)
);
arsort( $frequency );
// Pick the word for the user to guess ...
$word = $fourletter[ array_rand( $fourletter ) ];
echo "\e[39mWord Selected!\r\n";
echo "\e[32mIf you'd like to quit, submit an empty guess. Happy guessing!\r\n\e[0m";
$guess_history = '';
$guess = '';
while ( strtolower( $guess ) !== strtolower( $word ) ) {
$guessed_letters = array_unique( str_split( strtoupper( $guess_history ) ) );
print_frequency_chart( $frequency, $guessed_letters );
$prev_guesses = strlen( $guess_history ) / 4;
$guess = readline( "\e[39mGuess #\e[37m" . ( $prev_guesses + 1 ) . "\e[39m: " );
if ( $guess === $word ) {
echo "\e[37mYou got it!\r\n";
break;
} elseif ( '' === $guess ) {
if ( 'y' === strtolower( readline( "\r\n\e[39mDid you want to give up? [y/N] " ) ) ) {
break;
}
} elseif ( ! preg_match( '/^[a-z]{4}$/i', $guess ) ) {
echo "\t\e[31m‼️ Guesses must be four characters. Try again.\r\n\e[39m";
continue;
} elseif ( ! in_array( strtolower( $guess ), array_map( 'strtolower', $fourletter ) ) ) {
echo "\t\e[31m⁉️ That's not a known word. Try again.\r\n\e[39m";
continue;
}
$guess_history .= $guess;
echo "\t\e[37m=> \e[37m" . calculate_number( $guess, $word ) . "\r\n";
}
echo "\r\n\e[32mThe word was \e[37m{$word}\e[0m\r\n";
/**
* Custom Functions:
*/
function print_frequency_chart( $frequency_array, $guessed = array() ) {
echo "\r\n\e[39mLetter Frequency Chart:\r\n";
$guessed = array_map( 'strtoupper', $guessed );
foreach ( $frequency_array as $letter => $frequency ) {
if ( in_array( strtoupper( $letter ), $guessed ) ) {
echo "\e[31m";
} else {
echo "\e[37m";
}
echo strtoupper( $letter );
}
echo "\r\n\e[0m";
}
function calculate_number( $guess, $solution ) {
$number = 0;
$guess_arr = str_split( $guess );
foreach ( $guess_arr as $letter ) {
if ( str_contains( strtolower( $solution ), strtolower( $letter ) ) ) {
$number++;
}
}
return $number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment