Congratulations on making it this far! You've built a fully functional digital pet simulator. In this final recipe, we'll polish the status display to make it more informative and visually appealing. You'll learn about string interpolation, importing libraries, and using the
clamp
method to keep your pet's stats within reasonable bounds.
Problem: The current status display is basic. We want to improve its readability and add visual cues to represent hunger and happiness levels.
Solution:
We'll use string interpolation to create a more dynamic display, import the
dart:math
library to use the
clamp
method, and create a progress bar-like representation of hunger and happiness.
Step 1: Importing the dart:math Library
To use the
clamp
method, we need to import the
dart:math
library. Add this line at the top of your
pet_simulator.dart
file:
import 'dart:math';
The
clamp
method helps us keep our hunger and happiness values within the 0-10 range, preventing unexpected behavior.
Step 2: Improving the displayStatus Method
Let's enhance the
displayStatus
method in the
DigitalPet
class. We will replace the simple print statements with a more visually appealing output using string interpolation. We'll also add a simple progress bar using a loop.
Replace the existing displayStatus method with this:
void displayStatus() {
print("--- ${name}'s Status ---");
print('Hunger: [${_getStatusBar(_hunger)}]');
print('Happiness: [${_getStatusBar(_happiness)}]');
print('-------------------------');
}
String _getStatusBar(int value) {
String bar = '';
for (int i = 0; i < 10; i++) {
if (i < value) {
bar += '#';
} else {
bar += '-';
}
}
return bar;
}
The
_getStatusBar
helper function creates a simple progress bar representation of hunger and happiness (e.g., "#######---" for hunger level 7).
Step 3: Clamping Hunger and Happiness Values
Now, let's use the
clamp
method to ensure that the hunger and happiness values always stay within the range of 0 to 10. Modify the
feed,
play, and
timePasses
methods as follows:
Future<void> feed() async {
print('$name is eating...');
await Future.delayed(Duration(seconds: 2));
_hunger = (_hunger - 2).clamp(0, 10);
_happiness = (_happiness + 1).clamp(0, 10);
print('$name finished eating! Hunger decreased, happiness increased.');
}
//Similar changes to play and timePasses methods
The .clamp(0, 10) part ensures that the value never goes below 0 or above 10.
Congratulations! You've completed your digital pet simulator! You've learned the fundamentals of Dart programming, covering data types, control flow, functions, asynchronous operations, object-oriented programming, and error handling. You should be proud of what you've accomplished!
There are no further steps in this tutorial, but remember that this is just the beginning. You can expand upon this project in countless ways: add more actions, improve the user interface, create different types of pets, and much more! The possibilities are endless.
