개발 노트

[유니티 윷놀이] 말 잡기와 업기 본문

유니티

[유니티 윷놀이] 말 잡기와 업기

알 수 없는 사용자 2024. 2. 23. 15:18

윷놀이에는 이러한 국룰이 있다.

상대의 말을 잡을 때 상대를 돌려보내는 것, 그리고 나의 말과 만나면 업어서 같이 가는 것이다.

 

이것은 윷놀이에 핵심이기도 하다.


[말 잡기]

먼저 상대의 말을 잡는 것을 구현해야한다.

 

 foreach (PlayerInformation otherPlayer in players)
 {
     if (otherPlayer == currentPlayer)
     {
         continue;
     }

     foreach (PieceInformation otherPiece in otherPlayer.pieces)
     {
         if (otherPiece.currentPosition == currentPosition)
         {
             // 해당 플레이어의 초기 위치로 말을 이동시킵니다.
             int playerId = otherPlayer.playerId;
             Vector3[] initialPositions = playerId == 1 ? player1Positions : player2Positions;
             Vector3 initialPosition = initialPositions[otherPiece.peiceid];

             otherPiece.pieceObject.transform.position = initialPosition;
             otherPiece.currentPosition = initialPosition;
             otherPiece.currentWaypointIndex = 0;
             instance.throwCount--;
             instance.playHistory.text = "상대의 말을 잡았습니다. 한번더 던지세요";
         }
     }
 }

이것은 상대의 말을 잡는 것에 대한 코드이다.

 

처음 foreach문에서 플레이어들에 대한 정보를 순회하면서 다른플레이어와 현재 플레이어의 정보가 같다면 그것은 자신이기 때문에 다음 으로 넘어 간다.

 

그 다음으로 나와는 다른 말들의 정보를 순회하면서, 상대방의 말과 자신의 말이 같은 위치에 있다면

초기 지정했던 위치로 설정하여 초기 값으로 보내고 말들은 배열블럭의 값을 지정해주기 때문에 

CurrentWaypointIndex 즉 현재 배열블럭위치 값을 0으로 초기화 시켜 그의 배열값과 위치값을 초기화 시킨다.

 

이렇게해서 말을 잡는 코드를 완성한다.

 


[말 업기]

 

다음으로 핵심인 말 업기이다.

 

 if (movingPiece.currentWaypointIndex == 0)
 {
     movingPiece.MovePiece(steps, BoardManager.instance, players, currentPlayer);
 }
 else
 {
     // 같은 위치에 있는 다른 캐릭터들을 함께 이동할 리스트에 추가합니다.
     List<PieceInformation> piecesToMoveTogether = new List<PieceInformation>();
     foreach (PieceInformation otherPiece in currentPlayer.pieces)
     {
         if (otherPiece != movingPiece && otherPiece.currentWaypointIndex == movingPiece.currentWaypointIndex)
         {
             piecesToMoveTogether.Add(otherPiece);
             Debug.Log("Added piece " + otherPiece.peiceid + " to pieces to move together list. Position: " + otherPiece.currentPosition);
         }
     }

     // 선택된 캐릭터를 함께 이동할 리스트에 추가합니다.
     piecesToMoveTogether.Add(movingPiece);

     // 함께 이동할 캐릭터들을 이동시킵니다.
     foreach (PieceInformation piece in piecesToMoveTogether)
     {
         piece.MovePiece(steps, BoardManager.instance, players, currentPlayer);
     }
 }

이것은 말을 업어서 이동하는 코드이다.

 

일단 MovePiece는 이동함수이다. 조건문을 보면 해당 정보의 말의 배열위치값이 0이면 움직이는 것인데, 이렇게 설정한 이유는 모든 말의 시작점은 배열 0이기 때문에 같이 이동 되는 것을 방지 하기 위함이다.

 

이제 시작점이 배열 0의 값이 아니면 자신이 아닌 또 다른 말과 같은 배열 위치값을 가졌다면 그 나와 또다른 말들을 리스트에 저장하고 그 다음 나의 말도 리스트에 저장시키는 것이다.

 

그 다음으로 리스트에 저장되어있는 말들을 이동함수를 통해 이동시키는 것이다.

 

이러한 과정으로 말을 업어서 같이 이동할 수 있게 된다.