What are the best practices for implementing a rock-paper-scissors game in PHP, including user input validation and game logic?
To implement a rock-paper-scissors game in PHP with user input validation and game logic, you can use an array to store the possible choices (rock, paper, scissors), validate user input to ensure it is one of these choices, generate a random choice for the computer, compare the user and computer choices to determine the winner, and display the result to the user.
<?php
// Array of possible choices
$choices = ['rock', 'paper', 'scissors'];
// Validate user input
$user_choice = strtolower($_POST['choice']);
if (!in_array($user_choice, $choices)) {
echo "Invalid choice. Please choose rock, paper, or scissors.";
exit;
}
// Generate random choice for computer
$computer_choice = $choices[array_rand($choices)];
// Game logic to determine the winner
if ($user_choice == $computer_choice) {
$result = "It's a tie!";
} elseif (
($user_choice == 'rock' && $computer_choice == 'scissors') ||
($user_choice == 'paper' && $computer_choice == 'rock') ||
($user_choice == 'scissors' && $computer_choice == 'paper')
) {
$result = "You win!";
} else {
$result = "Computer wins!";
}
// Display the result to the user
echo "You chose: $user_choice<br>";
echo "Computer chose: $computer_choice<br>";
echo "Result: $result";
?>