| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- import java.io.*;
- public class Pet implements java.io.Serializable {
- // serializable version number
- private static final long serialVersionUID = 1;
- // the pet's stats
- private int hunger;
- private int thirst;
- private int energy;
- private boolean life;
-
- // everything starts off good
- public Pet(){
- hunger = 0;
- thirst = 0;
- energy = 100;
- life = true;
- }
-
- // reset the pet's hunger
- public void feed(){
- hunger = 0;
- thirst += 5;
- energy -= 5;
- if(hunger > 100 || thirst > 100 || energy < 0){
- this.kill();
- }
- }
-
- // reset the pet's thirst
- public void water(){
- hunger += 5;
- thirst = 0;
- energy -= 5;
- if(hunger > 100 || thirst > 100 || energy < 0){
- this.kill();
- }
- }
-
- // reset the pet's energy
- public void rest(){
- hunger += 5;
- thirst += 5;
- energy = 100;
- if(hunger > 100 || thirst > 100 || energy < 0){
- this.kill();
- }
- }
-
- // kill the pet
- public void kill(){
- hunger = 0;
- thirst = 0;
- energy = 0;
- life = false;
- }
-
- // do nothing
- public void neglect(){
- hunger += 5;
- thirst += 5;
- energy -= 5;
- if(hunger > 100 || thirst > 100 || energy < 0){
- this.kill();
- }
- }
-
- // print the pet's stats
- public void printStatus(){
- if(life){
- System.out.println("\tHunger: " + hunger);
- System.out.println("\tThirst: " + thirst);
- System.out.println("\tEnergy: " + energy);
- } else{
- System.out.println("This pet died.");
- }
- }
- // helper methods
- public int getHunger(){
- return hunger;
- }
- public int getThirst(){
- return thirst;
- }
- public int getEnergy(){
- return energy;
- }
- public boolean isAlive(){
- return life;
- }
-
- // save the current pet to the disk
- public void saveToDisk(){
- try{
- FileOutputStream fos = new FileOutputStream("pet.pet");
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(this);
- oos.close();
- fos.close();
- }catch(IOException ioe){
- ioe.printStackTrace();
- }
- }
-
- // read a pet from the disk
- public static Pet loadFromDisk(){
- Pet pet = null;
- try{
- FileInputStream fin = new FileInputStream("pet.pet");
- ObjectInputStream oin = new ObjectInputStream(fin);
- pet = (Pet) oin.readObject();
- oin.close();
- fin.close();
- }catch(IOException ioe){
- // ioe.printStackTrace();
- }catch(ClassNotFoundException cnfe){
- cnfe.printStackTrace();
- }
- return pet;
- }
- }
|