메모리 게임: 자바 구현
1. 내용 설명
메모리 게임은 숨겨진 그림을 찾아 짝을 맞추는 게임입니다. 사용자는 뒤집힌 카드를 클릭하여 그림을 볼 수 있으며, 같은 그림의 카드 두 개를 찾아 짝을 맞춰야 합니다. 모든 짝이 맞춰지면 게임이 종료됩니다. 이 게임은 기억력과 집중력을 테스트하는 재미있는 방법입니다.
2. 프로그램 간 사용 함수 설명
- createAndShowGUI(): 게임의 사용자 인터페이스를 생성하고 보여줍니다.
- initializeGame(): 게임을 초기화하고 카드를 섞습니다.
- flipCard(): 사용자가 클릭한 카드를 뒤집습니다.
- checkMatch(): 두 카드가 일치하는지 확인하고, 일치하면 카드를 고정합니다.
- endGame(): 모든 카드가 맞춰졌는지 확인하고 게임을 종료합니다.
3. 코딩 내용
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
public class MemoryGame implements ActionListener {
private JFrame frame;
private ArrayList<JButton> buttons;
private ArrayList<String> cardValues;
private JButton selectedButton1;
private JButton selectedButton2;
private int matchedPairs;
public MemoryGame() {
frame = new JFrame("Memory Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4, 4));
buttons = new ArrayList<>();
cardValues = new ArrayList<>();
matchedPairs = 0;
initializeGame();
frame.pack();
frame.setVisible(true);
}
private void initializeGame() {
for (int i = 0; i < 8; i++) {
cardValues.add("Card" + i);
cardValues.add("Card" + i);
}
Collections.shuffle(cardValues);
for (int i = 0; i < 16; i++) {
JButton button = new JButton();
button.setActionCommand(cardValues.get(i));
button.addActionListener(this);
buttons.add(button);
frame.add(button);
}
}
public void actionPerformed(ActionEvent e) {
if (selectedButton1 == null) {
selectedButton1 = (JButton) e.getSource();
selectedButton1.setText(selectedButton1.getActionCommand());
} else if (selectedButton2 == null && selectedButton1 != e.getSource()) {
selectedButton2 = (JButton) e.getSource();
selectedButton2.setText(selectedButton2.getActionCommand());
checkForMatch();
}
}
private void checkForMatch() {
if (selectedButton1.getActionCommand().equals(selectedButton2.getActionCommand())) {
selectedButton1.setEnabled(false);
selectedButton2.setEnabled(false);
matchedPairs++;
if (matchedPairs == 8) {
JOptionPane.showMessageDialog(frame, "You've matched all pairs!");
}
} else {
Timer timer = new Timer(1000, e -> resetButtons());
timer.setRepeats(false);
timer.start();
}
}
private void resetButtons() {
selectedButton1.setText("");
selectedButton2.setText("");
selectedButton1 = null;
selectedButton2 = null;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MemoryGame());
}
}
4. 전문용어
- JFrame: Swing GUI의 윈도우 프레임입니다.
- ArrayList: 자바 컬렉션 프레임워크의 일부로, 가변 크기의 배열입니다.
- JButton: 클릭 가능한 버튼 컴포넌트입니다.
- GridLayout: 컴포넌트를 격자 형태로 배치하는 레이아웃 매니저입니다.
- ActionListener: 버튼 클릭과 같은 액션 이벤트를 처리하는 리스너 인터페이스입니다.
5. 라이브러리 추가 및 실행 방법
- 본 프로그램은 자바 표준 라이브러리의 Swing 컴포넌트를 사용합니다.
컴파일:
javac MemoryGame.java
실행:
java MemoryGame
'자바(java)' 카테고리의 다른 글
음식 주문 시스템: 메뉴에서 음식을 선택하고 주문하는 시스템을 구축합니다. (1) | 2023.12.19 |
---|---|
사전 애플리케이션: 사용자가 단어를 검색하고 의미를 확인할 수 있는 사전 앱을 제작합니다. (0) | 2023.12.19 |
토끼와 거북이 경주 게임: 토끼와 거북이가 경주하는 게임을 만들어 승자를 결정합니다. (0) | 2023.12.19 |
캘린더 애플리케이션: 달력을 표시하고 일정을 추가하고 관리하는 애플리케이션을 제작합니다. (0) | 2023.12.19 |
계산기: 기본적인 수학 연산을 수행하는 간단한 계산기를 디자인합니다. (0) | 2023.12.19 |