package tictac;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class tictac extends JFrame implements ActionListener {
private JLabel jlJudul;
private JPanel jpBawah,jpTengah;
private JButton jbUlang,jbKeluar;
private JButton jbm[][];
private int giliran=0;
public tictac (String caption) {
super (caption);
Container kotakFrame = this.getContentPane();
kotakFrame.setLayout(new BorderLayout());
jlJudul=new JLabel ("bermin tictac");
jlJudul.setHorizontalAlignment(SwingConstants.CENTER);
kotakFrame.add(jlJudul,BorderLayout.NORTH);
jpTengah = new JPanel();
jpTengah.setLayout(new GridLayout (3,3,5,5));
jbm=new JButton[3][3];
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
jbm[i][j]=new JButton("");
jbm[i][j].addActionListener(this);
jpTengah.add(jbm[i][j]);
}
}
kotakFrame.add(jpTengah,BorderLayout.CENTER);
jbUlang=new JButton ("ulang");
jbUlang.addActionListener(this);
jbKeluar=new JButton ("keluar");
jbKeluar.addActionListener(this);
jpBawah = new JPanel();
jpBawah.setLayout(new GridLayout (1,2,5,5));
jpBawah.add(jbUlang);
jpBawah.add(jbKeluar);
giliran=0;
kotakFrame.add(jpBawah,BorderLayout.SOUTH);
this.setSize(400,400);
this.setVisible(true);
}
public static void main(String args[]){
tictac b=new tictac ("ini kotak saya");
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jbUlang){
ulang();
}else if(e.getSource()==jbKeluar){
System.exit(0);
}else{
String pemain="";
if(giliran%2==0){
pemain="O";
}else{
pemain="X";
}
giliran++;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(e.getSource()==jbm[i][j]){
jbm[i][j].setText(pemain);
jbm[i][j].setEnabled(false);
}
}
}
String[] game=new String[8];
game[0]=jbm[0][0].getText()+jbm[0][1].getText()+jbm[0][2].getText();
game[1]=jbm[1][0].getText()+jbm[1][1].getText()+jbm[1][2].getText();
game[2]=jbm[2][0].getText()+jbm[2][1].getText()+jbm[2][2].getText();
game[3]=jbm[0][0].getText()+jbm[1][0].getText()+jbm[2][0].getText();
game[4]=jbm[0][1].getText()+jbm[1][1].getText()+jbm[2][1].getText();
game[5]=jbm[0][2].getText()+jbm[1][2].getText()+jbm[2][2].getText();
game[6]=jbm[0][0].getText()+jbm[1][1].getText()+jbm[2][2].getText();
game[7]=jbm[0][2].getText()+jbm[1][1].getText()+jbm[2][0].getText();
boolean cek=false;
for (int i=0;i<8;i++){
if (game[i].equals("XXX")||game[i].equals("OOO")){
cek=true;
}
}
if(cek){
JOptionPane.showMessageDialog(getParent(), "Pemain "+
pemain +" Ngegame ");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
jbm[i][j].setEnabled(false);
}
}
} }
}
public void ulang(){
giliran=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
jbm[i][j].setText("");
jbm[i][j].setEnabled(true);
}
}
}
}
Belum ada tanggapan untuk "make the game tictac"
Post a Comment