ds project.docx

19
MINI PROJECT: Snake Game implemented using Java Beans Group Members: 1) Megha Bhagat (04)

Upload: sanjaybhatia

Post on 04-Sep-2015

258 views

Category:

Documents


3 download

TRANSCRIPT

MINI PROJECT: Snake Game implemented using Java Beans

MINI PROJECT: Snake Game implemented using Java Beans

Group Members:1) Megha Bhagat (04)2) Ronak Bhatia (05)3) Shanti Dhami (10)4) Asmita Dhonde (11)5) Smriti Koul (30)6) Allwyn Symon (34)

Mini Project- Java Beans

Name: Class: TE- IT-A Date of Performance: Date of Submission: Grade: Signature:

Theory:In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a 0argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given[by whom?] to encompass this standard, which aims to create reusable software components for Java. JavaBeans Properties:A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including classes that you define. A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean's implementation class:Method DescriptiongetPropertyName()For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.setPropertyName()For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.A readonly attribute will have only a getPropertyName() method, and a writeonly attribute will have only a setPropertyName() method.Advantages The properties, events, and methods of a bean that are exposed to another application can be controlled. A bean may register to receive events from other objects and can generate events that are sent to those other objects. Auxiliary software can be provided to help configure a java bean. The configuration setting of bean can be saved in a persistent storage and restored.Disadvantages A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler cannot detect such a problem, and even if it is documented, there is no guarantee that the developer will see the documentation. Having to create a getter for every property and a setter for many, most, or all of them can lead to an immense quantity of boilerplate code. In computer programming, boilerplate code or boilerplate is the sections of code that have to be included in many places with little or no alteration.

JavaBeans APIThe JavaBeans functionality is provided by a set of classes and interfaces in the java.beans package.Interface DescriptionAppletInitializer Methods in this interface are used to initialize Beans that are also applets.BeanInfosThis interface allows the designer to specify information about the events, methods and properties of a Bean.CustomizerThis interface allows the designer to provide a graphical user interface through which a bean may be configured.DesignMode Methods in this interface determine if a bean is executing in design mode.ExceptionListener A method in this interface is invoked when an exception has occurred.PropertyChangeListener A method in this interface is invoked when a bound property is changed.PropertyEditorObjects that implement this interface allow the designer to change and display property values.VetoableChangeListener A method in this interface is invoked when a Constrained property is changed.VisibilityMethods in this interface allow a bean to execute in environments where the GUI is not available

JavaBean conventionsIn order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect Java Beans.The required conventions are as follows: The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks. The class properties must be accessible using get, set, is (can be used for Boolean properties instead of get), and other methods (socalled accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument. The class should be serializable. [This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.]MethodsgetPropertyTypepublic Class getPropertyType()Returns:The Java type info for the property. Note that the "Class" object may describe a builtin Java type such as "int". The result may be "null" if this is an indexed property that does not support nonindexed access. This is the type that will be returned by the ReadMethod.

getReadMethodpublic Method getReadMethod()Returns:The method that should be used to read the property value. May return null if the property can't be read.

getWriteMethodpublic Method getWriteMethod()Returns:The method that should be used to write the property value. May return null if the property can't be written.

isBoundpublic boolean isBound()Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.Returns: True if this is a bound property.

setBound public void setBound(boolean bound)Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.Parameters:bound True if this is a bound property.

isConstrainedpublic boolean isConstrained()Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed. Returns: True if this is a constrained property.

setConstrained public void setConstrained(boolean constrained)Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.Parameters:constrained True if this is a constrained property.

setPropertyEditorClasspublic void setPropertyEditorClass(Class propertyEditorClass)Normally PropertyEditors will be found using the PropertyEditorManager. However if for some reason you want to associate a particular PropertyEditor with a given property, then you can do it with this method.Parameters: propertyEditorClass The Class for the desired PropertyEditor.

getPropertyEditorClass public Class getPropertyEditorClass()Returns: Any explicit PropertyEditor Class that has been registered for this property. Normally this will return "null", indicating that no special editor has been registered, so the PropertyEditorManager should be used to locate a suitable PropertyEditor.

Main.javapublic class Main { public static void main(String[] args) { new Snake(); }}

Snake.java

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;public class Snake { // GUI components private JPanel board; private JButton[] snakeBodyPart; private JButton bonusfood; private JTextArea scoreViewer;

// Constants private final int SNAKE_RUNNING_SPEED_FASTEST = 25; private final int SNAKE_RUNNING_SPEED_FASTER = 50; private final int SNAKE_RUNNING_SPEED_FAST = 100; private final int BOARD_WIDTH = 500; private final int BOARD_HEIGHT = 250; private final int SCORE_BOARD_HEIGHT = 20; private final int SNAKE_LENGTH_DEFAULT = 4; private final int SNAKE_BODY_PART_SQURE = 10; private final int BONUS_FOOD_SQURE = 15; private final Point INIT_POINT = new Point(100, 150);

// Others values private enum GAME_TYPE {NO_MAZE, BORDER, TUNNEL}; private int selectedSpeed = SNAKE_RUNNING_SPEED_FASTER; private GAME_TYPE selectedGameType = GAME_TYPE.NO_MAZE; private int totalBodyPart; private int directionX; private int directionY; private int score; private Point pointOfBonusFood = new Point(); private boolean isRunningLeft; private boolean isRunningRight; private boolean isRunningUp; private boolean isRunningDown; private boolean isBonusFoodAvailable; private boolean isRunning; private Random random = new Random();

Snake() { //initialize all variables. resetDefaultValues(); // initialize GUI. init(); // Create Initial body of a snake. createInitSnake(); // Initialize Thread. isRunning = true; createThread(); }

public void init() { JFrame frame = new JFrame("Snake"); frame.setSize(500, 330);

//Create Menue bar with functions setJMenueBar(frame); // Start of UI design JPanel scorePanel = new JPanel(); scoreViewer = new JTextArea("Score ==>" + score); scoreViewer.setEnabled(false); scoreViewer.setBackground(Color.BLACK);

board = new JPanel(); board.setLayout(null); board.setBounds(0, 0, BOARD_WIDTH, BOARD_HEIGHT); board.setBackground(Color.WHITE); scorePanel.setLayout(new GridLayout(0, 1)); scorePanel.setBounds(0, BOARD_HEIGHT, BOARD_WIDTH, SCORE_BOARD_HEIGHT); scorePanel.setBackground(Color.RED); scorePanel.add(scoreViewer); // will contain score board

frame.getContentPane().setLayout(null); frame.getContentPane().add(board); frame.getContentPane().add(scorePanel); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { snakeKeyPressed(e); } }); frame.setResizable(false); }

public void setJMenueBar(JFrame frame) {

JMenuBar mymbar = new JMenuBar();

JMenu game = new JMenu("Game"); JMenuItem newgame = new JMenuItem("New Game"); JMenuItem exit = new JMenuItem("Exit"); newgame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { startNewGame(); } }); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); game.add(newgame); game.addSeparator(); game.add(exit); mymbar.add(game);

JMenu type = new JMenu("Type"); JMenuItem noMaze = new JMenuItem("No Maze"); noMaze.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedGameType = GAME_TYPE.NO_MAZE; startNewGame(); } }); JMenuItem border = new JMenuItem("Border Maze"); border.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedGameType = GAME_TYPE.BORDER; startNewGame(); } }); type.add(noMaze); type.add(border); mymbar.add(type);

JMenu level = new JMenu("Level"); JMenuItem level1 = new JMenuItem("Level 1"); level1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedSpeed = SNAKE_RUNNING_SPEED_FAST; startNewGame(); } }); JMenuItem level2 = new JMenuItem("Level 2"); level2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedSpeed = SNAKE_RUNNING_SPEED_FASTER; startNewGame(); } }); JMenuItem level3 = new JMenuItem("Level 3"); level3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedSpeed = SNAKE_RUNNING_SPEED_FASTEST; startNewGame(); } }); level.add(level1); level.add(level2); level.add(level3); mymbar.add(level);

JMenu help = new JMenu("Help"); JMenuItem creator = new JMenuItem("Creator"); JMenuItem instruction = new JMenuItem("Instraction"); creator.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Author: Abdullah al hasb\nVersion: 1.0.1 \n Blog: http://imhasib.wordpress.com/"); } });

help.add(creator); help.add(instruction); mymbar.add(help);

frame.setJMenuBar(mymbar); }

public void resetDefaultValues() { snakeBodyPart = new JButton[2000]; totalBodyPart = SNAKE_LENGTH_DEFAULT; directionX = SNAKE_BODY_PART_SQURE; directionY = 0; score = 0; isRunningLeft = false; isRunningRight = true; isRunningUp = true; isRunningDown = true; isBonusFoodAvailable = false; }

void startNewGame() { resetDefaultValues(); board.removeAll(); createInitSnake(); scoreViewer.setText("Score==>" + score); isRunning = true; }

/** * This method is responsible to initialize the snake with four body part. */ public void createInitSnake() { // Location of the snake's head. int x = (int) INIT_POINT.getX(); int y = (int) INIT_POINT.getY();

// Initially the snake has three body part. for (int i = 0; i < totalBodyPart; i++) { snakeBodyPart[i] = new JButton(); snakeBodyPart[i].setBounds(x, y, SNAKE_BODY_PART_SQURE, SNAKE_BODY_PART_SQURE); snakeBodyPart[i].setBackground(Color.GRAY); board.add(snakeBodyPart[i]); // Set location of the next body part of the snake. x = x - SNAKE_BODY_PART_SQURE; }

// Create food. createFood(); }

/** * This method is responsible to create food of a snake. * The most last part of this snake is treated as a food, which has not become a body part of the snake yet. * This food will be the body part if and only if when snake head will touch it. */ void createFood() { int randomX = SNAKE_BODY_PART_SQURE + (SNAKE_BODY_PART_SQURE * random.nextInt(48)); int randomY = SNAKE_BODY_PART_SQURE + (SNAKE_BODY_PART_SQURE * random.nextInt(23));

snakeBodyPart[totalBodyPart] = new JButton(); snakeBodyPart[totalBodyPart].setEnabled(false); snakeBodyPart[totalBodyPart].setBounds(randomX, randomY, SNAKE_BODY_PART_SQURE, SNAKE_BODY_PART_SQURE); board.add(snakeBodyPart[totalBodyPart]);

totalBodyPart++; }

private void createBonusFood() { bonusfood = new JButton(); bonusfood.setEnabled(false); //Set location of the bonus food. int bonusFoodLocX = SNAKE_BODY_PART_SQURE * random.nextInt(50); int bonusFoodLocY = SNAKE_BODY_PART_SQURE * random.nextInt(25);

bonusfood.setBounds(bonusFoodLocX, bonusFoodLocY, BONUS_FOOD_SQURE, BONUS_FOOD_SQURE); pointOfBonusFood = bonusfood.getLocation(); board.add(bonusfood); isBonusFoodAvailable = true; }

/** * Process next step of the snake. * And decide what should be done. */ void processNextStep() { boolean isBorderTouched = false; // Generate new location of snake head. int newHeadLocX = (int) snakeBodyPart[0].getLocation().getX() + directionX; int newHeadLocY = (int) snakeBodyPart[0].getLocation().getY() + directionY;

// Most last part of the snake is food. int foodLocX = (int) snakeBodyPart[totalBodyPart - 1].getLocation().getX(); int foodLocY = (int) snakeBodyPart[totalBodyPart - 1].getLocation().getY();

// Check does snake cross the border of the board? if (newHeadLocX >= BOARD_WIDTH - SNAKE_BODY_PART_SQURE) { newHeadLocX = 0; isBorderTouched = true; } else if (newHeadLocX = BOARD_HEIGHT - SNAKE_BODY_PART_SQURE) { newHeadLocY = 0; isBorderTouched = true; } else if (newHeadLocY 0; i--) { Point frontBodyPartPoint = snakeBodyPart[i - 1].getLocation(); snakeBodyPart[i].setLocation(frontBodyPartPoint); } snakeBodyPart[0].setBounds(headLocX, headLocY, SNAKE_BODY_PART_SQURE, SNAKE_BODY_PART_SQURE); }

public void snakeKeyPressed(KeyEvent e) { // snake should move to left when player pressed left arrow if (isRunningLeft == true && e.getKeyCode() == 37) { directionX = -SNAKE_BODY_PART_SQURE; // means snake move right to left by 10 pixel directionY = 0; isRunningRight = false; // means snake cant move from left to right isRunningUp = true; // means snake can move from down to up isRunningDown = true; // means snake can move from up to down } // snake should move to up when player pressed up arrow if (isRunningUp == true && e.getKeyCode() == 38) { directionX = 0; directionY = -SNAKE_BODY_PART_SQURE; // means snake move from down to up by 10 pixel isRunningDown = false; // means snake can move from up to down isRunningRight = true; // means snake can move from left to right isRunningLeft = true; // means snake can move from right to left } // snake should move to right when player pressed right arrow if (isRunningRight == true && e.getKeyCode() == 39) { directionX = +SNAKE_BODY_PART_SQURE; // means snake move from left to right by 10 pixel directionY = 0; isRunningLeft = false; isRunningUp = true; isRunningDown = true; } // snake should move to down when player pressed down arrow if (isRunningDown == true && e.getKeyCode() == 40) { directionX = 0; directionY = +SNAKE_BODY_PART_SQURE; // means snake move from left to right by 10 pixel isRunningUp = false; isRunningRight = true; isRunningLeft = true; } }

private void createThread() { // start thread Thread thread = new Thread(new Runnable() {

public void run() { runIt(); } }); thread.start(); // go to runIt() method }

public void runIt() { while (true) { if(isRunning) { // Process what should be next step of the snake. processNextStep(); try { Thread.sleep(selectedSpeed); } catch (InterruptedException ie) { ie.printStackTrace(); } } } }}

GUI.java/* * To change this template, choose Tools | Templates * and open the template in the editor. */public class GUI {

}

OUTPUT: