Virtual Pet Game Java, Android

👤 Sharing: AI
```java
// VirtualPet.java
public class VirtualPet {
    private String name;
    private int hunger;
    private int happiness;
    private int energy;

    public VirtualPet(String name) {
        this.name = name;
        this.hunger = 50;
        this.happiness = 50;
        this.energy = 50;
    }

    public String getName() {
        return name;
    }

    public int getHunger() {
        return hunger;
    }

    public int getHappiness() {
        return happiness;
    }

    public int getEnergy() {
        return energy;
    }

    public void feed() {
        hunger = Math.max(0, hunger - 20);
        happiness = Math.min(100, happiness + 5);
        energy = Math.min(100, energy + 10);
        System.out.println(name + " eats some food!");
    }

    public void play() {
        happiness = Math.min(100, happiness + 20);
        hunger = Math.min(100, hunger + 10);
        energy = Math.max(0, energy - 15);
        System.out.println(name + " plays and has fun!");
    }

    public void sleep() {
        energy = Math.min(100, energy + 30);
        hunger = Math.min(100, hunger + 5);
        happiness = Math.max(0, happiness - 10);
        System.out.println(name + " takes a nap.");
    }

    public void tick() {
        hunger = Math.min(100, hunger + 5);
        happiness = Math.max(0, happiness - 5);
        energy = Math.max(0, energy - 5);
    }

    public boolean isAlive() {
        return hunger < 100 && happiness > 0 && energy > 0;
    }

    public String toString() {
        return "Name: " + name + "\n" +
                "Hunger: " + hunger + "\n" +
                "Happiness: " + happiness + "\n" +
                "Energy: " + energy;
    }
}
```

```java
// VirtualPetActivity.java (Android)

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class VirtualPetActivity extends AppCompatActivity {

    private VirtualPet pet;
    private TextView nameTextView;
    private TextView hungerTextView;
    private TextView happinessTextView;
    private TextView energyTextView;
    private EditText nameEditText;
    private Button createButton;
    private Button feedButton;
    private Button playButton;
    private Button sleepButton;

    private Handler handler = new Handler();
    private Runnable tickRunnable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_virtual_pet);

        nameTextView = findViewById(R.id.nameTextView);
        hungerTextView = findViewById(R.id.hungerTextView);
        happinessTextView = findViewById(R.id.happinessTextView);
        energyTextView = findViewById(R.id.energyTextView);
        nameEditText = findViewById(R.id.nameEditText);
        createButton = findViewById(R.id.createButton);
        feedButton = findViewById(R.id.feedButton);
        playButton = findViewById(R.id.playButton);
        sleepButton = findViewById(R.id.sleepButton);

        feedButton.setEnabled(false);
        playButton.setEnabled(false);
        sleepButton.setEnabled(false);


        createButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String petName = nameEditText.getText().toString().trim();
                if (!petName.isEmpty()) {
                    pet = new VirtualPet(petName);
                    updateUI();
                    Toast.makeText(VirtualPetActivity.this, petName + " is born!", Toast.LENGTH_SHORT).show();
                    createButton.setEnabled(false); // Disable create after pet is created
                    nameEditText.setEnabled(false); //Disable editting name after pet is created
                    feedButton.setEnabled(true);
                    playButton.setEnabled(true);
                    sleepButton.setEnabled(true);


                    // Start the tick runnable
                    startTick();
                } else {
                    Toast.makeText(VirtualPetActivity.this, "Please enter a name for your pet!", Toast.LENGTH_SHORT).show();
                }
            }
        });


        feedButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pet != null) {
                    pet.feed();
                    updateUI();
                    checkIfAlive();
                }
            }
        });

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pet != null) {
                    pet.play();
                    updateUI();
                    checkIfAlive();
                }
            }
        });

        sleepButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pet != null) {
                    pet.sleep();
                    updateUI();
                    checkIfAlive();
                }
            }
        });


        tickRunnable = new Runnable() {
            @Override
            public void run() {
                if (pet != null && pet.isAlive()) {
                    pet.tick();
                    updateUI();
                    checkIfAlive();
                    handler.postDelayed(this, 5000); // Tick every 5 seconds
                }
            }
        };
    }


    private void startTick() {
        handler.postDelayed(tickRunnable, 5000);
    }

    private void stopTick() {
        handler.removeCallbacks(tickRunnable);
    }


    private void updateUI() {
        if (pet != null) {
            nameTextView.setText("Name: " + pet.getName());
            hungerTextView.setText("Hunger: " + pet.getHunger());
            happinessTextView.setText("Happiness: " + pet.getHappiness());
            energyTextView.setText("Energy: " + pet.getEnergy());
        }
    }

    private void checkIfAlive() {
        if (pet != null && !pet.isAlive()) {
            Toast.makeText(this, pet.getName() + " has passed away...", Toast.LENGTH_LONG).show();
            stopTick();

            //Disable buttons
            feedButton.setEnabled(false);
            playButton.setEnabled(false);
            sleepButton.setEnabled(false);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTick(); // Stop the tick when the activity is destroyed to avoid memory leaks
    }
}
```

```xml
<!-- activity_virtual_pet.xml (Android layout) -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".VirtualPetActivity">

    <TextView
        android:id="@+id/nameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name: "
        android:textSize="18sp" />

    <TextView
        android:id="@+id/hungerTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hunger: "
        android:textSize="18sp" />

    <TextView
        android:id="@+id/happinessTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Happiness: "
        android:textSize="18sp" />

    <TextView
        android:id="@+id/energyTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Energy: "
        android:textSize="18sp" />

    <EditText
        android:id="@+id/nameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter pet's name"
        android:inputType="text" />

    <Button
        android:id="@+id/createButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create Pet" />

    <Button
        android:id="@+id/feedButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Feed" />

    <Button
        android:id="@+id/playButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

    <Button
        android:id="@+id/sleepButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Sleep" />

</LinearLayout>
```

**How to Use (Android):**

1.  **Create a New Android Project:**  In Android Studio, create a new project with an empty activity.
2.  **Add the `VirtualPet.java` file:** Create a new Java class named `VirtualPet.java` in your project's `app/java/<your_package_name>/` directory and paste the `VirtualPet.java` code into it.
3.  **Modify `activity_virtual_pet.xml`:** Open your layout file (`app/res/layout/activity_virtual_pet.xml`) and replace its contents with the provided XML code.  This defines the user interface with TextViews for displaying stats, an EditText for the pet's name, and Buttons for actions.
4.  **Modify `VirtualPetActivity.java`:** Open your main activity file (`app/java/<your_package_name>/VirtualPetActivity.java`) and replace its contents with the provided `VirtualPetActivity.java` code. Make sure the package name at the top of the file matches your project's package name.
5.  **Run the App:** Build and run the app on an emulator or a connected Android device.

**Explanation of the Code:**

*   **`VirtualPet.java`:**
    *   This class represents the virtual pet.
    *   It has attributes like `name`, `hunger`, `happiness`, and `energy`.
    *   It has methods like `feed()`, `play()`, and `sleep()` to simulate actions and update the pet's stats.
    *   `tick()` is called periodically to simulate the passage of time and make the pet's stats change automatically.
    *   `isAlive()` checks if the pet is still alive based on its stats.
    *   `toString()` provides a formatted string representation of the pet's status.

*   **`VirtualPetActivity.java` (Android):**
    *   This is the main activity of the Android app.
    *   It contains UI elements (TextViews, EditText, Buttons) to display the pet's status and allow the user to interact with it.
    *   When the "Create Pet" button is clicked, a new `VirtualPet` object is created, and the UI is updated.
    *   The `feed()`, `play()`, and `sleep()` methods are called when the corresponding buttons are clicked.
    *   The `tick()` method is called periodically using a `Handler` and a `Runnable`. This simulates the passage of time and updates the pet's stats automatically.
    *   The `updateUI()` method updates the UI elements with the pet's current stats.
    *   The `checkIfAlive()` method checks if the pet is still alive and displays a message if it has died.
    *   The `onDestroy()` method is called when the activity is destroyed.  It's important to stop the `tick()` Runnable to prevent memory leaks.

*   **`activity_virtual_pet.xml` (Android Layout):**
    *   This XML file defines the layout of the user interface.
    *   It contains TextViews for displaying the pet's name, hunger, happiness, and energy.
    *   It also contains an EditText for entering the pet's name and Buttons for creating the pet and performing actions (feed, play, sleep).

**Important Considerations:**

*   **Error Handling:** The code could be improved by adding more error handling, such as checking for invalid input or handling exceptions.
*   **UI Enhancements:** The UI could be enhanced with images, animations, and more sophisticated layouts.
*   **Persistence:** The pet's state is not saved when the app is closed.  You could use SharedPreferences, files, or a database to save the pet's state and load it when the app is restarted.
*   **Game Balancing:** The rates at which the pet's stats change could be adjusted to make the game more challenging or rewarding.
*   **Notifications:** You could add notifications to remind the user to care for their pet.
*   **Sound Effects:** Add sound effects when performing actions (feeding, playing, sleeping) to enhance the user experience.
*   **Polishing:** Improve the visual appeal with custom drawables, themes, and styling.
*   **Testing:** Thoroughly test all features to ensure stability and a smooth user experience.  Use both emulators and physical devices.
*   **Memory Management:** Be mindful of memory usage, especially when using images or animations. Recycle bitmaps and use appropriate data structures.
👁️ Viewed: 27

Comments