Skip to content

Instantly share code, notes, and snippets.

@foxfabi
Created September 25, 2020 09:54
Show Gist options
  • Save foxfabi/dc7337153c9d13e0402b7f0c0654233f to your computer and use it in GitHub Desktop.
Save foxfabi/dc7337153c9d13e0402b7f0c0654233f to your computer and use it in GitHub Desktop.
PHP Quiz: Who Wants to Be a Millionaire?
<?php
/**
* WWTBAM: Who Wants to Be a Millionaire?
*
* At the end of this file you will find the JSON data structure.
*
* Author: Fabian Dennler
*/
$playing = true; // Flag to check if game is running
$index = 0; // Index of current question
$storage = "./WWTBAM.json"; // File containing the questionaire
$payout = 0; // Contains the actual winning amount
$safepoint = null; // Index of last security point
$json = file_get_contents($storage); // Read JSON file TODO: Check if file exists
$questionaire = json_decode($json, true); // Decode JSON TODO: Check if is valid and not empty
print("\nSo you want to be a millionaire?\n");
printf("Answer the following %d questions ...\n\n", sizeof($questionaire));
while($playing) {
if(askQuestion($questionaire[$index])) {
$payout = $questionaire[$index]["WIN"];
if ($questionaire[$index]["ISSAFE"] == "true") {
$safepoint = $index; // Remember this safepoint for fallback
print("You reached a safepoint ;)\n\n");
}
$index++;
} else {
$playing = false;
if (is_numeric($safepoint)) {
$payout = $questionaire[$safepoint]["WIN"];
print("You're lucky! Falling into safety net ...\n\n");
} else {
$payout = 0;
}
}
// If question index is greater the amount of questions
if ($index > (sizeof($questionaire) - 1)) {
$playing = false;
}
}
if ($payout > 0) {
printf("Your payout is %d.\n\n", $payout);
} else {
print("Back to school with empty hands :o\n\n");
}
function askQuestion($question) {
$delay = 1; // Delay between answers and result
$continue = true; // Return value
printf("%s\n", $question["QUESTION"]);
sleep($delay);
foreach($question["ANSWERS"] as $key => $answer) {
printf("%s: %s\n", $key, $answer);
sleep($delay);
}
// TODO: add Lifelines/Jokers
print("\nEnter your choice: ");
fscanf(STDIN, "%s", $answer);
sleep($delay);
if ($question["RIGHTONE"] === $answer) {
print("\nCongrats! That's the right answer.\n\n");
} else {
print("\nFail! That's the wrong answer.\n\n");
$continue = false;
}
return $continue;
}
// Questionaire as JSON data structure
/*
[
{
"QUESTION": "Question 1?",
"ANSWERS": {
"A": "A",
"B": "B",
"C": "C",
"D": "D"
},
"RIGHTONE": "B",
"WIN": "100",
"ISSAFE": true
},
{
"QUESTION": "Question 2?",
"ANSWERS": {
"A": "A",
"B": "B",
"C": "C",
"D": "D"
},
"RIGHTONE": "C",
"WIN": "200",
"ISSAFE": false
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment