LogoDart Beginner Tutorials

Tracking Your Pets Time

Learn about loops, while loops, switch statements, and user input to add a time-passing mechanism to your pet simulator.

Welcome to Part 4! We've made great progress—our digital pet can now eat and play! But what about the passage of time? In this recipe, we'll add a time-passing mechanism to our game, making it even more engaging. You'll learn about loops, the while loop, switch statements, and how to handle user input more effectively.

Problem: You want to add a mechanism that simulates the passage of time, affecting your pet's hunger and happiness levels. You also want to provide the user with more control over the game flow.

Solution: We'll use a while loop to keep the game running indefinitely. A switch statement will be used to handle user input more efficiently, and we'll use stdin.readLineSync() to take input from the user.

Step 1: Adding a Time-Passing Function

Let's create a new function, timePasses, that simulates the passage of time. This function will increase the hunger level and decrease the happiness level of your pet over time. We'll again use Future.delayed to introduce a pause:

Future<void> timePasses() async {
  print('Time passes...');
  await Future.delayed(Duration(seconds: 1));
  hunger++;
  happiness--;
  if (hunger >= 10) {
    print('$petName is very hungry!');
  }
  if (happiness <= 0) {
    print('$petName is very sad!');
  }
}

Step 2: Implementing a while Loop for the Game

To keep the game running until the user chooses to quit, we'll embed our existing code within a while (true) loop. This loop will continue indefinitely until explicitly broken.

void main() async {
  // ... (Previous code) ...
  while (true) {  // The game loop
    // ... (Existing code for displaying status and choices) ...
    // ... (Existing switch statement to handle choice) ...

  }
}

Step 3: Enhancing User Input with a switch Statement

Currently, we're using if/else if/else to process user choices. Let’s refactor this to use a switch statement, which is more concise and easier to read when dealing with multiple options:

  switch (choice) {
    case '1':
      await feed();
      break;
    case '2':
      await play();
      break;
    case '3':
      await timePasses();
      break;
    case '4':
      print('Goodbye!');
      return; // Exit the main function
    default:
      print('Invalid choice. Please try again.');
  }

We've added a case for the timePasses function, and a case for exiting the game ('4'). The return statement exits the main function, thus breaking the while loop.

Step 4: Adding an Exit Condition

Right now, the game runs forever. Let's provide a way to exit gracefully. Add a fourth option "Exit" to the user menu and handle the case within the switch statement as shown above.

Step 5: Reading User Input with stdin.readLineSync()

We're already using stdin.readLineSync() to get user input. Ensure you have import 'dart:io'; at the top of your file to use this function. This function reads a line from the standard input (typically the console).

Congratulations! You've successfully implemented a game loop, enhanced user input handling, and added a time-passing mechanism to your pet simulator!

Next Steps: In the next recipe, we'll refactor our code using object-oriented programming principles to create a DigitalPet class. This will improve the organization and maintainability of our code.