본문 바로가기

자바(java)

오목 게임: 오목 보드 게임을 구현하고 두 플레이어가 대결할 수 있게 합니다.

반응형

오목 게임 프로그램은 두 플레이어가 번갈아 가며 돌을 놓고, 먼저 일렬로 5개의 돌을 놓은 플레이어가 승리하는 게임입니다. 자바로 구현된 이 프로그램은 간단한 그래픽 사용자 인터페이스(GUI)를 포함합니다.

1. 내용 설명

오목은 15x15 격자판에서 진행되는 전략 보드 게임입니다. 두 플레이어가 검은색과 흰색 돌을 번갈아 놓으며, 먼저 가로, 세로, 대각선 중 하나로 연속된 다섯 개의 돌을 놓는 플레이어가 승리합니다.

2. 프로그램간 사용 함수 설명

  • placeStone(int x, int y, StoneColor color): 지정된 위치에 돌을 놓습니다.
  • checkWin(int x, int y): 승리 조건을 만족하는지 확인합니다.
  • initializeBoard(): 보드를 초기화합니다.
  • main(String[] args): 프로그램의 진입점입니다.

3. 코딩 내용

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class OmokGame extends JFrame {
    private final int BOARD_SIZE = 15;
    private final int CELL_SIZE = 40;
    private final int PADDING = 20;
    private StoneColor[][] board;
    private StoneColor currentPlayer;

    public OmokGame() {
        initializeBoard();
        setupUI();
    }

    private void initializeBoard() {
        board = new StoneColor[BOARD_SIZE][BOARD_SIZE];
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                board[i][j] = StoneColor.NONE;
            }
        }
        currentPlayer = StoneColor.BLACK;
    }

    private void setupUI() {
        setTitle("Omok Game");
        setSize(BOARD_SIZE * CELL_SIZE + PADDING * 2, BOARD_SIZE * CELL_SIZE + PADDING * 2);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                drawBoard(g);
            }
        };

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = (e.getX() - PADDING) / CELL_SIZE;
                int y = (e.getY() - PADDING) / CELL_SIZE;

                if (placeStone(x, y, currentPlayer)) {
                    repaint();
                    if (checkWin(x, y)) {
                        JOptionPane.showMessageDialog(panel, currentPlayer + " wins!");
                        initializeBoard();
                    }
                    currentPlayer = (currentPlayer == StoneColor.BLACK) ? StoneColor.WHITE : StoneColor.BLACK;
                }
            }
        });

        add(panel);
        setVisible(true);
    }

    private void drawBoard(Graphics g) {
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                int x = i * CELL_SIZE + PADDING;
                int y = j * CELL_SIZE + PADDING;
                g.drawRect(x, y, CELL_SIZE, CELL_SIZE);

                if (board[i][j] == StoneColor.BLACK) {
                    g.setColor(Color.BLACK);
                    g.fillOval(x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4);
                } else if (board[i][j] == StoneColor.WHITE) {
                    g.setColor(Color.WHITE);
                    g.fillOval(x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4);
                }
            }
        }
    }

    private boolean placeStone(int x, int y, StoneColor color) {
        if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == StoneColor.NONE) {
            board[x][y] = color;
            return true;
        }
        return false;
    }

    private boolean checkWin(int x, int y) {
    StoneColor color = board[x][y];

        // 가로, 세로, 대각선 방향에 대한 확인
        int[] dx = {1, 0, 1, 1};
        int[] dy = {0, 1, 1, -1};

        for (int i = 0; i < 4; i++) {
           int count = 1; // 현재 돌을 포함해야 하므로 1부터 시작
           count += countStones(x, y, dx[i], dy[i], color);
           count += countStones(x, y, -dx[i], -dy[i], color);

           if (count >= 5) {
              return true; // 5개 이상 연속하는 경우 승리
          }
       }

       return false; // 승리 조건을 만족하지 않는 경우
   }

   private int countStones(int x, int y, int dx, int dy, StoneColor color) {
      int count = 0;
      for (int i = 1; i < 5; i++) {
          int nx = x + dx * i;
          int ny = y + dy * i;

           if (nx >= 0 && nx < BOARD_SIZE && ny >= 0 && ny < BOARD_SIZE && board[nx][ny] == color) {
               count++;
           } else {
               break;
          }
      }
      return count;
   }

    public static void main(String[] args) {
        new OmokGame();
    }
}

enum StoneColor {
    BLACK, WHITE, NONE
}

4. 전문용어

  • Java: 객체 지향 프로그래밍 언어입니다.
  • GUI (Graphical User Interface): 사용자가 그래픽을 통해 상호작용하는 인터페이스입니다.
  • JFrame, JPanel: Java Swing 라이브러리의 GUI 컴포넌트입니다.
  • MouseListener: 마우스 이벤트를 처리하는 리스너입니다.

5. 라이브러리 추가 및 실행 방법

라이브러리

  • Java Swing 라이브러리 사용

실행 방법

  1. Java 개발 환경을 설치합니다.
  2. 위의 코드를 Java 파일로 저장합니다.
  3. 컴파일 후 실행합니다.

컴파일

javac -encoding UTF-8 OmokGame.java

 

실행

java OmokGame

반응형