User Tools

Site Tools


virtual_pet

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
virtual_pet [2026/03/01 14:14] frchrisvirtual_pet [2026/03/01 15:02] (current) – [Part C] frchris
Line 126: Line 126:
 </file> </file>
 ===== Activity 4 ===== ===== Activity 4 =====
 +==== Part A: Food ====
 <file java Food.java> <file java Food.java>
 /** /**
Line 132: Line 132:
  * @author (your name)  * @author (your name)
  * @version (a version number or a date)  * @version (a version number or a date)
 + 
 + * A Food object is created with parameters that define the name of the food, 
 + * the increase in energy level, the increase in happiness level, 
 + * and the amount of weight gained if the food is consumed by a 
 + * VirtualPet object. 
 + 
 + * The Food class provides a constructor with the following header: 
 + * public Food(String name, int energyIncrease, int happinessIncrease, int weightGain). 
 + * The Food class also has accessor methods for all instance variables.
  */  */
 public class Food public class Food
Line 140: Line 149:
 } }
 </file> </file>
 +==== Part B: Game ====
 <file java Game.java> <file java Game.java>
 /** /**
Line 172: Line 181:
 } }
 </file> </file>
 +
  
  
Line 333: Line 343:
 } }
 </file> </file>
 +==== Part C Putting it all together ====
  
-===== Activity 5 =====+Now that we have a Game and Food class, let’s revise the VirtualPet class to include interactions with these classes.  
 +  - Write the class VirtualPet4. You may copy your code implementation of VirtualPet from Activity 3 but be sure to modify the class header and constructor to match the new class name. 
  
-==== Try this GUI Runner ==== +  - Modify the ''feed()'' method to take a ''Food'' parameter. The method should increase the ''energy'' level, ''happiness'' level, and ''weight'' of the virtual pet object based on the ''getEnergyRating()'', getHappinessRating(), and getWeightGain() accessor methods of the Food parameter. It is possible for the ''happiness level'' to decrease depending on the ''Food'' consumed.  
-<file java VirtualPetGUIRunner.java>+ 
 +  - Modify the ''play()'' method to take a ''Game'' parameter and return a ''boolean'' value indicating whether the game was won. The method should decrease the weight based on the ''getWeightLoss()'' accessor method of the ''Game'' parameter. Remember, the weight can not go below the minimum ''weight'' value. The method should also increase the ''happiness'' level only if the ''Game parameter’s'' accessor method ''isWinner()'' returns ''true''. The method should decrease the happiness level if isWinner() returns false. The method should return the same value returned by ''isWinner()''. (Note: Be sure to call ''isWinner()'' only once in the method. Repeated calls may result in different return values.)  
 + 
 + === GUI Based Runner for Activity 4 === 
 + 
 +  - [[https://mathorama.com/apcs2/petHappy.gif|petHappy.gif]] 
 +  - [[https://mathorama.com/apcs2/petEat.gif|petEat.gif]] 
 +  - [[https://mathorama.com/apcs2/petPlay.gif|petPlay.gif]] 
 +  - [[https://mathorama.com/apcs2/petSad.gif|petSad.gif]] 
 + 
 + 
 +<file java VirtualPetGUIRunner4.java>
 /** /**
  * A GUI class to run the Virtual Pet Lab  * A GUI class to run the Virtual Pet Lab
Line 345: Line 368:
  * @November 2024  * @November 2024
  */  */
 +
 import java.awt.BorderLayout; import java.awt.BorderLayout;
 import java.awt.Color; import java.awt.Color;
Line 360: Line 384:
 import javax.swing.Box; import javax.swing.Box;
 import javax.swing.BoxLayout; import javax.swing.BoxLayout;
 +import javax.swing.ButtonGroup;
 import javax.swing.ImageIcon; import javax.swing.ImageIcon;
 import javax.swing.JButton; import javax.swing.JButton;
Line 369: Line 394:
 import javax.swing.JOptionPane; import javax.swing.JOptionPane;
 import javax.swing.JPanel; import javax.swing.JPanel;
 +import javax.swing.JRadioButton;
 import javax.swing.Timer; import javax.swing.Timer;
  
-public class VirtualPetGUIRunner +public class VirtualPetGUIRunner4 extends JFrame
 { {
-    // CHANGE THIS VARIABLE VALUE TO TEST AT A DIFFERENT SPEED+    // Edit this value to change speed of update
     private final int INTERVAL_IN_SECONDS = 10;     private final int INTERVAL_IN_SECONDS = 10;
          
Line 379: Line 405:
     private int timerSeconds, animationTimerSeconds;     private int timerSeconds, animationTimerSeconds;
     private boolean isEating, isPlaying;     private boolean isEating, isPlaying;
-    private VirtualPet pet3;+    private VirtualPet4 pet4; 
 +    private Food apple, cupcake, broccoli, potato; 
 +    private Game coinToss, hoopJumping, simonSays;
     private ImageIcon imageHappy, imageSad, imageEat, imagePlay;     private ImageIcon imageHappy, imageSad, imageEat, imagePlay;
     private JFrame frame;     private JFrame frame;
Line 385: Line 413:
     private JLabel petLabel,statsLabel, messageLabel, timerLabel;     private JLabel petLabel,statsLabel, messageLabel, timerLabel;
     private JButton foodButton, playButton;     private JButton foodButton, playButton;
 +    private JRadioButton appleButton, cupcakeButton, broccoliButton, potatoButton, coinButton, hoopButton, simonButton;
 +    private ButtonGroup foodGroup, gameGroup;
     private JMenu newPetMenu;     private JMenu newPetMenu;
     private JMenuItem petRunner3, petRunner4;     private JMenuItem petRunner3, petRunner4;
     private JMenuBar menuBar;     private JMenuBar menuBar;
          
-    public VirtualPetGUIRunner(String name) +    public VirtualPetGUIRunner4(String name) throws IOException
     {     {
-        pet3 = new VirtualPet(name); +        // Initializes VirtualPet, Food, and Game objects 
-        isPlaying = isEating false;+        initVirtualPetObjects(name); 
 +        animationTimerSeconds -1;
                  
         // Automatically calls update after INTERVAL_IN_SECONDS time         // Automatically calls update after INTERVAL_IN_SECONDS time
         ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);         ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
-        scheduler.scheduleAtFixedRate(() -> { pet3.updateStatus(); }, INTERVAL_IN_SECONDS, INTERVAL_IN_SECONDS, TimeUnit.SECONDS);+        scheduler.scheduleAtFixedRate(() -> { pet4.updateStatus(); }, 10, INTERVAL_IN_SECONDS, TimeUnit.SECONDS);
                  
         // Calls helper methods to initialize components of GUI         // Calls helper methods to initialize components of GUI
 +        initTimerPanel();   
         initPetDisplayPanel();         initPetDisplayPanel();
-        initTimerPanel(); 
         initStatsPanel();         initStatsPanel();
-        initButtons();+        initFoodButtons(); 
 +        initGameButtons(); 
 +        initMenuPanel();
         fillLayout();         fillLayout();
         initMenuBar();         initMenuBar();
Line 408: Line 441:
         // Initializes the frame         // Initializes the frame
         frame = new JFrame();         frame = new JFrame();
-        frame.setPreferredSize(new Dimension(350, 500));+        frame.setPreferredSize(new Dimension(400, 500));
         frame.setTitle("Virtual Pet");         frame.setTitle("Virtual Pet");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Line 419: Line 452:
     }     }
          
-    // Initializes the Feed and Play buttons and the panel that contains them +    // Initializes VirtualPet, Food, and Game objects 
-    public void initButtons()+    public void initVirtualPetObjects(String name)
     {     {
-        GridBagConstraints c = new GridBagConstraints(); +        pet4 = new VirtualPet4(name); 
-         +        apple = new Food("Apple", 21, 1);  
-        foodButton = new JButton("Feed"); +        cupcake = new Food("Cupcake", 12, 2); 
-        foodButton.addActionListener(new FoodButtonListener()); +        broccoli = new Food("Broccoli", 3-11); 
-        foodButton.setPreferredSize(new Dimension(8030)); +        potato = new Food("Potato", 20, 2); 
-        foodButton.setMaximumSize(new Dimension(8030)); +        coinToss = new Game("Coin Toss", 1, 0); 
-         +        hoopJumping = new Game("Hoop Jumping", 2, 2); 
-        playButton = new JButton("Play"); +        simonSays = new Game("Simon Says", 1, 2); 
-        playButton.addActionListener(new PlayButtonListener()); +        isEating false
-        playButton.setPreferredSize(new Dimension(8030)); +        isPlaying false;
-        playButton.setMaximumSize(new Dimension(8030)); +
-         +
-        menuPanel = new JPanel(); +
-        menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));  +
-        menuPanel.add(Box.createVerticalStrut(50)); +
-        menuPanel.add(foodButton, c); +
-        menuPanel.add(Box.createVerticalStrut(10)); +
-        menuPanel.add(playButton, c); +
-        menuPanel.add(Box.createVerticalStrut(10)); +
-    } +
-     +
-    // Initializes the panel that contains the information text +
-    public void initStatsPanel() +
-    { +
-        info = "" + pet3.toString().replaceAll("\n", "") + ""; +
-        statsLabel = new JLabel(info); +
-        statsLabel.setBorder(BorderFactory.createEmptyBorder(01515, 0)); +
-         +
-        messageLabel = new JLabel("Happy Birthday, + pet3.getName() + "!"); +
-        messageLabel.setForeground(Color.blue); +
-        messageLabel.setBorder(BorderFactory.createEmptyBorder(015150)); +
-         +
-        statsPanel = new JPanel(new GridLayout(2,1)); +
-        statsPanel.add(messageLabel); +
-        statsPanel.add(statsLabel); +
-    } +
-     +
-    // Initializes the panel that displays the VirtualPet +
-    public void initPetDisplayPanel()  +
-    { +
-        imageHappy = new ImageIcon("petHappy.gif"); +
-        imageSad = new ImageIcon("petSad.gif"); +
-        imageEat = new ImageIcon("petEat.gif"); +
-        imagePlay new ImageIcon("petPlay.gif")+
-        petLabel new JLabel(imageHappy); +
-         +
-        petPanel = new JPanel(new BorderLayout()); +
-        petPanel.add(petLabel);+
     }     }
          
Line 484: Line 479:
                 int remainingSeconds = timerSeconds % 60;                 int remainingSeconds = timerSeconds % 60;
                 timerLabel.setText(String.format("%02d:%02d", minutes, remainingSeconds));                 timerLabel.setText(String.format("%02d:%02d", minutes, remainingSeconds));
-                info = ""pet3.toString().replaceAll("\n", "") + "";+                info = "<html>" + pet4.toString().replaceAll("\n", "<br>") + "</html>";
                 statsLabel.setText(info);                 statsLabel.setText(info);
                 if(!isPlaying && !isEating)                 if(!isPlaying && !isEating)
                 {                 {
-                    if((ImageIcon)petLabel.getIcon() != imageSad && (pet3.getEnergyLevel() < 5 || pet3.getHappinessLevel() < 5))+                    if((ImageIcon)petLabel.getIcon() != imageSad && (pet4.getEnergyLevel() < 5 || pet4.getHappinessLevel() < 5))
                         petLabel.setIcon(imageSad);                         petLabel.setIcon(imageSad);
-                    else if((ImageIcon)petLabel.getIcon() != imageHappy && (pet3.getEnergyLevel() >= 5 && pet3.getHappinessLevel() >= 5))+                    else if((ImageIcon)petLabel.getIcon() != imageHappy && (pet4.getEnergyLevel() >= 5 && pet4.getHappinessLevel() >= 5))
                         petLabel.setIcon(imageHappy);                         petLabel.setIcon(imageHappy);
                 }                 }
Line 499: Line 494:
         timerPanel.add(timerLabel);         timerPanel.add(timerLabel);
         timerPanel.setLayout(new GridBagLayout());         timerPanel.setLayout(new GridBagLayout());
 +    }
 +    
 +    // Initializes the panel that displays the VirtualPet
 +    public void initPetDisplayPanel() 
 +    {
 +        imageHappy = new ImageIcon("petHappy.gif");
 +        imageSad = new ImageIcon("petSad.gif");
 +        imageEat = new ImageIcon("petEat.gif");
 +        imagePlay = new ImageIcon("petPlay.gif");
 +        
 +        petLabel = new JLabel(imageHappy);
 +        petPanel = new JPanel(new BorderLayout());
 +        petPanel.add(petLabel);
 +    }
 +    
 +    // Initializes the panel that contains the information text
 +    public void initStatsPanel()
 +    {
 +        info = "<html>" + pet4.toString().replaceAll("\n", "<br>") + "</html>";
 +        statsLabel = new JLabel(info);
 +        statsLabel.setBorder(BorderFactory.createEmptyBorder(0, 15, 15, 0));
 +        
 +        messageLabel = new JLabel("Happy Birthday, " + pet4.getName() + "!");
 +        messageLabel.setForeground(Color.blue);
 +        messageLabel.setBorder(BorderFactory.createEmptyBorder(0, 15, 15, 0));
 +        
 +        statsPanel = new JPanel(new GridLayout(2,1));
 +        statsPanel.add(messageLabel);
 +        statsPanel.add(statsLabel);
 +    }
 +    
 +    // Initializes the Food and food option buttons
 +    public void initFoodButtons()
 +    {
 +        foodButton = new JButton("Feed");
 +        foodButton.addActionListener(new FoodButtonListener());
 +        foodButton.setPreferredSize(new Dimension(80, 30));
 +        foodButton.setMaximumSize(new Dimension(80, 30));
 +        
 +        appleButton = new JRadioButton("Apple");
 +        cupcakeButton = new JRadioButton("Cupcake");
 +        broccoliButton = new JRadioButton("Broccoli");
 +        potatoButton = new JRadioButton("Potato");
 +        
 +        foodGroup = new ButtonGroup();
 +        foodGroup.add(appleButton);
 +        foodGroup.add(cupcakeButton);
 +        foodGroup.add(broccoliButton);
 +        foodGroup.add(potatoButton);
 +        appleButton.setSelected(true);
 +    }
 +    
 +    // Initializes the Game and game option buttons
 +    public void initGameButtons()
 +    {
 +        playButton = new JButton("Play");
 +        playButton.addActionListener(new PlayButtonListener());
 +        playButton.setPreferredSize(new Dimension(80, 30));
 +        playButton.setMaximumSize(new Dimension(80, 30));
 +        coinButton = new JRadioButton("Coin Toss");
 +        hoopButton = new JRadioButton("Hoop Jump");
 +        simonButton = new JRadioButton("Simon Says");
 +        gameGroup = new ButtonGroup();
 +        gameGroup.add(coinButton);
 +        gameGroup.add(hoopButton);
 +        gameGroup.add(simonButton);
 +        coinButton.setSelected(true);
 +    }
 +    
 +    // Initializes the menu panel that contains all buttons
 +    public void initMenuPanel()
 +    {
 +        GridBagConstraints c = new GridBagConstraints();
 +        menuPanel = new JPanel();
 +        menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS)); 
 +        menuPanel.add(Box.createVerticalStrut(10));
 +        menuPanel.add(foodButton, c);
 +        menuPanel.add(appleButton, c);
 +        menuPanel.add(cupcakeButton, c);
 +        menuPanel.add(broccoliButton, c);
 +        menuPanel.add(potatoButton, c);
 +        menuPanel.add(Box.createVerticalStrut(10));
 +        menuPanel.add(playButton, c);
 +        menuPanel.add(coinButton, c);
 +        menuPanel.add(hoopButton, c);
 +        menuPanel.add(simonButton, c);
 +        menuPanel.add(Box.createVerticalStrut(10));
     }     }
          
Line 523: Line 605:
         c.fill = GridBagConstraints.BOTH;         c.fill = GridBagConstraints.BOTH;
         c.weightx = 60;         c.weightx = 60;
-        c.weighty = 70;+        c.weighty = 50;
         c.gridx = 0;         c.gridx = 0;
         c.gridy = 0;         c.gridy = 0;
Line 531: Line 613:
         mainPanel.add(menuPanel, c);         mainPanel.add(menuPanel, c);
         c.weightx = 60;         c.weightx = 60;
-        c.weighty = 30; 
         c.gridx = 0;          c.gridx = 0; 
         c.gridy = 1;         c.gridy = 1;
Line 545: Line 626:
         public void actionPerformed(ActionEvent e)          public void actionPerformed(ActionEvent e) 
         {         {
-            pet3.feed(); +            Food f = apple; 
-            messageLabel.setText("You have fed " + pet3.getName()); +            if(cupcakeButton.isSelected()) 
-            info = ""pet3.toString().replaceAll("\n", "") + "";+                f = cupcake; 
 +            else if(broccoliButton.isSelected()) 
 +                f = broccoli; 
 +            else if(potatoButton.isSelected()) 
 +                f = potato; 
 +            pet4.feed(f); 
 +            messageLabel.setText("You have fed " + pet4.getName() + " 1 " + f.getName()); 
 +            info = "<html>" + pet4.toString().replaceAll("\n", "<br>") + "</html>";
             statsLabel.setText(info);             statsLabel.setText(info);
-            animationTimerSeconds = 0; 
             animationTimerSeconds = 0;             animationTimerSeconds = 0;
             isEating = true;             isEating = true;
Line 560: Line 647:
                     if(animationTimerSeconds >= 2)                     if(animationTimerSeconds >= 2)
                     {                     {
-                        if(pet3.getEnergyLevel() < 5 || pet3.getHappinessLevel() < 5)+                        if(pet4.getEnergyLevel() < 5 || pet4.getHappinessLevel() < 5)
                             petLabel.setIcon(imageSad);                             petLabel.setIcon(imageSad);
                         else                         else
Line 570: Line 657:
             });             });
             animationTimer.start();             animationTimer.start();
 +            animationTimerSeconds = -1;
         }         }
     }     }
-    +   
     // Defines the action when the Play button is clicked     // Defines the action when the Play button is clicked
     class PlayButtonListener implements ActionListener      class PlayButtonListener implements ActionListener 
Line 578: Line 666:
         public void actionPerformed(ActionEvent e)          public void actionPerformed(ActionEvent e) 
         {         {
-            pet3.play(); +            Game g = coinToss; 
-            messageLabel.setText("You have played with " + pet3.getName()); +            if(hoopButton.isSelected()) 
-            info = ""pet3.toString().replaceAll("\n", "") + "";+                g = hoopJumping; 
 +            else if(simonButton.isSelected()) 
 +                g = simonSays; 
 +            if(pet4.play(g)) 
 +                messageLabel.setText("<html>You have played " + g.getName()+ " with<br>" + pet4.getName() + ", and won!</html>"); 
 +            else 
 +                messageLabel.setText("<html>You have played " + g.getName()+ " with<br>" + pet4.getName() + ", and lost!</html>"); 
 +            info = "<html>" + pet4.toString().replaceAll("\n", "<br>") + "</html>";
             statsLabel.setText(info);             statsLabel.setText(info);
             animationTimerSeconds = 0;             animationTimerSeconds = 0;
Line 592: Line 687:
                     if(animationTimerSeconds >= 2)                     if(animationTimerSeconds >= 2)
                     {                     {
-                        if(pet3.getEnergyLevel() < 5 || pet3.getHappinessLevel() < 5)+                        if(pet4.getEnergyLevel() < 5 || pet4.getHappinessLevel() < 5)
                             petLabel.setIcon(imageSad);                             petLabel.setIcon(imageSad);
                         else                         else
Line 611: Line 706:
         {         {
             try             try
-            {        +            {
                 String input = JOptionPane.showInputDialog("Enter your virtual pet's name:");                 String input = JOptionPane.showInputDialog("Enter your virtual pet's name:");
                 VirtualPetGUIRunner init = new VirtualPetGUIRunner(input);                 VirtualPetGUIRunner init = new VirtualPetGUIRunner(input);
Line 628: Line 723:
         public void actionPerformed(ActionEvent e)          public void actionPerformed(ActionEvent e) 
         {         {
- // "Uncomment" code when you complete Activity 4 and include 
- // VirtualPetGUIRunner4 in your project 
- /* 
             try             try
             {             {
Line 641: Line 733:
                 System.out.println(err);                 System.out.println(err);
             }             }
- */ 
         }         }
     }     }
Line 648: Line 739:
     {     {
         String input = JOptionPane.showInputDialog("Enter your virtual pet's name:");         String input = JOptionPane.showInputDialog("Enter your virtual pet's name:");
-        VirtualPetGUIRunner init = new VirtualPetGUIRunner(input);+        VirtualPetGUIRunner4 init = new VirtualPetGUIRunner4(input);
     }     }
 } }
 </file> </file>
 +===== Activity 5 =====
 +
 +==== Adding Your Own Features ====
 +Copy your code from ''Food.java'' and ''Game.java'' to your working project for Activity 5. Copy your code from ''VirtualPet4.java'' to a new file named ''VirtualPet5.java''. Be sure to modify your class header to match the name of your ''.java'' file.  
  
 +Implement two new features in your ''VirtualPet5'' class or ''Game'' class. Your new features should add instance variables and/or methods to your ''VirtualPet5'' class. 
  
 +The following are ideas for additional features, inspired by the original Tamagotchi: 
 +  - Your virtual pet has a hidden health level based on their energy, happiness, sickness, and cleanliness.  
 +  - Your virtual pet will randomly use the bathroom and will need to be cleaned. 
 +  - Your virtual pet will randomly get sick and need to be given medicine. 
 +  - Your virtual pet will notify the user if their energy level is 0, if their happiness level is 0, if they are sick, or if they used the bathroom and need to be cleaned.  
 +  - Create a more interactive game in the Game class for the ''VirtualPet'' to play. 
virtual_pet.1772392446.txt.gz · Last modified: by frchris

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki