LogoDart Beginner Tutorials

Part 5: Keeping Track! – Advanced Logic and Status Bars#

Our digital pet is thriving, but wouldn't it be nice to have a clearer visual representation of its hunger and happiness levels? In this part, we'll enhance our simulator with simple progress bars, making it easier to monitor our pet's well-being. We'll also introduce for loops and switch statements to make our code more efficient and readable.

Let's start by adding a displayStatus() function to our DigitalPet class. This function will use a helper function, _getStatusBar(), to create our progress bars:

  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++) { //Creates a bar of 10 characters
      if (i < value) {
        bar += '#';
      } else {
        bar += '-';
      }
    }
    return bar;
  }

The _getStatusBar() function uses a for loop. A for loop is a handy tool for repeating a block of code a specific number of times. Here, it iterates 10 times, creating a string of '#' and '-' characters representing the pet's current status. The more '#' characters, the higher the value.

Now, let's improve our main game loop using a switch statement. A switch statement provides a more structured and readable way to handle multiple choices compared to a long chain of if/else if statements. We'll replace our existing if/else if structure with a switch statement:

  switch (choice) {
    case '1':
      await myPet.feed();
      break;
    case '2':
      await myPet.play();
      break;
    case '3':
      await myPet.timePasses();
      break;
    case '4':
      print('Goodbye! Thanks for playing with ${myPet.name}.');
      return;
    default:
      print('Invalid choice. Please try again.');
  }

This switch statement neatly handles each user choice, making the code much clearer. Each case corresponds to a user input, and the break statement prevents the code from falling through to the next case. The default case handles invalid inputs.

Finally, let's add string interpolation to make our output even more informative. We'll modify our print statements to include the pet's name directly within the string:

print('What would you like to do?');
print('1. Feed ${myPet.name}');
print('2. Play with ${myPet.name}');
print('3. Wait (time passes)');
print('4. Exit');

Now, run your code! You'll see nicely formatted progress bars indicating your pet's hunger and happiness, and a more streamlined user interface.

In the next part, "A Day in the Life!", we'll add a timePasses() function to simulate the passage of time, updating your pet's hunger and happiness automatically. We'll also address edge cases and refine our simulator to make it even more complete. Prepare for the final flourish!