본문 바로가기

자바(java)

메모리 게임: 숨겨진 그림을 찾아 짝을 맞추는 기억력 게임을 구현합니다.

반응형

메모리 게임: 자바 구현

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

반응형