728x90
package swing.exam.bing01;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
//-----------------------------------------------------------------------------------------------------------
//public class Bingo extends JFrame
//-----------------------------------------------------------------------------------------------------------
public class Bingo extends JFrame{
final int SIZE = 5; // 빙고판의 크기
JButton[] btnArr = null; // 25개의 버튼을 가리키기 위한 참조변수
String[] animal = { // 25개의 버튼 위에 쓰여질 글자들
"고양이", "강아지", "거북이", "토끼", "사자",
"호랑이", "기린", "코끼리", "하마", "코뿔소",
"부엉이", "돼지", "소", "펭귄", "독수리",
"타조", "캥거루", "원숭이", "코알라", "다람쥐",
"수달", "살쾡이", "두루미", "고라니", "까마귀"
};
int[] bingNum = new int[SIZE*SIZE]; // 버튼 위치에 숨겨져 있는 숫자를 담을 배열
int bingoCount = 0; // 완성된 라인 수
// 빙고판의 체크 여부를 확인하기 위한 2차원 배열
private boolean[][] btnOX = new boolean[SIZE][SIZE];
//-----------------------------------------------------------------------------------------------------------
// 매개변수가 있는 생성자
//-----------------------------------------------------------------------------------------------------------
Bingo(String title) {
super(title);
setLayout(new GridLayout(SIZE, SIZE)); // 컨텐트팬에 5x5를 사용할 수 있는 작업관리자를 설정한다.
MyEventHandler handler = new MyEventHandler();
addWindowListener(handler);
btnArr = new JButton[SIZE * SIZE]; // 5x5=25개의 버튼을 담을 객체 배열을 만든다.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 버튼 위치에 숨겨져 있는 숫자를 담을 배열 변수를 만든다.
for(int i = 0; i < SIZE*SIZE; i++) {
bingNum[i] = (int)(Math.random() * (SIZE*SIZE) + 1); // 버튼에 랜덤한 정수 값을 저장한다.
// 똑같은 값이 있으면 숫자를 다시 추출한다.
if(i > 0) { // 맨 처음 방의 값은 비교에서 제외시킨다.
for(int j = 0; j < i; j++) { // 현재 순번보다 앞의 방들과 값을 비교해 나간다.
if(bingNum[j] == bingNum[i]) { // 방의 값이 같으면
i--; // 추출하는 횟수를 1 줄인다.
break;
}
}
}
} // End - for
// 버튼 위치에 숨겨 놓은 숫자를 콘솔에 출력한다.
for(int i = 0; i < SIZE*SIZE; i++) {
System.out.print(bingNum[i] + " ");
}
// JFrame에 버튼을 추가한다.
for(int i = 0; i < SIZE*SIZE; i++) {
btnArr[i] = new JButton(animal[i]);
btnArr[i].addActionListener(handler); // 버튼 하나하나마다 리스너를 장착시킨다.
add(btnArr[i]);
}
setBounds(500, 200, 500, 500); // setBounds = setLocation + setSize; (x, y, width, height)
setVisible(true);
} // End - Bingo(String title)
//-----------------------------------------------------------------------------------------------------------
// class MyEventMandler extends WindowAdapter implements ActionListener
//-----------------------------------------------------------------------------------------------------------
class MyEventHandler extends WindowAdapter implements ActionListener {
//-----------------------------------------------------------------------------------------------------------
// JFrame의 우측 상단의 x버튼(닫기 버튼)을 누르면 프로그램을 종료하는 이벤트
//-----------------------------------------------------------------------------------------------------------
public void windowClosing(WindowEvent e) {
e.getWindow().setVisible(false);
e.getWindow().dispose();
System.exit(0);
} // End - public void windowClosing(WindowEvent e)
//-----------------------------------------------------------------------------------------------------------
// public void actionPerformed(ActionEvent e)
//-----------------------------------------------------------------------------------------------------------
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton)e.getSource();
// System.out.println("btn -> " + btn);
for(int indexNo = 0; indexNo < SIZE*SIZE; indexNo++) {
if((JButton)btn == btnArr[indexNo]) { // 눌려진 버튼을 찾으면
System.out.println("눌러진 버튼의 인덱스 번호 : " + indexNo);
btnArr[indexNo].setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 28));
btnArr[indexNo].setText(String.valueOf(bingNum[indexNo]));
// 현재 누른 버튼에 해당하는 btnOX의 값을 true로 바꾸기.
btnOX[indexNo/SIZE][indexNo%SIZE] = true;
/*
int cnt = 0;
for(int row = 0; row < SIZE; row++) {
for(int col = 0; col < SIZE; col++) {
if(indexNo == cnt) {
btnOX[row][col] = true;
}
cnt++;
}
}
*/
}
}
// 눌려진 버튼의 배경색을 변경한다.
btn.setBackground(Color.YELLOW);
// 빙고가 완성되었는지 검사한다.
if(checkBingo() == true) {
System.out.println("빙고!!!\n축하합니다.");
}
// 빙고판의 상태를 콘솔에 출력한다.
displayOX();
} // End - public void actionPerformed(ActionEvent e)
} // End - class MyEventMandler extends WindowAdapter implements ActionListener
//-----------------------------------------------------------------------------------------------------------
// 빙고판의 상태를 콘솔에 출력한다.
//-----------------------------------------------------------------------------------------------------------
public void displayOX() {
for(int row = 0; row < btnOX.length; row++) {
for(int col = 0; col < btnOX[row].length; col++) {
System.out.print(btnOX[row][col]? "●" : "X");
}
System.out.println();
}
System.out.println("현재 맞춘 라인 수 : " + bingoCount);
System.out.println("------------------------------------");
} // End - public void displayOX()
//-----------------------------------------------------------------------------------------------------------
// 빙고가 완성되었는지 검사하는 메서드
//-----------------------------------------------------------------------------------------------------------
boolean checkBingo() {
this.bingoCount = 0; // 완성된 라인수
int garoCount = 0; // 가로로 완성된 개수
int seroCount = 0; // 세로로 완성된 개수
int crossCount1 = 0; // 대각선(↘)으로 완성된 개수
int crossCount2 = 0; // 대각선(↙)으로 완성된 개수
for(int row = 0; row < btnOX.length; row++) {
for(int col = 0; col < btnOX[row].length; col++) {
// 가로 검사
if(btnOX[row][col] == true) {
garoCount++;
// 한 줄이 모두 true이면 5개의 버튼의 색을 변경한다.
if(garoCount == SIZE) {
for(int n = row * SIZE; n < row * SIZE + SIZE; n++)
btnArr[n].setBackground(Color.GREEN);
}
}
// 세로 검사
if(btnOX[col][row] == true) {
seroCount++;
if(seroCount == SIZE) { // 세로 한 줄에 대해서 5개가 모두 true이면 배경색을 바꾼다.
for(int n = row; n < btnArr.length; n = n + 5) { // 5씩 증가시키면서 색을 변경한다.
btnArr[n].setBackground(Color.GREEN);
}
}
}
// 대각선(↘) 검사
if(row == col && btnOX[row][col] == true) {
crossCount1++;
if(crossCount1 == SIZE) {
// 0부터 시작해서 6씩 증가되는 곳의 색을 변경한다.
/*
for(int n = 0; n < btnArr.length; n = n + 6) {
btnArr[n].setBackground(Color.GREEN);
*/
for(int n = 0; n < SIZE; n++) {
btnArr[SIZE * n + n].setBackground(Color.GREEN);
}
}
}
// 대각선(↙) 검사
if( (row + col == SIZE - 1) && (btnOX[row][col] == true) ) {
crossCount2++;
if(crossCount2 == SIZE) {
/*
for(int n = SIZE - 1; n < btnArr.length - 1; n = n + (SIZE -1) ) {
btnArr[n].setBackground(Color.GREEN);
}
*/
for(int n = (btnArr.length - 4); n > 0; n--) {
if(n % 4 == 0) {
btnArr[n].setBackground(Color.GREEN);
}
}
}
}
} // End - 내부 for
if(garoCount == SIZE) bingoCount++; // 가로 한 줄에 5개가 true이면 한줄 완성
if(seroCount == SIZE) bingoCount++; // 세로 한 줄에 5개가 true이면 한줄 완성
// 한 줄에 대한 검사가 끝나면 garoCount와 seroCount를 0으로 초기화한다.
garoCount = 0;
seroCount = 0;
} // End - 외부 for
// 대각선 1과 대각선 2는 오로지 1개씩만 존재하므로 이중 for문이 끝난 곳에서 bingoCount를 증가시켜야 한다.
if(crossCount1 == SIZE) bingoCount++;
if(crossCount2 == SIZE) bingoCount++;
return bingoCount >= SIZE;
} // End - boolean checkBingo()
//-----------------------------------------------------------------------------------------------------------
// public static void main(String[] args)
//-----------------------------------------------------------------------------------------------------------
public static void main(String[] args) {
new Bingo("빙고게임");
} // End - public static void main(String[] args)
} // End - public class Bingo extends JFrame
'Language > Java' 카테고리의 다른 글
[Java] 정리 (클래스와 객체...) (0) | 2022.08.21 |
---|---|
[Java] 정리 (기초) (0) | 2022.08.20 |
[Java] 정리 (다형성, 추상...) (0) | 2022.08.19 |
[Java] 클래스(Class), 객체(Object), 인스턴스(Instanse)의 개념 (0) | 2022.08.19 |
[Java] 제어자 (modifier) (0) | 2022.08.19 |