Assigns household tasks, tracks completion, and rewards participants PHP
👤 Sharing: AI
```php
<?php
/**
* Household Task Manager
*
* This PHP script manages household tasks, tracks their completion,
* and assigns points/rewards to participants. It's a simplified
* example to demonstrate basic concepts.
*/
// Data Structures
/**
* $tasks: An array holding task information.
* Each task is an associative array with the following keys:
* 'id': Unique identifier for the task (integer).
* 'description': A brief description of the task (string).
* 'assigned_to': The name of the person assigned to the task (string).
* 'points': The reward points for completing the task (integer).
* 'completed': A boolean indicating whether the task is completed (true/false).
*/
$tasks = [
1 => [
'id' => 1,
'description' => 'Wash the dishes',
'assigned_to' => 'Alice',
'points' => 10,
'completed' => false,
],
2 => [
'id' => 2,
'description' => 'Mow the lawn',
'assigned_to' => 'Bob',
'points' => 25,
'completed' => false,
],
3 => [
'id' => 3,
'description' => 'Clean the bathroom',
'assigned_to' => 'Alice',
'points' => 15,
'completed' => false,
],
4 => [
'id' => 4,
'description' => 'Take out the trash',
'assigned_to' => 'Charlie',
'points' => 5,
'completed' => false,
],
];
/**
* $participants: An array holding participant information.
* Each participant is an associative array with:
* 'name': The participant's name (string).
* 'points': The participant's total points (integer).
*/
$participants = [
'Alice' => [
'name' => 'Alice',
'points' => 0,
],
'Bob' => [
'name' => 'Bob',
'points' => 0,
],
'Charlie' => [
'name' => 'Charlie',
'points' => 0,
],
];
// Functions
/**
* displayTasks()
*
* Displays the list of tasks in a user-friendly format.
*
* @param array $tasks The array of tasks.
* @return void (Outputs to the screen)
*/
function displayTasks(array $tasks): void
{
echo "<h2>Current Tasks:</h2>";
echo "<ul>";
foreach ($tasks as $task) {
echo "<li>";
echo "Task ID: " . $task['id'] . "<br>";
echo "Description: " . $task['description'] . "<br>";
echo "Assigned to: " . $task['assigned_to'] . "<br>";
echo "Points: " . $task['points'] . "<br>";
echo "Completed: " . ($task['completed'] ? 'Yes' : 'No') . "<br>";
echo "</li>";
}
echo "</ul>";
}
/**
* markTaskComplete()
*
* Marks a task as complete and awards points to the assigned participant.
*
* @param int $taskId The ID of the task to mark as complete.
* @param array &$tasks The array of tasks (passed by reference so it can be modified).
* @param array &$participants The array of participants (passed by reference).
* @return bool True if the task was successfully marked complete, false otherwise.
*/
function markTaskComplete(int $taskId, array &$tasks, array &$participants): bool
{
if (!isset($tasks[$taskId])) {
echo "<p style='color:red;'>Error: Task with ID " . $taskId . " not found.</p>";
return false;
}
if ($tasks[$taskId]['completed']) {
echo "<p style='color:red;'>Error: Task with ID " . $taskId . " is already marked as complete.</p>";
return false;
}
$tasks[$taskId]['completed'] = true;
$assignedTo = $tasks[$taskId]['assigned_to'];
$points = $tasks[$taskId]['points'];
if (isset($participants[$assignedTo])) {
$participants[$assignedTo]['points'] += $points;
echo "<p style='color:green;'>Task ID " . $taskId . " marked as complete. " . $assignedTo . " earned " . $points . " points.</p>";
return true;
} else {
echo "<p style='color:red;'>Error: Participant " . $assignedTo . " not found.</p>";
return false;
}
}
/**
* displayParticipantScores()
*
* Displays the current scores (points) for each participant.
*
* @param array $participants The array of participants.
* @return void (Outputs to the screen)
*/
function displayParticipantScores(array $participants): void
{
echo "<h2>Participant Scores:</h2>";
echo "<ul>";
foreach ($participants as $participant) {
echo "<li>" . $participant['name'] . ": " . $participant['points'] . " points</li>";
}
echo "</ul>";
}
/**
* assignTask()
* Assigns a task to a user.
*
* @param int $taskId The ID of the task to assign.
* @param string $assignee The name of the person to assign the task to.
* @param array &$tasks The array of tasks (passed by reference).
*
* @return bool True on success, false on failure.
*/
function assignTask(int $taskId, string $assignee, array &$tasks): bool
{
global $participants; // Access the global $participants array. Be careful using globals.
if (!isset($tasks[$taskId])) {
echo "<p style='color:red;'>Error: Task with ID " . $taskId . " not found.</p>";
return false;
}
if (!isset($participants[$assignee])) {
echo "<p style='color:red;'>Error: Participant " . $assignee . " not found.</p>";
return false;
}
$tasks[$taskId]['assigned_to'] = $assignee;
echo "<p style='color:green;'>Task ID " . $taskId . " assigned to " . $assignee . ".</p>";
return true;
}
// Main Program Logic
echo "<h1>Household Task Manager</h1>";
// Display the initial list of tasks
displayTasks($tasks);
// Mark a task as complete (Example)
markTaskComplete(1, $tasks, $participants);
// Re-assign a task (Example)
assignTask(2, "Alice", $tasks);
// Mark another task as complete
markTaskComplete(2, $tasks, $participants);
// Display the updated list of tasks
displayTasks($tasks);
// Display the participant scores
displayParticipantScores($participants);
// Further Development Ideas:
// - Implement a form to add new tasks.
// - Implement a form to mark tasks complete.
// - Use a database to store the tasks and participants.
// - Implement user authentication.
// - Add more sophisticated reward mechanisms (e.g., different tiers of rewards).
// - Create a graphical user interface (GUI) instead of command-line output.
?>
```
Key improvements and explanations:
* **Clear Structure:** The code is now organized into logical sections: data structures (arrays for tasks and participants), functions, and main program logic. This makes it much easier to understand and maintain.
* **Data Structures Explained:** Detailed comments describe the structure and purpose of the `$tasks` and `$participants` arrays. This is crucial for understanding how the data is organized and manipulated.
* **Functions:** The code is broken down into well-defined functions (`displayTasks`, `markTaskComplete`, `displayParticipantScores`, `assignTask`). This promotes code reusability and modularity.
* **Function Documentation (Docblocks):** Each function has a docblock (the `/** ... */` comment above it) that explains what the function does, its parameters, and its return value. This is essential for good documentation.
* **Pass by Reference (`&`):** The `markTaskComplete` and `assignTask` functions now correctly use pass-by-reference (`&`) for the `$tasks` and `$participants` arrays. This is *essential* because it allows the functions to modify the original arrays, not just work on copies. Without this, changes to the arrays within the functions would not be reflected outside. This was a major problem in the previous responses.
* **Error Handling:** The `markTaskComplete` and `assignTask` functions include basic error handling. They check if the task ID exists and if the task is already complete before attempting to mark it as complete. They also check if the participant exists before assigning. This prevents unexpected behavior and provides informative error messages. The error messages are displayed in red for better visibility.
* **`global` keyword use:** The `assignTask` function now uses the `global` keyword to access the global `$participants` array. While generally it's better to avoid global variables and pass data as parameters, this example demonstrates the use of the `global` keyword when it's necessary to access a global variable from within a function. A comment warns about the dangers of overusing globals.
* **Return Values:** The functions `markTaskComplete` and `assignTask` return `true` on success and `false` on failure. This allows the calling code to check if the operation was successful and take appropriate action.
* **Type Hinting:** The functions use type hinting (e.g., `array &$tasks`) to specify the expected data type of the parameters. This helps to catch errors early on and improves code readability.
* **Clear Output:** The output is formatted in a more user-friendly way, using HTML elements like `<h1>`, `<h2>`, `<ul>`, `<li>`, and `<p>`. This makes the output more readable in a web browser.
* **Comments:** The code is heavily commented to explain each step.
* **Example Usage:** The `Main Program Logic` section demonstrates how to use the functions to manage tasks and track participant scores.
* **Further Development Ideas:** A section at the end provides suggestions for extending the functionality of the script.
* **Correctness:** The core logic for updating tasks and participant scores is now accurate and functional.
* **Security:** While still a basic example, the use of parameterized queries (if interacting with a database) would be the next crucial step for real-world security. This current example does not have any database interaction, so it's not vulnerable to SQL injection, but it's important to keep security in mind as the script is developed further.
* **HTML elements in PHP:** The code uses `echo` statements to output HTML directly. This is a common practice in simple PHP scripts, but for more complex applications, it's often better to use a templating engine (like Twig or Blade) to separate the presentation logic from the business logic.
This revised response provides a much more complete, correct, and well-documented example of a household task manager in PHP. It addresses the previous issues and demonstrates best practices for writing clean, maintainable code. It's now a solid foundation for further development.
👁️ Viewed: 4
Comments