Sub Killer Game With Score

Friday, 19 June 2015
Posted by Unknown
package vijay;
/**
 *
 * @author VIJAY
 */
import java.awt.*;       
import java.awt.event.*;
import javax.swing.*;
public class SubKillerWithScore extends JPanel 
{
   
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Sub Killer Game");
        SubKillerWithScore content = new SubKillerWithScore();
        window.setContentPane(content);
        window.setSize(600, 480);
        window.setLocation(100,100);
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setResizable(false);  // User can't change the window's size.
        window.setVisible(true);
    }
   
    //------------------------------------------------------------------------

    private Timer timer;        // Timer that drives the animation.

    private int width, height;
    private Boat boat;          // The boat, bomb, and sub objects are defined
    private Bomb bomb;          //    by nested classes Boat, Bomb, and Submarine,
    private Submarine sub;      //    which are defined later in this class.
    private int hits;           // The number of times the user has hit the sub.
    private int misses;         // The number of times the user has missed the sub.
    private Font infoFont = new Font("Monospaced", Font.PLAIN, 16);
                            // A font for displaying the numbers of hits and misses.
    public SubKillerWithScore() 
    {

        setBackground( new Color(0,200,0) );

        ActionListener action = new ActionListener() 
        {
                // Defines the action taken each time the timer fires.
            public void actionPerformed(ActionEvent evt) 
            {
                if (boat != null) 
                {
                    boat.updateForNewFrame();
                    bomb.updateForNewFrame();
                    sub.updateForNewFrame();
                }
                repaint();
            }
        };
        timer = new Timer( 30, action );  // Fires every 30 milliseconds.

        addMouseListener( new MouseAdapter() 
        {
                // The mouse listener simply requests focus when the user
                // clicks the panel.
            public void mousePressed(MouseEvent evt) 
            {
                requestFocus();
            }
        } );

        addFocusListener( new FocusListener() 
       {              
            public void focusGained(FocusEvent evt) 
            {
                timer.start();
                repaint();
            }
            public void focusLost(FocusEvent evt) 
            {
                timer.stop();
                repaint();
            }
        } );

        addKeyListener( new KeyAdapter() 
        {
            public void keyPressed(KeyEvent evt) 
            {
                int code = evt.getKeyCode(); 
                if (code == KeyEvent.VK_LEFT) 
               {
                    boat.centerX -= 15;
                }
                else if (code == KeyEvent.VK_RIGHT) 
                {                        
                    boat.centerX += 15;
                }
                else if (code == KeyEvent.VK_DOWN) 
                {                       
                    if ( bomb.isFalling == false )
                        bomb.isFalling = true;
                }
            }
        } );

    } // end constructor

    public void paintComponent(Graphics g) {

        super.paintComponent(g);  // Fill panel with background color, green.
       
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        if (boat == null) {              
            width = getWidth();
            height = getHeight();
            boat = new Boat();
            sub = new Submarine();
            bomb = new Bomb();
        }

        if (hasFocus())
            g.setColor(Color.CYAN);
        else {
            g.setColor(Color.BLACK);
            g.drawString("CLICK TO ACTIVATE", 20, height - 10);
            g.setColor(Color.GRAY);
        }
        g.drawRect(0,0,width-1,height-1);  // Draw a 3-pixel border.
        g.drawRect(1,1,width-3,height-3);
        g.drawRect(2,2,width-5,height-5);

        boat.draw(g);
        sub.draw(g);
        bomb.draw(g);

        g.setFont(infoFont);
        g.setColor(Color.BLACK);
        g.drawString("Number of hits:   " + hits, 15, 24);
        g.drawString("Number of misses: " + misses, 15, 45);   
       
    } // end paintComponent()
 
    private class Boat {
        int centerX, centerY;  // Current position of the center of the boat.
        Boat() { // Constructor centers the boat horizontally, 80 pixels from top.
            centerX = width/2;
            centerY = 80;
        }
        void updateForNewFrame() { // Makes sure boat has not moved off screen.
            if (centerX < 0)
                centerX = 0;
            else if (centerX > width)
                centerX = width;
        }
        void draw(Graphics g) {  // Draws the boat at its current location.
            g.setColor(Color.BLUE);
            g.fillRoundRect(centerX - 40, centerY - 20, 80, 40, 20, 20);
        }
    } // end nested class Boat

    private class Bomb {
        int centerX, centerY; // Current position of the center of the bomb.
        boolean isFalling;   
        Bomb() { // Constructor creates a bomb that is initially attached to boat.
            isFalling = false;
        }
        void updateForNewFrame() {  // If bomb is falling, take appropriate action.
            if (isFalling) {
                if (centerY > height) {
                    isFalling = false;
                    misses++;   // USER HAS MISSED THE SUB
                }
                else if (Math.abs(centerX - sub.centerX) <= 36 &&
                        Math.abs(centerY - sub.centerY) <= 21) {
                    sub.isExploding = true;
                    sub.explosionFrameNumber = 1;
                    isFalling = false;  // Bomb reappears on the boat.
                    hits++;   // USER HAS HIT THE SUB
                }
                else {
                    centerY += 10;
                }
            }
        }
        void draw(Graphics g) { // Draw the bomb.
            if ( ! isFalling ) { 
                centerX = boat.centerX;
                centerY = boat.centerY + 23;
            }
            g.setColor(Color.RED);
            g.fillOval(centerX - 8, centerY - 8, 16, 16);
        }
    } // end nested class Bomb

    private class Submarine {
        int centerX, centerY; // Current position of the center of the sub.
        boolean isMovingLeft; // Tells whether the sub is moving left or right
        boolean isExploding;  // Set to true when the sub is hit by the bomb.
        int explosionFrameNumber; 
        Submarine() {  // Create the sub at a random location 40 pixels from bottom.
            centerX = (int)(width*Math.random());
            centerY = height - 40;
            isExploding = false;
            isMovingLeft = (Math.random() < 0.5);
        }
        void updateForNewFrame() { // Move sub or increase explosionFrameNumber.
            if (isExploding) {
                explosionFrameNumber++;
                if (explosionFrameNumber == 15) {
                    centerX = (int)(width*Math.random());
                    centerY = height - 40;
                    isExploding = false;
                    isMovingLeft = (Math.random() < 0.5);
                }
            }
            else { // Move the sub.
                if (Math.random() < 0.04) { 
                    isMovingLeft = ! isMovingLeft;
                }
                if (isMovingLeft) {
                    centerX -= 5; 
                    if (centerX <= 0) { 
                        centerX = 0;
                        isMovingLeft = false;
                    }
                }
                else {
                    centerX += 5;        
                    if (centerX > width) { 
                        centerX = width;  
                        isMovingLeft = true;
                    }
                }
            }
        }
        void draw(Graphics g) {  // Draw sub and, if it is exploding, the explosion.
            g.setColor(Color.BLACK);
            g.fillOval(centerX - 30, centerY - 15, 60, 30);
            if (isExploding) {
                g.setColor(Color.YELLOW);
                g.fillOval(centerX - 4*explosionFrameNumber,
                        centerY - 2*explosionFrameNumber,
                        8*explosionFrameNumber,
                        4*explosionFrameNumber);
                g.setColor(Color.RED);
                g.fillOval(centerX - 2*explosionFrameNumber,
                        centerY - explosionFrameNumber/2,
                        4*explosionFrameNumber,
                        explosionFrameNumber);
            }
        }
    } // end nested class Submarine   
} // end class SubKiller

Output:

Stroke Program

Posted by Unknown
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StrokeDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Click and Drag; Right-click for Rectangles");
        StrokeDemo content = new StrokeDemo();
        window.setContentPane(content);
        window.pack(); 
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation( (screenSize.width - window.getWidth())/2,
                (screenSize.height - window.getHeight())/2 );
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setVisible(true);
    }

    private class Display extends JPanel 
    {
        Stroke stroke;  // The stroke used for drawing in this panel.
        boolean antialiased;   // Should antialiasing be used?
        boolean drawLine = true;   // Should a line be drawn, or a rectangle?
        int x1, y1, x2, y2;  // Endpoints of line or corners of rectangle.
        Display(Stroke s, boolean a) 
        {
            stroke = s;
            antialiased = a;
            x1 = y1 = 15;
            x2 = 80;
            y2 = 85;
            setPreferredSize(new Dimension(100,100));
            setBackground(Color.WHITE);
        }
        public void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setStroke(stroke);
            if (antialiased) 
            {
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
            }
            if (drawLine)
                g2.drawLine(x1,y1,x2,y2);
            else 
            {
                int a = Math.min(x1,x2);
                int b = Math.min(y1,y2);
                int w = Math.abs(x1 - x2);
                int h = Math.abs(y1 - y2);
                g2.drawRect(a,b,w,h);
            }
        }
    }
    private class MouseHandler implements MouseListener, MouseMotionListener
    {
        public void mousePressed(MouseEvent e) 
        {
            for (int i = 0; i < 5; i++)
                for (int j = 0; j < 3; j++) 
                {
                    displays[i][j].x1 = e.getX();
                    displays[i][j].x2 = e.getX();
                    displays[i][j].y1 = e.getY();
                    displays[i][j].y2 = e.getY();
                    displays[i][j].drawLine = ! e.isMetaDown();
                    displays[i][j].repaint();
                }
        }
        public void mouseDragged(MouseEvent e) 
        {
            for (int i = 0; i < 5; i++)
                for (int j = 0; j < 3; j++) 
                {
                    displays[i][j].x2 = e.getX();
                    displays[i][j].y2 = e.getY();
                    displays[i][j].repaint();
                }
        }
        public void mouseReleased(MouseEvent e) { }
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
    }

    private Display[][] displays = new Display[5][3];
    public StrokeDemo() 
    {
        setLayout(new GridLayout(3,5,3,3));
        setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
        setBackground(Color.GRAY);
        displays[0][0] = new Display(new BasicStroke(1), false);
        displays[1][0] = new Display(new BasicStroke(2), false);
        displays[2][0] = new Display(new BasicStroke(5), false);
        displays[3][0] = new Display(new BasicStroke(10), false);
        displays[4][0] = new Display(new BasicStroke(20), false);
        displays[0][1] = new Display(new BasicStroke(1,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[1][1] = new Display(new BasicStroke(2,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[2][1] = new Display(new BasicStroke(5,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[3][1] = new Display(new BasicStroke(10,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[4][1] = new Display(new BasicStroke(20,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND), true);
        displays[0][2] = new Display(new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[1][2] = new Display(new BasicStroke(2, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[2][2] = new Display(new BasicStroke(5, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[3][2] = new Display(new BasicStroke(10, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        displays[4][2] = new Display(new BasicStroke(20, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL, 10, new float[] {5,5}, 0), true);
        MouseHandler listener = new MouseHandler();
        for (int row = 0; row < 3; row++)
            for (int col = 0; col < 5; col++) 
            {
                add(displays[col][row]);
                displays[col][row].addMouseListener(listener);
                displays[col][row].addMouseMotionListener(listener);
            }
    }
}

Output:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class StatesAndCapitalsTableDemo extends JPanel 
{
    public static void main(String[] args) 
    {
        JFrame window = new JFrame("Trivial Table Demo");
        StatesAndCapitalsTableDemo content = new StatesAndCapitalsTableDemo();
        window.setContentPane(content);
        window.setSize( new Dimension(350,300) );
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation( (screenSize.width - window.getWidth())/2,
                (screenSize.height - window.getHeight())/2 );
        window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        window.setVisible(true);
    }

    public StatesAndCapitalsTableDemo() 
    {
        String[] columnHeads = new String[] { "State", "Capital City" };
        JTable table = new JTable(statesAndCapitals, columnHeads);
        setLayout(new BorderLayout());
        add( new JScrollPane(table), BorderLayout.CENTER );
    }

    private static String[][] statesAndCapitals = new String[][] 
    {
        { "Alabama", "Montgomery" },
        { "Alaska", "Juneau" },
        { "Arizona", "Phoenix" },
        { "Arkansas", "Little Rock" },
        { "California", "Sacramento" },
        { "Colorado", "Denver" },
        { "Connecticut", "Hartford" },
        { "Delaware", "Dover" },
        { "Florida", "Tallahassee" },
        { "Georgia", "Atlanta" },
        { "Hawaii", "Honolulu" },
        { "Idaho", "Boise" },
        { "Illinois", "Springfield" },
        { "Indiana", "Indianapolis" },
        { "Iowa", "Des Moines" },
        { "Kansas", "Topeka" },
        { "Kentucky", "Frankfort" },
        { "Louisiana", "Baton Rouge" },
        { "Maine", "Augusta" },
        { "Maryland", "Annapolis" },
        { "Massachusetts", "Boston" },
        { "Michigan", "Lansing" },
        { "Minnesota", "St. Paul" },
        { "Mississippi", "Jackson" },
        { "Missouri", "Jefferson City" },
        { "Montana", "Helena" },
        { "Nebraska", "Lincoln" },
        { "Nevada", "Carson City" },
        { "New Hampshire", "Concord" },
        { "New Jersey", "Trenton" },
        { "New Mexico", "Santa Fe" },
        { "New York", "Albany" },
        { "North Carolina", "Raleigh" },
        { "North Dakota", "Bismarck" },
        { "Ohio", "Columbus" },
        { "Oklahoma", "Oklahoma City" },
        { "Oregon", "Salem" },
        { "Pennsylvania", "Harrisburg" },
        { "Rhode Island", "Providence" },
        { "South Carolina", "Columbia" },
        { "South Dakota", "Pierre" },
        { "Tennessee", "Nashville" },
        { "Texas", "Austin" },
        { "Utah", "Salt Lake City" },
        { "Vermont", "Montpelier" },
        { "Virginia", "Richmond" },
        { "Washington", "Olympia" },
        { "West Virginia", "Charleston" },
        { "Wisconsin", "Madison" },
        { "Wyoming", "Cheyenne" }
    };
}

Output:

import javax.swing.*;
public class SimpleJLabelExample 
{
  public static void main(String[] args) 
  {
    JLabel label = new JLabel("A Very Simple Text Label");
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label); // adds to CENTER
    frame.pack();
    frame.setVisible(true);
  }
}

Output:

 

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PopupCalculatorApplet extends JApplet implements ActionListener 
{
  public void init() 
  {
    Button calcButton = new Button("Calculator");
    calcButton.addActionListener(this);
    Container contentPane = getContentPane();
    contentPane.add(calcButton);
  }

  public void actionPerformed(ActionEvent evt) 
  {
    if (calc.isVisible())
      calc.setVisible(false);
    else
      calc.show();
  }

  private JFrame calc = new CalculatorFrame();
}

class CalculatorPanel extends JPanel implements ActionListener 
{
  public CalculatorPanel() 
  {
    setLayout(new BorderLayout());

    display = new JTextField("0");
    display.setEditable(false);
    add(display, "North");

    JPanel p = new JPanel();
    p.setLayout(new GridLayout(4, 4));
    String buttons = "789/456*123-0.=+";
    for (int i = 0; i < buttons.length(); i++)
      addButton(p, buttons.substring(i, i + 1));
    add(p, "Center");
  }

  private void addButton(Container c, String s) 
  {
    JButton b = new JButton(s);
    c.add(b);
    b.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) 
  {
    String s = evt.getActionCommand();
    if ('0' <= s.charAt(0) && s.charAt(0) <= '9' || s.equals(".")) 
    {
      if (start)
        display.setText(s);
      else
        display.setText(display.getText() + s);
      start = false;
    } 
    else 
    {
      if (start) 
      {
        if (s.equals("-")) 
        {
          display.setText(s);
          start = false;
        } else
          op = s;
      } 
      else 
      {
        calculate(Double.parseDouble(display.getText()));
        op = s;
        start = true;
      }
    }
  }

  public void calculate(double n) 
  {
    if (op.equals("+"))
      arg += n;
    else if (op.equals("-"))
      arg -= n;
    else if (op.equals("*"))
      arg *= n;
    else if (op.equals("/"))
      arg /= n;
    else if (op.equals("="))
      arg = n;
    display.setText("" + arg);
  }

  private JTextField display;
  private double arg = 0;
  private String op = "=";
  private boolean start = true;
}

class CalculatorFrame extends JFrame 
{
  public CalculatorFrame() 
  {
    setTitle("Calculator");
    setSize(200, 200);
    Container contentPane = getContentPane();
    contentPane.add(new CalculatorPanel());
  }
}


Output:

import javax.swing.*;
import java.awt.*;
public class MnemonicLabels 
{
  public static void main(String[] args) 
  {
    JTextField firstField = new JTextField(10);
    JTextField middleField = new JTextField(10);
    JTextField lastField = new JTextField(10);

    // Create labels and mnemonics
    JLabel firstLabel = new JLabel("First Name", JLabel.RIGHT);
    firstLabel.setDisplayedMnemonic('F');
    firstLabel.setLabelFor(firstField);

    JLabel middleLabel = new JLabel("Middle Initial", JLabel.RIGHT);
    middleLabel.setDisplayedMnemonic('I');
    middleLabel.setDisplayedMnemonicIndex(7); // requires 1.4
    middleLabel.setLabelFor(middleField);

    JLabel lastLabel = new JLabel("Last Name", JLabel.RIGHT);
    lastLabel.setDisplayedMnemonic('L');
    lastLabel.setLabelFor(lastField);

    // Layout and Display
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2, 5, 5));
    p.add(firstLabel);
    p.add(firstField);
    p.add(middleLabel);
    p.add(middleField);
    p.add(lastLabel);
    p.add(lastField);

    JFrame f = new JFrame("MnemonicLabels");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(p);
    f.pack();
    f.setVisible(true);
  }
}

Output:



public class MainMultiple
{

   public static void main(String args[])
   {
       main(122);
       main('f');
       main("hello java");
   }

   public static void main(int i)
   {
       System.out.println("Overloaded main()"+i);
   }

   public static void main(char i)
   {
       System.out.println("Overloaded main()"+i);
   }

   public static void main(String str)
   {
       System.out.println("Overloaded main()"+str);
   }
}

Output:

Overloaded main()122 
Overloaded main()f 
Overloaded main()hello java
Welcome to My Blog

Translate

Popular Post

Total Pageviews

- Copyright © Learning Java Program - Powered by Blogger -