Menu
Coddy logo textTech

Playing with the Pet

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 21 of 61.

challenge icon

Challenge

Easy

Your pet is fed and happy—now let's give it some exercise! In this step, you'll add a play method that lets you interact with your virtual companion.

Playing with your pet should cost energy but also make it hungrier. When your pet plays, its energy decreases by 20 and its hunger increases by 15. However, energy should never drop below 0, and hunger should never exceed 100.

You'll also need an energy getter method to check how tired your pet is after playtime.

In your main.rs, read the pet's name along with initial energy and hunger values. After setting up your pet, call play once and display both the energy and hunger levels.

The play method should print a message showing your pet had fun:

{name} had fun playing!

Then your main file should display the stats:

Energy: {energy_level}
Hunger: {hunger_level}

For example, if the input is:

Buddy
50
30

The output should be:

Buddy had fun playing!
Energy: 30
Hunger: 45

If energy starts at 10, playing would bring it to 0 (not negative). If hunger starts at 90, playing would cap it at 100.

You'll need to add a set_energy method alongside your existing set_hunger to initialize both values for testing.

Try it yourself

mod pet;

use pet::Pet;

fn main() {
    let mut name = String::new();
    std::io::stdin().read_line(&mut name).expect("Failed to read line");
    let name = name.trim().to_string();

    let mut energy_input = String::new();
    std::io::stdin().read_line(&mut energy_input).expect("Failed to read line");
    let initial_energy: u32 = energy_input.trim().parse().expect("Failed to parse energy");

    let mut hunger_input = String::new();
    std::io::stdin().read_line(&mut hunger_input).expect("Failed to read line");
    let initial_hunger: u32 = hunger_input.trim().parse().expect("Failed to parse hunger");

    let mut my_pet = Pet::new(name);
    my_pet.set_energy(initial_energy);
    my_pet.set_hunger(initial_hunger);
    my_pet.play();

    println!("Energy: {}", my_pet.energy());
    println!("Hunger: {}", my_pet.hunger());
}

All lessons in Object Oriented Programming