Last active
June 25, 2024 18:56
-
-
Save Girgias/e912f932599399a8c571623721b66356 to your computer and use it in GitHub Desktop.
A small implementation of Tic-Tac-Toe in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
const PLAYER_1 = 'X'; | |
const PLAYER_2 = 'O'; | |
function format_grid(array $grid): string { | |
return join( | |
array_map( | |
fn($grid_str_line) => "\t{$grid_str_line}\n", | |
array_map( | |
fn (array $grid_list_line): string => join('|', $grid_list_line), | |
array_chunk($grid, 3) | |
) | |
) | |
); | |
} | |
function is_index_played(string $value): bool { | |
return $value === PLAYER_1 || $value === PLAYER_2; | |
} | |
function is_grid_full(array $grid): bool { | |
return array_sum( | |
array_map( | |
is_index_played(...), | |
$grid | |
) | |
) === 9; | |
} | |
function is_grid_won(array $grid): bool { | |
for ($i = 0; $i < 9; $i += 3) { | |
/* Check rows */ | |
if ($grid[$i] === $grid[$i+1] && $grid[$i] === $grid[$i+2]) { | |
return true; | |
} | |
/* Check columns */ | |
$j = $i % 3; | |
if ($grid[$j] === $grid[$j+3] && $grid[$j] === $grid[$j+6]) { | |
return true; | |
} | |
} | |
/* Check diagonals, which are either 1 or 4 away from the centre */ | |
$center = 4; | |
return ($grid[$center] === $grid[$center-1] && $grid[$center] === $grid[$center+1]) | |
|| ($grid[$center] === $grid[$center-4] && $grid[$center] === $grid[$center+4]); | |
} | |
/* Use numeric string semantics to parse the input */ | |
function parse_input(int $string) { | |
return $string-1; | |
} | |
function toggle_player(string $player): string { | |
return $player === PLAYER_1 ? PLAYER_2 : PLAYER_1; | |
} | |
$player = PLAYER_1; | |
$grid = range('1', '9'); | |
echo "Welcome to Tic-Tac-Toe! | |
The rules are simple, first person to align 3 symbols of their choice wins. | |
Select a cell by typing in the number of it. | |
Good luck!\n"; | |
do { | |
echo "Grid status:\n", format_grid($grid); | |
retry: | |
$raw_input = readline("Player {$player} which cell do you want to play?\t"); | |
try { | |
$input = parse_input($raw_input); | |
} catch (TypeError) { | |
echo "Please enter a number\n"; | |
goto retry; | |
} | |
if (is_index_played($grid[$input])) { | |
echo "The cell you have chosen is already taken\n"; | |
goto retry; | |
} | |
$grid[$input] = $player; | |
if (is_grid_won($grid)) { | |
echo "Congratulations player $player has won!\n"; | |
exit(0); | |
} | |
$player = toggle_player($player); | |
} while (!is_grid_full($grid)); | |
echo "Sadly no one has won this round\n"; | |
echo "Grid status:\n", format_grid($grid); | |
exit(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment