자바 오목 미니 게임 실현 코드

11246 단어 자바오목
머리말
앞서 자바 기초 과정 을 마치 고 자바 의 오목 게임 을 간단하게 만들어 기록 해 보 았 습 니 다.
인터페이스
직접 사용 하 는 자바 라 이브 러 리 의 기본 컨트롤 러 에 GUI 를 썼 기 때문에 최적화 를 많이 하지 않 았 기 때문에 추 한 것 같 습 니 다.
다음은 인터페이스 전시:

흑점 이 먼저 갔 지만 내 쪽 에 서 는 규칙 을 간소화 하고 흑점 이 먼저 가 는 금 수 를 고려 하지 않 았 다.
아래 에 코드 를 바로 붙 입 니 다.
인터페이스 클래스
나 는 오목 인터페이스의 일부 상수 를 모두 이 인터페이스 류 에 정의 하 였 는데,바둑판 의 시작 좌표,바둑판 선의 간격 과 바둑판 반지름 을 포함한다.

public interface constant {

    int[][] chessLocation = new int[15][15];
    static final int x = 50;   //     
    static final int y = 50;
    static final int LN = 15;  //      
    static final int R = 45;
}
실현 류
인터페이스
이 클래스 는 constant,Mouse Listener,Action Listener 세 개의 인 터 페 이 스 를 계승 합 니 다.
그 중:
constant 는 자신 을 정의 합 니 다마우스 리 스 너 는 마우스 감청Action Listener 는 사건 감청 입 니 다함수.
show()창 기본 프레임 그리 기
paint()바둑판 격자 선과 바둑 알 그리 기
IsWin()의 승 패 를 판단 하 는 기본 논리
mouseClicked()마우스 위치 획득,바둑돌 타 점 판단 등
actionPerformed()는 마우스 가 어떤 단 추 를 누 르 는 지 판단 합 니 다.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class game_logic extends JPanel implements constant, MouseListener, ActionListener {
    int chess_x = 0, chess_y = 0;
    int X = 0, Y = 0;
    boolean IsBlack = true; //    
    boolean flag = false;  //        
 //        
    JFrame frame = new JFrame();
    JButton start = new JButton("    ");
    JButton regret = new JButton("  ");
    JButton Lost = new JButton("  ");
 
    public void ShowUI() {
        frame.setSize(740, 800);
        frame.setTitle("   ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//        
        frame.setLocationRelativeTo(null);//    
        frame.setVisible(true);//     
        frame.setResizable(false);//        
        frame.add(this);

        this.setBackground(Color.LIGHT_GRAY);//      
        this.addMouseListener(this);//          

        start.setSize(50, 80);//      
        start.addActionListener(this);//         
        Lost.setSize(50, 80);
        Lost.addActionListener(this);
        regret.setSize(50, 80);
        regret.addActionListener(this);

        this.add(start);//        
        this.add(Lost);
        this.add(regret);

    }

    /**
     *     
     *        
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);

        for (int i = 0; i < LN; i++) {       //   
            g.drawLine(x, y + i * R, x + (LN - 1) * R, y + i * R);// *15
            g.drawLine(x + i * R, y, x + i * R, y + (LN - 1) * R);// *15
        }

        for (int i = 0; i < LN; i++) {       //   
            for (int j = 0; j < LN; j++) {

                if (chessLocation[i][j] == 1) {
                    g.setColor(Color.BLACK);//    
                    g.fillOval(50 + i * R - 23, 50 + j * R - 23, R, R);
                }
                if (chessLocation[i][j] == 2) {
                    g.setColor(Color.WHITE);
                    g.fillOval(50 + i * R - 23, 50 + j * R - 23, R, R);
                }
                repaint();
            }
        }
    }

    /**
    *    
    *
    */
    public int IsWin() {
        int k = 0;
        for (int f = 2; f < 12; f++) {
            for (int g = 2; g < 12; g++) {
                if (chessLocation[f][g] == 1) {
                    if (chessLocation[f][g] == chessLocation[f - 1][g] && chessLocation[f - 1][g] == chessLocation[f - 2][g] && chessLocation[f - 2][g] == chessLocation[f + 1][g] && chessLocation[f + 1][g] == chessLocation[f + 2][g]) {
                        k = 1;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f][g - 1] && chessLocation[f][g - 1] == chessLocation[f][g - 2] && chessLocation[f][g - 2] == chessLocation[f][g + 1] && chessLocation[f][g + 1] == chessLocation[f][g + 2]) {
                        k = 1;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f - 1][g - 1] && chessLocation[f - 1][g - 1] == chessLocation[f - 2][g - 2] && chessLocation[f - 2][g - 2] == chessLocation[f + 1][g + 1] && chessLocation[f + 1][g + 1] == chessLocation[f + 2][g + 2]) {
                        k = 1;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f - 1][g + 1] && chessLocation[f - 1][g + 1] == chessLocation[f - 2][g + 2] && chessLocation[f - 2][g + 2] == chessLocation[f + 1][g - 1] && chessLocation[f + 1][g - 1] == chessLocation[f + 2][g - 2]) {
                        k = 1;
                        break;
                    }
                }
                if (chessLocation[f][g] == 2) {
                    if (chessLocation[f][g] == chessLocation[f - 1][g] && chessLocation[f - 1][g] == chessLocation[f - 2][g] && chessLocation[f - 2][g] == chessLocation[f + 1][g] && chessLocation[f + 1][g] == chessLocation[f + 2][g]) {
                        k = 2;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f][g - 1] && chessLocation[f][g - 1] == chessLocation[f][g - 2] && chessLocation[f][g - 2] == chessLocation[f][g + 1] && chessLocation[f][g + 1] == chessLocation[f][g + 2]) {
                        k = 2;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f - 1][g - 1] && chessLocation[f - 1][g - 1] == chessLocation[f - 2][g - 2] && chessLocation[f - 2][g - 2] == chessLocation[f + 1][g + 1] && chessLocation[f + 1][g + 1] == chessLocation[f + 2][g + 2]) {
                        k = 2;
                        break;
                    }
                    if (chessLocation[f][g] == chessLocation[f - 1][g + 1] && chessLocation[f - 1][g + 1] == chessLocation[f - 2][g + 2] && chessLocation[f - 2][g + 2] == chessLocation[f + 1][g - 1] && chessLocation[f + 1][g - 1] == chessLocation[f + 2][g - 2]) {
                        k = 2;
                        break;
                    }
                }
            }
        }
        return k;

    }

    @Override
    public void mouseClicked(MouseEvent e) {

        X = e.getX();
        Y = e.getY();                          //      
        if (flag == true) {
            if (X >= 25 && X <= 705 && Y >= 25 && Y <= 705) {   //               ,       
                //          
                chess_x = (X - 20) / R;
                chess_y = (Y - 20) / R;

                if (chessLocation[chess_x][chess_y] == 0) {   //      ,      
                    if (IsBlack == true) {
                        chessLocation[chess_x][chess_y] = 1;
                        IsBlack = false;
                    } else {
                        chessLocation[chess_x][chess_y] = 2;
                        IsBlack = true;
                    }

                    if (IsWin() == 1) {
                        JOptionPane.showMessageDialog(this, "    ");
                        flag = false;

                    }
                    if (IsWin() == 2) {
                        JOptionPane.showMessageDialog(this, "    ");
                        flag = false;
                    }
                    repaint();
                }
            }
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String buttonName = e.getActionCommand();

        if (buttonName.equals("    ") && flag == false) {//    ,    
            flag = true;
            for (int i = 0; i < LN; i++) {
                for (int j = 0; j < LN; j++) {
                    chessLocation[i][j] = 0;
                }
            }
            IsBlack = true;
            repaint();
        }

        if (buttonName.equals("  ") && flag == true) {
            flag = false;
            if (IsBlack) {
                JOptionPane.showMessageDialog(this, ",    ,    ");
            } else {
                JOptionPane.showMessageDialog(this, ",    ,    ");
            }
        }

        if (buttonName.equals("  ") && flag == true) {
            if (chessLocation[chess_x][chess_y] == 1) {
                JOptionPane.showMessageDialog(this, "    ");
            }
            if (chessLocation[chess_x][chess_y] == 2) {
                JOptionPane.showMessageDialog(this, "    ");
            }
            chessLocation[chess_x][chess_y] = 0;
            IsBlack = !IsBlack;
            repaint();
        }
    }
}
그 중에서 비교적 재 미 있 는 것 은 오목 으로 승 부 를 판단 하 는 방식 이다.바둑판 의 크기 가 15*15 라 고 가정 하면 나 는 한가운데 에 있 는 13*13d 의 칸 만 판단 하고 양쪽 으로 확장 하여 5 자 연주 여 부 를 판단 해 야 한다.
구체 적 인 설명 코드 에는 모두 주석 이 있어 서 군말 이 많 지 않다.
주 함수 클래스

public class Main_game {
    public static void main(String[] args) {
        game_logic start=new game_logic();
        start.ShowUI();
    }
}
총결산
오목 미니 게임 의 기본 기능 을 실현 하 였 으 나 약간 거 칠 고 디 테 일이 부족 하 다.기본 컨트롤 에 대해 배 울 수 있 는 작은 게임 demo 를 만 드 는 것 은 절차 통제 와 조작 논리 에 대한 훈련 에 효과 적 인 방식 이다.예전 에 다른 사람의 코드 를 보면 간단 하 다 고 생각 했 지만 자신 이 쓸 때 논리 적 절차 가 연속 되 기 어렵 고 생각 이 혼 란 스 러 웠 다.어떤 과정 은 자신 이 써 야 그 중의 구 덩이 를 알 수 있다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기