LogoDart Beginner Tutorials

Part 3: Playtime Fun! – More Functions and Asynchronous Operations#

Our digital pet is fed and happy (hopefully!), but it's time for some playtime fun! In this part, we'll add another function to let our pet play and introduce some exciting new concepts: async and await. These powerful tools will help us simulate actions that take time, making our pet simulator feel even more realistic.

Think about it: when you play with a real pet, it doesn't happen instantaneously. There's a period of interaction, some playful actions, and then the result. We can mimic that using async and await.

Let's create a play() function. This function will be similar to the feed() function, but instead of affecting hunger, it will primarily increase happiness. We'll also use Future.delayed to simulate the time it takes to play:

  Future<void> play() async {
    print('$name is playing...');
    await Future.delayed(Duration(seconds: 3)); // Simulate playing for 3 seconds

    _happiness = (_happiness + 3).clamp(0, 10); // Happiness increases by 3
    _hunger = (_hunger + 1).clamp(0, 10);    // Hunger slightly increases
    print('$name finished playing! Happiness increased, hunger increased.');
  }

The async keyword indicates that this function will perform asynchronous operations. The await keyword pauses execution of the function until the Future.delayed operation (simulating the delay) completes. This makes the output more natural and reflects real-world interactions.

Now we need to integrate this new play() function into our main game loop. Add the following option to your switch statement inside the main function:

   switch (choice) {
     // ... (other cases) ...
     case '2':
       await myPet.play();
       break;
     // ... (rest of switch statement) ...
   }

This simple addition allows the user to choose the 'play' action. The await keyword before myPet.play() is essential because play() is an asynchronous function. Without await, the program would continue to the next iteration of the loop before the playing action is finished, creating a jumbled output.

Run your code! Now you should be able to choose between feeding and playing with your digital pet, observing the changes in hunger and happiness levels.

In the next part, "Happy or Hungry?", we'll dive into the world of Object-Oriented Programming (OOP) by creating a dedicated DigitalPet class, and you'll learn about classes, objects, and how they help in building more complex programs. You'll also master game loops to keep your pet simulation running. Get ready to level up your coding skills!