현재

체스판 만들기(미완) 본문

알고리즘/기타알고리즘문제

체스판 만들기(미완)

AAAge 2023. 9. 18. 16:54

<문제의도>

클래스를 활용해서 각 필요한 방법들을 호출해서 각각 명령에 맞는 행동을 하는것이다.

 

<풀이 코드>

public class Test{
    public static void main(String[] args) throws Exception{

        Board board = new Board();

        board.printBoard();
        board.generateObj();
        System.out.println("--------------------");
        board.printBoard();
        board.goFoward();
        System.out.println("--------------------");
        board.printBoard();

    }
}

class Board {       //Board class : 간이 체스판

    public Board(){
        for ( int x = 0 ; x < 8 ; x ++){ // 체스판 만듬
            for ( int y = 0 ; y < 8 ; y++){
                if ( x % 2 == y % 2){
                    chess[x][y] = 1;
                }else if ( x % 2 == y % 2){
                    chess[x][y] = 0;
                }
            }
        }
    }

    private static int chess[][] = new int[8][8];      //  8x8 사이즈의 int 배열
   
    public void printBoard(){       // 1. printBoard : int 배열 값이 0이면 □, 1이면 ■을 출력해 8x8 보드를 출력한다
   
        for ( int x = 0 ; x < 8 ; x ++){
            System.out.println("");
            for ( int y = 0 ; y < 8; y++){
                if(chess[x][y] == 1){
                    System.out.print("■ ");
                }else if ( chess[x][y] == 0){
                    System.out.print("□ ");
                }else if ( chess[x][y] == 2){
                    System.out.print("♬ ");
            }
        }
    }
    System.out.println();
    }
    public void generateObj(){      // 2. genetateObj : 배열에 2가 없다면 아무 곳이나 2를 하나 만들어낸다
        int min = 0; // 원하는 최소값
        int max = 8; // 원하는 최대값 + 1
        int randomCoordinateX = (int) (min + Math.random() * (max - min));
        int randomCoordinateY = (int) (min + Math.random() * (max - min));

        System.out.println((randomCoordinateX+1)+","+(randomCoordinateY+1)+ "에 이미지를 생성합니다.");
        chess[randomCoordinateX][randomCoordinateY] = 2;
       

    }

    public void goFoward(){         // 3. goFoward : 배열의 2를 한칸 앞으로 움직인다*/

        for ( int x = 0 ; x < 8 ; x++){
            for ( int y = 0 ; y < 8 ; y++){
                if ( chess[x][y] == 2){
                    int temp = chess[x][y]; // 이미지 저장
                    if ( chess[x+1][y] == 1 || chess[x-1][y] == 1 || chess[x][y+1] == 1 || chess[x][y-1] == 1 ){
                            chess[x][y] = 0; // 이미지에 아래꺼있는거 가져옴; 원래꺼 가져와야함;
                    }else if(chess[x+1][y] == 0 || chess[x-1][y] == 0 || chess[x][y+1] == 0 || chess[x][y-1] == 0){
                        chess[x][y] = 1;
                    }
                    chess[x-1][y] = temp; // 한칸앞에 이미지 저장

                }
            }
        }
    }
   
}


<풀면서 느낀점>

로직은 그렇게 어렵지 않다고 생각했는데 처음으로 이제 클래스를 작성하려니까 까다롭게 느껴졌다.

public, static, 생성자등 제대로 모르는게 많았어서 좀더 제대로 알아보고 공부해야할 필요성을 느꼈다.