Question
//CarrotComponent.java 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.java
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
myPoints.add( randomPoint( ) );
}
myX = getWidth( ) / 2;
myY = 0;
myDy = 0;
repaint( );
}
//Advance things by one tick -- do gravity, check collisions
public void tick( ) {
myDy = myDy + GRAVITY; // increase dy
myY += myDy; // figure new y
// check if hit bottom
if (myY + PIXELS >= 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
Point point = (Point) myPoints.get(i);
// if we overlap a carrot, remove it
if (Math.abs(point.getX( ) - myX)
&& Math.abs(point.getY( ) - myY)
myPoints.remove(i); // removes the ith elem from an ArrayList
i--; // tricky:
// back i up, since we removed the ith element
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
Point p = (Point) myPoints.get(i);
// point.getX( ) returns a double, so we must cast to int
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.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( );
}
}
Here you can find a list of Virtual Keys in Java... (Links to an external site.)
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Here is a zip file of some images that you can use...
https://smccd.instructure.com/courses/13083/files/1106338/download?verifier=aCtTZnw8kSavmaV3kVEdCReThIT6H4pVqXoSkbqm&wrap=1
CLASS PATH Environment Variable (Links to an external site.)Links to an external site.
https://docs.oracle.com/javase/tutorial/essential/environment/paths.html
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.drawString0, where g is the Graphics handle that Swing sends as a parameter when it calls your JComponent's paintComponent0). 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 e 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.drawString0, where g is the Graphics handle that Swing sends as a parameter when it calls your JComponent's paintComponent0). 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 eStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started