I have posted a question earlier and and did not posted a few classes codes, i g
ID: 3834991 • Letter: I
Question
I have posted a question earlier and and did not posted a few classes codes,
i got the solution for the most part but for few methods i didnt got,,
and i got also got this reply,,
"I have given you the classes as you asked for, but the methods in PowerUp class and Paddle class, I could not implement. Because i don't knonw about the KeyboardControllerClass and GamePanel etc." -ugeshGupta... thanks
but now i am uploading the KeyboardControllerClass and GamePanel class,, can you help me plzz.... i already poseted the question this is the continous from that question if you guys find it...
KeywordControlller Class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
*
* @author araderma
*/
public class KeyboardController implements KeyListener
{
private boolean[] keyStatus;
public KeyboardController()
{
keyStatus = new boolean[256];
}
public boolean getKeyStatus(int keyCode)
{
if(keyCode < 0 || keyCode > 255)
{
return false;
}
else
{
return keyStatus[keyCode];
}
}
public void resetController()
{
keyStatus = new boolean[256];
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
keyStatus[ke.getKeyCode()] = true;
}
@Override
public void keyReleased(KeyEvent ke) {
keyStatus[ke.getKeyCode()] = false;
}
}
/*GamePanelClass
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Game;
import Controller.KeyboardController;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* @author araderma
*/
public class GamePanel extends JPanel
{
// Required components. Do not remove!
private Timer gameTimer;
private KeyboardController controller;
// Controls size of game window and framerate
private final int gameWidth = 800;
private final int gameHeight = 720;
private final int framesPerSecond = 60;
public final void setupGame()
{
// Initialize field values here
}
@Override
public void paint(Graphics g)
{
// Draw GameObjects here
}
public void updateGameState(int frameNumber)
{
// Move GameObjects and check for collisions here
}
/**
* Constructor method for GamePanel class.
* It is not necessary for you to modify this code at all
*/
public GamePanel()
{
// Set the size of the Panel
this.setSize(gameWidth, gameHeight);
this.setPreferredSize(new Dimension(gameWidth, gameHeight));
this.setBackground(Color.BLACK);
// Register KeyboardController as KeyListener
controller = new KeyboardController();
this.addKeyListener(controller);
// Call setupGame to initialize fields
this.setupGame();
this.setFocusable(true);
this.requestFocusInWindow();
}
/**
* Method to start the Timer that drives the animation for the game.
* It is not necessary for you to modify this code unless you need to in
* order to add some functionality.
*/
public void start()
{
// Set up a new Timer to repeat every 20 milliseconds (50 FPS)
gameTimer = new Timer(1000 / framesPerSecond, new ActionListener() {
// Tracks the number of frames that have been produced.
// May be useful for limiting action rates
private int frameNumber = 0;
@Override
public void actionPerformed(ActionEvent e)
{
// Update the game's state and repaint the screen
updateGameState(frameNumber++);
repaint();
}
});
gameTimer.setRepeats(true);
gameTimer.start();
}
}
Thanks
Explanation / Answer
note : i poted few files only
GameFrame.java
package Game;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class GameFrame extends JFrame
{
private GamePanel game;
public GameFrame()
{
// Add text to title bar
super("Space Invaders IV: The Battle Continues");
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Create an instance of the Game class and turn on double buffering
// to ensure smooth animation
game = new GamePanel(this);
game.setDoubleBuffered(true);
// Add the Breakout instance to this frame's content pane to display it
this.getContentPane().add(game);
this.pack();
// Start the game
game.start();
}
public void hook()
{
this.dispose();
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
StartScreen newScreen = new StartScreen();
newScreen.setVisible(true);
}
});
}
}
StartScreen.java
package Game;
import Controller.KeyboardController;
import GameObjects.Ship;
import java.awt.Color;
import java.awt.Graphics;
public class StartScreen extends javax.swing.JFrame {
public StartScreen() {
super("Space Invaders IV: The Battle Continues");
initComponents();
}
private KeyboardController controller;
Ship ship2 = new Ship(500, 500, Color.RED, controller);
@Override
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(100,100, 600, 520);
g.setColor(Color.LIGHT_GRAY);
g.fillOval(200, 200, 200, 200);
g.setColor(Color.BLACK);
g.fillOval(240, 215, 200, 175);
ship2.draw(g);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
titleLabel = new javax.swing.JLabel();
playButton = new javax.swing.JButton();
quitButton = new javax.swing.JButton();
highScoresButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
titleLabel.setFont(new java.awt.Font("Lucida Grande", 1, 24)); // NOI18N
titleLabel.setText("Space Invaders IV: The Battle Continues");
playButton.setText("Play Game");
playButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playButtonActionPerformed(evt);
}
});
quitButton.setText("Quit");
quitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
quitButtonActionPerformed(evt);
}
});
highScoresButton.setText("View High Scores");
highScoresButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
highScoresButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(142, 142, 142)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(titleLabel)
.addGroup(layout.createSequentialGroup()
.addComponent(playButton, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(highScoresButton)
.addGap(18, 18, 18)
.addComponent(quitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(165, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 582, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(playButton)
.addComponent(highScoresButton)
.addComponent(quitButton))
.addGap(54, 54, 54))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed
GameFrame game = new GameFrame();
game.setVisible(true);
this.dispose();
}//GEN-LAST:event_playButtonActionPerformed
private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitButtonActionPerformed
System.exit(0);
}//GEN-LAST:event_quitButtonActionPerformed
private void highScoresButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_highScoresButtonActionPerformed
// TODO add your handling code here:
HighScoreScreen screen = new HighScoreScreen();
screen.setVisible(true);
this.dispose();
}//GEN-LAST:event_highScoresButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton highScoresButton;
private javax.swing.JButton playButton;
private javax.swing.JButton quitButton;
private javax.swing.JLabel titleLabel;
// End of variables declaration//GEN-END:variables
}
HighScoreList.java
package Game;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class HighScoreList {
//instance variables
private HighScore [] list = new HighScore [10];
//constructor
public HighScoreList()
{
populateHighScores();
buildHighScoreArray( readHighScoreFile() );
}
//accessor method
public HighScore[] getHighScoreArray()
{
HighScore[] temp = new HighScore [list.length];
for(int i = 0; i < list.length; i++)
{
temp[i] = list[i];
}
return temp;
}
public void compareScore(int score)
{
int indexToReplace = -1;
String name = "";
for(int i = 0; i < list.length; i++)
{
if( score > list[i].getScore())
{
indexToReplace = i;
name = JOptionPane.showInputDialog(null, "Congratulations! You made the High Score list." +
" Please enter your name for the record.");
if(name == null)
{
name = "Player 1";
}
else
{
//checks whether input is only whitespace characters
String nameTemp = new String(name);
if(nameTemp.replaceAll(" ", "").isEmpty() )
{
name = "Player 1";
}
}
break;
}
}
if(indexToReplace == 9)
{
list[indexToReplace] = new HighScore(name, score);
}
//replaces element other than last element in array
else if (indexToReplace >= 0 && indexToReplace <9)
{
for(int i = 8; i >= indexToReplace; i--)
{
list[i+1] = list[i];
}
//places element in the index position that is to be replaced
list[indexToReplace] = new HighScore(name, score);
}
saveHighScoreArray();
}
public void clearHighScores()
{
for(int i = 0; i < list.length; i++)
{
list[i] = new HighScore();
}
saveHighScoreArray();
}
@Override
public String toString()
{
String message = "";
for(HighScore score: list)
{
message += score + " " ;
}
return message;
}
private void populateHighScores()
{
for(int i = 0; i < list.length; i++)
{
list[i] = new HighScore();
}
}
private ArrayList<String> readHighScoreFile()
{
ArrayList<String> temp = new ArrayList<String> (0);
try
{
File hs = new File("SpaceInvaderHighScores.txt");
Scanner scan = new Scanner(hs);
while(scan.hasNext() )
{
String stringRead = scan.nextLine();
temp.add(stringRead);
}
scan.close();
}
catch (FileNotFoundException fnfe)
{
System.out.println("Unable to find file.");
}
catch( Exception e)
{
e.printStackTrace();
}
//returns value no matter whether there was an exception
finally
{
if(temp.size() == 0)
{
return null;
}
else
{
return temp;
}
}
}
private void buildHighScoreArray(ArrayList<String> stringArray)
{
//sets all array elements to default HighScore objects
populateHighScores();
try
{
//sets individual array elements if ArrayList contains objects
if(stringArray != null && !stringArray.isEmpty())
{
//for each String object in ArrayList, constructs new HighScore object
for(int i = 0; i < stringArray.size(); i++)
{
//checks whether HighScore array contains index position before continuing
if(i < list.length)
{
String name;
int score;
//parses into a <String> name and an <int> score
Scanner parse = new Scanner(stringArray.get(i) );
parse.useDelimiter(",");
name = parse.next();
score = Integer.parseInt( parse.next() );
//constructs new HighScore object based on input and assigns to current index position
list[i]= new HighScore(name, score);
}
}
}
}
catch(InputMismatchException ime)
{
System.out.println("Error: InputMismatchException. HighScore list set as default values.");
}
}
//prints the HighScore array to file
private void saveHighScoreArray()
{
try
{
FileOutputStream os = new FileOutputStream("SpaceInvaderHighScores.txt", false);
PrintWriter pw = new PrintWriter(os);
for(int i = 0; i < list.length; i++)
{
pw.println(list[i].getName() + "," + list[i].getScore());
}
pw.close();
}
catch(FileNotFoundException fnfe)
{
System.out.println("File not found. Exiting...");
}
catch (Exception e)
{
e.printStackTrace();
}
}
//creates file in case of file not existing
private void buildFile()
{
try
{
FileOutputStream os = new FileOutputStream("SpaceInvaderHighScores.txt", false);
PrintWriter pw = new PrintWriter(os);
pw.close();
}
catch (FileNotFoundException fnfe)
{
System.out.println("Error: File cannot be created!");
}
}
}
HighScore.java
package Game;
public class HighScore {
//instance variables
private String name;
private int score;
//default constructor
public HighScore()
{
score = 0;
name = "Empty";
}
//constructor
public HighScore(String name, int score)
{
this.name = name;
this.score = score;
}
//accessor method
public int getScore()
{
return score;
}
//accessor method
public String getName()
{
return name;
}
//mutator method
public void setScore(int score)
{
this.score = score;
}
//mutator method
public void setName(String name)
{
this.name = name;
}
@Override
public String toString()
{
return String.format("Name: %-20s Score: %6d", name, score);
}
}
Ship.java
package GameObjects;
import Controller.KeyboardController;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Ship extends ControlledGameObject{
//instance variables
private int xLength = 40;
private int yLength = 40;
private int xVelocity = 10;
//constructor
public Ship(int xPosition, int yPosition, Color color, KeyboardController control)
{
super(xPosition, yPosition, color, control);
}
//accessor method
public int getXLength()
{
return xLength;
}
//accessor method
public int getYLength()
{
return yLength;
}
//draws the Ship
@Override
public void draw(Graphics g)
{
//bounding box
g.setColor( super.getColor() );
//g.fillRect( super.getXPosition() , super.getYPosition(), xLength, yLength);
//base wing
g.fillRect(super.getXPosition(), super.getYPosition() + (int) (0.5*yLength), xLength, (int) (0.25*yLength) );
//Side guns
g.fillRect(super.getXPosition(), super.getYPosition() + (int) (0.25*yLength),
(int) (xLength*0.05), yLength - (int) (0.5*yLength));
g.fillRect(super.getXPosition() + (xLength - (int) (xLength*0.05)) ,
super.getYPosition() + (int) (0.25*yLength) , (int) (xLength*0.05), yLength - (int) (0.5*yLength));
//engines
g.fillRect(super.getXPosition() + (int) (xLength*0.25), super.getYPosition() + (int) (0.75*yLength) ,
(int) (xLength*0.2), (int) (0.25*yLength));
g.fillRect(super.getXPosition() + (int) (xLength*0.55), super.getYPosition() + (int) (0.75*yLength) ,
(int) (xLength*0.2), (int) (0.25*yLength));
//rear body
g.fillRect(super.getXPosition() + (int) (xLength*0.25), super.getYPosition() + (int) (0.75*yLength),
(int) (xLength*0.5), (int) (0.15*yLength));
//Triangle body
Polygon body = new Polygon();
body.addPoint(super.getXPosition() + xLength / 2, super.getYPosition());
body.addPoint(super.getXPosition() + (int) (xLength*0.25) , super.getYPosition() + (int) (yLength*0.75) );
body.addPoint(super.getXPosition() + (int) (xLength*0.75), super.getYPosition() + (int) (yLength*0.75) );
g.fillPolygon(body);
}
//returns Rectangle object representing a bounding box for the Ship
@Override
public Rectangle getBounds()
{
return new Rectangle( super.getXPosition(), super.getYPosition(), xLength, yLength);
}
@Override
public void move()
{
//checks if key is pressed
boolean leftArrowIsPressed;
boolean rightArrowIsPressed;
leftArrowIsPressed = super.getKeyboardController().getKeyStatus(KeyEvent.VK_LEFT);
rightArrowIsPressed = super.getKeyboardController().getKeyStatus(KeyEvent.VK_RIGHT);
//moves Ship if key is pressed
if( leftArrowIsPressed && !detectLeftEdge() )
{
super.setXPosition( super.getXPosition() - xVelocity);
}
if( rightArrowIsPressed && !detectRightEdge() )
{
super.setXPosition( super.getXPosition() + xVelocity);
}
}
//determines if Ship has reached right edge of GamePanel
private boolean detectRightEdge()
{
if( super.getXPosition() + xLength >= 800)
{
return true;
}
return false;
}
private boolean detectLeftEdge()
{
if( super.getXPosition() <= 0)
{
return true;
}
return false;
}
}
ControlledGameObject.java
package GameObjects;
import Controller.KeyboardController;
import Interfaces.Moveable;
import java.awt.Color;
public abstract class ControlledGameObject extends GameObject implements Moveable{
//instance variables
KeyboardController control;
//constructor
public ControlledGameObject( int xPosition, int yPosition, Color color, KeyboardController control)
{
super( xPosition, yPosition, color);
this.control = control;
}
//accessor method
public KeyboardController getKeyboardController()
{
return control;
}
}
GameObject.java
package GameObjects;
import Interfaces.Drawable;
import java.awt.Color;
import java.awt.Rectangle;
public abstract class GameObject implements Drawable {
//instance variables
private int xPosition; //represents x coordinate of GameObject
private int yPosition; //represents y coordinate of GameObject
private Color color;
//constructor
public GameObject(int xPosition, int yPosition, Color color)
{
this.xPosition = xPosition;
this.yPosition = yPosition;
this.color = color;
}
//accessor method
public int getXPosition()
{
return xPosition;
}
//accessor method
public int getYPosition()
{
return yPosition;
}
//accessor method
public Color getColor()
{
return color;
}
//mutator method
public void setXPosition(int x)
{
xPosition = x;
}
//mutator method
public void setYPosition(int y)
{
yPosition = y;
}
//mutator method
public void setColor( Color color)
{
this.color = color;
}
//abstract method
public abstract Rectangle getBounds();
public boolean isColliding(GameObject other)
{
return this.getBounds().intersects(other.getBounds() );
}
}
Drawable.java
package Interfaces;
import java.awt.Graphics;
public interface Drawable {
//g is a Graphics object on which something should be drawn
public abstract void draw(Graphics g);
}
Moveable.java
package Interfaces;
public interface Moveable {
//method allows any class that implements it to move by changing its position in some way
public abstract void move();
}