# Godot 3 {#godot-3}

Addon `zokogames` (`packages/sdk-engines/godot3/addons/zokogames`) nhắm tới các bản xuất HTML5 của **Godot 3** (mục tiêu là 3.5 và 3.6 LTS, 3.3 và 3.4 cũng nên chạy được, 3.0 đến 3.2 không được hỗ trợ). Nó có cùng API công khai như [addon Godot 4](https://docs.zokogames.com/vn/engines/godot): cùng autoload `ZokoGames`, cùng tên phương thức và cùng signal, nên một dự án có thể chuyển qua lại giữa hai bên. Nó được viết bằng GDScript 1 (không có `await`, không có lambda) và gọi JavaScript SDK qua singleton `JavaScript`, dùng một cầu nối nhỏ (`window.ZokoBridge`) được định nghĩa trong HTML shell của bản xuất. Ngoài trình duyệt (trong trình soạn thảo, hoặc chạy trên desktop), một trình giả lập tích hợp sẽ trả lời thay, nên cùng một mã chạy ở mọi nơi. Các thuật ngữ như "midgame" và "rewarded" nằm trong [bảng thuật ngữ](https://docs.zokogames.com/vn/getting-started/glossary).

> [!NOTE]
> Trạng thái (1.8.0): đã chạy headless trong editor Godot 3.6.3 chính thức trên macOS. Addon import không có lỗi hay cảnh báo (cảnh báo được coi là lỗi), bật plugin sẽ đăng ký autoload, mọi phương thức công khai và signal hoạt động đúng như tài liệu ở chế độ giả lập, và HTML5 export có chứa cầu nối và chạy được trong trình duyệt. Godot 3.3 đến 3.5 chưa được xác minh, và chưa có lần chạy nào với cổng thật. Nếu lần import đầu tiên thất bại, hãy gửi phiên bản Godot và lỗi chính xác tới [bộ phận hỗ trợ](https://docs.zokogames.com/vn/business/support).

Trên Godot 4, addon này từ chối khởi động (`init()` thất bại với `unsupportedEngine`); ở đó hãy dùng [trang Godot 4](https://docs.zokogames.com/vn/engines/godot).

## Cài đặt {#install}

Tải plugin Godot 3: [/sdk-engines/zokogames-godot3-1.8.1.zip](https://www.zokogames.com/sdk-engines/zokogames-godot3-1.8.1.zip) (cùng các tệp với thư mục trong kho mã).

[/sdk-engines/godot3.zip](https://www.zokogames.com/sdk-engines/godot3.zip) luôn là phiên bản mới nhất. Checksum: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Danh mục mọi gói engine kèm phiên bản, kích thước và SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json). Mã nguồn cũng được đăng tại [github.com/zokogames/zokogames-godot3](https://github.com/zokogames/zokogames-godot3). Plugin cũng có trên Godot Asset Library (asset 5620): tìm ZokoGames trong tab AssetLib của trình soạn thảo (Godot 3), hoặc cài từ tệp zip.

1. Giải nén bản tải về và sao chép thư mục `addons/zokogames` của nó vào thư mục `res://addons/` của dự án (tạo `addons` nếu chưa có). Nó gồm `plugin.cfg`, `plugin.gd`, `zokogames.gd` (autoload), `zoko_banner.gd` và `export/zokogames_shell.html`.
2. **Project > Project Settings > Plugins**: bật **ZokoGames**. Thao tác này đăng ký autoload `ZokoGames` (`res://addons/zokogames/zokogames.gd`) và các thiết lập `zokogames/simulator/*`.
3. **Project > Export**: thêm một preset **HTML5** và đặt **Custom HTML Shell** (tab Options > HTML) thành `res://addons/zokogames/export/zokogames_shell.html`. Shell tải `https://sdk.zokogames.com/zokogames-sdk-v1.js` trước engine, tạo `window.ZokoBridge`, và báo cáo lượng tải engine tới thanh tải của cổng. Với shell của riêng bạn, hãy thêm thẻ script vào `<head>` và sao chép khối cầu nối từ shell được cung cấp.
4. `yield(ZokoGames.init_async(), "completed")` một lần khi khởi động, trước mọi lệnh gọi khác.
5. Tùy chọn: thêm một node `ZokoBanner` (`zoko_banner.gd`) lên vùng bạn có thể dành cho banner. Thư mục `examples/` cạnh addon có `zoko_demo.gd` và `zoko_store.gd`.

> [!IMPORTANT]
> Nếu không có shell tùy chỉnh, `window.ZokoBridge` không tồn tại. Addon ghi một cảnh báo và lùi về trình giả lập, nên game vẫn chạy nhưng không dùng quảng cáo, người dùng hay bản lưu thật.

### Bộ khởi đầu {#starter-kit}

Một dự án Godot 3 sẵn sàng với addon, shell và một cảnh demo nhỏ: [/starter-kits/godot3.zip](https://www.zokogames.com/starter-kits/godot3.zip). Xem trang [bộ khởi đầu](https://docs.zokogames.com/vn/getting-started/starter-kits).

## Điểm khác so với Godot 4 {#what-differs-from-godot-4}

| Godot 4 | Godot 3 |
| --- | --- |
| `await ZokoGames.get_user_async()` | `yield(ZokoGames.get_user_async(), "completed")`, trả về cùng Dictionary |
| `callback: Callable` | `callback`: a `FuncRef`, `funcref(self, "_on_done")` |
| `ZokoGames.ad_started.connect(f)` | `ZokoGames.connect("ad_started", self, "_on_ad_started")` |
| Addon tạm dừng cây và tắt tiếng bus Master khi quảng cáo phát và áp dụng cài đặt tắt tiếng của cổng (`pause_game_during_ads`, `mute_audio_during_ads`, `follow_portal_mute`, mặc định đều là `true`) | Cùng thuộc tính và giá trị mặc định; các node của riêng bạn cần phản ứng trong lúc quảng cáo phát phải có `pause_mode = PAUSE_MODE_PROCESS` |
| `JavaScriptBridge` | `JavaScript` |

Một lệnh gọi `_async` trả về một đối tượng yêu cầu (có `id`, `done`, `result` và signal `completed(result)`), và `yield(..., "completed")` cho ra Dictionary kết quả. Mọi yêu cầu hoàn tất ở một khung hình sau, nên `yield` không thể bỏ lỡ nó.

## Một script hoạt động được {#a-working-script}

Đặt đoạn này vào một script trên một node ở cảnh đầu tiên của bạn (hoặc vào autoload của riêng bạn). Nó bao gồm khởi tạo, quảng cáo midgame, quảng cáo rewarded, bắt đầu và dừng gameplay, lưu và tải, và gửi điểm lên bảng xếp hạng.

```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
```

## Điểm số bảng xếp hạng và mã hóa {#leaderboard-scores-and-encryption}

Một bảng **có** khóa mã hóa chỉ tính payload được mã hóa đúng ([bảng xếp hạng](https://docs.zokogames.com/vn/sdk/leaderboards#client-submission)). Từ plugin 1.8.0, `encrypt_score_async(score, KEY)` niêm phong điểm số bằng khóa bảng của bạn và trả về payload cho `submit_score_async`; `""` chỉ dùng được với bảng không có khóa.

```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)
```

Đối số thứ ba tùy chọn `earned_at` (mili giây Unix, mặc định 0 cho một lượt chơi trực tiếp) niêm phong bản sao bị trì hoãn của một điểm số. Khóa nằm trong bản build chỉ ngăn được việc sửa tùy tiện, không ngăn được người chơi quyết tâm: khi có lợi ích thật, hãy tính điểm trên máy chủ của bạn và dùng API máy chủ.

## Các lệnh gọi hoạt động thế nào {#how-calls-work}

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

Tên trong GDScript dùng snake_case. Mọi phương thức giao tiếp với cổng đều có hai dạng:

| Dạng | Ví dụ | Dùng cho |
| --- | --- | --- |
| Callback | `ZokoGames.get_user(callback)` | Các lệnh gọi bắn rồi quên. `FuncRef` là tùy chọn và đứng cuối, trừ trong `store_get_catalog_items(callback, limit, offset)` và `store_get_player_inventory(callback, limit, offset)`, nơi nó đứng đầu, và trong `get_user_token(signing_key_type, callback)`. |
| Yêu cầu | `yield(ZokoGames.get_user_async(), "completed")` | Mã viết thẳng một mạch. Tên kết thúc bằng `_async`. |

Cả hai đều trả về một Dictionary, `{ "ok": true, "result": <value> }` hoặc `{ "ok": false, "error": { "code": "...", "message": "..." } }` (`request_ad` nhận một Dictionary các FuncRef thay vào đó). Mọi phương thức nằm trực tiếp trên autoload; không có các đối tượng con `ad.`, `game.` hay `user.`.

| JavaScript | GDScript |
| --- | --- |
| `SDK.init()` | `yield(ZokoGames.init_async(), "completed")` or `ZokoGames.init(callback)`; signal `initialized(ok)` |
| `SDK.environment` | `ZokoGames.environment` (`"local"`, `"zokogames"` or `"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})` (FuncRefs) or `yield(ZokoGames.request_ad_async(type), "completed")` |
| `SDK.ad.hasAdblock()` | `ZokoGames.has_adblock(callback)` or `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()` (and `_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`), signal `settings_changed` |
| `SDK.game.isOffline`, offline listener | `ZokoGames.is_offline`, signal `offline_changed(offline)` |
| `SDK.game.isInstantMultiplayer` / `inviteParams` | `ZokoGames.is_instant_multiplayer` (alias `is_instant_join`) / `ZokoGames.invite_params`, signal `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")`, signal `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 shell option `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)`; also `data_has_key`, `data_remove_item`, `data_clear` (all synchronous) |
| `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)` (synchronous); signals `purchase_completed(item_id)`, `purchase_failed(error)` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `yield(ZokoGames.achievements_list_async(), "completed")` / `achievements_unlock_async(key)`, signal `achievement_unlocked(achievement)`; see [achievements](https://docs.zokogames.com/vn/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)` |


Các signal trên autoload: `initialized`, `ad_started`, `ad_finished`, `ad_error(error)`, `auth_changed`, `settings_changed`, `offline_changed`, `join_room`, `purchase_completed`, `purchase_failed`. Kết nối chúng bằng `ZokoGames.connect("ad_finished", self, "_on_ad_finished")`. Các mã lỗi nằm trong `ZokoGames.ERROR_CODES` (một Dictionary theo khóa mô-đun, ví dụ `ZokoGames.ERROR_CODES.ad`); `ZokoGames.has_error_code(res, "purchaseCancelled")` kiểm tra một kết quả. `unsupportedEngine` là mã bổ sung trong addon này.

**Chế độ trẻ em.** `ZokoGames.settings.get("kidsMode", false)` là true khi game chạy ở chế độ trẻ em (game có cờ trẻ em, hoặc người chơi đang ở chế độ trẻ em); khi đó hãy ẩn chat, phòng, lời nhắc đăng nhập và màn hình cửa hàng. Hãy tiếp tục tôn trọng cả `ZokoGames.settings.disableChat`. Để kiểm thử, hãy bật `zokogames/simulator/kids_mode`. Xem [chế độ trẻ em](https://docs.zokogames.com/vn/guides/kids-mode).

## Lưu đám mây cho user:// (bản phản chiếu IndexedDB) {#cloud-save-for-user-indexeddb-mirror}

Bản xuất web giữ các tệp `user://` trong IndexedDB của trình duyệt (`/userfs`). Để lưu chúng vào bản lưu đám mây của người chơi, hãy thêm dòng này vào **Export > HTML > Head Include**:

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

Shell khôi phục bản sao đám mây trước khi engine khởi động và tải các lần ghi sau đó lên trong vài giây. Dữ liệu được phản chiếu không được vượt quá 1 MiB, và mô-đun dữ liệu phải được bật cho game. `ZokoGames.stop_mirror_indexed_db()` dừng việc phản chiếu. `ZokoGames.mirror_local_storage({"prefix": "save_"})` là bản phản chiếu riêng cho `localStorage` phía JavaScript; nó không thấy các tệp `user://`.

## Kênh dữ liệu phòng {#room-data-channel}

Kênh dữ liệu phòng (SDK 1.3.0) cho phép những người chơi trong cùng một phòng trao đổi các thông điệp JSON nhỏ và chia sẻ một trạng thái nhỏ mà chỉ host được ghi. Nó dành cho dữ liệu game, không phải chat văn bản. Giới hạn và mã lỗi giống như trong Godot 4: xem [mô-đun game](https://docs.zokogames.com/vn/sdk/game#room-data-channel) và [hướng dẫn multiplayer](https://docs.zokogames.com/vn/guides/multiplayer-invites#6-exchange-game-data-in-the-room). Payload đi qua cầu nối dưới dạng JSON (số trả về là `float`; hãy chuyển bằng `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)` | signal `room_message(message)` (`from`, `data`, `direct`, `seq`, `ts`) |
| `room.setState(patch)` | `room_set_state(patch, cb)` / `room_set_state_async(patch)` (giá trị `null` xóa khóa) |
| `room.getState()`, `room.onState(cb)` | `room_get_state()`, `room_get_state_value(key, default)`; signal `room_state(state, change)` |
| `room.members()`, `room.onMembers(cb)` | `room_get_members()`; signal `room_members(members)` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `room_is_host()`; signal `room_host_changed(host_id, is_host)`; `room_self_id()` |
| `room.addLeftListener(cb)` (1.7.0) | signal `room_left(reason, room_id)` |
| `room.onError(cb)` | signal `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")
```

## Banner {#banners}

Các hình chữ nhật của banner tính theo pixel cửa sổ. Hãy thả một node `ZokoBanner` (một `Control`) vào nơi banner cần nằm; nó báo cáo hình chữ nhật trên màn hình của mình (có tính đến chế độ stretch), yêu cầu ở `_ready`, và tự xóa khi rời khỏi cây.

| Thuộc tính | Ý nghĩa |
| --- | --- |
| `container_id` | Id banner, mặc định `zoko-banner`. |
| `size_mode` | `responsive` (kích thước lớn nhất vừa vặn) hoặc một trong `728x90`, `300x250`, `320x50`, `468x60`, `320x100`. |
| `request_on_ready` | Tự động yêu cầu trong `_ready`. |
| `show_simulator_placeholder` | Vẽ một hình chữ nhật giữ chỗ khi trình giả lập trả lời. |

Làm thủ công: `yield(ZokoGames.request_responsive_banner_async("menu", $BannerSlot.get_global_rect()), "completed")`. Chỉ yêu cầu banner ở các màn hình menu.

## Mua hàng {#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
```

Hãy xác minh quyền sở hữu trên máy chủ của bạn (xem [mua hàng trong game](https://docs.zokogames.com/vn/sdk/purchases)). `examples/zoko_store.gd` là luồng đầy đủ.

## Các thiết lập xuất HTML5 quan trọng {#html5-export-settings-that-matter}

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

- **Custom HTML Shell**: `res://addons/zokogames/export/zokogames_shell.html`, như ở trên. Canvas phủ kín khung, vì vậy hãy dùng **Canvas Resize Policy** là `Adaptive` và, trong Project Settings > Display > Window > Stretch, **Mode** là `2d` hoặc `viewport` với aspect `expand` hoặc `keep`.
- **Thread.** Godot 3 không có bản xuất web đa luồng, nên không có gì để bỏ tích. Trang game không được cách ly cross-origin, vì vậy hãy để tắt mọi tùy chọn `SharedArrayBuffer` nếu bản build của bạn hiển thị một tùy chọn như vậy.
- **GDNative.** Tắt. Thư viện native không chạy trong bản build web trừ khi bạn kèm một thư viện tương thích web. **Export With Debug**: tắt cho bản build được tải lên.
- **Focus Canvas on Start**: bật. **Experimental Virtual Keyboard**: bật nếu game có nhập văn bản trên điện thoại.
- **Tên tệp.** Hãy xuất ra một tệp tên `index.html`: cổng cần `index.html` ở gốc của tệp lưu trữ, và bản xuất đặt tên các tệp còn lại theo nó: `index.js`, `index.wasm`, `index.pck`. **Đừng** đổi tên chúng thành `.br` hoặc `.gz`: engine yêu cầu tên thường.
- **Nén texture.** Hãy bật nén VRAM cho cả desktop (S3TC) và di động (ETC2) để mọi trình duyệt đều có một định dạng dùng được.
- **Dung lượng.** Dùng một mẫu xuất tùy chỉnh với các mô-đun không dùng bị tắt và giữ `.pck` nhỏ. Giới hạn: 1.500 tệp, 250 MB khi giải nén, khoảng 50 MB tải ban đầu (20 MB cho di động).
- **Bộ nhớ.** Trình duyệt di động có heap nhỏ; hãy tải các màn chơi theo từng phần bằng `ResourceLoader.load_interactive` thay vì tải trước mọi texture, và giới hạn độ phân giải trên điện thoại, xem [di động](https://docs.zokogames.com/vn/guides/mobile).
- **Mở khóa âm thanh.** Trình duyệt giữ âm thanh ở trạng thái tạm dừng cho tới lần nhấp hoặc nhấn phím đầu tiên. Hãy hiển thị màn hình "nhấp để chơi" và bắt đầu nhạc từ lần nhập đó, không phải trong `_ready`.
- **Toàn màn hình.** Dùng nút toàn màn hình trên thanh khung của cổng; `OS.window_fullscreen = true` chỉ phóng canvas của bạn, vì vậy đừng thêm một nút cạnh tranh.
- **Tải.** Shell đã báo cáo lượng tải engine và gọi `loadingStop` khi engine đã khởi động. Với một màn hình tải dài hơn trong game, hãy tự gọi `ZokoGames.loading_start()`, `loading_progress(percent)` và `loading_stop()`.

Tải lên: **Project > Export**, chọn preset **HTML5**, nhấp **Export Project...**, và lưu vào một thư mục trống với tên tệp `index.html`. Nén nội dung thư mục thành zip để `index.html` nằm ở gốc kho, tải nó lên trong bảng điều khiển nhà phát triển, và chạy [công cụ Preview](https://www.zokogames.com/vn/preview) trước.

## Quy tắc quảng cáo {#ad-rules}

Không có preroll: game của bạn không thể yêu cầu quảng cáo trước khi game bắt đầu. Midgame là loại interstitial duy nhất, nên quảng cáo interstitial hoặc commercial break từ nền tảng khác trở thành quảng cáo midgame (`request_ad("midgame")`); loại khác duy nhất là `rewarded`. Hãy gọi `ZokoGames.gameplay_start()` khi người chơi nắm quyền điều khiển: quảng cáo midgame đầu tiên cần nó (hoặc 30 giây thời gian hiển thị trang), và ở chế độ cục bộ một yêu cầu midgame trước đó thất bại với `adCooldown`. Quảng cáo rewarded không bị giữ lại vì điều này. Chi tiết: [tài liệu tham khảo quảng cáo](https://docs.zokogames.com/vn/sdk/ads#gameplay-first) và [hướng dẫn quảng cáo](https://docs.zokogames.com/vn/guides/ad-monetisation).

## Kiểm thử cục bộ {#test-locally}

- **Trong editor hoặc khi chạy trên desktop**, `ZokoGames.is_simulated` là true. Hãy tinh chỉnh trình giả lập trong **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` và `verbose`. Bản lưu đám mây nằm trong `user://zoko_sim_data.json`, kho đồ mô phỏng trong `user://zoko_sim_inventory.json`. Trình giả lập không áp dụng thời gian chờ midgame ba phút.
- **Một bản xuất HTML5 trên `localhost`.** Hãy phục vụ thư mục xuất từ một máy chủ web cục bộ (mở `index.html` từ đĩa không hoạt động với WebAssembly). Cầu nối tồn tại, nên `is_simulated` là false và JavaScript SDK chạy [chế độ cục bộ](https://docs.zokogames.com/vn/getting-started/local-testing) của chính nó.
- **Sau đó** mở [công cụ Preview](https://www.zokogames.com/vn/preview) với địa chỉ cục bộ của bạn và xem danh sách kiểm tra lần lượt được tích.

## Lỗi thường gặp {#known-pitfalls}

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

- **`sdkNotLoaded`.** Trang không có thẻ script SDK; hãy dùng shell tùy chỉnh.
- **Thiếu autoload `ZokoGames`.** Plugin chưa được bật.
- **Các lệnh gọi thất bại với `sdkNotInitialized`.** Hãy `yield(ZokoGames.init_async(), "completed")` trước.
- **`unsupportedEngine`.** Bạn đang chạy addon này trên Godot 4; hãy dùng addon Godot 4.
- **Một `yield` không bao giờ trả về.** Một `yield` trong hàm bị giải phóng trước (do đổi cảnh) sẽ bị bỏ; hãy giữ mã chờ trong một node tồn tại lâu, hoặc dùng dạng callback.
- **Chạy được trong editor, không chạy trong trình duyệt.** Hãy mở console của trình duyệt và kiểm tra `window.ZokoBridge` có tồn tại không (shell định nghĩa nó).
- **Game vẫn bị tạm dừng hoặc tắt tiếng sau quảng cáo.** Có thứ khác đã đổi `get_tree().paused` hoặc bus Master trong lúc quảng cáo. Hãy đặt `pause_game_during_ads` hoặc `mute_audio_during_ads` thành `false` và tự xử lý `ad_started`, `ad_finished` và `ad_error`. Đừng dùng `CONNECT_ONESHOT` cho `ad_started`: khi quảng cáo thất bại, nó không bao giờ kích hoạt.
- **Banner không bao giờ hiện.** Node `ZokoBanner` cần có kích thước và phải hiển thị.
- **Các bản lưu `user://` không nằm trên đám mây.** Hãy dùng `data_set_item`, hoặc bản phản chiếu IndexedDB ở trên.

## Báo cáo chat và ảnh chụp màn hình {#chat-reports-and-screenshots}

`ZokoGames.report_chat({"reportedName": "Trixie", "message": "buy gold", "reason": "spam"}, callback)` (hoặc `report_chat_async`) gửi một báo cáo chat. `ZokoGames.set_screenshot_provider(funcref)` thay thế bản chụp viewport mặc định (được đăng ký khi khởi tạo sau `frame_post_draw`), và `clear_screenshot_provider()` gỡ bản của bạn. Trình giả lập trong editor chấp nhận cả hai.

## Sự kiện tùy chỉnh {#custom-events}

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

Gọi và quên; lệnh gọi không bao giờ ném lỗi. Cổng cộng dồn `value` dạng số theo từng tên sự kiện và hiển thị số lần gọi, số người chơi và tổng trong **Sự kiện riêng của game bạn** ở bảng điều khiển nhà phát triển (cần người chơi đồng ý phân tích; xem [phân tích](https://docs.zokogames.com/vn/sdk/analytics#custom-events-track)). Tên và các khóa khớp `[a-z][a-z0-9_]{0,39}`, tối đa 10 tham số. Lỗi không bắt được do SDK tự báo cáo, nên không cần gọi gì cho chúng.

## Tiếp theo {#next}

- Kiểm tra bản build của bạn theo [quy tắc xác thực build](https://docs.zokogames.com/vn/requirements/build-validation) và [danh sách kiểm tra ra mắt](https://docs.zokogames.com/vn/requirements/checklist).
- Tải lên và xuất bản: [hướng dẫn gửi game](https://docs.zokogames.com/vn/getting-started/submission-walkthrough).
- Các dự án Godot 4: [Godot](https://docs.zokogames.com/vn/engines/godot). Các engine khác và quy tắc chung: [tổng quan về engine](https://docs.zokogames.com/vn/engines/overview).
