# Godot 3

`zokogames` 애드온(`packages/sdk-engines/godot3/addons/zokogames`)은 **Godot 3** HTML5 내보내기를 대상으로 합니다(대상은 3.5와 3.6 LTS이며, 3.3과 3.4도 동작할 것입니다. 3.0~3.2는 지원하지 않습니다). [Godot 4 애드온](https://docs.zokogames.com/kr/engines/godot)과 같은 공개 API를 가집니다. 같은 오토로드 `ZokoGames`, 같은 메서드 이름, 같은 시그널을 쓰므로 프로젝트를 둘 사이에서 옮길 수 있습니다. GDScript 1로 작성되어 있고(`await`도 람다도 없음), 내보내기 HTML 셸에 정의된 작은 브리지(`window.ZokoBridge`)를 통해 `JavaScript` 싱글톤으로 JavaScript SDK를 호출합니다. 브라우저 밖(에디터나 데스크톱 실행)에서는 내장 시뮬레이터가 대신 응답하므로, 같은 코드가 어디서나 실행됩니다. "midgame", "rewarded" 같은 용어는 [용어집](https://docs.zokogames.com/kr/getting-started/glossary)에 있습니다.

> [!NOTE]
> 현재 상태(1.8.0): macOS의 공식 Godot 3.6.3 에디터에서 헤드리스로 실행했습니다. 애드온은 오류나 경고 없이 가져와지고(경고를 오류로 처리), 플러그인을 활성화하면 오토로드가 등록되며, 모든 공개 메서드와 시그널이 시뮬레이터 모드에서 문서대로 동작하고, HTML5 내보내기에는 브리지가 포함되어 브라우저에서 실행됩니다. Godot 3.3~3.5는 검증하지 않았고, 라이브 포털에 대한 실행도 하지 않았습니다. 첫 가져오기가 실패하면 Godot 버전과 정확한 오류를 [지원](https://docs.zokogames.com/kr/business/support)으로 보내 주세요.

Godot 4에서는 이 애드온이 시작을 거부합니다(`init()`이 `unsupportedEngine`으로 실패합니다). 그쪽에서는 [Godot 4 페이지](https://docs.zokogames.com/kr/engines/godot)를 사용하세요.

## 설치 {#install}

Godot 3 플러그인 다운로드: [/sdk-engines/zokogames-godot3-1.8.1.zip](https://www.zokogames.com/sdk-engines/zokogames-godot3-1.8.1.zip)(저장소의 폴더와 같은 파일입니다).

[/sdk-engines/godot3.zip](https://www.zokogames.com/sdk-engines/godot3.zip)은 항상 최신 버전입니다. 체크섬: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). 모든 엔진 패키지의 버전, 크기, SHA-256 색인: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json). 소스는 [github.com/zokogames/zokogames-godot3](https://github.com/zokogames/zokogames-godot3)에도 공개되어 있습니다. Godot Asset Library(asset 5620)에도 있습니다. 에디터의 AssetLib 탭(Godot 3)에서 ZokoGames를 검색하거나 zip으로 설치하세요.

1. 다운로드한 파일의 압축을 풀고 `addons/zokogames` 폴더를 프로젝트의 `res://addons/` 폴더에 복사합니다(`addons`가 없으면 만드세요). 이 폴더에는 `plugin.cfg`, `plugin.gd`, `zokogames.gd`(오토로드), `zoko_banner.gd`, `export/zokogames_shell.html`이 들어 있습니다.
2. **Project > Project Settings > Plugins**: **ZokoGames**를 활성화합니다. 그러면 오토로드 `ZokoGames`(`res://addons/zokogames/zokogames.gd`)와 `zokogames/simulator/*` 설정이 등록됩니다.
3. **Project > Export**: **HTML5** 프리셋을 추가하고 **Custom HTML Shell**(Options 탭 > HTML)을 `res://addons/zokogames/export/zokogames_shell.html`로 설정합니다. 이 셸은 엔진보다 먼저 `https://sdk.zokogames.com/zokogames-sdk-v1.js`를 로드하고, `window.ZokoBridge`를 만들며, 엔진 다운로드를 포털의 로딩 바에 보고합니다. 자체 셸을 쓴다면 `<head>`에 스크립트 태그를 넣고 제공된 셸의 브리지 블록을 복사하세요.
4. 시작할 때 한 번, 다른 호출보다 먼저 `yield(ZokoGames.init_async(), "completed")`를 실행합니다.
5. 선택 사항: 배너에 내줄 수 있는 공간 위에 `ZokoBanner` 노드(`zoko_banner.gd`)를 추가합니다. 애드온 옆의 `examples/` 폴더에 `zoko_demo.gd`와 `zoko_store.gd`가 있습니다.

> [!IMPORTANT]
> 커스텀 셸이 없으면 `window.ZokoBridge`가 존재하지 않습니다. 애드온은 경고를 기록하고 시뮬레이터로 대체하므로, 게임은 실행되지만 실제 광고, 사용자, 저장은 사용하지 않습니다.

### 스타터 킷 {#starter-kit}

애드온, 셸, 작은 데모 씬이 들어 있는 준비된 Godot 3 프로젝트: [/starter-kits/godot3.zip](https://www.zokogames.com/starter-kits/godot3.zip). [스타터 킷](https://docs.zokogames.com/kr/getting-started/starter-kits) 페이지를 참고하세요.

## Godot 4와 다른 점 {#what-differs-from-godot-4}

| Godot 4 | Godot 3 |
| --- | --- |
| `await ZokoGames.get_user_async()` | `yield(ZokoGames.get_user_async(), "completed")`, 같은 Dictionary를 반환합니다 |
| `callback: Callable` | `callback`: a `FuncRef`, `funcref(self, "_on_done")` |
| `callback: Callable` | `callback`: `FuncRef`, `funcref(self, "_on_done")` |
| 광고가 재생되는 동안 애드온이 트리를 일시정지하고 Master 버스를 음소거하며 포털의 음소거 설정을 따릅니다(`pause_game_during_ads`, `mute_audio_during_ads`, `follow_portal_mute`, 모두 `true`) | 같은 속성과 기본값입니다. 광고 중에도 반응해야 하는 자체 노드에는 `pause_mode = PAUSE_MODE_PROCESS`가 필요합니다 |
| `JavaScriptBridge` | `JavaScript` |

`_async` 호출은 요청 객체(`id`, `done`, `result`, 시그널 `completed(result)` 포함)를 반환하고, `yield(..., "completed")`는 결과 Dictionary를 돌려줍니다. 모든 요청은 이후 프레임에서 완료되므로 `yield`가 놓치는 일은 없습니다.

## 동작하는 스크립트 {#a-working-script}

첫 씬의 노드에 있는 스크립트(또는 자체 오토로드)에 넣으세요. 초기화, 미드게임 광고, 보상형 광고, 게임플레이 시작과 중지, 저장과 불러오기, 리더보드 점수를 다룹니다.

```gdscript
extends Node

func _ready() -> void:
	pause_mode = PAUSE_MODE_PROCESS                            # keep running while an ad pauses the tree
	var res = yield(ZokoGames.init_async(), "completed")
	if not res.ok:
		push_warning("ZokoGames unavailable: %s" % res.error.code)
	# The addon pauses the tree and mutes Master during an ad, and follows the portal's mute setting
	# (pause_game_during_ads, mute_audio_during_ads, follow_portal_mute): no ad or mute handlers needed.
	var level = int(ZokoGames.data_get_item("level", "1"))     # load: synchronous Strings
	start_game(level)

# Call when the player takes control, and when play stops.
func on_play_start() -> void:
	if ZokoGames.is_available():
		ZokoGames.gameplay_start()
func on_play_stop() -> void:
	if ZokoGames.is_available():
		ZokoGames.gameplay_stop()

func show_midgame() -> void:
	var res = yield(ZokoGames.request_ad_async("midgame"), "completed")   # completes after the ad is over
	if not res.ok:
		print("no ad: ", res.error.code)                       # adCooldown, unfilled, adblock ...

func on_reward_button() -> void:
	var res = yield(ZokoGames.request_ad_async("rewarded"), "completed")
	if res.ok:
		grant_reward()                                         # reward only after the ad finished

func save_progress(level: int) -> void:
	var r = ZokoGames.data_set_item("level", str(level))       # synchronous, uploaded in the background
	if not r.ok:
		push_warning(r.error.code)                             # for example dataLimitExceeded

func submit_score(score: float) -> void:
	var user = yield(ZokoGames.get_user_async(), "completed")
	if not user.ok or user.result == null:
		return                                                 # guests are not ranked
	var r = yield(ZokoGames.submit_score_async("", score), "completed")   # "" works only on a board WITHOUT an encryption key
	if not r.ok:
		print(r.error.code)

func start_game(_level: int) -> void:
	pass
func grant_reward() -> void:
	pass
```

## 리더보드 점수와 암호화 {#leaderboard-scores-and-encryption}

암호화 키가 **있는** 보드는 올바르게 암호화된 페이로드만 집계합니다([리더보드](https://docs.zokogames.com/kr/sdk/leaderboards#client-submission)). 플러그인 1.8.0부터 `encrypt_score_async(score, KEY)`가 보드 키로 점수를 봉인하고 `submit_score_async`에 넘길 페이로드를 반환합니다. `""`는 키가 없는 보드에서만 동작합니다.

```gdscript
const BOARD_KEY = "paste-your-board-key-here"

func submit_secure_score(score: float) -> void:
	var sealed = yield(ZokoGames.encrypt_score_async(score, BOARD_KEY), "completed")
	if not sealed.ok:
		print(sealed.error.code)                               # userNotAuthenticated for guests, invalidArgument for a bad score or key
		return
	var r = yield(ZokoGames.submit_score_async(sealed.result, score), "completed")
	if not r.ok:
		print(r.error.code)
```

선택 사항인 세 번째 인수 `earned_at`(Unix 밀리초, 실시간 플레이는 기본값 0)은 지연 전송되는 점수의 사본을 봉인합니다. 빌드 안의 키는 가벼운 변조를 막을 뿐 작정한 플레이어는 막지 못합니다. 중요한 경품이 걸려 있다면 서버에서 점수를 계산하고 서버 API를 사용하세요.

## 호출 방식 {#how-calls-work}

<!-- search: headings-only -->

GDScript 이름은 snake_case입니다. 포털과 통신하는 모든 메서드는 두 가지 형태로 제공됩니다.

| 형태 | 예시 | 용도 |
| --- | --- | --- |
| 콜백 | `ZokoGames.get_user(callback)` | 호출만 하고 잊는 경우. `FuncRef`는 선택 사항이며 마지막에 오지만, `store_get_catalog_items(callback, limit, offset)`와 `store_get_player_inventory(callback, limit, offset)`에서는 맨 앞에 오고 `get_user_token(signing_key_type, callback)`에서는 `signing_key_type` 뒤에 옵니다. |
| 요청 | `yield(ZokoGames.get_user_async(), "completed")` | 위에서 아래로 읽히는 코드. 이름이 `_async`로 끝납니다. |

둘 다 Dictionary를 전달합니다. `{ "ok": true, "result": <value> }` 또는 `{ "ok": false, "error": { "code": "...", "message": "..." } }`입니다(`request_ad`는 대신 FuncRef의 Dictionary를 받습니다). 모든 메서드는 오토로드에 직접 있으며 `ad.`, `game.`, `user.` 같은 하위 객체는 없습니다.

| JavaScript | GDScript |
| --- | --- |
| `SDK.init()` | `yield(ZokoGames.init_async(), "completed")` 또는 `ZokoGames.init(callback)`; 시그널 `initialized(ok)` |
| `SDK.environment` | `ZokoGames.environment` (`"local"`, `"zokogames"` 또는 `"disabled"`), `ZokoGames.is_available()`, `ZokoGames.is_simulated`, `ZokoGames.is_qa_tool`, `ZokoGames.VERSION` |
| `SDK.ad.requestAd(type, cbs)` | `ZokoGames.request_ad(type, {"ad_started": f, "ad_finished": f, "ad_error": f})` (FuncRef) 또는 `yield(ZokoGames.request_ad_async(type), "completed")` |
| `SDK.ad.hasAdblock()` | `ZokoGames.has_adblock(callback)` 또는 `yield(ZokoGames.has_adblock_async(), "completed")` |
| `SDK.banner.requestBanner(...)` | `yield(ZokoGames.request_banner_async(id, width, height, window_rect), "completed")` |
| `SDK.banner.requestResponsiveBanner(id)` | `yield(ZokoGames.request_responsive_banner_async(id, window_rect), "completed")` |
| `SDK.banner.clearBanner(id)` / `clearAllBanners()` | `ZokoGames.clear_banner(id)` / `ZokoGames.clear_all_banners()` |
| `SDK.banner.hideAllBanners()` / `showAllBanners()` (1.8.0) | `ZokoGames.hide_all_banners()` / `ZokoGames.show_all_banners()` (및 `_async`) |
| `SDK.game.gameplayStart()` / `gameplayStop()` | `ZokoGames.gameplay_start()` / `ZokoGames.gameplay_stop()` |
| `SDK.game.loadingStart()` / `loadingStop()` / `loadingProgress(n)` | `ZokoGames.loading_start()` / `loading_stop()` / `loading_progress(n)` |
| `SDK.game.happytime()` | `ZokoGames.happytime()` |
| `SDK.game.reportGameCompletedPercentage(n)` | `ZokoGames.report_game_completed_percentage(n)` |
| `SDK.game.setGameContext(obj)` / `clearGameContext()` | `ZokoGames.set_game_context(dict)` / `ZokoGames.clear_game_context()` |
| `SDK.game.updateRoom(u)` / `leftRoom()` | `ZokoGames.update_room(dict)` / `ZokoGames.left_room()` |
| `SDK.game.inviteLink(p)` / `getInviteParam(k)` | `yield(ZokoGames.invite_link_async(dict), "completed")` / `ZokoGames.get_invite_param(key)` |
| `SDK.game.showInviteButton(p)` / `hideInviteButton()` | `yield(ZokoGames.show_invite_button_async(dict), "completed")` / `ZokoGames.hide_invite_button()` |
| `SDK.game.settings` | `ZokoGames.settings` (`disableChat`, `muteAudio`), 시그널 `settings_changed` |
| `SDK.game.isOffline`, 오프라인 리스너 | `ZokoGames.is_offline`, 시그널 `offline_changed(offline)` |
| `SDK.game.isInstantMultiplayer` / `inviteParams` | `ZokoGames.is_instant_multiplayer` (별칭 `is_instant_join`) / `ZokoGames.invite_params`, 시그널 `join_room(params)` |
| `SDK.user.isUserAccountAvailable` / `systemInfo` | `ZokoGames.is_user_account_available` / `ZokoGames.system_info` |
| `SDK.user.getUser()` | `yield(ZokoGames.get_user_async(), "completed")` |
| `SDK.user.getUserToken(opts)` | `yield(ZokoGames.get_user_token_async(signing_key_type), "completed")` |
| `SDK.user.showAuthPrompt()` | `yield(ZokoGames.show_auth_prompt_async(), "completed")`, 시그널 `auth_changed(user)` |
| `SDK.user.showAccountLinkPrompt()` | `yield(ZokoGames.show_account_link_prompt_async(), "completed")` |
| `SDK.user.listFriends(opts)` | `yield(ZokoGames.list_friends_async(page, size), "completed")` |
| `SDK.user.submitScore(opts)` | `yield(ZokoGames.submit_score_async(encrypted_score, score), "completed")` |
| `SDK.user.encryptScore(score, key)` (1.8.0) | `yield(ZokoGames.encrypt_score_async(score, key), "completed")` |
| `SDK.game.gameId` (1.8.0) | `ZokoGames.game_id` / `get_game_id()` |
| `SDK.data.mirrorIndexedDB()` (1.8.0) | HTML 셸 옵션 `window.ZOKO_MIRROR_INDEXEDDB = true` (Head Include); `ZokoGames.stop_mirror_indexed_db()` |
| `SDK.data.getItem(k)` / `setItem(k, v)` | `ZokoGames.data_get_item(key, default)` / `ZokoGames.data_set_item(key, value)`; 그 외 `data_has_key`, `data_remove_item`, `data_clear` (모두 동기) |
| `SDK.store.*` | `store_get_catalog_items_async`, `store_get_player_inventory_async`, `store_buy_item_async(item_id)`, `store_consume_item_async(sku, qty)`, `store_get_purchase_token_async()`, `is_store_available`, `store_set_sandbox(bool)` (동기); 시그널 `purchase_completed(item_id)`, `purchase_failed(error)` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `yield(ZokoGames.achievements_list_async(), "completed")` / `achievements_unlock_async(key)`, 시그널 `achievement_unlocked(achievement)`; [업적](https://docs.zokogames.com/kr/sdk/achievements) 참고 |
| `SDK.analytics.trackOrder(p, o)` | `yield(ZokoGames.track_order_async(provider, order), "completed")` |
| `SDK.analytics.track(name, params)` (1.7.0) | `ZokoGames.track(name, params)` / `track_async(name, params)` |


오토로드의 시그널: `initialized`, `ad_started`, `ad_finished`, `ad_error(error)`, `auth_changed`, `settings_changed`, `offline_changed`, `join_room`, `purchase_completed`, `purchase_failed`. `ZokoGames.connect("ad_finished", self, "_on_ad_finished")`로 연결하세요. 오류 코드는 `ZokoGames.ERROR_CODES`(모듈별 키를 가진 Dictionary, 예: `ZokoGames.ERROR_CODES.ad`)에 있으며, `ZokoGames.has_error_code(res, "purchaseCancelled")`로 결과를 검사합니다. `unsupportedEngine`은 이 애드온에만 추가된 코드입니다.

**어린이 모드.** 게임이 어린이 모드로 실행될 때(어린이 플래그가 있는 게임이거나 어린이 모드의 플레이어) `ZokoGames.settings.get("kidsMode", false)`가 true입니다. 이때는 채팅, 방, 로그인 프롬프트, 상점 화면을 숨기세요. `ZokoGames.settings.disableChat`도 계속 따르세요. 테스트하려면 `zokogames/simulator/kids_mode`를 켜세요. [어린이 모드](https://docs.zokogames.com/kr/guides/kids-mode)를 참고하세요.

## user://용 클라우드 저장(IndexedDB 미러) {#cloud-save-for-user-indexeddb-mirror}

웹 내보내기는 `user://` 파일을 브라우저의 IndexedDB(`/userfs`)에 보관합니다. 이 파일을 플레이어의 클라우드 저장에 저장하려면 **Export > HTML > Head Include**에 다음 줄을 추가하세요.

```html
<script>window.ZOKO_MIRROR_INDEXEDDB = true;</script>
```

셸은 엔진이 시작되기 전에 클라우드 사본을 복원하고, 이후의 쓰기를 몇 초 안에 업로드합니다. 미러링되는 데이터는 1 MiB를 넘을 수 없으며, 게임에 데이터 모듈이 켜져 있어야 합니다. `ZokoGames.stop_mirror_indexed_db()`는 미러링을 멈춥니다. `ZokoGames.mirror_local_storage({"prefix": "save_"})`는 JavaScript 쪽 `localStorage`를 위한 별도의 미러이며 `user://` 파일은 보지 못합니다.

## 방 데이터 채널 {#room-data-channel}

방 데이터 채널(SDK 1.3.0)을 쓰면 한 방의 플레이어끼리 작은 JSON 메시지를 주고받고, 호스트만 쓸 수 있는 작은 상태를 공유할 수 있습니다. 텍스트 채팅이 아니라 게임 데이터용입니다. 한도와 오류 코드는 Godot 4와 같습니다. [game 모듈](https://docs.zokogames.com/kr/sdk/game#room-data-channel)과 [멀티플레이어 가이드](https://docs.zokogames.com/kr/guides/multiplayer-invites#6-exchange-game-data-in-the-room)를 참고하세요. 페이로드는 JSON으로 브리지를 건너므로 숫자는 `float`로 돌아옵니다. `int()`로 변환하세요.

| JavaScript | Godot |
| --- | --- |
| `room.send(data, { to })` | `ZokoGames.room_send(data, to, cb)` / `room_send_async(data, to)` / `room_send_to(member_id, data, cb)` |
| `room.onMessage(cb)` | 시그널 `room_message(message)` (`from`, `data`, `direct`, `seq`, `ts`) |
| `room.setState(patch)` | `room_set_state(patch, cb)` / `room_set_state_async(patch)` (`null` 값은 키를 제거합니다) |
| `room.getState()`, `room.onState(cb)` | `room_get_state()`, `room_get_state_value(key, default)`; 시그널 `room_state(state, change)` |
| `room.members()`, `room.onMembers(cb)` | `room_get_members()`; 시그널 `room_members(members)` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `room_is_host()`; 시그널 `room_host_changed(host_id, is_host)`; `room_self_id()` |
| `room.addLeftListener(cb)` (1.7.0) | 시그널 `room_left(reason, room_id)` |
| `room.onError(cb)` | 시그널 `room_error(error)` |

```gdscript
extends Node

func _ready() -> void:
	yield(ZokoGames.init_async(), "completed")
	ZokoGames.connect("room_message", self, "_on_message")
	ZokoGames.connect("room_host_changed", self, "_on_host_changed")
	yield(ZokoGames.update_room_async({"roomId": "match-1", "isJoinable": true}), "completed")

func _on_host_changed(_host_id, is_host) -> void:
	if is_host:
		ZokoGames.room_set_state({"turn": "X"})

func _on_message(message) -> void:
	print(message.from, " played cell ", int(message.data.cell))

func play_cell(cell: int) -> void:
	yield(ZokoGames.room_send_async({"cell": cell, "mark": "X"}), "completed")
```

## 배너 {#banners}

배너 사각형은 창 픽셀 단위입니다. 배너가 들어갈 자리에 `ZokoBanner` 노드(`Control`)를 두세요. 이 노드는 (스트레치 모드를 고려한) 화면상의 사각형을 보고하고, `_ready`에서 요청하며, 트리를 떠날 때 스스로 지웁니다.

| 속성 | 의미 |
| --- | --- |
| `container_id` | 배너 id, 기본값 `zoko-banner`. |
| `size_mode` | `responsive`(들어가는 가장 큰 크기) 또는 `728x90`, `300x250`, `320x50`, `468x60`, `320x100` 중 하나. |
| `request_on_ready` | `_ready`에서 자동으로 요청합니다. |
| `show_simulator_placeholder` | 시뮬레이터가 응답하는 동안 자리 표시 사각형을 그립니다. |

직접 하려면: `yield(ZokoGames.request_responsive_banner_async("menu", $BannerSlot.get_global_rect()), "completed")`. 배너는 메뉴 화면에서만 요청하세요.

## 구매 {#purchases}

```gdscript
func buy_first_item() -> void:
	if not ZokoGames.is_store_available:
		return
	var catalog = yield(ZokoGames.store_get_catalog_items_async(), "completed")
	if not catalog.ok or catalog.result.empty():
		return
	var bought = yield(ZokoGames.store_buy_item_async(catalog.result[0].sku), "completed")
	if ZokoGames.has_error_code(bought, "purchaseCancelled"):
		return
	var token = yield(ZokoGames.store_get_purchase_token_async(), "completed")   # send to your server and verify there
```

서버에서 소유권을 검증하세요([인게임 구매](https://docs.zokogames.com/kr/sdk/purchases) 참고). `examples/zoko_store.gd`에 전체 흐름이 있습니다.

## 중요한 HTML5 내보내기 설정 {#html5-export-settings-that-matter}

<!-- search: headings-only -->

- **Custom HTML Shell**: 위와 같이 `res://addons/zokogames/export/zokogames_shell.html`. 캔버스가 프레임을 채우므로 **Canvas Resize Policy**는 `Adaptive`로, Project Settings > Display > Window > Stretch에서는 **Mode**를 `2d` 또는 `viewport`로, aspect를 `expand` 또는 `keep`으로 하세요.
- **스레드.** Godot 3에는 스레드 웹 내보내기가 없으므로 끌 것이 없습니다. 게임 페이지는 cross-origin isolated가 아니므로, 빌드에 `SharedArrayBuffer` 옵션이 보이면 꺼 두세요.
- **GDNative.** 끔. 웹과 호환되는 네이티브 라이브러리를 직접 제공하지 않는 한 네이티브 라이브러리는 웹 빌드에서 실행되지 않습니다. **Export With Debug**: 업로드할 빌드에서는 끔.
- **Focus Canvas on Start**: 켬. **Experimental Virtual Keyboard**: 게임에 휴대폰 텍스트 입력이 있으면 켬.
- **파일 이름.** `index.html`이라는 이름으로 내보내세요. 포털은 아카이브 루트에 `index.html`이 있어야 하고, 내보내기는 나머지 파일 이름을 이것에 맞춰 `index.js`, `index.wasm`, `index.pck`로 지정합니다. 이를 `.br`이나 `.gz`로 **바꾸지 마세요**. 엔진은 일반 이름을 요청합니다.
- **텍스처 압축.** 모든 브라우저에 형식이 있도록 데스크톱(S3TC)과 모바일(ETC2) 모두에 VRAM 압축을 켜세요.
- **크기.** 사용하지 않는 모듈을 끈 커스텀 내보내기 템플릿을 쓰고 `.pck`를 작게 유지하세요. 한도: 파일 1,500개, 압축 해제 시 250 MB, 초기 다운로드 약 50 MB(모바일 20 MB).
- **메모리.** 모바일 브라우저는 힙이 작습니다. 모든 텍스처를 처음에 불러오지 말고 `ResourceLoader.load_interactive`로 레벨을 조금씩 불러오고, 휴대폰에서는 해상도를 제한하세요. [모바일](https://docs.zokogames.com/kr/guides/mobile)을 참고하세요.
- **오디오 잠금 해제.** 브라우저는 첫 클릭이나 키 입력 전까지 오디오를 일시 중단 상태로 둡니다. "클릭하여 플레이" 화면을 보여 주고, `_ready`가 아니라 그 입력에서 음악을 시작하세요.
- **전체 화면.** 포털 프레임 바의 전체 화면 버튼을 사용하세요. `OS.window_fullscreen = true`는 캔버스만 전체 화면으로 만들므로 경쟁하는 버튼을 추가하지 마세요.
- **로딩.** 셸이 이미 엔진 다운로드를 보고하고 엔진이 시작되면 `loadingStop`을 호출합니다. 게임 내 로딩 화면을 더 길게 보여 주려면 `ZokoGames.loading_start()`, `loading_progress(percent)`, `loading_stop()`을 직접 호출하세요.

업로드: **Project > Export**에서 **HTML5** 프리셋을 선택하고 **Export Project...**를 클릭한 뒤, 빈 폴더에 파일 이름 `index.html`로 저장합니다. `index.html`이 아카이브 루트에 오도록 폴더의 내용을 압축하고, 개발자 콘솔에서 업로드한 다음, 먼저 [Preview 도구](https://www.zokogames.com/kr/preview)를 실행하세요.

## 광고 규칙 {#ad-rules}

프리롤은 없습니다. 게임은 시작하기 전에 광고를 요청할 수 없습니다. 미드게임이 유일한 전면 광고 유형이므로, 다른 플랫폼의 전면 광고나 커머셜 브레이크는 미드게임 광고(`request_ad("midgame")`)가 되며, 다른 유형은 `rewarded` 하나뿐입니다. 플레이어가 조작을 시작할 때 `ZokoGames.gameplay_start()`를 호출하세요. 첫 미드게임 광고에는 이것(또는 보이는 페이지 시간 30초)이 필요하며, 로컬 모드에서는 그 전의 미드게임 요청이 `adCooldown`으로 실패합니다. 보상형 광고는 이 때문에 지연되지 않습니다. 자세한 내용: [광고 레퍼런스](https://docs.zokogames.com/kr/sdk/ads#gameplay-first)와 [광고 가이드](https://docs.zokogames.com/kr/guides/ad-monetisation).

## 로컬에서 테스트 {#test-locally}

- **에디터나 데스크톱 실행에서** `ZokoGames.is_simulated`는 true입니다. **Project Settings > zokogames/simulator**에서 시뮬레이터를 조정하세요: `ad_behaviour`(`fill`, `no_fill`, `error`), `ad_duration_seconds`, `adblock`, `disabled`, `account_available`, `logged_in`, `username`, `user_id`, `friend_count`, `mute_audio`, `disable_chat`, `offline`, `store_available`, `verbose`. 클라우드 저장은 `user://zoko_sim_data.json`, 시뮬레이션된 인벤토리는 `user://zoko_sim_inventory.json`에 있습니다. 시뮬레이터는 3분 미드게임 쿨다운을 강제하지 않습니다.
- **`localhost`의 HTML5 내보내기.** 내보내기 폴더를 로컬 웹 서버로 제공하세요(`index.html`을 디스크에서 직접 열면 WebAssembly가 동작하지 않습니다). 브리지가 존재하므로 `is_simulated`는 false이고, JavaScript SDK가 자체 [로컬 모드](https://docs.zokogames.com/kr/getting-started/local-testing)로 실행됩니다.
- **그다음** 로컬 주소로 [Preview 도구](https://www.zokogames.com/kr/preview)를 열고 체크리스트가 채워지는 것을 확인하세요.

## 알려진 함정 {#known-pitfalls}

<!-- search: headings-only -->

- **`sdkNotLoaded`.** 페이지에 SDK 스크립트 태그가 없습니다. 커스텀 셸을 사용하세요.
- **`ZokoGames` 오토로드가 없음.** 플러그인이 활성화되어 있지 않습니다.
- **호출이 `sdkNotInitialized`로 실패함.** 먼저 `yield(ZokoGames.init_async(), "completed")`를 실행하세요.
- **`unsupportedEngine`.** 이 애드온을 Godot 4에서 실행하고 있습니다. Godot 4 애드온을 사용하세요.
- **`yield`가 끝내 반환되지 않음.** 먼저 해제되는 함수(씬 전환)의 `yield`는 버려집니다. 기다리는 코드를 남아 있는 노드에 두거나 콜백 형태를 사용하세요.
- **에디터에서는 되는데 브라우저에서는 안 됨.** 브라우저 콘솔을 열어 `window.ZokoBridge`가 있는지 확인하세요(셸이 정의합니다).
- **광고 후 게임이 일시정지되거나 음소거된 채로 남음.** 광고 중에 다른 무언가가 `get_tree().paused`나 Master 버스를 바꿨습니다. `pause_game_during_ads` 또는 `mute_audio_during_ads`를 `false`로 설정하고 `ad_started`, `ad_finished`, `ad_error`를 직접 처리하세요. `ad_started`에는 `CONNECT_ONESHOT`을 쓰지 마세요. 광고가 실패하면 발생하지 않습니다.
- **배너가 표시되지 않음.** `ZokoBanner` 노드에는 크기가 필요하고 보이는 상태여야 합니다.
- **`user://` 저장이 클라우드에 없음.** `data_set_item`을 쓰거나 위의 IndexedDB 미러를 사용하세요.

## 채팅 신고와 스크린샷 {#chat-reports-and-screenshots}

`ZokoGames.report_chat({"reportedName": "Trixie", "message": "buy gold", "reason": "spam"}, callback)`(또는 `report_chat_async`)은 채팅 신고를 보냅니다. `ZokoGames.set_screenshot_provider(funcref)`는 기본 뷰포트 캡처(초기화 시 `frame_post_draw` 이후에 등록됨)를 대체하고, `clear_screenshot_provider()`는 사용자가 등록한 것을 제거합니다. 에디터 시뮬레이터는 둘 다 받아들입니다.

## 커스텀 이벤트 {#custom-events}

```gdscript
ZokoGames.track("level_complete", {"level": 3, "value": 1250})   # value is summed per event name
```

실행 후 결과를 기다리지 않으며 호출은 예외를 던지지 않습니다. 포털은 이벤트 이름별로 숫자 `value`를 합산하고, 호출 수, 플레이어 수, 합계를 개발자 콘솔의 **게임 자체 이벤트**에 표시합니다(플레이어의 분석 동의가 필요합니다. [분석](https://docs.zokogames.com/kr/sdk/analytics#custom-events-track) 참고). 이름과 키는 `[a-z][a-z0-9_]{0,39}` 형식이어야 하며 매개변수는 최대 10개입니다. 처리되지 않은 오류는 SDK가 자동으로 보고하므로 따로 호출할 것이 없습니다.

## 다음 {#next}

- [빌드 검증 규칙](https://docs.zokogames.com/kr/requirements/build-validation)과 [출시 체크리스트](https://docs.zokogames.com/kr/requirements/checklist)에 맞춰 빌드를 확인하세요.
- 업로드와 게시: [제출 안내](https://docs.zokogames.com/kr/getting-started/submission-walkthrough).
- Godot 4 프로젝트: [Godot](https://docs.zokogames.com/kr/engines/godot). 다른 엔진과 공통 규칙: [엔진 개요](https://docs.zokogames.com/kr/engines/overview).
