이 마지막 튜토리얼 단계에서는 코드를 개선하는 방법을 알아보는 동시에, 진행하며 중요한 Verse 개념 몇 가지도 배우게 됩니다.
Verse 코드 개선
이 페이지에서는 코드 변경을 단계별로 상세히 안내하지만, 작업물을 확인하고 싶다면 완성된 코드 섹션에서 최종 결과를 검토하세요.
리팩터링이란 기존 코드의 구조를 변경하여 비헤이비어는 유지하면서도 디자인 또는 구현을 개선하는 과정을 말합니다. 다음은 코드 리팩터링 시 가장 일반적인 목표입니다.
더 나은 변수 이름 지정, 개선된 공백 또는 전체적인 코드 구조로 가독성을 향상합니다.
보다 간소하거나 보다 효율적인 비헤이비어 구현을 통해 퍼포먼스를 향상합니다.
유사한 함수를 하나로 압축하거나 유형 및 목적이 비슷한 여러 변수를 배열과 같은 컨테이너로 모아 반복과 코드 팽창(크거나, 불필요하거나, 지나치게 복잡한 코드)을 줄입니다.
다음 목표를 따라 리팩터링하면 유지 보수가 가능하고, 읽고 다시 확인하기가 쉬우며, 확장 가능하고, 추후 비헤이비어 향상 가능성을 확장하기가 쉬운 코드를 작성하는 데 도움이 됩니다. 게임의 수준을 크게 끌어올리세요!
GetFirstPlayer()
가독성 좋은 코드를 작성하는 것은 훌륭한 프로그래밍 연습입니다. 예를 들어, GetFirstPlayer()는 GetPlayspace().GetPlayers()[0]보다 명확합니다. 또한 이러한 방법은 연산의 의도가 명확하므로 프로그래밍 일반 연산에 있어 모범 사례입니다.
Shooting_range_manager_device.verse파일을 엽니다.GetFirstPlayer메서드를 추가합니다.Verse# Returns the first player in the playspace. GetFirstPlayer()<decides><transacts>:player= return GetPlayspace().GetPlayers()[0]AdjustScore메서드를 수정해 신규GetFirstPlayer메서드를 사용합니다.GetFirstPlayer메서드는 실패 가능하기 때문에 소괄호 대신 대괄호를 사용해 호출된다는 점에 유의하세요.Verse# Adjusts the player's score by the provided value. AdjustScore(Value:int):void= # Start the timer if it hasn't started yet. if (not IsTimerStarted?): StartTimer() # Sets the score award to the base value of the target multiplied by the current weapon level. ScoreManager.SetScoreAward(Value * CurrentWeaponLevel) <# --- New Code Start --- #>IncreaseWeaponLevel메서드를 수정해 신규GetFirstPlayer메서드를 사용합니다.Verse# Increases the player's weapon level by one (up to the maximum value). IncreaseWeaponLevel():void= if: # If able to retrieve the first player and current weapon level isn't maxed, then... <# --- New Code Start --- #> Player:player = GetFirstPlayer[] <# --- New Code End --- #>
대상 클래스 래퍼 및 배열
코드 정리 시 또 하나의 주요 목표는 중복을 최소화하는 것입니다. 현재 구현에서 각 좋은 타깃 및 나쁜 타깃은 자체적인 콜백 및 적중 플래그를 정의하므로, 코드가 반복적이게 됩니다.
더 나은 방법은 개별 타깃에 필요한 모든 것이 포함되는 래퍼 클래스를 만드는 것입니다. 이후 사격장 관리 장치에서 각 컴포넌트를 개별 정의하는 대신 이러한 타깃 래퍼를 배열 내에서 관리할 수 있습니다.
이로써 중복이 줄어들 뿐만 아니라 확장성도 향상됩니다. 추가 코드를 작성하지 않고도 원하는 만큼 타깃을 추가할 수 있습니다.
good_target_wrapper클래스를 정의합니다.shooting_range_manager_device클래스 정의 위에 배치할 수 있습니다.Verse# A wrapper class for the good targets to support array storage with a self-contained event callback. good_target_wrapper := class: @editable Target:shooting_range_target_track_device = shooting_range_target_track_device{} @editable Score:int = 100 # A circular reference to the shooting range manager device.bad_target_wrapper클래스를 정의합니다.shooting_range_manager_device클래스 정의 위에 배치할 수 있습니다.Verse# A wrapper class for the bad targets to support array storage with a self-contained event callback. bad_target_wrapper := class: @editable Target:shooting_range_target_device = shooting_range_target_device{} @editable Score:int = -100 # A circular reference to the shooting range manager device.사격장 관리 장치에 다음 배열 프로퍼티를 추가합니다.
Verse@editable: GoodTargets:[]good_target_wrapper = array{} @editable BadTargets:[]bad_target_wrapper = array{}사격장 관리 장치에서 다음을 제거합니다. 이는 이제 래퍼 클래스로 처리됩니다.
GoodTarget1-3
GoodTargetScore
BadTarget1-3
BadTargetScore
HitGoodTarget1-3
OnGoodTarget1-3Hit()
OnBadTarget1-3Hit()
OnBegin메서드를 수정해 배열을 통해 반복함으로써 좋은 타깃과 나쁜 타깃을 초기화합니다.Verse# Runs when the device is started in a running game. OnBegin<override>()<suspends>:void= <# --- New Code Start --- #> # Initialize GoodTargets. for (GoodTarget : GoodTargets): GoodTarget.Init(Self) # Initialize BadTargets.CheckCombo메서드를 수정하여 좋은 타깃 배열을 통한 반복으로 콤보가 완료되는지 확인합니다.Verse# If the combo is complete, enable the ComboTarget. CheckCombo():void= <# --- New Code Start --- #> # If any of the good targets are not hit, exit the function. for (GoodTarget : GoodTargets): if (not GoodTarget.IsHit?): returnResetCombo메서드를 업데이트해 좋은 타깃 배열을 통해 반복되도록 합니다.Verse# Resets the combo tracking variables, re-enables all GoodTargets, and disables the ComboTarget. ResetCombo():void= <# --- New Code Start --- #> for (GoodTarget : GoodTargets): GoodTarget.Reset() <# --- New Code End --- #>Verse 코드를 저장 및 빌드합니다.
완성된 코드
using { /Fortnite.com/Devices }
using { /Verse.org/Random }
using { /Verse.org/Simulation }
<#>
Utility Classes
<#>
# A wrapper class for the good targets to support array storage with a self-contained event callback.
good_target_wrapper := class:
모두 합치기
Verse 장치의 변경된 편집 가능 프로퍼티에 새로운 값을 설정해야 합니다.
뷰포트 또는 아웃라이너(Outliner) 패널에서 shooting_range_manager_device를 선택합니다.
디테일(Details) 패널에서 다음 파라미터를 설정합니다.
GoodTargets 배열에 3가지 구성 요소를 추가하고 각각을 해당하는 타깃에 설정합니다. 선택 사항으로, 이제 개별 타깃의 득점 값도 변경할 수 있습니다.
BadTargets 배열에 3가지 구성 요소를 추가하고 각각을 해당하는 타깃에 설정합니다. 이제 개별 타깃의 득점 값도 변경할 수 있습니다(선택 사항).
다른 모른 프로퍼티가 의도한 대로 설정되었는지 검증합니다.
직접 해보기
이 섹션은 끝났지만, 배움은 끝나지 않습니다. 더 많은 Verse 기능과 게임플레이에 대해 알아보려면 게임 메카닉 배우기의 문서를 참고하세요.