Selasa, 05 Juni 2012

Program java permainan ular

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import java.util.ArrayList;

public class Snake extends JFrame implements ActionListener {

    private static final long serialVersionUID = 123654L;   // just to avoid compile warning
    // number of squares in the grid, size of each of them
    private static final int SIZE = 25, WIDTH = 20;
    // the labels for displaying the snake and its foods
    private SnakeLabel[][] label = new SnakeLabel[SIZE][SIZE];
    // arrayList containing all of the snake position (Labels)
    private SnakeList snakeList = new SnakeList();
    // the label displaying if I am running or not and the size of the snake
    private JLabel statusLabel = new JLabel("Initializing");
    // random number generator to find a new spot for a new food when I eat one
    private Random random = new Random();
    // if I am in a pause state or not
    boolean pause = false;
    // the button to switch from pause to not pause
    private JButton pauseResume = new JButton("Pause");
    // which direction I am running and where is my head
    private int directionX = 0, directionY = -1, headX, headY;
    // the refresh rate
    private int refreshRate;
    // The Timer that moves the Snake
    private Timer timer;

    Snake() {
        super("Snake Game");
        // to hold all the labels with a gap of 1 pixel
        JPanel panel = new JPanel(new GridLayout(SIZE, SIZE, 1, 1));
        // the same color as the Snake so the back will show a continuos snake
        panel.setBackground(Color.BLUE);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        // create all the JLabels
        initLabels(panel);

        // add the 4 foods
        initFood();
        // init the snake the length of a quarter of our size
        initSnake(SIZE / 4);
        add(panel, BorderLayout.CENTER);

        // label if I am running well and size of the snake
        statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
        statusLabel.setOpaque(true);
        statusLabel.setBackground(Color.YELLOW);
        add(statusLabel, BorderLayout.NORTH);
        // listener so the pause button will work
        pauseResume.setForeground(Color.RED);
        pauseResume.addActionListener(this);
        add(pauseResume, BorderLayout.SOUTH);
        // general JFrame stuff its size and visible
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(SIZE * WIDTH - 5, SIZE * WIDTH - 5);
        setVisible(true);
        // start the thread that move the snakes
        refreshRate = 5000 / (snakeList.size() / 2);
        timer = new Timer(refreshRate, this);
        timer.start();
    }

    // to initialize the labels filling the grid
    // this method is called only once
    private void initLabels(JPanel p) {
        for(int j = 0; j < SIZE; j++) {
            for(int i = 0; i < SIZE; i++) {
                label[i][j] = new SnakeLabel(i, j);
                p.add(label[i][j]);
            }
        }

    }
    // to put the initial 4 food labels in 1/4 of the grid
    // this method will be called only once
    private void initFood() {
        // north/west at 1/4 of the grid
        int x = SIZE / 4;
        int y = x;
        label[x][y].setFood(true);
        // north east so x is the same delta from the end
        x = SIZE - x;
        label[x][y].setFood(true);
        // south/west
        y = x;
        x = SIZE / 4;
        label[x][y].setFood(true);
        // south east
        x = y;
        label[x][y].setFood(true);       
    }

    // to position the snake at the beginning of game
    private void initSnake(int length) {
        // the snake in the middle of everything initial size of length
        headX = SIZE / 2;
        headY = (SIZE / 2) - (length / 2);
        // declare these label as holding the snake
        // registering them in the arrayList
        for(int i = headY; i < headY + length; i++)
            snakeList.addLabel(label[headX][i]);
        // set the color for the first time
        snakeList.updateColor();
    }

    // run
    public void runSnake() {

        // wait according to snake length... determine an empiric way
        int oldRefreshRate = refreshRate;
        refreshRate = 5000 / (snakeList.size() / 2);
        // manage to have at least a minimum refresh rate
        if(refreshRate < 10)
            refreshRate = 10;
        // if refresh rate changed, update Timer delay
        if(oldRefreshRate != refreshRate)
            timer.setDelay(refreshRate);
       
        // if the "Pause" button was pushed go to next turn
        if(pause)
            return;
        // update snake head position
        headX += directionX;
        headY += directionY;
        // check if we are going out of bound
        if(headX < 0 || headX >= SIZE || headY < 0 || headY >= SIZE) {
            statusLabel.setText("Out of bound... length: " + snakeList.size());
            timer.stop();
            pauseResume.setEnabled(false);
            return;
        }
        // check if we are eating ourself
        if(label[headX][headY].isSnake) {
            statusLabel.setText("You eat yourself... length: " + snakeList.size());
            timer.stop();
            pauseResume.setEnabled(false);
            return;
        }
        // if we hit food
        if(label[headX][headY].isFood) {
            snakeList.updateHead();     // without updating tail
            // found new place for food
            for(;;) {
                int x = random.nextInt(SIZE);
                int y = random.nextInt(SIZE);
                // start again if new random place is already in the snake or is already food
                if(label[x][y].isFood)
                    continue;
                if(label[x][y].isSnake)
                    continue;
                // ok good dpot not used yet/// declare it as food
                label[x][y].setFood(true);
                break;
            }
        }
        else {
            snakeList.updateTail();     // first if I pass on my back
            snakeList.updateHead();
        }
        statusLabel.setText("Running... snake length: " + snakeList.size()
                + "    Refresh Rate: " + refreshRate + "/1000 sec");

    }
    // called when the pause/resume button is hit
    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if(o == pauseResume) {
            // change the state
            pause = !pause;
            // update button text accordingly
            if(pause) {
                pauseResume.setText("Resume");
                timer.stop();
            }
            else {
                pauseResume.setText("Pause");
                timer.restart();
            }
            return;
        }
        else {    // it is the Timer if it is not the pauseResume button
            runSnake();
        }
    }
    // to run the whole damned thing
    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Snake();
            }
        });
    }
    // array list that contains the position taken by the snake
    private class SnakeList extends ArrayList<SnakeLabel> {
        private static final long serialVersionUID = 654321L;  // to avoid compile warning
        // the 2 colours of the snake
        private Color[] snakeColor = {new Color(0, 0, 255), new Color(75, 75, 255)};
        // for initial build when we install the snake first positions
        private boolean addLabel(SnakeLabel sl) {
            // flag the SnakeLabel as being part of the Snake
            sl.setSnake(true);
            // call father's method to add an object into the arrayList
            return add(sl);
        }
        // remove (make free) the tail of the snake
        private void updateTail() {
            SnakeLabel sl = remove(size() - 1);
            sl.setSnake(false);
        }
        // to update the head to new position
        private void updateHead() {
            // declare it as part of the snake
            label[headX][headY].setSnake(true);
            // add it to the head of the snake
            add(0, label[headX][headY]);
            // switch colors
            updateColor();
        }

        // to put 2 colours in the snake
        private void updateColor() {
            int len = size();
            // the head in black
            get(0).setBackground(Color.BLACK);
            // variation of blue for the others
            for(int i = 1; i < len; i++) {
                get(i).setBackground(snakeColor[i % snakeColor.length]);
            }
        }
    } // end of inner class SnakeList

    // specialized JLabel to keep coordinate X and Y and have a mouseListener if cliked
    private class SnakeLabel extends JLabel implements MouseListener{
        private static final long serialVersionUID = 123456L;   // to avoid compile warning
        // my coordinates on the Grid so the mouseListener can know where I am situate
        private int x, y;
        // init not food and not snake
        boolean isFood = false;         // not a food case
        boolean isSnake = false;        // not part of the snake
        // constructor
        SnakeLabel(int x, int y) {
            super("");
            // save my coordinates
            this.x = x; this.y = y;
            // opaque because I use background to represent myself
            setOpaque(true);
            // so I will react if I am cleicked
            addMouseListener(this);
            // default color
            setBackground(Color.WHITE);
        }
        // declares me as a food case or not
        private void setFood(boolean state) {
            isFood = state;
            // change color accordingly
            if(state)
                setBackground(Color.RED);       // food color
            else
                setBackground(Color.WHITE);     // regular color
        }
        // declares me as part of the snake or not
        private void setSnake(boolean state) {
            isSnake = state;
            // change my color accordingly
            if(state) {
                setFood(false);      // make it available again as food slot
                setBackground(Color.BLUE);
            }
            else {
                setBackground(Color.WHITE);
            }
        }

        // ok click on me I just chek for the Pressed event to react faster
        // (important when the snake goes very fast)
        public void mousePressed(MouseEvent e) {
            // so am I going vertically or horitonaly
            if(directionX == 0) {
                // if clicked on my same X nothing to do
                if(x == headX)
                    return;
                directionY = 0;                // stop updating Y
                // if clicked to my left
                if(x < headX) {
                    // update the way I am going
                    directionX = -1;
                }   
                else  {   // so to my rioght
                    directionX = +1;               
                }
            }
            else {                  // OK I am moving horizontaly
                if(y == headY)
                    return;
                directionX = 0;
                if(y < headY) {     // to my left
                    directionY = -1;
                }
                else {     // to my right
                    directionY = +1;
                }               
            }
        }
        // do not react to those but as I implement MouseListener have have to implement these
        public void mouseEntered(MouseEvent arg0) {}
        public void mouseExited(MouseEvent arg0) {}
        public void mouseClicked(MouseEvent arg0) {}
        public void mouseReleased(MouseEvent arg0) {}

    }  // end inner class SnakeLabel
}

Program java Kalender

import java.util.*;
public class yearCalendar
    {
        public static void yearCalendar(int year)
            {
                GregorianCalendar a = new GregorianCalendar();
                int today = a.get(GregorianCalendar.DAY_OF_MONTH);
                int month1 = a.get(GregorianCalendar.MONTH);
                int year1 = a.get(GregorianCalendar.YEAR);
                a.set(GregorianCalendar.YEAR,year);
                System.out.println();
                System.out.println("    YEAR : "+year);
                for(int i=0;i<12;i++)
                    {
                        a.set(GregorianCalendar.MONTH,i);
                        a.set(GregorianCalendar.DAY_OF_MONTH,1);
                        int month = a.get(GregorianCalendar.MONTH);
                        int weekday = a.get(GregorianCalendar.DAY_OF_WEEK);
                        switch(month)
                    {
                        case 0:
                        System.out.println();
                        System.out.println("        JANUARY            ");
                        System.out.println();
                        break;
                        case 1:
                        System.out.println();
                        System.out.println("        FEBRUARY           ");
                        System.out.println();
                        break;
                        case 2:
                        System.out.println();
                        System.out.println("         MARCH            ");
                        System.out.println();
                        break;
                        case 3:
                        System.out.println();
                        System.out.println("         APRIL           ");
                        System.out.println();
                        break;
                        case 4:
                        System.out.println();
                        System.out.println("          MAY            ");
                        System.out.println();
                        break;
                        case 5:
                        System.out.println();
                        System.out.println("          JUNE          ");
                        System.out.println();
                        break;
                        case 6:
                        System.out.println();
                        System.out.println("          JULY            ");
                        System.out.println();
                        break;
                        case 7:
                        System.out.println();
                        System.out.println("         AUGUST           ");
                        System.out.println();
                        break;
                        case 8:
                        System.out.println();
                        System.out.println("       SEPTEMBER            ");
                        System.out.println();
                        break;
                        case 9:
                        System.out.println();
                        System.out.println("        OCTOBER           ");
                        System.out.println();
                        break;
                        case 10:
                        System.out.println();
                        System.out.println("        NOVEMBER            ");
                        System.out.println();
                        break;
                        case 11:
                        System.out.println();
                        System.out.println("        DECEMBER           ");
                        System.out.println();
                        break;
              }
                        System.out.println("Sun Mon Tue Wed Thu Fri Sat");
                        for(int j=GregorianCalendar.SUNDAY; j<weekday;j++)
                            {
                                System.out.print("    ");
                            }
                        do
                            {  
                         int day = a.get(GregorianCalendar.DAY_OF_MONTH);
                          if(day<10)
                                    {
                                        System.out.print(" "+day);
                                    }
                                   
                                else if(day>=10)
                                    {
                                        System.out.print(day);
                                    }
                                    if(day == today&&month1 == month&&year == year1)
                System.out.print("* ");
                else
                System.out.print("  ");
                                 if(weekday == GregorianCalendar.SATURDAY)
                                    {
                                        System.out.println();
                                    }
                                a.add(GregorianCalendar.DAY_OF_MONTH,1);
                                weekday = a.get(GregorianCalendar.DAY_OF_WEEK);
                            }
                      while(a.get(GregorianCalendar.MONTH) == month);
                    if(weekday != GregorianCalendar.SUNDAY)
                    {
                   System.out.println();
                     }
                    }
                    System.out.println();
                System.out.println("Note : '*' over any digit is current date");
                System.out.println("If it is not displayed then year might not be current year");
                }
            }

Java Binary Search Algorithm

/* Snippet: Binary Search
 * Author: SPlutard
 *
 *Description: An efficient method for searching SORTED arrays. Returns the number if found, otherwise returns -1.
 */

public static int binarySearch(int[] list, int listLength, int searchItem) {
    int first=0;
    int last = listLength - 1;
    int mid;
   
    boolean found = false;
   
    //Loop until found or end of list.
    while(first <= last &&!found) {
        //Find the middle.
        mid = (first + last) /2;
       
        //Compare the middle item to the search item.
        if(list[mid] == searchItem) found = true;
        else { //Not found, readjust search parameters, halving the size & start over.
            if(list[mid] > searchItem) last = mid -1;
            else first = mid + 1;
        }
    }
   
    if(found) return mid;
    else return(-1);
}

Program java vectors

import java.util.Vector; //Needed for the Vector itself.
import java.util.Scanner; //Needed for console input.

class Main extends Thread { //The extension/inheritance is only for the 3.5 second waits I've placed, not required for Vectors.
    public static void main(String[] args) throws InterruptedException { //The throw is only for the 3.5 second waits I've placed, not required for Vectors.
        int i=0, index=-1;
        Integer element;
        Integer[] exampleArray = new Integer[25];
       
        //Info.
        System.out.println("**This shows you a bit about the Vector class as an alternative to arrays.**\n");
        Thread.sleep(3500); //These just has the app wait for 3.5 seconds to let you catch up.
       
        /* Declare the Vector.
         * NOTE: Primitives cannot be used; use autoboxing/autounboxing & wrappers instead (like Integer, below)
         */
        Vector<Integer> exampleVector = new Vector<Integer>();
       
        //We haven't initialized the Vector yet, so it's empty. See for yourself:
        if(exampleVector.isEmpty()) System.out.println("Yup, it's empty alright.\n");
        Thread.sleep(3500);
       
        //Now we'll add to the Vector. Let's get it done quickly by using a for loop to add 10 items:
        System.out.print("Here are the elements we're adding: \n");
        for(i=0; i<10; i++) {
            exampleVector.addElement(i);
            System.out.print(i + " ");
        }
        System.out.println("\n");
        Thread.sleep(3500);
       
        /* But wait! I want to add 100 to the 4th position (index 3). If this were an array, we'd be running into a few problems here,
         * but since this is a Vector, it's as easy as: */
        exampleVector.insertElementAt(100, 3);
        //Now, check it out (also notice the for condition's operator ( .size() ):
        for (i=0; i<exampleVector.size(); i++) {
            System.out.print(exampleVector.elementAt(i) + " "); //Also notice how we get at elements: the elementAt(index) dot-operator.
        }
        System.out.println("\n");
        Thread.sleep(3500);
       
        //We can check if the Vector contains a specific element anywhere by using the .contains(Object) method:
        System.out.println("Is the number 2 in the Vector?");
        if(exampleVector.contains(2) == true) System.out.println("--> Yup.\n");
        else System.out.println("--> Nope.\n");
        Thread.sleep(3500);
       
        //Ok. So now we know an element is present. What if I want to know its index so I can change it? It's this easy:
        index = exampleVector.indexOf(2);
        System.out.println("2 is at the index " + index + "\n");
        Thread.sleep(3500);
       
        /* Actually, I've decided that I don't want 2 in the list anymore. I want to delete it.
         * Again, if this were an array, this would present some problems, but with a Vector, all we do is: */
        exampleVector.removeElement(2);
        //We also could have used the following code: exampleVector.removeElementAt(exampleVector.indexof(2)); -- they're equivalent.
        //Let's see what happened:
        for (i=0; i<exampleVector.size(); i++) {
            System.out.print(exampleVector.elementAt(i) + " ");
        }
        System.out.println("\n");
        Thread.sleep(3500);
        //**The really cool thing about Vectors is that their actual size is dynamic. That element we removed
        //  actually shortened the whole Vector. Arrays are fixed in size once they are declared - inconvenient, huh?
       
        //Of course, there are tons of other Vector methods; I suggest you head over to the API & check them out. Here are a couple:
        //firstElement:
        System.out.println("What's the first element in the Vector?");
        element = exampleVector.firstElement();
        System.out.println("--> " + element);
        //lastElement:
        element = exampleVector.lastElement();
        System.out.println("What's the last element?\n--> " + element + "\n");
        Thread.sleep(3500);
       
        //If, for some weird reason, you really need an array, you can copy your Vector into an array like this:
        exampleVector.copyInto(exampleArray);
        //Let's see if it's really there:
        for(i=0; i< 25; i++) {      //25 is the length of the array above.
            if(exampleArray[i] != null) System.out.print(exampleArray[i] + " ");
        }
        System.out.println("\n");
        Thread.sleep(3500);
       
        //Lastly, we can clear the Vector to end with what we started with like this:
        exampleVector.removeAllElements();
        System.out.println("Empty?");
        if(exampleVector.isEmpty() == true) System.out.println("Yup, it is.\n");
        else System.out.println("Nope. \n");
        Thread.sleep(3500);
       
        System.out.println("Well, that's the end of this tutorial/snippet. Hope you learned a bit about the advantages of using Vecotrs." +
                            "\nIf you're interested in learning more, you should check out the API to unlock all the Vector class' possibilities in your apps.!");
       
    }
}

Program java Producer/Consumer

package prodcongui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener
{
  private JButton start;
  private JPanel button_panel, prod_panel, con_panel;
  private JLabel prod=new JLabel("Producer is not producing.");
  private JLabel con=new JLabel("Consumer is not consuming.");
  private Container cp;
  private Thread producer=new Thread(new Runner(),"Producer");
  private Thread consumer=new Thread(new Runner2(),"Consumer");
  private int buffer[]={-1,-1,-1,-1};
  private int buffer_count=0, sum=0, read=0, write=0;
  public GUI()
  {
    super("Producer Consumer");
    cp=getContentPane();
    start=new JButton("Start Threads");
    button_panel=new JPanel();
    prod_panel=new JPanel();
    con_panel=new JPanel();
    button_panel.add(start);
    cp.add(button_panel,BorderLayout.SOUTH);
    prod_panel.add(prod);
    con_panel.add(con);
    cp.add(prod_panel,BorderLayout.NORTH);
    cp.add(con_panel,FlowLayout.CENTER);
    prod_panel.setBackground(Color.RED);
    con_panel.setBackground(Color.RED);
    start.addActionListener(this);
    setSize(330,200);
    setLocation(330,330);
    setResizable(false);
    setVisible(true);
  }
  public static void main(String[] args)
  {
    GUI app=new GUI();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public synchronized void set(int value)
  {
    while(buffer_count==buffer.length)
    {
      try
      {
        SwingUtilities.invokeLater(new ChangeProdCon("Producer can't produce "+"\n"+
                                                  "Producer must wait.",prod,Color.ORANGE,prod_panel));
        wait();
      }
      catch(InterruptedException e){}
    }
    SwingUtilities.invokeLater(new ChangeProdCon("Producer produced "+value,prod,Color.GREEN,prod_panel));
    buffer[write]=value;
    write=(write+1)%buffer.length;
    buffer_count++;
    notify();
  }
  public synchronized int get()
  {
    while(buffer_count==0)
    {
      try
      {
        SwingUtilities.invokeLater(new ChangeProdCon("Consumer can't consume "+"\n"+
                                                  "Consumer must wait.",con,Color.ORANGE,con_panel));
        wait();
      }
      catch(InterruptedException e){}
    }
    int readval=buffer[read];
    SwingUtilities.invokeLater(new ChangeProdCon("Consumer consumed "+readval,con,Color.GREEN,con_panel));
    read=(read+1)%buffer.length;
    buffer_count--;
    notify();
    return readval;
  }
  private class ChangeProdCon implements Runnable
  {
    JLabel lbl;
    String s1;
    Color col;
    JPanel pnl;
    public ChangeProdCon(String s, JLabel l, Color c, JPanel p)
    {
      lbl=l;
      s1=s;
      col=c;
      pnl=p;
    }
    public void run()
    {
      lbl.setText(s1);
      pnl.setBackground(col);
    }
  }
  public void actionPerformed(ActionEvent e)
  {
    producer.start();
    consumer.start();
  }
  private class Runner implements Runnable
  {
    public void run()
    {
      for(int i=10; i<=500; i++)
      {
        try
        {
          Thread.sleep((int)(Math.random()*3001));
          set(i);
        }
        catch(InterruptedException e){}
      }
      SwingUtilities.invokeLater(new ChangeProdCon("Producer has finished producing.",prod,Color.RED,prod_panel));
    }
  }
  private class Runner2 implements Runnable
  {
    public void run()
    {
      for(int i=10; i<=500; i++)
      {
        try
        {
          Thread.sleep((int)(Math.random()*3001));
          sum+=get();
        }
        catch(InterruptedException e){}
      }
      SwingUtilities.invokeLater(new ChangeProdCon("Consumer has finished consuming.",con,Color.RED,con_panel));
    }
  }
}

Program java kalkulator sederhana

import java.util.Scanner;

public class SimpleCalc {

    public static void main(String args[]) {
   
        double a, b, c;
   
        Scanner scn = new Scanner(System.in);

        System.out.println("\n1. Add");
        System.out.println("2. Subtract");
        System.out.println("3. Multiply");
        System.out.println("4. Divide\n");
        System.out.print("Please make a selection: ");
        int function = scn.nextInt();
       
        System.out.print("\nA = ");
        a = scn.nextDouble();
        System.out.print("B = ");
        b = scn.nextDouble();
       
        switch(function) {
        case 1:
        c = a + b;
        System.out.println(a + " + " + b + " = " + c);
        break;
        case 2:
        c = a - b;
        System.out.println(a + " - " + b + " = " + c);
        break;
        case 3:
        c = a * b;
        System.out.println(a + " * " + b + " = " + c);
        break;
        case 4:
        c = a / b;
        System.out.println(a + " / " + b + " = " + c);
        break;       
        }
   
    }

}
resep donat empuk ala dunkin donut resep kue cubit coklat enak dan sederhana resep donat kentang empuk lembut dan enak resep es krim goreng coklat kriuk mudah dan sederhana resep es krim coklat lembut resep bolu karamel panggang sarang semut

Copyright © Deja Area | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑