GUNADARMA OF UNIVERSITY

TEKNIK INFORMATIKA'09
Tampilkan postingan dengan label programing JAVA. Tampilkan semua postingan
Tampilkan postingan dengan label programing JAVA. Tampilkan semua postingan

Kamis, 30 September 2010

Game acak gambar

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.event.*;
import java.sql.*;

public class Games extends JFrame {
public String namaanda;
private static final int TOTAL_BUTTONS = 40;
private static final int TOTAL_PAIRS = TOTAL_BUTTONS>>1;
private int buttonsLeft;
private int totalRetries;
private int waktubagi=1;
private JMenuBar menuBar=new JMenuBar();
private JMenu mnuGame = new JMenu("Game"),
         mnuAbout = new JMenu("About");
private JMenuItem mnuItemNew=new JMenuItem("New Game"),
 mnuItemScore=new JMenuItem("Score"),
 mnuItemExit=new JMenuItem("Exit");
private JMenuItem mnuItemHelp=new JMenuItem("Help"),
 mnuItemAboutMe=new JMenuItem("About Me");
private JPanel northPanel = new JPanel(new GridLayout(1,5,10,10));
private JLabel lblButtonsLeft = new JLabel(""+ TOTAL_BUTTONS);
private JLabel lblTotalRetries = new JLabel("0");
private JLabel lblnamaanda = new JLabel("");
private JDesktopPane southPanel = new JDesktopPane();
private GamesButton[] buttons = new GamesButton[TOTAL_BUTTONS];
private Container contentPane = getContentPane();
private GamesButtonHandler eventHandler = new GamesButtonHandler(this);
private Dimension Dimensi=Toolkit.getDefaultToolkit().getScreenSize();

public Games() {
initDisplay();
initGame();
setJam();
}

private void initDisplay() {
setTitle("Games");
mnuGame.add(mnuItemNew);
mnuItemNew.setActionCommand("reset");
mnuItemNew.addActionListener(eventHandler);
mnuGame.add(mnuItemScore);
mnuItemScore.setActionCommand("score");
mnuItemScore.addActionListener(eventHandler);
mnuGame.addSeparator();
mnuGame.add(mnuItemExit);
mnuItemExit.setActionCommand("exit");
mnuItemExit.addActionListener(eventHandler);
mnuAbout.add(mnuItemHelp);
mnuItemHelp.setActionCommand("help");
mnuItemHelp.addActionListener(eventHandler);
mnuAbout.addSeparator();
mnuAbout.add(mnuItemAboutMe);
mnuItemAboutMe.setActionCommand("aboutme");
mnuItemAboutMe.addActionListener(eventHandler);
menuBar.add(mnuGame);
menuBar.add(mnuAbout);
mnuGame.setMnemonic ('G');
mnuAbout.setMnemonic ('A');
mnuItemNew.setMnemonic ('N');
mnuItemScore.setMnemonic ('S');
mnuItemExit.setMnemonic ('X');
mnuItemHelp.setMnemonic ('H');
mnuItemAboutMe.setMnemonic ('A');
northPanel.add(new JLabel("Jumlah Percobaan : "));
northPanel.add(lblTotalRetries);
northPanel.add(new JLabel("Sisa Button : "));
northPanel.add(lblButtonsLeft);
northPanel.add(new JLabel("Nama Anda : "));
northPanel.add(lblnamaanda);

int baris=1,kolom=1;

for(int i=0;i<TOTAL_BUTTONS;i++) {
buttons[i] = new GamesButton();
buttons[i].addActionListener(eventHandler);
if(kolom>8){
baris++;
kolom=1;
}

buttons[i].setBounds(100*kolom-50,100*baris-50,100,100);

kolom++;
southPanel.add(buttons[i]);
}
setJMenuBar (menuBar);
contentPane.add(northPanel,BorderLayout.NORTH);
contentPane.add(southPanel,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(910,650);
setLocation((Dimensi.width-getWidth())/2,(Dimensi.height-getHeight())/2);
show();
namaanda=JOptionPane.showInputDialog(this,"Masukan Nama","Nama anda ?",JOptionPane.QUESTION_MESSAGE);
lblnamaanda.setText(namaanda);
}

private void initGame() {
buttonsLeft = TOTAL_BUTTONS;
totalRetries = 0;
lblButtonsLeft.setText("" + buttonsLeft);
lblTotalRetries.setText("" + totalRetries);
ArrayList list = new ArrayList(TOTAL_BUTTONS);
Random rd = new Random();

for(int i=0;i<TOTAL_PAIRS;i++) {
list.add(new Integer(rd.nextInt(20)));
}

ArrayList tmpList = (ArrayList)list.clone();

for(int i=TOTAL_PAIRS;i>0;i--) {
int pos = rd.nextInt(i);
list.add(tmpList.get(pos));
tmpList.remove(pos);
}

for(int i=0;i< TOTAL_BUTTONS;i++) {
buttons[i].setVal((Integer)list.get(i));
}

list = null;
tmpList = null;
show();
}

public void updateTotalButtonsLeft() {
buttonsLeft-=2;

if(buttonsLeft==0) {
int nilaitotal=0;
if(totalRetries<=20){
nilaitotal=10000;
}else if(totalRetries<=23){
nilaitotal=9900;
}else if(totalRetries<=26){
nilaitotal=9800;
}else if(totalRetries<=29){
nilaitotal=9500;
}else if(totalRetries<=32){
nilaitotal=9000;
}else if(totalRetries<=35){
nilaitotal=8500;
}else if(totalRetries<=38){
nilaitotal=8000;
}else if(totalRetries<=41){
nilaitotal=7500;
}else if(totalRetries<=44){
nilaitotal=7000;
}else if(totalRetries<=47){
nilaitotal=6500;
}else if(totalRetries<=50){
nilaitotal=6000;
}else if(totalRetries<=55){
nilaitotal=5500;
}else if(totalRetries<=60){
nilaitotal=5000;
}else if(totalRetries<=65){
nilaitotal=4500;
}else if(totalRetries<=70){
nilaitotal=4000;
}else if(totalRetries<=75){
nilaitotal=3500;
}else if(totalRetries<=80){
nilaitotal=3000;
}else if(totalRetries<=85){
nilaitotal=2500;
}else if(totalRetries<=90){
nilaitotal=2000;
}else if(totalRetries<=95){
nilaitotal=1500;
}else if(totalRetries<=100){
nilaitotal=1000;
}else if(totalRetries<=110){
nilaitotal=500;
}else if(totalRetries<=120){
nilaitotal=400;
}else if(totalRetries<=130){
nilaitotal=300;
}else if(totalRetries<=140){
nilaitotal=200;
}else if(totalRetries<=150){
nilaitotal=100;
}else if(totalRetries>150){
nilaitotal=0;
}
System.out.println("Total Retries = "+totalRetries);
System.out.println("Nama : " + namaanda);
System.out.println("Waktu anda : " + waktubagi);
System.out.println("Nilai : " + nilaitotal);
System.out.println("Nilai Total : " + nilaitotal/waktubagi);
int result = JOptionPane.showConfirmDialog(this,"Score anda adalah "+nilaitotal+"\nPermainan sudah selesai, Anda ingin mengulang ? " ,"Game Over",JOptionPane.YES_NO_OPTION);
/*
try{
Connect aa=new Connect();
Connection con=aa.OpenConnect();
Statement st=con.createStatement();
String sql="select * from score where Nama='" + namaanda + "'" ;
ResultSet rows=st.executeQuery(sql);
if(rows.next()){
String nilaiawaldatabase=rows.getString("Nilai");
if(Integer.parseInt(nilaiawaldatabase)<=nilaitotal){
String sql1="update score set Nilai='"+nilaitotal+"' where Nama='" + namaanda + "'";
int rows1=st.executeUpdate(sql1);
}
}else{
String sql2="insert into score(Nama,Nilai) values ('"+namaanda+"','"+nilaitotal+"')";
int rows2=st.executeUpdate(sql2);
}
con.close();
}catch(SQLException e){
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(this,"ERROR","ERROR",JOptionPane.ERROR_MESSAGE);
}
*/
if(result==JOptionPane.YES_OPTION)resetGame();
}
lblButtonsLeft.setText("" + buttonsLeft);
}

public void updateTotalRetries() {
totalRetries++;
lblTotalRetries.setText("" + totalRetries);
}
public void resetGame() {
for(int i=0;i<TOTAL_BUTTONS;i++) {
buttons[i].hideValue();
buttons[i].setEnabled(true);
}
namaanda=JOptionPane.showInputDialog(this,"Masukan Nama","Nama anda ?",JOptionPane.QUESTION_MESSAGE);
lblnamaanda.setText(namaanda);
waktubagi=1;
initGame();
}

public static void main(String[] args) {
Games game = new Games();
}
public void setJam() {
ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {      
waktubagi++;
}
   };
    new Timer(10000, taskPerformer).start();
   }
}

class GamesButton extends JButton {
private static final String HIDDEN_CHAR = "XXX";
private Integer val;
public GamesButton() {
hideValue();
}
public void displayValue(){
setText(val.toString());
setIcon(new ImageIcon("gambar/gambar ("+val.toString()+").png"));
}
public void hideValue() {
setText(HIDDEN_CHAR);
setIcon(new ImageIcon("gambar/bg.JPG"));
}
public void setVal(Integer val) {
this.val = val;
}
public Integer getVal() {
return val;
}
}

class GamesButtonHandler implements ActionListener,Runnable{
// private formScore formscoreall=new formScore();
private GamesButton prevButton = null;
private GamesButton currButton = null;
private boolean inAction = false;
private Games parentFrame = null;
public GamesButtonHandler(Games parentFrame) {
this.parentFrame = parentFrame;
}

public void run() {
currButton.displayValue();
try{
Thread.sleep(500);
}catch(Exception err) {}
if(currButton.getVal().intValue()==prevButton.getVal().intValue()){
prevButton.setEnabled(false);
prevButton = null;
currButton.setEnabled (false);
parentFrame.updateTotalButtonsLeft();
}else {
prevButton.hideValue();
prevButton = null;
currButton.hideValue();
}
parentFrame.updateTotalRetries();
inAction = false;
}
public void actionPerformed(ActionEvent e) {
if(inAction)return;

if(e.getActionCommand().equals("reset")) {
parentFrame.resetGame();
return;
}
if(e.getActionCommand().equals("score")) {
// formscoreall.show();
// formscoreall.tampilketabel1();
return;
}
if(e.getActionCommand().equals("exit")) {
System.exit(0);
return;
}
if(e.getActionCommand().equals("help")) {
JOptionPane.showMessageDialog(this.parentFrame,"Peraturan Permainan\n1. Peraturan 1\n2. Peraturan 2\n3. Peraturan 3","Help",JOptionPane.INFORMATION_MESSAGE);
return;
}
if(e.getActionCommand().equals("aboutme")) {
JOptionPane.showMessageDialog(this.parentFrame,"Created By : Nick Alexander \nGame Tebak Gambar...\n@Copyrigth 2009-2010","About Me",JOptionPane.INFORMATION_MESSAGE);
return;
}
currButton = (GamesButton)e.getSource();
if(prevButton==null){
currButton.displayValue();
prevButton = currButton;
} else if(prevButton!=currButton){
inAction = true;
Thread workerThread = new Thread(this);
workerThread.start();
}
}
}

NB : bisa menggunakan JCreator atau Edit Plus+

Game java

//mengimport class javax.swing untuk membuat tampilan GUI
import javax.swing.*;


//membuat kelas kloset yang mempunyai 3 method untuk digunakan dipermainan
class kloset{
protected String nama,namaMonster; //deklarasi variabel bersifat protected agar tidak bisa diakses dari luar 
protected int pisang,jeruk;


//frame untuk messageDialog
JFrame frame = new JFrame();


    //Constructor dari kelas kloset yang terdiri dari 4 variabel
kloset(String nama,String namaMonster,int pisang,int jeruk){
this.nama=nama;
this.namaMonster=namaMonster;
this.pisang=pisang;
this.jeruk=jeruk;
}


        //method2 dibawah bersifat void artinya tidak mengembalikan nilai, nilai dari variabel akan diakses dari kelas utama 
        
        //method monstercloset untuk mengambil banana dan orange
void monsterCloset(){
pisang = 0;
jeruk = 0;
JOptionPane.showMessageDialog(frame,"WATCH OUT...!!!\n"+namaMonster+"  attacks you and steal all of your bananas and oranges");
}


//method genieCloset untuk memberi banana sebanyak 2 dan orange sebanyak 1
void genieCloset(){
pisang += 2;
jeruk += 1;
JOptionPane.showMessageDialog(frame,"ABRAKADABRA...!!!\nA Genie grants you 2 bananas and 1 orange");
}

//method untuk mencetak gambar
void pictureCloset(){
JOptionPane.showMessageDialog(frame,"You Found the picture\n   *******  \n * --- --- * \n*     O     *\n *   ---   *\n  *******");
}


}


class tugas{
public static void main(String[] args){

//deklarasi variabel kelas utama 
String nama,monster,pintu;
int random,jumlah;
int exit=0;

//frame untuk messagedialog
JFrame frame = new JFrame();

// perintah untuk menginput nama pemain dan nama monster dengan tampilan GUI
nama = JOptionPane.showInputDialog("Please enter your name : ");
monster = JOptionPane.showInputDialog("Name your scariest monster : ");

// menginstansiasi objek klst dari kelas kloset
kloset klst = new kloset(nama,monster,5,3);//constructor kelas kloset otomatis dipanggil dengan mengassign 4 variabel


//perulangan untuk memilih pintu dan perulangan akan berakhir ketika pemain menemukan pintu keluar
         do{
//mencetak pesan  sisa banana dan orange yang diaskses dari objeks klast tiap pemain selesai membuka pintu
JOptionPane.showMessageDialog(frame,nama +"  You are in rooms with 4 doors\nYou are carrying "+klst.pisang+" bananas and "+ klst.jeruk+" oranges");

//input filter checking : perintah dibawah untuk mengulangi input jika pemain memasukan kata selain w,n,e,dan s
        do{
//perintah untuk memasukan input pintu mana yang harus dibuka
pintu = JOptionPane.showInputDialog("Pick a door to open by typing[W/N/E/S] : ");
        pintu = pintu.toUpperCase();
        }while(pintu.equals("W")==false && pintu.equals("N")==false && pintu.equals("E")==false && pintu.equals("S")==false);
        
/*teknik random :merandom angka 1 sampai 4 untuk randomisasi pemanggilan method sehingga pintu W yang dibuka saat pertama
 hasilnya tidak akan sama pada saat pintu W dibuka kedua kalinya */
random =  1 +(int)(Math.random()*4);

//case untuk pemanggilan method
switch(random){
case 1: klst.monsterCloset();break;
case 2: klst.genieCloset();break;
case 3: klst.pictureCloset();break;
case 4: exit=1;break;
}

         }while(exit==0);

//mencetak pesan terakhir dengan menampilkan score
jumlah = klst.pisang + klst.jeruk;
JOptionPane.showMessageDialog(frame,"You Found the exit\n " + "Your score is "+jumlah+"("+klst.pisang+" bananas and " +klst.jeruk+" orange )\nBye... Bye");

}
}


pengertian dari Game ini yaitu :

Ini adalah sebuah game petualangan. Dalam game ini , pemain akan mulai di dalam suatu ruangan dengan 4 pintu. 3 buah pintu  berisi kloset dan 1 buah pintu berisi jalan keluar. Dalam 3 pintu yang berisi kloset : 1 pintu berisi  monster , 1 buah pintu berisi genie , dan 1 buah pintu berisi picture.
Pada saat pertama kali, pemain akan mendapat 2 buah barang yaitu banana dan orange. Banana sebanyak 5 dan orange sebanyak 3.

The game should ask the player to open the door. 
  If the player opens the closet with the monster inside, the monster will steal all of bananas
and oranges the user is holding.
  If the player opens the closet with the genie inside, the genie will give the user 2 bananas
and 1 oranges.
  If  the  player  opens  the  closet  with  the  picture  inside,  the  game  should  just  drawn  the
picture on the screen.
  Finally, if the player chooses the door to exit, the game should end.
  When  the  game  ends,  give  the  player  his/her  score.  The  score  is  the  total  number  of
bananas and oranges that the player is holding when exits the room.


You must write  each  function/method  for  each  closet. When  the  player  chooses  a  door  in  a
certain direction (W/N/E/S), the program should call the function/method for the closet in that
direction or end program  if  they choose  the door to exit. You will need variables  to store  the
number of bananas and oranges the player has on them.

Here is what each function should do :
  Monster  closet,  Reduce  the  value  of  the  variables  storing  the  number  of  bananas  and
oranges  to 0. This  function  should also  tell  the player what monster attack  them. At  the
beginning of  the program, you should ask  the user  for scariest monster  they can  think of
and then store their answer in a string variable. Pass the type of monster into the function
to use as the monster attack them
  Genie closet, Increase the values of variables storing the number of bananas and oranges
by  appropriate  number  (2  bananas  and  1 orange). You  should  also  have  some massage
telling the player what happened.
  Picture closet, draw a picture to the screen.

Bonus  :
1.  Have the closet and exit move around randomly from game to game, so the first game the
east door may the monster closet, the next game is played the east door may be the exit.
2.  Input error checking (Only N/E/S/W can be chosen for direction)
3.  Correct Output :
a.  Output players name, when asking which door to open
b.  Output players scariest monster from within monster
c.  Output of items player has after opening each door
d.  Output score before exiting the program
4.  Method :
a.  Do not use global variable
b.  Monster method
c.  Genie method
d.  Picture method
5.  style :
a.  Good variable/function name
b.  Proper indentation/spacing
c.  Good comment