Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

CarrotComponent import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.imageio.*; /* * Implements the main component for the carrot game. */ public

CarrotComponent import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.imageio.*; /* * Implements the main component for the carrot game. */ public class CarrotComponent extends JComponent { public static final int SIZE = 500; // initial size public static final int PIXELS = 50; // square size per image public static final int MOVE = 20; // keyboard move public static final int GRAVITY = 2; // gravity move public static final int CARROTS = 20; // number of carrots private ArrayList myPoints; // x,y upper left of each carrot private int myX; // upper left of head x private int myY; // upper left of head y private int myDy; // change in y for gravity private Image carrotImage; private Image headImage; public CarrotComponent( ) { setPreferredSize(new Dimension(SIZE, SIZE)); // getScaledInstance( ) gives us re-sized version of the image -- // speeds up the drawImage( ) if the image is already the right size // See paintComponent( ) headImage = readImage("bunny.jpg"); headImage = headImage.getScaledInstance(PIXELS, PIXELS, Image.SCALE_SMOOTH); carrotImage = readImage("carrot.gif"); carrotImage = carrotImage.getScaledInstance(PIXELS, PIXELS, Image.SCALE_SMOOTH); myPoints = new ArrayList( ); } // Utility -- create a random point within the window // leaving PIXELS space at the right and bottom private Point randomPoint( ) { Point p = new Point( (int) (Math.random( ) * (getWidth( ) PIXELS)), (int) (Math.random( ) * (getHeight( ) PIXELS))); return(p); } // Reset things for the start of a game public void reset( ) { myPoints.clear( ); // removes all the points for (int i=0; i = getHeight( )) { // back y up myY -= myDy;

// reverse direction of dy (i.e. bounce), but with 98% efficiency

myDy = (int) (0.98 * -myDy); } checkCollisions( ); repaint( ); } // Check the current x,y vs. the carrots public void checkCollisions( ) { for (int i=0; i

repaint( ); } } if (myPoints.size( ) == 0) { reset( ); // new game } } // Process one key click -- up, down, left, right public void key(int code) { if (code == KeyEvent.VK_UP) {

myY += -MOVE; } else if (code == KeyEvent.VK_DOWN) { myY += MOVE; } else if (code == KeyEvent.VK_LEFT) { myX += -MOVE; } else if (code == KeyEvent.VK_RIGHT) { myX += MOVE; } checkCollisions( ); repaint( ); } // Utility to read in an Image object // If image cannot load, prints error output and returns null. private Image readImage(String filename) { Image image = null; try { image = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println("Failed to load image '" + filename + "'"); e.printStackTrace( ); } return(image); } // Draws the head and carrots public void paintComponent(Graphics g) { g.drawImage(headImage, myX, myY, PIXELS, PIXELS, null);

// Draw all the carrots for (int i=0; i

g.drawImage(carrotImage, (int) (p.getX( )), (int) (p.getY( )), PIXELS, PIXELS, null); } } } public interface KeyListener extends EventListener { // Invoked when a key has been typed public void keyTyped(keyevent e); // invoked when a key has been pressed public void keyPressed(keyevent e); // invoked when a key has been released public void keyReleased(keyevent e); } public class KeyAdapter implements KeyListener { // Invoked when a key has been typed public void keyTyped(keyevent e) { } // invoked when a key has been pressed public void keyPressed(keyevent e) { } // invoked when a key has been released public void keyReleased(keyevent e) { } } public interface ActionListener extends EventListener { // Invoked when an action is performed public void actionPerformed(keyEvent e); }

CarrotFrame // CarrotFrame.java

import java.awt.*; import java.awt.event.*; import javax.swing.*; /* * Implements the Frame for the carrot game. * Manages the buttons and keyboard events. */ class CarrotFrame extends JFrame implements KeyListener, ActionListener { private CarrotComponent carrot; private JButton start; private JButton fast; private JButton slow; private int delay; private javax.swing.Timer timer; public static final int DELAY = 50; // milliseconds public CarrotFrame( ) { setTitle("Carrot"); Container content = getContentPane( ); content.setLayout(new BorderLayout( )); carrot = new CarrotComponent( ); content.add(carrot, BorderLayout.CENTER); carrot.addKeyListener(this); carrot.setFocusable(true); JPanel panel = new JPanel( ); start = new JButton("Start"); start.addActionListener(this); panel.add(start); start.setFocusable(false); fast = new JButton("Faster"); fast.addActionListener(this); panel.add(fast); fast.setFocusable(false); slow = new JButton("Slower"); slow.addActionListener(this); panel.add(slow); slow.setFocusable(false); delay = DELAY; timer = new javax.swing.Timer(delay, this); content.add(panel, BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack( ); carrot.requestFocusInWindow( ); setVisible(true); } // Handle timer and button events public void actionPerformed(ActionEvent e) { if (e.getSource( ).equals(timer)) { carrot.tick( ); } else if (e.getSource( ).equals(fast)) { delay = (int)(delay * 0.90); timer.setDelay(delay); } else if (e.getSource( ).equals(slow)) { delay = (int)(delay / 0.90); timer.setDelay(delay); } else if (e.getSource( ).equals(start)) { carrot.reset( ); timer.start( ); } } // Must implement the next three methods to implement the KeyListener // interface -- aka "notifications" sent by the system on various events // Key typed notification -- down and up public void keyTyped(KeyEvent e) { /* not relevant to this application */ } // Key pressed -- the downstroke public void keyPressed(KeyEvent e) { // use e.getCharCode( ) to get its character // use e.getKeyCode( ) for things like up/down arrow // (See the KeyEvent class) carrot.key(e.getKeyCode( )); } // Key released -- the up stroke public void keyReleased(KeyEvent e) { /* not relevant to this application */ } public static void main(String[ ] args) { CarrotFrame frame = new CarrotFrame( ); } }

image text in transcribed

More Inheritance and Interfaces using the Java Swing Framework Please refer to slides 75-97 in the Java Swing Basics (additional class notes) Assignment Specification Extend the given Bunny and Carrot starter code as follows 1) Add a second bunny. Note that the first bunny moves are controlled by the Up, Down, Left, and Right Virtual Keys of the keyboard VK_UP, VK_DOWN, VK_LEFT and VK_RIGHT So, for the second bunny, choose 4 keys from the opposite (left) end of the keyboard. Here you can find a list of Virtual Keys in Java... 2) Maintain scores for each of the two bunnies, say each carrot is worth 5 points Display the scores on the upper left corner and upper right corner. Use g.drawString), where g is the Graphics handle that Swing sends as a parameter when it calls your JComponent's paintComponent). Hint: you just used g.drawString to display the Affirms. What to submit The two modified source code files: CarrotComponent.java and CarrotFrame.java (Note that the Point class is from the Abstract Window Toolkit (awt) Java Framework. Three screenshots showing progress at stages of the game. Here is a zip file of some images that you can use You can also use any other images that you have. Warning: make sure that the images are in a folder that your program can find. You may have to update your CLASS PATH Environment Variable Now you have a game of two competing bunnies, have fun! More Inheritance and Interfaces using the Java Swing Framework Please refer to slides 75-97 in the Java Swing Basics (additional class notes) Assignment Specification Extend the given Bunny and Carrot starter code as follows 1) Add a second bunny. Note that the first bunny moves are controlled by the Up, Down, Left, and Right Virtual Keys of the keyboard VK_UP, VK_DOWN, VK_LEFT and VK_RIGHT So, for the second bunny, choose 4 keys from the opposite (left) end of the keyboard. Here you can find a list of Virtual Keys in Java... 2) Maintain scores for each of the two bunnies, say each carrot is worth 5 points Display the scores on the upper left corner and upper right corner. Use g.drawString), where g is the Graphics handle that Swing sends as a parameter when it calls your JComponent's paintComponent). Hint: you just used g.drawString to display the Affirms. What to submit The two modified source code files: CarrotComponent.java and CarrotFrame.java (Note that the Point class is from the Abstract Window Toolkit (awt) Java Framework. Three screenshots showing progress at stages of the game. Here is a zip file of some images that you can use You can also use any other images that you have. Warning: make sure that the images are in a folder that your program can find. You may have to update your CLASS PATH Environment Variable Now you have a game of two competing bunnies, have fun

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Database Upgrade Migration And Transformation Tips And Techniques

Authors: Edward Whalen ,Jim Czuprynski

1st Edition

0071846050, 978-0071846059

More Books

Students also viewed these Databases questions

Question

What is paper chromatography?

Answered: 1 week ago

Question

Explain the cost of capital.

Answered: 1 week ago

Question

Define capital structure.

Answered: 1 week ago

Question

5. Structure your speech to make it easy to listen to

Answered: 1 week ago

Question

1. Describe the goals of informative speaking

Answered: 1 week ago