From 24c1b3b4161c96cff32ddf8bd8228c674dd7bc41 Mon Sep 17 00:00:00 2001 From: shen <> Date: Mon, 19 Oct 2026 07:13:56 -0700 Subject: [PATCH] Integrate AVA2 native shop and refine mobile controls and locale tooltips --- audit/evidence/itemshop/cleanup.json | 11 + audit/evidence/itemshop/db-faults.json | 18 + audit/evidence/itemshop/final-widgets.json | 1 + audit/evidence/itemshop/integer-discount.json | 1 + audit/evidence/itemshop/lost-reply.json | 27 + audit/evidence/itemshop/minimap-tooltips.json | 1 + audit/evidence/itemshop/nonstackable.json | 10 + .../evidence/itemshop/original-catalogue.json | 1 + audit/evidence/itemshop/server-tests.json | 126 + audit/evidence/itemshop/transactions.json | 57 + audit/evidence/itemshop/ui.json | 1 + audit/evidence/itemshop/widget-events.json | 1 + audit/evidence/mobile-ui/acceptance.json | 16 + audit/history.jsonl | 2 + docs/ANDROID-TESTING.md | 22 + docs/AVA2-ITEMSHOP.md | 94 + docs/AVA2-PARITY-PLAN.md | 7 + src/host/sdl_window.cpp | 6 +- src/host/touch_controller.h | 80 +- .../ScriptLib/Ava2ItemShopNewSource.inc | 2514 +++++++++++++++++ src/platform/ScriptLib/Ava2ItemShopScript.inc | 248 ++ .../ScriptLib/MinimapOuterRingScript.inc | 10 +- src/platform/ScriptLib/MobileHUDScript.inc | 56 +- src/platform/ScriptLib/PythonBoot.cpp | 23 + src/platform/ScriptLib/PythonBoot.h | 2 + .../UserInterface/PythonNetworkStream.cpp | 12 +- src/port/UserInterface/PythonNetworkStream.h | 1 + .../PythonNetworkStreamPhaseGame.cpp | 10 +- ...ythonNetworkStreamPhaseGameAva2Queries.cpp | 10 + tests/port/port_login_flow_test.cpp | 68 +- tests/wiki/test_itemshop.py | 75 + tests/wiki/test_minimap_buttons.py | 28 +- tools/ava2-native/import_sources.py | 2 +- tools/ava2-native/sources.json | 8 + tools/ava2-native/stage_resources.py | 2 +- tools/server/ava2-items/make_items.py | 2 +- 36 files changed, 3501 insertions(+), 52 deletions(-) create mode 100644 audit/evidence/itemshop/cleanup.json create mode 100644 audit/evidence/itemshop/db-faults.json create mode 100644 audit/evidence/itemshop/final-widgets.json create mode 100644 audit/evidence/itemshop/integer-discount.json create mode 100644 audit/evidence/itemshop/lost-reply.json create mode 100644 audit/evidence/itemshop/minimap-tooltips.json create mode 100644 audit/evidence/itemshop/nonstackable.json create mode 100644 audit/evidence/itemshop/original-catalogue.json create mode 100644 audit/evidence/itemshop/server-tests.json create mode 100644 audit/evidence/itemshop/transactions.json create mode 100644 audit/evidence/itemshop/ui.json create mode 100644 audit/evidence/itemshop/widget-events.json create mode 100644 audit/evidence/mobile-ui/acceptance.json create mode 100644 docs/AVA2-ITEMSHOP.md create mode 100644 src/platform/ScriptLib/Ava2ItemShopNewSource.inc create mode 100644 src/platform/ScriptLib/Ava2ItemShopScript.inc create mode 100644 tests/wiki/test_itemshop.py diff --git a/audit/evidence/itemshop/cleanup.json b/audit/evidence/itemshop/cleanup.json new file mode 100644 index 00000000..721f0300 --- /dev/null +++ b/audit/evidence/itemshop/cleanup.json @@ -0,0 +1,11 @@ +{ + "active_original_products": 49, + "source_products": 217, + "qa_coins": 0, + "qa_orders": 0, + "qa_awards": 0, + "test_stack": 0, + "test_triggers": 0, + "game_sha256": "56975b48aa2fd40389c57eab84d017b0a2518cf6e1b573d967bf239f4ae04aba", + "db_sha256": "dc940401fe6ccc3410c8d90ce98d2a5bad2e2c023279665bcd664c008d011699" +} diff --git a/audit/evidence/itemshop/db-faults.json b/audit/evidence/itemshop/db-faults.json new file mode 100644 index 00000000..b9279442 --- /dev/null +++ b/audit/evidence/itemshop/db-faults.json @@ -0,0 +1,18 @@ +[ + { + "case": "wallet lock timeout", + "status": 6, + "elapsed_seconds": 2.17, + "unchanged": true + }, + { + "case": "SQL connection lost before commit", + "status": 6, + "unchanged": true + }, + { + "case": "SQL reconnect and persistent order replay", + "status": 0, + "unchanged": true + } +] diff --git a/audit/evidence/itemshop/final-widgets.json b/audit/evidence/itemshop/final-widgets.json new file mode 100644 index 00000000..275b71e8 --- /dev/null +++ b/audit/evidence/itemshop/final-widgets.json @@ -0,0 +1 @@ +{"catalogue": 49, "pending": null, "quantity_before": 1, "scroll_before": 0.0, "balance": 0, "scroll_after": 0.06876790830945559, "quantity_after": 2, "widget_bound_confirmation": true, "all_icons": true} \ No newline at end of file diff --git a/audit/evidence/itemshop/integer-discount.json b/audit/evidence/itemshop/integer-discount.json new file mode 100644 index 00000000..9fb1edf0 --- /dev/null +++ b/audit/evidence/itemshop/integer-discount.json @@ -0,0 +1 @@ +{"quote": [900001, 1, 29, 71084], "confirmation": ["\u8d2d\u4e70 \u7269\u54c1\u5c5e\u6027\u8f6c\u6362\u79d8\u7c4d\uff1f", "\u4ef7\u683c\uff1a29 \u9f99\u5e01"], "display": ["\u539f\u4ef7 58\uff08\u4f18\u60e0 50%\uff09", " 29 \u9f99\u5e01"], "confirm_button": "\u786e\u8ba4"} \ No newline at end of file diff --git a/audit/evidence/itemshop/lost-reply.json b/audit/evidence/itemshop/lost-reply.json new file mode 100644 index 00000000..18f95128 --- /dev/null +++ b/audit/evidence/itemshop/lost-reply.json @@ -0,0 +1,27 @@ +{ + "at": 145.56300354003906, + "balance": 9749, + "dropped": [ + { + "status": 0, + "token": "25f1ade2e0549b0e3f9e899b8dd84b1e", + "balance": 9749, + "time": 123.39399719238281 + } + ], + "pending": null, + "replies": [ + [ + "25f1ade2e0549b0e3f9e899b8dd84b1e", + 0, + 9749 + ] + ], + "assertions": { + "one_additional_order": true, + "one_additional_unit": true, + "deducted_exactly": 29, + "same_token_replayed": true, + "pending_cleared": true + } +} diff --git a/audit/evidence/itemshop/minimap-tooltips.json b/audit/evidence/itemshop/minimap-tooltips.json new file mode 100644 index 00000000..ba53e1ca --- /dev/null +++ b/audit/evidence/itemshop/minimap-tooltips.json @@ -0,0 +1 @@ +{"labels": ["[F5] \u526f\u672c\u4fe1\u606f", "[F6] \u6218\u6597\u901a\u884c\u8bc1", "[F7] \u751f\u7269\u5b66\u5bb6", "[F8] \u70b9\u51fb\u6362\u7ebf"], "passed": true, "encoding": "native locale bridge"} \ No newline at end of file diff --git a/audit/evidence/itemshop/nonstackable.json b/audit/evidence/itemshop/nonstackable.json new file mode 100644 index 00000000..1dbb21ee --- /dev/null +++ b/audit/evidence/itemshop/nonstackable.json @@ -0,0 +1,10 @@ +{ + "original_product": 170, + "vnum": 70002, + "quantity": 2, + "paid": 198, + "wallet_after": 0, + "award_rows": 2, + "each_award_count": 1, + "prototype_lookup_correct_after_sort": true +} diff --git a/audit/evidence/itemshop/original-catalogue.json b/audit/evidence/itemshop/original-catalogue.json new file mode 100644 index 00000000..fbddd0db --- /dev/null +++ b/audit/evidence/itemshop/original-catalogue.json @@ -0,0 +1 @@ +{"count": 49, "all_prototypes_and_icons": true, "offers": [{"price": 99, "vnum": 70002, "id": 170, "icon": "icon\\item\\70002.tga"}, {"price": 99, "vnum": 71234, "id": 172, "icon": "icon\\item\\71234.tga"}, {"price": 99, "vnum": 71254, "id": 177, "icon": "icon\\item\\71254.tga"}, {"price": 349, "vnum": 71502, "id": 3, "icon": "icon\\item\\71502.tga"}, {"price": 349, "vnum": 71505, "id": 6, "icon": "icon\\item\\71505.tga"}, {"price": 349, "vnum": 71508, "id": 9, "icon": "icon\\item\\71508.tga"}, {"price": 349, "vnum": 71511, "id": 12, "icon": "icon\\item\\71511.tga"}, {"price": 60, "vnum": 54003, "id": 78, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54006, "id": 79, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54009, "id": 80, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54012, "id": 81, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54015, "id": 82, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54018, "id": 83, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54021, "id": 84, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54024, "id": 85, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54027, "id": 86, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54030, "id": 87, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54033, "id": 88, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54036, "id": 89, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54039, "id": 90, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54042, "id": 91, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54045, "id": 92, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54048, "id": 93, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54051, "id": 94, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54054, "id": 95, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54057, "id": 96, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54060, "id": 97, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54063, "id": 98, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54066, "id": 99, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54069, "id": 100, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54072, "id": 101, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54075, "id": 102, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54078, "id": 103, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54126, "id": 183, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54129, "id": 184, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54132, "id": 185, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54135, "id": 186, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54138, "id": 187, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54141, "id": 188, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54144, "id": 189, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54147, "id": 190, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54150, "id": 191, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54153, "id": 192, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54156, "id": 193, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54159, "id": 194, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54162, "id": 195, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54168, "id": 197, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54171, "id": 198, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54174, "id": 199, "icon": "icon\\item\\54126.tga"}], "categories": [1, 2, 3, 5]} \ No newline at end of file diff --git a/audit/evidence/itemshop/server-tests.json b/audit/evidence/itemshop/server-tests.json new file mode 100644 index 00000000..26e50f0b --- /dev/null +++ b/audit/evidence/itemshop/server-tests.json @@ -0,0 +1,126 @@ +[ + { + "script": "test_applies.py", + "passed": true + }, + { + "script": "test_attr_lock.py", + "passed": true + }, + { + "script": "test_attr_lock_snapshots.py", + "passed": true + }, + { + "script": "test_attr_lock_use.py", + "passed": true + }, + { + "script": "test_attr_lock_views.py", + "passed": true + }, + { + "script": "test_ava2_channel_registry.py", + "passed": true + }, + { + "script": "test_ava2_chest.py", + "passed": true + }, + { + "script": "test_ava2_dungeon_track.py", + "passed": true + }, + { + "script": "test_ava2_pickup.py", + "passed": true + }, + { + "script": "test_ava2_ticket_shop.py", + "passed": true + }, + { + "script": "test_ava2_track.py", + "passed": true + }, + { + "script": "test_battlepass.py", + "passed": true + }, + { + "script": "test_bosses.py", + "passed": true + }, + { + "script": "test_calendar.py", + "passed": true + }, + { + "script": "test_chest.py", + "passed": true + }, + { + "script": "test_cmd_prefix.py", + "passed": true + }, + { + "script": "test_costume_attr.py", + "passed": true + }, + { + "script": "test_drops.py", + "passed": true + }, + { + "script": "test_itemshop.py", + "passed": true + }, + { + "script": "test_mount.py", + "passed": true + }, + { + "script": "test_native_queries.py", + "passed": true + }, + { + "script": "test_pendant.py", + "passed": true + }, + { + "script": "test_pickup.py", + "passed": true + }, + { + "script": "test_queries.py", + "passed": true + }, + { + "script": "test_rings.py", + "passed": true + }, + { + "script": "test_sash.py", + "passed": true + }, + { + "script": "test_stone_socket.py", + "passed": true + }, + { + "script": "test_switchbot.py", + "passed": true + }, + { + "script": "test_switchbot_matching.py", + "passed": true + }, + { + "script": "test_travel.py", + "passed": true + }, + { + "script": "test_vip.py", + "passed": true + } +] diff --git a/audit/evidence/itemshop/transactions.json b/audit/evidence/itemshop/transactions.json new file mode 100644 index 00000000..20b16190 --- /dev/null +++ b/audit/evidence/itemshop/transactions.json @@ -0,0 +1,57 @@ +[ + { + "case": "same token replays original purchase", + "status": 0, + "unchanged": true + }, + { + "case": "same token changed quantity refused", + "status": 7, + "unchanged": true + }, + { + "case": "insufficient coins", + "status": 1, + "unchanged": true + }, + { + "case": "weekly quantity limit", + "status": 2, + "unchanged": true + }, + { + "case": "monthly quantity limit", + "status": 3, + "unchanged": true + }, + { + "case": "stock remaining less than quantity", + "status": 4, + "unchanged": true + }, + { + "case": "expired offer", + "status": 5, + "unchanged": true + }, + { + "case": "disabled product", + "status": 6, + "unchanged": true + }, + { + "case": "missing prototype", + "status": 6, + "unchanged": true + }, + { + "case": "price changed after confirmation", + "status": 9, + "unchanged": true + }, + { + "case": "award insert failure rolls back wallet stock order", + "status": 6, + "unchanged": true + } +] diff --git a/audit/evidence/itemshop/ui.json b/audit/evidence/itemshop/ui.json new file mode 100644 index 00000000..ecab88d9 --- /dev/null +++ b/audit/evidence/itemshop/ui.json @@ -0,0 +1 @@ +{"search_matches": 1, "balance": 9852, "subcategories": [[0, 0], [0, 1], [0, 2], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [5, 0], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]], "catalogue_count": 1} \ No newline at end of file diff --git a/audit/evidence/itemshop/widget-events.json b/audit/evidence/itemshop/widget-events.json new file mode 100644 index 00000000..b2af83a7 --- /dev/null +++ b/audit/evidence/itemshop/widget-events.json @@ -0,0 +1 @@ +{"after": 2, "confirmed_count": 2, "id": 84, "before": 1} \ No newline at end of file diff --git a/audit/evidence/mobile-ui/acceptance.json b/audit/evidence/mobile-ui/acceptance.json new file mode 100644 index 00000000..d8386974 --- /dev/null +++ b/audit/evidence/mobile-ui/acceptance.json @@ -0,0 +1,16 @@ +{ + "device": "Mi 8 Lite", + "android": "15", + "server": "in-process offline fixture; production untouched", + "distance_before": 1550.002197265625, + "distance_spread": 774.980712890625, + "distance_closed": 1549.99169921875, + "position_unchanged": true, + "drawer_touch_opened": true, + "final_skill_layout": "original arc restored per user feedback", + "secondary_menu_visual_scale": 0.72, + "minimum_hit_target_dp": 48, + "native_touch_and_camera_test": "MT_TEST_MOBILE=1 MT_TEST_PINCH=1 MT_TEST_WIKI=1 port_login_flow_test", + "layout_test": "tests/host/touch_layout_test.cpp", + "note": "Pinch and drawer tested with injected Android MotionEvents; final visual layout checked separately on device." +} diff --git a/audit/history.jsonl b/audit/history.jsonl index 0f7f3b9a..a92f811a 100644 --- a/audit/history.jsonl +++ b/audit/history.jsonl @@ -660,3 +660,5 @@ {"time": "2026-10-19T04:37:42.044205+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/AttrLockViewsScript", "finding": "AVA2 lock-line styling extended to existing exchange, shop/builder, safebox/mall and GM equipment tooltip setters using bounded read-only contextual queries. Base item packets and CWindow algorithms unchanged.", "evidence": ["docs/AVA2-ATTR-LOCK-VIEWS.md", "tests/wiki/test_attr_lock_ui.py", "tests/wiki/test_attr_lock_views.py"], "result": "macOS/sbtest two-player trade/shop/storage and real GM equipment lock highlights verified; ordinary equipment queries and closed contexts denied. 126 client tests and native macOS/Android builds passed; fixtures and temporary test GM removed. Active switchbot/hyperlink lock metadata remains pending; no aggregate parity upgrade."} {"time": "2026-10-19T05:08:12.881941+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/AttrLockSnapshotsScript", "finding": "Owner metadata follows existing item packets; bounded post-entry synchronization bridges loading-phase command loss. Versioned seven-slot chat snapshots and active switchbot lock lines preserve the classic wire layouts and original CWindow algorithms. Chinese active descriptions use measured text width.", "evidence": ["docs/AVA2-ATTR-LOCK-SNAPSHOTS.md", "tests/wiki/test_attr_lock_snapshots.py", "docs/AVA2-PARITY-PLAN.md"], "result": "132 client tests and macOS/Android offline builds passed. macOS/sbtest first-entry sync, immutable link/relay, active roll/stop, slot moves and same-process relogin passed. Final layout measured 348 versus longest text 308; test weapon/902 switchers and original unlocked state restored. Production unchanged; no aggregate parity upgrade."} {"time": "2026-10-19T06:35:09.108370+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/Ava2NativeSystems", "finding": "Vendor active AVA2 uiBattlePassEx, uiWiki/WikiUI, uiDropItem and uiEventCalendarNew; preserve classic SHOP_SIGN39 by moving event payload to GC214, configured-db battlepass persistence, real loaded drop data and original CWindow algorithms. Correct active-versus-legacy protocol mapping.", "evidence": ["docs/AVA2-NATIVE-SYSTEMS.md", "tests/wiki/test_native_systems.py", "tools/ava2-native/sources.json", "docs/AVA2-PARITY-PLAN.md"], "result": "146 client tests, 30 server feature scripts with updated version-marker retest, native macOS/Android offline builds; sbtest mission/final idempotency, persistent native views, drop data, scoped calendar/icon verified. Production game a8d606ea deployed; backup /root/backup-native-systems/20261019-083154. No aggregate parity upgrade; phone not tested."} +{"time": "2026-10-19T13:52:09.182541+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/Ava2ItemShop", "finding": "Vendor active uiitemshopnew.py; native GC93 and authenticated GD/DG76, InnoDB wallet/catalogue/order/award transaction, durable token and confirmed quote, bounded atomic decoder, native UI locale/event/scroll/preview adapters. Correct db prototype pointer index after sort. Classic item layout and CWindow algorithms remain unchanged.", "evidence": ["docs/AVA2-ITEMSHOP.md", "tests/wiki/test_itemshop.py", "tools/ava2-native/sources.json", "audit/evidence/itemshop/"], "result": "157 client tests; 31 server feature scripts including native-layout, integer-total and real prototype-index body tests. macOS/sbtest purchase, redemption, refusal/rollback, restart replay, SQL loss/lock timeout, lost-result retry and real widget callbacks verified. 49 original offers with matching IDs/prices/icons enabled only on sbtest; other 168 and recharge/wheel remain closed. Android offline build only; no production deployment or aggregate parity upgrade."} +{"time": "2026-10-19T14:13:41.385041+00:00", "event": "authorized_mobile_ui_fix", "unit": "ScriptLib/MobileHUD and host/TouchController", "finding": "Fix UTF-8 minimap tooltip boundaries. Retain original skill arc per user feedback; smaller secondary menu artwork with 48dp hit targets, compact menus with drawer and native shop entry. Proportional two-finger camera zoom, stationary-stick fix and gesture cancellation.", "evidence": ["tests/wiki/test_minimap_buttons.py", "tests/port/port_login_flow_test.cpp", "audit/evidence/mobile-ui/acceptance.json", "audit/evidence/itemshop/minimap-tooltips.json", "docs/ANDROID-TESTING.md"], "result": "158 Python tests; focused real TouchController/camera offline flow; Mi 8 Lite Android multi-pointer and menu checks. No production deployment or aggregate parity upgrade."} diff --git a/docs/ANDROID-TESTING.md b/docs/ANDROID-TESTING.md index 5be041be..25634bd4 100644 --- a/docs/ANDROID-TESTING.md +++ b/docs/ANDROID-TESTING.md @@ -48,3 +48,25 @@ ANDROID_SERIAL= python3 tools/perf/run_render_isolation.py build/qa/devi ``` 每段排除首个加载后的采样窗口,记录 6 个 2 秒窗口;输出 CSV、截图、内存快照和汇总 JSON,结束后恢复正常登录启动。 + +## 手机操作与布局(2026-10-19) + +根据本轮用户反馈,六个技能保留原先围绕右下攻击键的弧形排列,道具和自动狩猎位置随原技能布局保持一致。 +菜单按钮图形缩小28%,同时保留至少48dp触摸区域;头像和战斗按钮不随次要菜单缩小。 +角色、背包、好友、设置及商城/更多排在小地图左侧;任务、挂机设置、帮助、聊天在“更多”中展开。 +左侧保留移动摇杆和主要视野,副本/战令/生物学家入口继续在小地图外环。 + +场景空白处双指张开拉近、收拢拉远;左右手先后落下均可,界面和战斗按钮优先接收各自手势。 +已经推动的摇杆不会被新落下的右手抢作缩放。缩放直接按指距比例改变镜头距离,原镜头距离上限和地形碰撞仍有效。 +系统取消触摸或应用失去焦点时清掉残留手势;摇杆停在中心时不再误发送移动。 + +可重复的离线手势检查(真实TouchController和镜头,未连接正式服): + +```sh +cmake --build build/native --target port_login_flow_test -j4 +MT_TEST_MOBILE=1 MT_TEST_PINCH=1 MT_TEST_WIKI=1 \ + build/native/src/port/port_login_flow_test "$PWD/build/ava2-parity-20261018/Client" "$PWD/build/native/python27.zip" +``` + +`MT_TEST_PINCH`只运行加载及移动端镜头/折叠菜单验收,跳过无关的频道状态探测和后续经典交互测试。 +布局边界和按钮不重叠由 `tests/host/touch_layout_test.cpp` 覆盖不同屏宽、刘海留白和最小触摸尺寸。 diff --git a/docs/AVA2-ITEMSHOP.md b/docs/AVA2-ITEMSHOP.md new file mode 100644 index 00000000..c3ee2163 --- /dev/null +++ b/docs/AVA2-ITEMSHOP.md @@ -0,0 +1,94 @@ +# AVA2 原生商城移植 + +## 范围与入口 + +活动版本为 AVA2 `uiitemshopnew.py`,不是旧 `uiitemshop.py` / `uiitemshop_v2.py`。 +原始 Python 源码由 `tools/ava2-native/import_sources.py` 转码后原样嵌入,SHA256 记录在 +`tools/ava2-native/sources.json`。兼容、汉化及服务端接入位于 `Ava2ItemShopScript.inc`。 + +桌面入口:**F9**,以及与 AVA2 相同的任务栏圆形商城入口。经典商城仓库入口保留用于领货。 +包含八个主分类、17 个子分类、名称搜索、热销、折扣、数量 1–20、购买确认、余额、库存、最近100笔购买记录、可支持道具的模型预览。 +鼠标滚轮在商城列表中滚动,指针在商城窗口内时不改变游戏镜头。 + +充值按钮和幸运转盘保留“尚未开放”提示;不访问 AVA2 提供者的网站,不显示随机假奖励。 +它们需要各自的支付服务/奖励池和玩法验收,不能由商城窗口本身代替。 + +## 协议与经济规则 + +- 客户端 GC93:5字节头(BYTE + DWORD 长度),总长 6–32768;完整收齐后再分发。 +- 原生目录 `TIShopData` 49字节、记录 `TIShopLogData` 90字节。目录/记录整帧验证成功后才替换界面状态。 +- game/db 使用空闲 GD/DG76。请求为固定103字节;响应封套包含 account、player、payload size。 +- `/ishop data -1`、`/ishop log`,购买扩展为 `/ishop buy id count token quoted_total quoted_vnum`。 + token为32位随机十六进制串,绑定一次确认;超时最多重发3次,保持同一token。 +- 新客户端标识 `mt20261020`。game 仅接受这个版本及之后的商城请求,避免旧客户端收到未知GC93。 +- game按账号/角色构建请求,db再次检查在线账号所属peer和角色归属;返回时校验账号、角色和game阶段。 +- db按配置的SQL_ACCOUNT定位龙币,使用配置的SQL_PLAYER连接执行跨库InnoDB事务,禁止硬编码正式库名。 + SQL_ACCOUNT/SQL_PLAYER必须指向同一MySQL主机和端口;否则商城拒绝购买。 +- 同一事务锁定账号和商品,检查余额、有效期、数量、库存、周/月按件数限购及报价,再扣币、更新库存、写订单和商城发货记录。 +- 订单唯一键 `(account_id,token)`。重放同一订单不会再次扣币;更换数量、商品或报价的重放被拒绝。 +- 总价统一使用整数:`unit * count * (100-discount) / 100` 向下取整。 + 修复原版浮点误差(58龙币、五折应为29)以及折扣数量计算不一致。 +- 确认框打开后若商品或售价变化,拒绝付款并刷新,不按新价格直接扣款。 +- SQL连接在事务期间禁用自动重连,锁等待上限3秒。COMMIT结果不明确时保留原token重试。 +- 周期边界采用数据库时区的周一零点/每月一日零点。 +- 修复旧db在排序前建立道具指针索引的问题:排序完成后再建立映射,保证目录、堆叠属性和仓库发货使用正确模板。 +- 发货插入现有 `item_award`、`mall=1`,沿用商城仓库领取链路;非堆叠物品逐件发放。 + 背包满、掉线和关闭窗口不删除已付款的发货记录。 + +未改变经典物品7条属性/3个socket及CWindow算法。当前AVA2对齐整体仍为PARTIAL。 + +## 商品数据 + +从 `AVA2/2. Backup SF+SRC and SQL/MYSQL56.tgz` 恢复出 **217条** `player.ishop_data`。 +原价、分类、折扣、时间、销量、限购和限量字段保存在服务端 +`data/ava2-itemshop/original-products.tsv`,来源散列另见该目录的 `source.json`。 + +当前服务端模板核对:**55条缺模板,55条对应ITEM_NONE占位物品,107条有实际类型但仍须逐项确认玩法和资源**。 +这些数量不能理解为217条商品均可售卖。兼容清单见服务端 `compatibility.json`。 +迁移默认将217条全设为停用。已依据现有坐骑、外观强化和拾取实现整理 `verified-products.json`: +**49件原版商品**已在sbtest启用,全部通过当前客户端模板、图标和目录接收验证,售价保持AVA2原价。 +包括4件永久坐骑、2件坐骑外观、42件时装/发型/坐骑外观强化石、1件第三只手。 +其余168条继续保持停用;实际类型存在不代表对应玩法和模型已经完整。 +测试商品900001在验收后撤下。没有给正式玩家发币或上架未完成道具。 + +## 构建、测试与交付状态 + +候选客户端:`dist/itemshop/Metin2.app`。Android仅离线编译,按用户要求未测手机真机。 +自动化测试覆盖原生布局、截断/重复/越界帧、整数折扣、冻结报价、双击保护、重试和节流。 +真实sbtest验收结果及二进制散列见本文件的验收记录。 + +**正式服仍运行此前的原生战令/百科/日历版本;这次商城尚未部署到正式服。** +正式上线需要先备份账号和发货表,再执行服务端迁移并同步更新game/db;候选客户端不能单独让旧服务端具有商城能力。 + +## 数据库迁移 + +服务端运行: + +``` +python3 tools/ava2-itemshop/migrate.py --player player_sb --account account_sb --output /tmp/itemshop.sql +``` + +先审阅SQL和备份,再用MySQL执行。正式服使用实际配置的库名,不能照抄sbtest库名。 +对已确认实现的49件商品,可另生成并审阅: + +``` +python3 tools/ava2-itemshop/enable_verified.py --player player_sb --output /tmp/itemshop-enable.sql +``` + +该脚本核对原商品ID、vnum和实际模板类型,只改开关,不改售价。 +迁移将目录、订单、账号和发货表转为InnoDB,并在必要时添加龙币列;重复执行不重置余额、库存、订单或已有商品开关。 +回滚二进制时保留订单和发货记录,避免抹掉玩家已付款的物品。不要把账号表改回MyISAM。 + +## 本轮验收记录(2026-10-19) + +158项客户端Python测试和31个服务端功能脚本通过。sbtest确认49件原商品目录、原价、图标、原型一致; +购买、商城仓库领货、非堆叠逐件发货、重复请求、报价改变、余额/库存/限购/过期拒绝、SQL回滚、锁等待和断线恢复均已验证。 +故意丢弃一次成功响应后,客户端用同一token重试,数据库只产生一笔扣币及发货。 +测试币、订单、发货、道具及触发器已清理;sbtest game/db已重启,正式服二进制保持不变。 +具体结果及最新sbtest game/db SHA256见 `audit/evidence/itemshop/`。 + +小地图F5/F6/F7/F8、扩展栏自动洗练/百科提示统一通过本地代码页桥接。 +已在实际客户端确认F7“生物学家”正常显示,修复并非只改源文字。 + +候选Android包 `dist/itemshop/Metin2-Android.apk`;外置资源增量位于 `dist/itemshop/Client-patch/pack/`。 +APK不内含全部游戏地图包,手机安装时另行同步完整的候选Client资源。 diff --git a/docs/AVA2-PARITY-PLAN.md b/docs/AVA2-PARITY-PLAN.md index ba9728fd..f33b5ff3 100644 --- a/docs/AVA2-PARITY-PLAN.md +++ b/docs/AVA2-PARITY-PLAN.md @@ -162,3 +162,10 @@ AVA2 功能包头号在当前服务端基本空闲,可以直接沿用: 战令沿用现有赛季与进度/领取主键;百科模板和掉落来自当前203数据,日历展示实际已接入的月光宝箱/圣诞袜排期。 其他活动的服务端玩法、宠物等不因迁移窗口自动完成,整体 AVA2 对齐仍为 PARTIAL。 详见 [AVA2-NATIVE-SYSTEMS.md](AVA2-NATIVE-SYSTEMS.md),生产部署证据在同文档中单列。 + +### 2026-10-19:原生商城 + +AVA2活动版本 `uiitemshopnew.py` 已接入原生GC93和GD/DG76,事务扣币、限购、库存、订单去重与商城仓库发货; +新增确认报价校验,修复原版折扣数量/浮点误差和失效的目录更新。 +原217条商品配置已恢复,sbtest先开放49件已有玩法和资源的原版商品;其他168条依赖未闭合,充值/转盘未开放。 +正式服本轮未更新。详见 [AVA2-ITEMSHOP.md](AVA2-ITEMSHOP.md)。 diff --git a/src/host/sdl_window.cpp b/src/host/sdl_window.cpp index 4ccfefb2..0e41b90c 100644 --- a/src/host/sdl_window.cpp +++ b/src/host/sdl_window.cpp @@ -261,7 +261,10 @@ bool VulkanWindow::poll(bool forward_to_live_client) { } else if (event.type == SDL_EVENT_FINGER_MOTION) { touch_controller.on_finger_motion(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y); continue; - } else if (event.type == SDL_EVENT_FINGER_UP || event.type == SDL_EVENT_FINGER_CANCELED) { + } else if (event.type == SDL_EVENT_FINGER_CANCELED) { + touch_controller.cancel_gestures(); + continue; + } else if (event.type == SDL_EVENT_FINGER_UP) { touch_controller.on_finger_up(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y); continue; } @@ -275,6 +278,7 @@ bool VulkanWindow::poll(bool forward_to_live_client) { SDL_HideCursor(); os_cursor_hidden_ = true; } else if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) { + touch_controller.cancel_gestures(); SDL_CaptureMouse(false); PythonBoot::UIMouseButton(2, false, last_mx_, last_my_); PythonBoot::UIMouseButton(3, false, last_mx_, last_my_); diff --git a/src/host/touch_controller.h b/src/host/touch_controller.h index 827965e6..2581283f 100644 --- a/src/host/touch_controller.h +++ b/src/host/touch_controller.h @@ -33,12 +33,24 @@ public: } void set_enabled(bool enabled) { + if (enabled_ && !enabled) cancel_gestures(); enabled_ = enabled; #ifdef MT_NATIVE_HAS_LIVE_CLIENT PythonBoot::SetTouchInput(enabled); #endif } bool is_enabled() const { return enabled_; } + // OS cancellation/focus loss must discard gestures without synthesizing a world tap. + void cancel_gestures() { + release_gameplay_controls(); + ui_touch_finger_id_ = -1; + ui_gesture_ = UiGesture::None; + tap_stage_ = 0; + keyboard_requested_ = false; +#ifdef MT_NATIVE_HAS_LIVE_CLIENT + PythonBoot::SetInventoryDrag(false); +#endif + } void set_minimum_touch_target(float logicalSize) { minimum_touch_target_ = std::max(48.0f, logicalSize); } // Short vibration when a long press fires (the host wires it to the platform). void set_haptic(void (*haptic)()) { haptic_ = haptic; } @@ -110,7 +122,8 @@ public: controls_were_visible_ = true; if (joystick_active_) { #ifdef MT_NATIVE_HAS_LIVE_CLIENT - PythonBoot::SetMoveDirection(move_angle_, true); + PythonBoot::SetMoveDirection(move_angle_, + std::hypot(joystick_last_x_ - joystick_base_x_, joystick_last_y_ - joystick_base_y_) > 8.0f); #endif } } @@ -165,12 +178,38 @@ public: } #endif + // PORT: two scene fingers own a pinch before the second can become a joystick. + // A stationary new left thumb may join the pinch; an established moving stick stays movement. + if (controls_visible && pinch_finger_id_ >= 0) + return true; // Additional scene fingers cannot steal an ongoing pinch. + if (controls_visible) { + if (look_finger_id_ == finger_id) return true; + if (look_finger_id_ >= 0) { + begin_pinch(finger_id, px, py); + return true; + } + if (joystick_active_ && !joystick_moved_) { + look_finger_id_ = joystick_finger_id_; + look_last_x_ = joystick_last_x_; + look_last_y_ = joystick_last_y_; + look_can_rotate_ = true; + joystick_active_ = false; + joystick_finger_id_ = -1; +#ifdef MT_NATIVE_HAS_LIVE_CLIENT + PythonBoot::SetMoveDirection(0.0f, false); +#endif + begin_pinch(finger_id, px, py); + return true; + } + } + // Mobile-game layout: the left half moves (floating stick), the right half looks. if (controls_visible && norm_x < kMoveZoneRight && norm_y > kMoveZoneTop && !joystick_active_) { joystick_active_ = true; joystick_finger_id_ = finger_id; - joystick_base_x_ = px; - joystick_base_y_ = py; + joystick_base_x_ = joystick_last_x_ = px; + joystick_base_y_ = joystick_last_y_ = py; + joystick_moved_ = false; joystick_knob_x_ = px; joystick_knob_y_ = py; update_joystick_motion(px, py); @@ -195,15 +234,6 @@ public: #endif return true; } - if (pinch_finger_id_ < 0 && look_can_rotate_ && in_look_zone) { - pinch_finger_id_ = finger_id; - pinch_x_ = px; - pinch_y_ = py; - pinch_last_dist_ = std::hypot(px - look_last_x_, py - look_last_y_); - look_rotating_ = false; - look_moved_ = true; // a pinch never ends as a tap - return true; - } return false; } @@ -234,6 +264,10 @@ public: // 2. Virtual Joystick finger if (joystick_active_ && finger_id == joystick_finger_id_) { + joystick_last_x_ = px; + joystick_last_y_ = py; + if (std::hypot(px - joystick_base_x_, py - joystick_base_y_) > kLookDeadZone) + joystick_moved_ = true; update_joystick_motion(px, py); return true; } @@ -253,7 +287,7 @@ public: } } - // 4. Two-finger pinch zoom (look finger + second right-half finger) + // 4. Two-finger scene pinch: scale camera distance, without wheel inertia or UI scrolling. if (pinch_finger_id_ >= 0 && (finger_id == pinch_finger_id_ || finger_id == look_finger_id_)) { if (finger_id == pinch_finger_id_) { pinch_x_ = px; @@ -263,13 +297,13 @@ public: look_last_y_ = py; } const float cur_dist = std::hypot(pinch_x_ - look_last_x_, pinch_y_ - look_last_y_); - const float delta_d = cur_dist - pinch_last_dist_; - if (std::abs(delta_d) > 2.0f) { + // Rebase very close/crossed fingers instead of dividing by a near-zero span. + if (cur_dist >= 24.0f && pinch_last_dist_ >= 24.0f) { #ifdef MT_NATIVE_HAS_LIVE_CLIENT - PythonBoot::UIMouseWheel(int(delta_d * 8.0f)); + PythonBoot::CameraZoomBy(pinch_last_dist_ / cur_dist); #endif - pinch_last_dist_ = cur_dist; } + pinch_last_dist_ = cur_dist; return true; } @@ -615,6 +649,16 @@ public: } private: + void begin_pinch(int64_t finger_id, float px, float py) { + pinch_finger_id_ = finger_id; + pinch_x_ = px; + pinch_y_ = py; + pinch_last_dist_ = std::hypot(px - look_last_x_, py - look_last_y_); + look_rotating_ = false; + look_can_rotate_ = true; + look_moved_ = true; // Neither finger may turn into a tap after pinching. + } + bool gameplay_controls_visible() const { #ifdef MT_NATIVE_HAS_LIVE_CLIENT return PythonBoot::InGamePhase() && !PythonBoot::CurrentMapName().empty(); @@ -904,6 +948,8 @@ private: float joystick_radius_ = 65.0f; float joystick_knob_radius_ = 23.0f; float move_angle_ = 0.0f; + float joystick_last_x_ = 0.0f, joystick_last_y_ = 0.0f; + bool joystick_moved_ = false; // Zones are fractions of the screen; distances are logical UI pixels. static constexpr float kMoveZoneRight = 0.5f; diff --git a/src/platform/ScriptLib/Ava2ItemShopNewSource.inc b/src/platform/ScriptLib/Ava2ItemShopNewSource.inc new file mode 100644 index 00000000..86898024 --- /dev/null +++ b/src/platform/ScriptLib/Ava2ItemShopNewSource.inc @@ -0,0 +1,2514 @@ +// AVA2 original uiitemshopnew.py; generated by tools/ava2-native/import_sources.py. +static const char c_szAva2ItemShopNewSource[] = R"PY(# -*- coding: utf-8 -*- +import ui, app, item, net, os, constInfo, localeInfo +from _weakref import proxy + +itemshopData = {} +playerLog = [] + +UPDATE_TIME = -1 + +def ItemShopLogClear(): + global playerLog + playerLog=[] + +def ItemShopAppendLog(dateText, dateTime, playerName, ipAdress, itemVnum, itemCount, itemPrice): + dateTimeReal = "None" + dateSplit = dateText.split(" ") + if len(dateSplit) > 1: + dateFirst = dateSplit[0].split("-") + if len(dateFirst) == 3: + dateTimeReal = dateFirst[2]+"/"+dateFirst[1]+"/"+dateFirst[0] + dateTimeReal+=" " + dateSecond = dateSplit[1].split(":") + if len(dateSecond) == 3: + dateTimeReal += dateSecond[0]+":"+dateSecond[1] + + global playerLog + playerLog.append([dateTimeReal,dateTime,playerName,ipAdress,itemVnum,itemCount,itemPrice]) + +def ItemShopClear(time): + global itemshopData + global UPDATE_TIME + if time != UPDATE_TIME: + itemshopData.clear() + UPDATE_TIME = time + +def ItemShopAppendItem(categoryIndex, categorySubIndex, itemID, itemVnum, itemPrice, itemDiscount, itemOffertime, itemTopSelling, itemAddedTime, itemSellingCount, itemMaxSellingCount): + if not itemshopData.has_key(categoryIndex): + subCategoryList=[] + for x in xrange(10): + subCategoryList.append([]) + itemshopData[categoryIndex] = subCategoryList + itemshopData[categoryIndex][categorySubIndex].append([itemID, itemVnum, itemPrice, itemDiscount, itemOffertime, itemTopSelling, itemAddedTime, itemSellingCount, itemMaxSellingCount]) + +def ItemShopUpdateItem(itemID, itemVnum, itemPrice, itemDiscount, itemOffertime, itemTopSelling, itemAddedTime, itemSellingCount, itemMaxSellingCount): + global itemshopData + for key, items in itemshopData.items(): + for subCategory in items: + for shopItem in subCategory: + if shopItem[0] == itemID: + shopItem = [itemID, itemVnum, itemPrice, itemDiscount, itemOffertime, itemTopSelling, itemAddedTime, itemSellingCount, itemMaxSellingCount] + return + +buyQuestionDialog = None + +LIST_ITEM_ID=0 +LIST_ITEM_VNUM=1 +LIST_ITEM_PRICE=2 +LIST_ITEM_DISCOUNT=3 +LIST_ITEM_TIME=4 +LIST_ITEM_TOP_SELLING_INDEX=5 +LIST_ITEM_ADDED_TIME=6 +LIST_ITEM_SELLING_COUNT=7 +LIST_ITEM_MAX_SELLING_COUNT=8 + +LOG_DATE_TEXT = 0 +LOG_DATE = 1 +LOG_ACCOUNT = 2 +LOG_IP = 3 +LOG_ITEM = 4 +LOG_COUNT = 5 +LOG_PRICE = 6 + + +HOT_ITEM=1 +NEW_ITEM=2 +OFFER_ITEM=3 + +#Config + +WEBSITE_LINK = "https://dracarys.work" +eventCategory = [ + # [[FILENAMES],[CATEGORY, SUB_CATEGORY]] + [["costume_banner_0.tga","costume_banner_1.tga"],[0,0]], +] + +IMG_DIR ="d:/ymir work/ui/game/ishop/" + +WHEEL_DIR ="d:/ymir work/ui/game/ishop/wheel/default/" +wheel_random_items = [\ + [71084,50],[71084,100],[71084,200],[71084,1000],[100500,1],[100400,1],[100400,2],[100300,3],[100300,2],[70005,1],[55035,1],[25041,1],[25041,2],[72346,1],[72346,2],[72346,3],[55009,1],[72319,1]\ + ,[72319,2],[72320,1],[72320,2],[72320,5],[55001,1],[71035,1],[100001,1],[100003,1],[71097,1],[50255,10],[50255,20],[50255,50],[70043,1],[72067,1],[72067,2],[72067,3],[54716,1],[53012,1],[53999,1],[54715,1],[53005,1],[6884,1] +] + +itemShopCategoryData = { + 0:{ + "name":localeInfo.CATEGORY_0_NAME, + "subCategory":[localeInfo.CATEGORY_0_SUB_0_NAME,localeInfo.CATEGORY_0_SUB_1_NAME,localeInfo.CATEGORY_0_SUB_2_NAME], + }, + 1:{ + "name":localeInfo.CATEGORY_1_NAME, + "subCategory":[], + }, + 2:{ + "name":localeInfo.CATEGORY_2_NAME, + "subCategory":[localeInfo.CATEGORY_2_SUB_0_NAME,localeInfo.CATEGORY_2_SUB_1_NAME,localeInfo.CATEGORY_2_SUB_2_NAME,localeInfo.CATEGORY_2_SUB_3_NAME,localeInfo.CATEGORY_2_SUB_4_NAME], + }, + 3:{ + "name":localeInfo.CATEGORY_3_NAME, + "subCategory":[localeInfo.CATEGORY_3_SUB_0_NAME,localeInfo.CATEGORY_3_SUB_1_NAME,localeInfo.CATEGORY_3_SUB_2_NAME], + }, + 4:{ + "name":localeInfo.CATEGORY_4_NAME, + "subCategory":[], + }, + 5:{ + "name":localeInfo.CATEGORY_5_NAME, + "subCategory":[localeInfo.CATEGORY_5_SUB_0_NAME,localeInfo.CATEGORY_5_SUB_1_NAME,localeInfo.CATEGORY_5_SUB_2_NAME,localeInfo.CATEGORY_5_SUB_3_NAME,localeInfo.CATEGORY_5_SUB_4_NAME,localeInfo.CATEGORY_5_SUB_5_NAME], + }, + 6:{ + "name":localeInfo.CATEGORY_6_NAME, + "subCategory":[], + }, + 7:{ + "name":localeInfo.CATEGORY_7_NAME, + "subCategory":[], + }, +} + +class ItemShopWindow(ui.Window): + def __del__(self): + ui.Window.__del__(self) + def Destroy(self): + ItemShopLogClear() + if self.children.has_key("categoryListBox"): + self.children["categoryListBox"].RemoveAllItems() + if self.children.has_key("itemListBox"): + self.children["itemListBox"].RemoveAllItems() + if self.children.has_key("PurchasesListBox"): + self.children["PurchasesListBox"].RemoveAllItems() + self.CloseWeb() + + global buyQuestionDialog + if buyQuestionDialog != None: + buyQuestionDialog.Hide() + buyQuestionDialog.Destroy() + buyQuestionDialog=None + + self.RealMoney = 0 + self.NewMoney = 0 + self.MoneyRange = 0 + self.MoneyFlag = False + self.moneySize = 0 + + self.children = {} + def __init__(self): + ui.Window.__init__(self) + self.children = {} + self.Destroy() + self.LoadWindow() + + def LoadWindow(self): + self.AddFlag("movable") + self.AddFlag("attach") + self.AddFlag("float") + + boardImage = ui.ImageBox() + boardImage.SetParent(self) + boardImage.AddFlag("attach") + boardImage.LoadImage(IMG_DIR+"bg.tga") + self.SetSize(boardImage.GetWidth(),boardImage.GetHeight()) + boardImage.SetPosition(0,0) + boardImage.Show() + self.children["boardImage"] = boardImage + + closeBtn = ui.Button() + closeBtn.SetParent(boardImage) + closeBtn.SetUpVisual(IMG_DIR+"close_0.tga") + closeBtn.SetOverVisual(IMG_DIR+"close_1.tga") + closeBtn.SetDownVisual(IMG_DIR+"close_2.tga") + closeBtn.SetEvent(self.Close) + closeBtn.SetPosition(boardImage.GetWidth()-closeBtn.GetWidth()-5,5) + closeBtn.Show() + self.children["closeBtn"] = closeBtn + + leftDragonCoinImage = ui.ImageBox() + leftDragonCoinImage.SetParent(boardImage) + leftDragonCoinImage.LoadImage(IMG_DIR+"coin.tga") + leftDragonCoinImage.SetPosition(35,20) + leftDragonCoinImage.Show() + self.children["leftDragonCoinImage"] = leftDragonCoinImage + + dragonCoinText = MultiTextLine() + dragonCoinText.SetParent(boardImage) + dragonCoinText.SetPosition(35+leftDragonCoinImage.GetWidth()+10,17) + dragonCoinText.SetTextRange(17) + dragonCoinText.SetTextType("horizontal#left") + dragonCoinText.SetFontName("Tahoma:14") + dragonCoinText.SetOutline(True) + dragonCoinText.Show() + self.children["dragonCoinText"] = dragonCoinText + + + buyCoinBtn = ui.Button() + buyCoinBtn.SetParent(boardImage) + buyCoinBtn.SetUpVisual(IMG_DIR+"button1_0.tga") + buyCoinBtn.SetOverVisual(IMG_DIR+"button1_1.tga") + buyCoinBtn.SetDownVisual(IMG_DIR+"button1_2.tga") + buyCoinBtn.SetEvent(self.BuyDragonCoin) + buyCoinBtn.SetPosition(180,12) + buyCoinBtn.Show() + self.children["buyCoinBtn"] = buyCoinBtn + + buyCoinBtnText = MultiTextLine() + buyCoinBtnText.SetParent(buyCoinBtn) + buyCoinBtnText.SetTextRange(17) + buyCoinBtnText.SetPosition(buyCoinBtn.GetWidth()/2,10) + buyCoinBtnText.SetTextType("horizontal#center") + buyCoinBtnText.SetFontName("Tahoma:16") + buyCoinBtnText.SetText(localeInfo.ITEMSHOP_BUY_COIN) + buyCoinBtnText.Show() + buyCoinBtn.multiText = buyCoinBtnText + + wheelBtn = ui.Button() + wheelBtn.SetParent(boardImage) + wheelBtn.SetUpVisual(IMG_DIR+"wheel_button_0.tga") + wheelBtn.SetOverVisual(IMG_DIR+"wheel_button_1.tga") + wheelBtn.SetDownVisual(IMG_DIR+"wheel_button_2.tga") + wheelBtn.SetEvent(self.WheelBtn) + wheelBtn.SetPosition(180+buyCoinBtn.GetWidth()+7,12) + wheelBtn.Show() + self.children["wheelBtn"] = wheelBtn + + wheelBtnText = MultiTextLine() + wheelBtnText.SetParent(wheelBtn) + wheelBtnText.SetTextRange(17) + wheelBtnText.SetPosition(wheelBtn.GetWidth()/2,10) + wheelBtnText.SetTextType("horizontal#center") + wheelBtnText.SetFontName("Tahoma:16") + wheelBtnText.SetText(localeInfo.ITEMSHOP_WHEEL) + wheelBtnText.Show() + wheelBtn.multiText = wheelBtnText + + purchasesBtn = ui.Button() + purchasesBtn.SetParent(boardImage) + purchasesBtn.SetUpVisual(IMG_DIR+"button2_0.tga") + purchasesBtn.SetOverVisual(IMG_DIR+"button2_1.tga") + purchasesBtn.SetDownVisual(IMG_DIR+"button2_2.tga") + purchasesBtn.SetEvent(self.PurchaseBtn) + purchasesBtn.SetPosition(180+((buyCoinBtn.GetWidth()+7)*2),12) + purchasesBtn.Show() + self.children["purchasesBtn"] = purchasesBtn + + purchasesBtnText = MultiTextLine() + purchasesBtnText.SetParent(purchasesBtn) + purchasesBtnText.SetTextRange(17) + purchasesBtnText.SetPosition(purchasesBtn.GetWidth()/2,10) + purchasesBtnText.SetTextType("horizontal#center") + purchasesBtnText.SetFontName("Tahoma:16") + purchasesBtnText.SetText(localeInfo.ITEMSHOP_PURCHASES) + purchasesBtnText.Show() + purchasesBtn.multiText = purchasesBtnText + + hotItemsBtn = ui.Button() + hotItemsBtn.SetParent(boardImage) + hotItemsBtn.SetUpVisual(IMG_DIR+"button2_0.tga") + hotItemsBtn.SetOverVisual(IMG_DIR+"button2_1.tga") + hotItemsBtn.SetDownVisual(IMG_DIR+"button2_2.tga") + hotItemsBtn.SetEvent(self.HotItems) + hotItemsBtn.SetPosition(180+((buyCoinBtn.GetWidth()+7)*3),12) + hotItemsBtn.Show() + self.children["hotItemsBtn"] = hotItemsBtn + + hotItemsBtnText = MultiTextLine() + hotItemsBtnText.SetParent(hotItemsBtn) + hotItemsBtnText.SetTextRange(17) + hotItemsBtnText.SetPosition(hotItemsBtn.GetWidth()/2,10) + hotItemsBtnText.SetTextType("horizontal#center") + hotItemsBtnText.SetFontName("Tahoma:16") + hotItemsBtnText.SetText(localeInfo.ITEMSHOP_HOTITEMS) + hotItemsBtnText.Show() + hotItemsBtn.multiText = hotItemsBtnText + + offersBtn = ui.Button() + offersBtn.SetParent(boardImage) + offersBtn.SetUpVisual(IMG_DIR+"button2_0.tga") + offersBtn.SetOverVisual(IMG_DIR+"button2_1.tga") + offersBtn.SetDownVisual(IMG_DIR+"button2_2.tga") + offersBtn.SetEvent(self.OfferItems) + offersBtn.SetPosition(180+((buyCoinBtn.GetWidth()+7)*4),12) + offersBtn.Show() + self.children["offersBtn"] = offersBtn + + offersBtnText = MultiTextLine() + offersBtnText.SetParent(offersBtn) + offersBtnText.SetTextRange(17) + offersBtnText.SetPosition(offersBtn.GetWidth()/2,10) + offersBtnText.SetTextType("horizontal#center") + offersBtnText.SetFontName("Tahoma:16") + offersBtnText.SetText(localeInfo.ITEMSHOP_OFFERS) + offersBtnText.Show() + offersBtn.multiText = offersBtnText + + itemSearchBg = ui.ImageBox() + itemSearchBg.SetParent(boardImage) + itemSearchBg.LoadImage(IMG_DIR+"search_box.tga") + itemSearchBg.SetPosition(702,13) + itemSearchBg.Show() + self.children["itemSearchBg"] = itemSearchBg + + itemSearch = ui.EditLine() + itemSearch.SetParent(itemSearchBg) + itemSearch.SetMax(40) + itemSearch.SetPosition(16,10) + itemSearch.SetSize(itemSearchBg.GetWidth()-16, itemSearchBg.GetHeight()-10) + itemSearch.OnIMEUpdate = ui.__mem_func__(self.__OnValueUpdate) + itemSearch.OnPressEscapeKey = ui.__mem_func__(self.Close) + itemSearch.Show() + self.children["itemSearch"] = itemSearch + + itemSearchText = MultiTextLine() + itemSearchText.SetParent(itemSearch) + itemSearchText.SetTextRange(15) + itemSearchText.SetPosition(0,-2) + itemSearchText.SetFontColor(128,128,128) + itemSearchText.SetTextType("horizontal#left") + itemSearchText.SetFontName("Tahoma:16") + itemSearchText.SetText(localeInfo.ITEMSHOP_ITEMSEARCH_DEFAULT_TEXT) + itemSearchText.Show() + itemSearch.backText = itemSearchText + + categoryScrollBar = ScrollBar() + categoryScrollBar.SetParent(boardImage) + categoryScrollBar.SetPosition(169,76) + categoryScrollBar.SetScrollBarSize(435) + categoryScrollBar.SetScrollStep(0.07) + categoryScrollBar.Show() + self.children["categoryScrollBar"] = categoryScrollBar + + categoryListBox = ListBox() + categoryListBox.SetParent(boardImage) + categoryListBox.SetPosition(10,76) + categoryListBox.SetSize(150,55*8) + categoryListBox.SetItemStep(2) + categoryListBox.SetItemSize(150,55) + categoryListBox.SetScrollBar(categoryScrollBar) + categoryListBox.Show() + self.children["categoryListBox"] = categoryListBox + + itemScrollBar = ScrollBar() + itemScrollBar.SetParent(boardImage) + itemScrollBar.SetPosition(200+750+10,76) + itemScrollBar.SetScrollBarSize(435) + itemScrollBar.SetScrollStep(0.07) + itemScrollBar.Show() + self.children["itemScrollBar"] = itemScrollBar + + itemListBox = ListBox() + itemListBox.SetParent(boardImage) + itemListBox.SetPosition(200,76) + itemListBox.SetSize(750,445) + itemListBox.SetItemStep(8) + itemListBox.SetItemSize(750,122) + itemListBox.SetScrollBar(itemScrollBar) + #itemListBox.OnUpdate = self.OnUpdate() + itemListBox.Show() + self.children["itemListBox"] = itemListBox + + PurchasesScrollBar = ScrollBar() + PurchasesScrollBar.SetParent(boardImage) + PurchasesScrollBar.SetPosition(200+750+10,76) + PurchasesScrollBar.SetScrollBarSize(435) + PurchasesScrollBar.SetScrollStep(0.07) + self.children["PurchasesScrollBar"] = PurchasesScrollBar + + PurchasesListBox = ListBox() + PurchasesListBox.SetParent(boardImage) + PurchasesListBox.SetPosition(16,75) + PurchasesListBox.SetSize(927,440) + PurchasesListBox.SetItemStep(8) + PurchasesListBox.SetItemSize(927,28) + PurchasesListBox.SetScrollBar(PurchasesScrollBar) + self.children["PurchasesListBox"] = PurchasesListBox + + LoadingImage = ui.ExpandedImageBox() + LoadingImage.SetParent(boardImage) + LoadingImage.SetPosition(boardImage.GetWidth()/2,boardImage.GetHeight()/2) + LoadingImage.LoadImage(IMG_DIR+"load_.tga") + self.children["LoadingImage"] = LoadingImage + + self.children["LoadingImageRotation"] = 0 + + wheelBg = ui.ImageBox() + wheelBg.SetParent(self) + wheelBg.AddFlag("attach") + wheelBg.LoadImage(WHEEL_DIR+"wallpaper.tga") + wheelBg.SetPosition(2,61) + wheelBg.Hide() + self.children["wheelBg"] = wheelBg + + wheelBgDesign = ui.ImageBox() + wheelBgDesign.AddFlag("attach") + wheelBgDesign.SetParent(wheelBg) + wheelBgDesign.LoadImage(WHEEL_DIR+"wheel_bg.tga") + wheelBgDesign.SetAlpha(0.5) + wheelBgDesign.Show() + self.children["wheelBgDesign"] = wheelBgDesign + + wheelSpinCheck = ui.ToggleButton() + wheelSpinCheck.SetParent(wheelBg) + wheelSpinCheck.SetUpVisual(WHEEL_DIR+"no_selected.tga") + wheelSpinCheck.SetOverVisual(WHEEL_DIR+"no_selected.tga") + wheelSpinCheck.SetDownVisual(WHEEL_DIR+"selected.tga") + wheelSpinCheck.SetPosition(27,24) + wheelSpinCheck.SetToggleUpEvent(self.SetSpintAnimation,False) + wheelSpinCheck.SetToggleDownEvent(self.SetSpintAnimation,True) + wheelSpinCheck.Show() + self.children["wheelSpinCheck"] = wheelSpinCheck + + wheelSpinCheckText = MultiTextLine() + wheelSpinCheckText.SetParent(wheelBg) + wheelSpinCheckText.SetPosition(52,25) + wheelSpinCheckText.SetTextRange(17) + wheelSpinCheckText.SetTextType("horizontal#left") + wheelSpinCheckText.SetFontName("Tahoma:14") + wheelSpinCheckText.SetOutline(True) + wheelSpinCheckText.Show() + self.children["wheelSpinCheckText"] = wheelSpinCheckText + + backToItemShop = ui.Button() + backToItemShop.SetParent(wheelBg) + backToItemShop.SetUpVisual(WHEEL_DIR+"back_0.tga") + backToItemShop.SetOverVisual(WHEEL_DIR+"back_1.tga") + backToItemShop.SetDownVisual(WHEEL_DIR+"back_2.tga") + backToItemShop.SetPosition(19,425) + backToItemShop.SetEvent(self.BackToItemShop) + backToItemShop.Show() + self.children["backToItemShop"] = backToItemShop + + backToItemShopText = MultiTextLine() + backToItemShopText.SetParent(backToItemShop) + backToItemShopText.SetPosition(backToItemShop.GetWidth()+10,4) + backToItemShopText.SetTextRange(17) + backToItemShopText.SetTextType("horizontal#left") + backToItemShopText.SetFontName("Tahoma:14") + backToItemShopText.SetOutline(True) + backToItemShopText.SetText(localeInfo.ITEMSHOP_WHEEL_BACK_ISHOP) + backToItemShopText.Show() + backToItemShop.backToItemShopText = backToItemShopText + + whellTicketBtn = ui.RadioButton() + whellTicketBtn.SetParent(wheelBg) + whellTicketBtn.SetUpVisual(WHEEL_DIR+"no_selected.tga") + whellTicketBtn.SetOverVisual(WHEEL_DIR+"no_selected.tga") + whellTicketBtn.SetDownVisual(WHEEL_DIR+"selected.tga") + whellTicketBtn.SetPosition(797,400) + whellTicketBtn.SetEvent(self.SetTicketMode,0) + whellTicketBtn.Show() + self.children["whellTicketBtn"] = whellTicketBtn + + whellTicketBtnText = MultiTextLine() + whellTicketBtnText.SetParent(whellTicketBtn) + whellTicketBtnText.SetPosition(29,-1) + whellTicketBtnText.SetTextRange(17) + whellTicketBtnText.SetTextType("horizontal#left") + whellTicketBtnText.SetFontName("Tahoma:14") + whellTicketBtnText.SetOutline(True) + whellTicketBtnText.SetText(localeInfo.ITEMSHOP_WHEEL_TICKET_TEXT) + whellTicketBtnText.Show() + whellTicketBtn.whellTicketBtnText = whellTicketBtnText + + whellCoinBtn = ui.RadioButton() + whellCoinBtn.SetParent(wheelBg) + whellCoinBtn.SetUpVisual(WHEEL_DIR+"no_selected.tga") + whellCoinBtn.SetOverVisual(WHEEL_DIR+"no_selected.tga") + whellCoinBtn.SetDownVisual(WHEEL_DIR+"selected.tga") + whellCoinBtn.SetPosition(797,430) + whellCoinBtn.SetEvent(self.SetTicketMode,1) + whellCoinBtn.Show() + self.children["whellCoinBtn"] = whellCoinBtn + + whellCoinBtnText = MultiTextLine() + whellCoinBtnText.SetParent(whellCoinBtn) + whellCoinBtnText.SetPosition(29,-1) + whellCoinBtnText.SetTextRange(17) + whellCoinBtnText.SetTextType("horizontal#left") + whellCoinBtnText.SetFontName("Tahoma:14") + whellCoinBtnText.SetOutline(True) + whellCoinBtnText.SetText(localeInfo.ITEMSHOP_WHEEL_COIN_TEXT) + whellCoinBtnText.Show() + whellTicketBtn.whellCoinBtnText = whellCoinBtnText + + fortuneImg = ui.ImageBox() + fortuneImg.SetParent(wheelBg) + fortuneImg.AddFlag("not_pick") + fortuneImg.LoadImage(WHEEL_DIR+"fortune.tga") + fortuneImg.SetPosition(308,43) + fortuneImg.Show() + self.children["fortuneImg"] = fortuneImg + + fortuneSingle = ui.ExpandedImageBox() + fortuneSingle.SetParent(fortuneImg) + fortuneSingle.AddFlag("not_pick") + fortuneSingle.LoadImage(WHEEL_DIR+"single.tga") + fortuneSingle.SetPosition(125,6)#0 index. + fortuneSingle.Show() + self.children["fortuneSingle"] = fortuneSingle + + wheelCircle = ui.ExpandedImageBox() + wheelCircle.SetParent(fortuneImg) + wheelCircle.LoadImage(WHEEL_DIR+"circle.tga") + wheelCircle.AddFlag("not_pick") + wheelCircle.SetPosition(125,111) + wheelCircle.Show() + self.children["wheelCircle"] = wheelCircle + + wheelStartBtn = ui.Button() + wheelStartBtn.SetParent(fortuneImg) + wheelStartBtn.SetUpVisual(WHEEL_DIR+"wheel_0.tga") + wheelStartBtn.SetOverVisual(WHEEL_DIR+"wheel_1.tga") + wheelStartBtn.SetDownVisual(WHEEL_DIR+"wheel_2.tga") + wheelStartBtn.SetPosition(130,130) + wheelStartBtn.SetEvent(ui.__mem_func__(self.StartWheel)) + wheelStartBtn.Show() + self.children["wheelStartBtn"] = wheelStartBtn + + itemPosition = [[175,40], [245, 65], [290, 135], [290, 210], [245, 265], [175, 295], [100, 270], [60, 210], [55, 135], [100, 65]] + for j in xrange(len(itemPosition)): + wheelItem = ImageBoxSpecial() + wheelItem.SetParent(fortuneImg) + wheelItem.AddFlag("movable") + wheelItem.SetPosition(itemPosition[j][0],itemPosition[j][1]) + wheelItem.SetSize(32,32) + wheelItem.Show() + wheelItem.index = j + self.children["wheelItem%d"%j] = wheelItem + + self.SetTrailerMode() + self.SetTicketMode(0) + + self.SetDragonCoin(0) + self.SetCenterPosition() + self.LoadShopCategory() + + def SetTrailerMode(self): + self.children["wheelStep"] = 0 + self.children["circleRotation"] = 0 + self.children["wheelRotation"] = 0 + for j in xrange(10): + for x in xrange(10): + itemData = wheel_random_items[app.GetRandom(0,len(wheel_random_items)-1)] + item.SelectItem(itemData[0]) + self.children["wheelItem%d"%j].LoadImage(item.GetIconImageFileName(), itemData[0], itemData[1]) + + def UpdateSingleFortune(self): + single_pos = [[125,6,0], [193,33,35], [230,92,70], [228,161,110], [185,215,142], [117,237,180], [54,216,215], [11,159,250], [11,86,285], [53,26,324]] + index = self.GetRotationToIndex(self.children["circleRotation"]) + self.children["fortuneSingle"].SetRotation(single_pos[index][2]) + self.children["fortuneSingle"].SetPosition(single_pos[index][0],single_pos[index][1]) + + def OnSetWhell(self, giftIndex): + self.giftIndex = giftIndex + self.children["wheelRotation"] = self.GetGiftRotation(giftIndex) + + if self.children["wheelSpinCheckFlag"] == False: + self.children["wheelStep"] = app.GetRandom(10, 15) + else: + self.children["wheelStep"] = 0 + self.children["circleRotation"] = self.children["wheelRotation"] + self.children["wheelCircle"].SetRotation(self.children["circleRotation"]) + self.UpdateSingleFortune() + self.SendServerDone() + + def SetWheelItemData(self, data): + for j in xrange(10): + self.children["wheelItem%d"%j].Clear() + index = 0 + splitData = data.split("#") + for splitText in splitData: + splitItem = splitText.split("|") + if len(splitItem) == 2: + item.SelectItem(int(splitItem[0])) + self.children["wheelItem%d"%index].LoadImage(item.GetIconImageFileName(), int(splitItem[0]), int(splitItem[1])) + index += 1 + + def StartWheel(self): + net.SendChatPacket("/ishop wheel start %d"% self.children["wheelCointType"]) + + def SendServerDone(self): + net.SendChatPacket("/ishop wheel done") + + def CloseMessageWindow(self): + if self.children.has_key("message_window"): + msgWindow = self.children["message_window"] + if msgWindow != None: + msgWindow.Hide() + msgWindow = None + + def GetWheelGiftData(self, itemVnum, itemCount): + self.CloseMessageWindow() + self.children["message_window"] = MessageWindow() + self.children["message_window"].LoadMessage(itemVnum, itemCount) + + def SetTicketMode(self, index): + if not self.children.has_key("wheelSpinCheckFlag"): + self.children["wheelSpinCheckFlag"] = False + self.children["wheelCointType"] = index + self.__ClickRadioButton([self.children["whellTicketBtn"],self.children["whellCoinBtn"]],index) + self.SetSpintAnimation(self.children["wheelSpinCheckFlag"]) + + def WheelBtn(self): + self.children["wheelBg"].Show() + + def BackToItemShop(self): + self.children["wheelBg"].Hide() + + def SetSpintAnimation(self, flag): + self.children["wheelSpinCheckFlag"] = flag + text = localeInfo.ITEMSHOP_WHEEL_SKIP_ANIMATION + "\n" + if self.children["wheelCointType"] == 0: + text += localeInfo.ITEMSHOP_WHEEL_TICKET_TEXT_INFO + else: + text += localeInfo.ITEMSHOP_WHEEL_COIN_TEXT_INFO + self.children["wheelSpinCheckText"].SetText(text) + + def GetGiftRotation(self, giftIndex): + if giftIndex == 0: + if app.GetRandom(0,1) == 0: + return 341+app.GetRandom(4,18) + else: + return app.GetRandom(4,19) + else: + listofIndex = [0,20,58,94,126,160,196,232,268,304,341] + return listofIndex[giftIndex]+app.GetRandom(4,28) + + def GetRotationToIndex(self, rotation): + if rotation >= 341 and rotation <= 360 or rotation <= 20: + return 0 + elif rotation >= 305 and rotation <= 305+38: + return 9 + elif rotation >= 269 and rotation <= 269+38: + return 8 + elif rotation >= 233 and rotation <= 233+38: + return 7 + elif rotation >= 197 and rotation <= 197+38: + return 6 + elif rotation >= 161 and rotation <= 161+38: + return 5 + elif rotation >= 127 and rotation <= 127+38: + return 4 + elif rotation >= 95 and rotation <= 95+38: + return 3 + elif rotation >= 59 and rotation <= 59+38: + return 2 + elif rotation >= 21 and rotation <= 21+38: + return 1 + return 0 + + def OnUpdate(self): + if self.children["wheelStep"] > 0: + increaseValue = 0.5 * float((self.children["wheelStep"]*2)) + self.children["circleRotation"] += increaseValue + self.children["wheelCircle"].SetRotation(self.children["circleRotation"]) + self.UpdateSingleFortune() + if self.children["circleRotation"] >= 360: + if self.children["wheelStep"] > 1: + self.children["wheelStep"]-= 1 + self.children["circleRotation"]= 0 + if self.children["wheelStep"] == 1 and self.children["wheelRotation"] == self.children["circleRotation"]: + self.children["wheelStep"] -= 1 + self.SendServerDone() + return + + if self.children.has_key("itemListBox"): + listboxData = self.children["itemListBox"].GetItems() + for itemPointer in listboxData: + itemPointer.OnUpdate() + if self.children.has_key("LoadingImage"): + LoadingImage = self.children["LoadingImage"] + if LoadingImage.IsShow(): + self.children["LoadingImageRotation"] += 15 + LoadingImage.SetRotation(self.children["LoadingImageRotation"]) + + if self.MoneyFlag == True: + if self.moneySize>=0 and self.moneySize<=15: + if self.NewMoney > self.RealMoney: + self.RealMoney += ((self.MoneyRange)/15) + self.SetDragonCoinReal(self.RealMoney) + else: + self.RealMoney -= ((self.MoneyRange)/15) + self.SetDragonCoinReal(self.RealMoney) + self.moneySize+=1 + if self.moneySize ==15: + self.RealMoney = self.NewMoney + self.SetDragonCoinReal(self.RealMoney) + self.MoneyFlag = False + + def __OnValueUpdate(self): + itemSearch = self.children["itemSearch"] + ui.EditLine.OnIMEUpdate(itemSearch) + + self.ClearItemList() + searchItemList = [] + searchText = itemSearch.GetText().lower() + if len(searchText) > 0: + for key, data in itemshopData.items(): + for itemList in data: + for itemData in itemList: + item.SelectItem(itemData[LIST_ITEM_VNUM]) + if item.GetItemName().lower().find(searchText) != -1: + searchItemList.append(itemData) + self.RefreshItemList(searchItemList) + else: + self.LoadFirstOpening() + + + def LoadShopCategory(self): + self.categoryIndex = -1 + self.categorySubIndex = -1 + categoryListBox = self.children["categoryListBox"] + for key, data in itemShopCategoryData.items(): + categoryItem = CategoryItem() + categoryItem.SetParent(categoryListBox) + categoryItem.SetPosition(0,len(categoryListBox.GetItems())*57,True) + categoryItem.SetData(key, data["name"],categoryListBox) + categoryItem.SAFE_SetStringEvent("MOUSE_OVER_IN",self.OverInCategory,key, proxy(categoryItem)) + categoryItem.SAFE_SetStringEvent("MOUSE_OVER_OUT",self.OverOutCategory, key, proxy(categoryItem)) + categoryItem.SetEvent(self.ClickCategory, "mouse_click", key, -1) + categoryItem.Show() + categoryListBox.AppendItem(categoryItem) + categoryListBox.SetBasePos(1) + + def ClickCategory(self, emptyArg, categoryIndex, categorySubIndex = -1): + if self.categoryIndex == categoryIndex: + if categorySubIndex == self.categorySubIndex: + return + + oldIndex = self.categoryIndex + self.categoryIndex = categoryIndex + self.categorySubIndex = categorySubIndex + + categoryItems = self.children["categoryListBox"].GetItems() + for category in categoryItems: + if category.categoryIndex == oldIndex: + self.OverOutCategory(oldIndex, category) + elif category.categoryIndex == categoryIndex: + self.OverInCategory(categoryIndex, category) + + self.UpdateSubCategoryWindow() + self.RefreshItem() + + def OverOutCategory(self, categoryIndex, categoryItem): + self.ClearSubCategoryWindow() + if categoryIndex==self.categoryIndex: + return + categoryItem.LoadImage(IMG_DIR+"category_no_selected.tga") + categoryItem.OnRender() + + def OverInCategory(self, categoryIndex, categoryItem): + self.ClearSubCategoryWindow() + subCategoryBtns = self.CreateSubCategoryWindow(categoryIndex) + if subCategoryBtns != None: + subCategoryBtns.Show() + (px,py) = categoryItem.parent.GetLocalPosition() + maxYPos = py+categoryItem.parent.GetHeight() + (x, y) = categoryItem.GetLocalPosition() + + if y <= 0: + subCategoryBtns.SetPosition(px+categoryItem.GetWidth()+2,py) + elif (py+y+(len(subCategoryBtns.children)*39)) <= maxYPos: + subCategoryBtns.SetPosition(px+categoryItem.GetWidth()+2,py+y) + else: + subCategoryBtns.SetPosition(px+categoryItem.GetWidth()+2,maxYPos-(len(subCategoryBtns.children)*39)-1) + self.children["subCategoryBtns"]=subCategoryBtns + + categoryItem.LoadImage(IMG_DIR+"category_selected.tga") + categoryItem.OnRender() + + def UpdateSubCategoryWindow(self): + if self.children.has_key("subCategoryBtns"): + subCategoryBtns = self.children["subCategoryBtns"] + if subCategoryBtns != None: + if subCategoryBtns.categoryIndex == self.categoryIndex: + if self.categorySubIndex != -1: + self.__ClickRadioButton(subCategoryBtns.children, self.categorySubIndex) + + def ClearSubCategoryWindow(self): + if self.children.has_key("subCategoryBtns"): + subCategoryBtns = self.children["subCategoryBtns"] + if subCategoryBtns != None: + (x, y) = app.GetCursorPosition() + (sx,sy) = subCategoryBtns.GetGlobalPosition() + if x >= sx and x <= sx+115: + if y >= sy and y <= sy+(len(subCategoryBtns.children)*39): + return + + if subCategoryBtns: + for children in subCategoryBtns.children: + children.backText = None + subCategoryBtns.children = None + subCategoryBtns.Hide() + + self.children["subCategoryBtns"] = None + + def CreateSubCategoryWindow(self, categoryIndex): + if not itemShopCategoryData.has_key(categoryIndex): + return None + categoryData = itemShopCategoryData[categoryIndex]["subCategory"] + if len(categoryData) == 0: + return None + + subCategoryBtns = ui.ImageBox() + subCategoryBtns.SetParent(self) + children = [] + + for j in xrange(len(categoryData)): + categoryBtn = ui.RadioButton() + categoryBtn.SetParent(subCategoryBtns) + categoryBtn.SetUpVisual(IMG_DIR+"submenu_selected.tga") + categoryBtn.SetOverVisual(IMG_DIR+"submenu_selected2.tga") + categoryBtn.SetDownVisual(IMG_DIR+"submenu_selected2.tga") + categoryBtn.SetHideToolTipEvent(ui.__mem_func__(self.ClearSubCategoryWindow)) + categoryBtn.SetEvent(self.ClickCategory, "", categoryIndex, j) + categoryBtn.SetPosition(0,39*j) + categoryBtn.Show() + + categoryBtnText = MultiTextLine() + categoryBtnText.SetParent(categoryBtn) + categoryBtnText.SetTextRange(15) + categoryBtnText.SetPosition(categoryBtn.GetWidth()/2,8) + categoryBtnText.SetTextType("horizontal#center") + categoryBtnText.SetFontName("Tahoma:16") + categoryBtnText.SetText(categoryData[j]) + categoryBtnText.Show() + categoryBtn.backText = categoryBtnText + children.append(categoryBtn) + subCategoryBtns.categoryIndex = categoryIndex + subCategoryBtns.children = children + if self.categoryIndex == categoryIndex: + if self.categorySubIndex != -1: + self.__ClickRadioButton(subCategoryBtns.children, self.categorySubIndex) + subCategoryBtns.SetSize(115, len(children)*39) + return subCategoryBtns + + def RefreshItem(self): + self.ClearItemList() + itemListBox = self.children["itemListBox"] + if itemshopData.has_key(self.categoryIndex): + itemData = itemshopData[self.categoryIndex] + if self.categorySubIndex == -1: + allList = [] + for itemList in itemData: + for shopItem in itemList: + allList.append(shopItem) + self.RefreshItemList(allList) + else: + if self.categorySubIndex >= len(itemData): + return + itemList = itemData[self.categorySubIndex] + self.RefreshItemList(itemList) + + def SortList(self, itemDataList): + sortData = [] + for itemData in itemDataList: + sortItem = SortClass(itemData) + sortData.append(sortItem) + sortData.sort() + itemDataListEx = [] + for shortItem in sortData: + itemDataListEx.append(shortItem.arg) + return itemDataListEx + + def ClearItemList(self): + itemListBox = self.children["itemListBox"] + itemListBox.RemoveAllItems() + + def RefreshItemList(self, itemDataList): + self.ClosePurchasesWindow() + if len(itemDataList) == 0: + return + itemListBox = self.children["itemListBox"] + + itemDataList = self.SortList(itemDataList) + itemWindowPtr = ItemWindow(itemListBox) + itemWindowPtr.SetParent(itemListBox) + itemWindowPtr.SetPosition(0,len(itemListBox.GetItems())*132, True) + itemWindowPtr.Show() + for shopItem in itemDataList: + xItem = ItemShopItem() + xItem.SetParent(itemWindowPtr) + xItem.SetMouseWheelScrollEvent(itemListBox.OnMouseWheelScroll_ScrollBar) + xItem.SetPosition(len(itemWindowPtr.children)*250,0) + xItem.LoadData(shopItem) + xItem.Show() + itemWindowPtr.AppendWindow(xItem) + if len(itemWindowPtr.children) == 3: + itemListBox.AppendItem(itemWindowPtr) + itemWindowPtr = ItemWindow(itemListBox) + itemWindowPtr.SetParent(itemListBox) + itemWindowPtr.SetPosition(0,len(itemListBox.GetItems())*132, True) + itemWindowPtr.Show() + if itemWindowPtr != None: + if len(itemWindowPtr.children) > 0: + itemListBox.AppendItem(itemWindowPtr) + + def InsertItemWithType(self, itemDataList, insertType): + currentTime = app.GetGlobalTimeStamp() + for key, data in itemshopData.items(): + for categoryItems in data: + for itemData in categoryItems: + if insertType == LIST_ITEM_DISCOUNT: + if itemData[LIST_ITEM_DISCOUNT] > 0 or itemData[LIST_ITEM_TIME] > 0: + if not itemData in itemDataList: + itemDataList.append(itemData) + elif insertType == LIST_ITEM_TOP_SELLING_INDEX: + if itemData[LIST_ITEM_TOP_SELLING_INDEX] >= 0 and itemData[LIST_ITEM_TOP_SELLING_INDEX] <= 10: + if not itemData in itemDataList: + itemDataList.append(itemData) + elif insertType == LIST_ITEM_ADDED_TIME: + if itemData[LIST_ITEM_ADDED_TIME] > currentTime-(60*60*24*3): + if not itemData in itemDataList: + itemDataList.append(itemData) + else: + itemDataList.append(itemData) + + return itemDataList + + def OfferItems(self): + self.ClearItemList() + itemDataList = [] + itemDataList = self.InsertItemWithType(itemDataList, LIST_ITEM_DISCOUNT) + self.RefreshItemList(itemDataList) + + def HotItems(self): + self.ClearItemList() + + itemDataList = [] + itemDataList = self.InsertItemWithType(itemDataList, LIST_ITEM_TOP_SELLING_INDEX) + self.RefreshItemList(itemDataList) + + def LoadFirstOpening(self): + self.categoryIndex = -1 + self.categorySubIndex = -1 + self.ClearItemList() + itemListBox = self.children["itemListBox"] + + if len(eventCategory) <= 3: + itemWindowPtr = ItemWindow(itemListBox) + itemWindowPtr.SetParent(itemListBox) + itemWindowPtr.SetPosition(0,len(itemListBox.GetItems())*132, True) + itemWindowPtr.Show() + for banner in xrange(len(eventCategory)): + xBanner = ItemShopBanner() + xBanner.SetParent(itemWindowPtr) + xBanner.SetMouseWheelScrollEvent(itemListBox.OnMouseWheelScroll_ScrollBar) + + xBanner.SetPosition(len(itemWindowPtr.children)*250,0) + xBanner.LoadData(banner) + xBanner.SAFE_SetStringEvent("MOUSE_OVER_IN",self.OverInBanner,banner, proxy(xBanner)) + xBanner.SAFE_SetStringEvent("MOUSE_OVER_OUT",self.OverOutBanner, banner, proxy(xBanner)) + xBanner.SetEvent(self.ClickBanner, "mouse_click", eventCategory[banner][1][0],eventCategory[banner][1][1]) + xBanner.Show() + itemWindowPtr.AppendWindow(xBanner) + if itemWindowPtr != None: + if len(itemWindowPtr.children) > 0: + itemListBox.AppendItem(itemWindowPtr) + + itemDataList = [] + itemDataList = self.InsertItemWithType(itemDataList, LIST_ITEM_TOP_SELLING_INDEX) + itemDataList = self.InsertItemWithType(itemDataList, LIST_ITEM_DISCOUNT) + itemDataList = self.InsertItemWithType(itemDataList, LIST_ITEM_ADDED_TIME) + if len(itemDataList) == 0: + itemDataList = self.InsertItemWithType(itemDataList, 99) + itemDataList = self.SortList(itemDataList) + self.RefreshItemList(itemDataList) + + def ClickBanner(self, emptyArg, categoryIndex, categorySubIndex): + self.categoryIndex = categoryIndex + self.categorySubIndex = categorySubIndex + self.RefreshItem() + + def BuyDragonCoin(self): + self.LoadFirstOpening() + #os.system("start \"\" "+WEBSITE_LINK) + + def OpenWeb(self, url): + self.CloseWeb() + webWnd = WebWindow(self) + webWnd.Open(url) + self.children["WebWindow"] = webWnd + + def CloseWeb(self): + if self.children.has_key("WebWindow"): + webWnd = self.children["WebWindow"] + webWnd.Close() + webWnd.Destroy() + del self.children["WebWindow"] + + def OverOutBanner(self, index, bannerItem): + bannerItem.LoadImage(IMG_DIR+eventCategory[index][0][0]) + bannerItem.OnRender(self.children["itemListBox"]) + + def OverInBanner(self, index, bannerItem): + bannerItem.LoadImage(IMG_DIR+eventCategory[index][0][1]) + bannerItem.OnRender(self.children["itemListBox"]) + + def PurchaseBtn(self): + self.OpenPurchasesWindow() + + def SetDragonCoinReal(self, dragonCoinValue): + text = NumberToMoneyFormat(dragonCoinValue)+"\n|cffF8BE47"+localeInfo.ITEMSHOP_DRAGONCOINT + self.children["dragonCoinText"].SetText(text) + + def UpdateItem(self, itemID, itemMaxSellingCount): + itemList = self.children["itemListBox"].GetItems() + for listBox in itemList: + for shopItem in listBox.children: + if isinstance(shopItem, ItemShopItem): + if shopItem.data[LIST_ITEM_ID] == itemID: + shopItem.data[LIST_ITEM_MAX_SELLING_COUNT] = itemMaxSellingCount + shopItem.LoadData(shopItem.data) + + def SetDragonCoin(self, dragonCoinValue): + if self.RealMoney==0: + self.RealMoney = dragonCoinValue + self.SetDragonCoinReal(self.RealMoney) + else: + self.NewMoney = dragonCoinValue + if self.NewMoney == self.RealMoney: + self.MoneyFlag = False + else: + self.MoneyFlag = True + self.MoneyRange = self.NewMoney - self.RealMoney + self.moneySize = 0 + + def Open(self): + if not self.children.has_key("sendPacketData"): + self.children["sendPacketData"] = 1 + self.children["LoadingImage"].Show() + self.LoadFirstOpening() + global UPDATE_TIME + net.SendChatPacket("/ishop data %d" % UPDATE_TIME) + + self.Show() + self.SetTop() + + def CloseLoading(self): + self.children["LoadingImage"].Hide() + + def OpenPurchasesWindow(self): + self.BackToItemShop() + self.children["itemListBox"].Hide() + self.children["itemScrollBar"].Hide() + self.children["categoryListBox"].Hide() + self.children["categoryScrollBar"].Hide() + + self.children["PurchasesScrollBar"].Show() + self.children["PurchasesListBox"].Show() + + if not self.children.has_key("sendPacketDataLog"): + self.children["sendPacketDataLog"] = 1 + self.children["LoadingImage"].Show() + net.SendChatPacket("/ishop log") + else: + self.RefreshPurchasesWindow() + + def SortPurchasesWindow(self): + global playerLog + sortData = [] + for logData in playerLog: + sortLog = SortClass(logData,True) + sortData.append(sortLog) + sortData.sort() + logDataList = [] + for sortLog in sortData: + logDataList.append(sortLog.arg) + return logDataList + + def RefreshPurchasesWindow(self): + + PurchasesListBox = self.children["PurchasesListBox"] + PurchasesListBox.Show() + PurchasesListBox.RemoveAllItems() + + global playerLog + playerLog = self.SortPurchasesWindow() + + logTitle = PurchasesLog(PurchasesListBox) + logTitle.SetParent(PurchasesListBox) + logTitle.LoadData(-1) + logTitle.SetPosition(0,0, True) + logTitle.Show() + PurchasesListBox.AppendItem(logTitle) + + for j in xrange(len(playerLog)): + logItem = PurchasesLog(PurchasesListBox) + logItem.SetParent(PurchasesListBox) + logItem.LoadData(j) + logItem.SetPosition(0,len(PurchasesListBox.GetItems())*35, True) + logItem.Show() + PurchasesListBox.AppendItem(logItem) + PurchasesListBox.Render(0) + + def ClosePurchasesWindow(self): + self.BackToItemShop() + self.children["PurchasesScrollBar"].Hide() + self.children["PurchasesListBox"].Hide() + + self.children["itemListBox"].Show() + self.children["itemScrollBar"].Show() + self.children["categoryListBox"].Show() + self.children["categoryScrollBar"].Show() + + def Close(self): + self.CloseMessageWindow() + if self.children["wheelStep"] > 0: + self.children["wheelStep"] = 0 + self.children["circleRotation"] = self.children["wheelRotation"] + self.children["wheelCircle"].SetRotation(self.children["circleRotation"]) + self.UpdateSingleFortune() + self.SendServerDone() + + self.CloseWeb() + + global buyQuestionDialog + if buyQuestionDialog != None: + buyQuestionDialog.Hide() + buyQuestionDialog.Destroy() + buyQuestionDialog=None + + self.Hide() + def OnPressEscapeKey(self): + self.Close() + return True + def __ClickRadioButton(self, buttonList, buttonIndex): + try: + btn=buttonList[buttonIndex] + except IndexError: + return + for eachButton in buttonList: + eachButton.SetUp() + btn.Down() + +class PurchasesLog(ui.ExpandedImageBox): + def __del__(self): + ui.ExpandedImageBox.__del__(self) + def Destroy(self): + self.childrenImages = {} + self.childrenTextLine = {} + self.parent = None + def __init__(self, parent): + ui.ExpandedImageBox.__init__(self) + self.Destroy() + self.parent = proxy(parent) + def LoadData(self, index): + if index >= 0: + self.childrenImages["self"] = self + self.LoadImage(IMG_DIR+"purch_img.tga") + + try: + logData = playerLog[index] + except: + return + + if index >= 0: + dateText = logData[LOG_DATE_TEXT] + accountText = logData[LOG_ACCOUNT] + ipText = logData[LOG_IP] + if logData[LOG_ITEM] == 1: + itemText = localeInfo.ITEMSHOP_WHEEL_PURCHASE + else: + item.SelectItem(logData[LOG_ITEM]) + if logData[LOG_COUNT] > 1: + itemText = "|cffF7BD48%sx%d|r" % (item.GetItemName(),logData[LOG_COUNT]) + else: + itemText = "|cffF7BD48%s|r" % item.GetItemName() + priceText = localeInfo.PURCHASES_PRICE_TEXT % NumberToMoneyFormat(logData[LOG_PRICE]) + else: + dateText = localeInfo.PURCHASES_DATE + accountText = localeInfo.PURCHASES_ACCOUNTID + ipText = localeInfo.PURCHASES_IP + itemText = localeInfo.PURCHASES_ITEMBOUGHT + priceText = localeInfo.PURCHASES_PRICE + + textList = [ + [75,5,dateText], + [260,5,accountText], + [400,5,ipText], + [600,5,itemText], + [800,5,priceText], + ] + for j in xrange(len(textList)): + text = textList[j] + logText = ui.TextLine() + logText.SetParent(self) + logText.SetFontName("Tahoma:13") + logText.SetText(text[2]) + logText.SetHorizontalAlignCenter() + if index >= 0: + logText.SetPosition(text[0],text[1]) + else: + logText.SetPosition(text[0],0) + logText.Show() + self.childrenTextLine["text%d"%j] = logText + + def OnRender(self): + listboxHeight = self.parent.GetHeight() + (pgx,pgy) = self.parent.GetGlobalPosition() + for key, textline in self.childrenTextLine.items(): + (igx,igy) = textline.GetGlobalPosition() + if igy < pgy: + textline.Hide() + elif igy > (pgy+listboxHeight-25): + textline.Hide() + else: + textline.Show() + for key, image in self.childrenImages.items(): + (jgx,jgy) = image.GetGlobalPosition() + imageHeight = image.GetHeight() + if jgy < pgy: + image.SetRenderingRect(0,ui.calculateRect(imageHeight-abs(jgy-pgy),imageHeight),0,0) + elif jgy+imageHeight > (pgy+listboxHeight-8): + calculate = (pgy+listboxHeight-8) - (jgy+imageHeight) + if calculate == 0: + return + image.SetRenderingRect(0.0,0.0,0.0,ui.calculateRect(imageHeight-abs(calculate),imageHeight)) + else: + image.SetRenderingRect(0,0,0,0) + +class ItemShopBoard(ui.Window): + CORNER_WIDTH = 7 + CORNER_HEIGHT = 7 + LINE_WIDTH = 7 + LINE_HEIGHT = 7 + LT = 0 + LB = 1 + RT = 2 + RB = 3 + L = 0 + R = 1 + T = 2 + B = 3 + def __init__(self): + ui.Window.__init__(self) + self.MakeBoard() + self.MakeBase() + def MakeBoard(self): + cornerPath = IMG_DIR+"board/corner_" + linePath = IMG_DIR+"board/" + CornerFileNames = [ cornerPath+dir+".tga" for dir in ("left_top", "left_bottom", "right_top", "right_bottom") ] + LineFileNames = [ linePath+dir+".tga" for dir in ("left", "right", "top", "bottom") ] + self.Corners = [] + for fileName in CornerFileNames: + Corner = ui.ExpandedImageBox() + Corner.AddFlag("not_pick") + Corner.LoadImage(fileName) + Corner.SetParent(self) + Corner.SetPosition(0, 0) + Corner.Show() + self.Corners.append(Corner) + self.Lines = [] + for fileName in LineFileNames: + Line = ui.ExpandedImageBox() + Line.AddFlag("not_pick") + Line.LoadImage(fileName) + Line.SetParent(self) + Line.SetPosition(0, 0) + Line.Show() + self.Lines.append(Line) + self.Lines[self.L].SetPosition(0, self.CORNER_HEIGHT) + self.Lines[self.T].SetPosition(self.CORNER_WIDTH, 0) + def MakeBase(self): + self.Base = ui.ExpandedImageBox() + self.Base.AddFlag("not_pick") + self.Base.LoadImage(IMG_DIR+"board/base.tga") + self.Base.SetParent(self) + self.Base.SetPosition(self.CORNER_WIDTH, self.CORNER_HEIGHT) + self.Base.Show() + def __del__(self): + ui.Window.__del__(self) + def Destroy(self): + self.Base=0 + self.Corners=0 + self.Lines=0 + self.CORNER_WIDTH = 0 + self.CORNER_HEIGHT = 0 + self.LINE_WIDTH = 0 + self.LINE_HEIGHT = 0 + self.LT = 0 + self.LB = 0 + self.RT = 0 + self.RB = 0 + self.L = 0 + self.R = 0 + self.T = 0 + self.B = 0 + def SetSize(self, width, height): + width = max(self.CORNER_WIDTH*2, width) + height = max(self.CORNER_HEIGHT*2, height) + ui.Window.SetSize(self, width, height) + self.Corners[self.LB].SetPosition(0, height - self.CORNER_HEIGHT) + self.Corners[self.RT].SetPosition(width - self.CORNER_WIDTH, 0) + self.Corners[self.RB].SetPosition(width - self.CORNER_WIDTH, height - self.CORNER_HEIGHT) + self.Lines[self.R].SetPosition(width - self.CORNER_WIDTH, self.CORNER_HEIGHT) + self.Lines[self.B].SetPosition(self.CORNER_HEIGHT, height - self.CORNER_HEIGHT) + verticalShowingPercentage = float((height - self.CORNER_HEIGHT*2) - self.LINE_HEIGHT) / self.LINE_HEIGHT + horizontalShowingPercentage = float((width - self.CORNER_WIDTH*2) - self.LINE_WIDTH) / self.LINE_WIDTH + self.Lines[self.L].SetRenderingRect(0, 0, 0, verticalShowingPercentage) + self.Lines[self.R].SetRenderingRect(0, 0, 0, verticalShowingPercentage) + self.Lines[self.T].SetRenderingRect(0, 0, horizontalShowingPercentage, 0) + self.Lines[self.B].SetRenderingRect(0, 0, horizontalShowingPercentage, 0) + if self.Base: + self.Base.SetRenderingRect(0, 0, horizontalShowingPercentage, verticalShowingPercentage) + +class WebWindow(ItemShopBoard): + def __del__(self): + ItemShopBoard.__del__(self) + def Destroy(self): + self.oldPos=(0,0) + self.closeBtn=None + self.parent = None + def __init__(self, parent): + ItemShopBoard.__init__(self) + self.Destroy() + self.parent = proxy(parent) + self.LoadWindow() + def LoadWindow(self): + self.AddFlag("attach") + self.AddFlag("float") + #self.AddFlag("movable") + self.SetSize(450*2,450) + closeBtn = ui.Button() + closeBtn.SetParent(self) + closeBtn.SetUpVisual(IMG_DIR+"close_0.tga") + closeBtn.SetOverVisual(IMG_DIR+"close_1.tga") + closeBtn.SetDownVisual(IMG_DIR+"close_2.tga") + closeBtn.SetPosition(self.GetWidth()-closeBtn.GetWidth(),0) + closeBtn.SetEvent(self.parent.CloseWeb) + closeBtn.Show() + self.closeBtn=closeBtn + + def Close(self): + app.HideWebPage() + self.Hide() + + def Open(self, url): + self.SetSize(450*2,450) + self.Show() + self.SetTop() + self.SetCenterPosition() + + x, y = self.GetGlobalPosition() + sx, sy = x + 10, y + 30 + ex, ey = sx + self.GetWidth() - 20, sy + self.GetHeight() - 40 + app.ShowWebPage(url, (sx, sy, ex, ey)) + + def OnUpdate(self): + newPos = self.GetGlobalPosition() + if newPos == self.oldPos: + return + self.oldPos = newPos + x, y = newPos + sx, sy = x + 10, y + 30 + ex, ey = sx + self.GetWidth() - 20, sy + self.GetHeight() - 40 + app.MoveWebPage((sx, sy, ex, ey)) + +class BuyWindow(ItemShopBoard): + def __del__(self): + ItemShopBoard.__del__(self) + def __init__(self): + ItemShopBoard.__init__(self) + self.AddFlag("attach") + self.AddFlag("float") + self.Destroy() + buyText = MultiTextLine() + buyText.SetParent(self) + buyText.SetTextRange(25) + buyText.SetPosition(self.GetWidth()/2,28) + buyText.SetTextType("horizontal#center") + buyText.SetFontName("Tahoma:16") + buyText.Show() + self.children["buyText"] = buyText + yesBtn = ui.Button() + yesBtn.SetParent(self) + yesBtn.SetUpVisual(IMG_DIR+"buy_0.tga") + yesBtn.SetOverVisual(IMG_DIR+"buy_1.tga") + yesBtn.SetDownVisual(IMG_DIR+"buy_2.tga") + yesBtn.SetDownVisual(IMG_DIR+"buy_2.tga") + yesBtn.SetText(localeInfo.YES) + yesBtn.Show() + self.children["yesBtn"] = yesBtn + cancelBtn = ui.Button() + cancelBtn.SetParent(self) + cancelBtn.SetUpVisual(IMG_DIR+"buy_0.tga") + cancelBtn.SetOverVisual(IMG_DIR+"buy_1.tga") + cancelBtn.SetDownVisual(IMG_DIR+"buy_2.tga") + cancelBtn.SetText(localeInfo.UI_CANCEL) + cancelBtn.Show() + self.children["cancelBtn"] = cancelBtn + def Destroy(self): + self.children={} + def SetText(self, text): + buyText = self.children["buyText"] + buyText.SetText(text) + (x, y) = buyText.GetTextSize() + (minWidth,minHeight) = (256,142) + if x+40 > minWidth: + minWidth = x+40 + if not ((minWidth%2) == 0): + minWidth+=1 + self.SetSize(minWidth,minHeight) + buyText.SetPosition(self.GetWidth()/2,28) + self.children["yesBtn"].SetPosition((self.GetWidth()/2)+15,94) + self.children["cancelBtn"].SetPosition((self.GetWidth()/2)-self.children["cancelBtn"].GetWidth()-15,94) + def SetCancelEvent(self, func): + self.children["cancelBtn"].SetEvent(func) + def SetAcceptEvent(self, func): + self.children["yesBtn"].SetEvent(func) + def OnPressEscapeKey(self): + self.children["cancelBtn"].CallEvent() + return True + +class SortClass: + def __init__(self, arg, isLog = False): + self.arg = arg + self.isLog = isLog + def __del__(self): + self.arg = [] + def __lt__(self, other): + if self.isLog: + return self.arg[LOG_DATE] >= other.arg[LOG_DATE] + else: + currentTime = app.GetGlobalTimeStamp() + # hot item + if self.arg[LIST_ITEM_TOP_SELLING_INDEX] <= 10 or other.arg[LIST_ITEM_TOP_SELLING_INDEX] <= 10: + return self.arg[LIST_ITEM_TOP_SELLING_INDEX] <= other.arg[LIST_ITEM_TOP_SELLING_INDEX] + # time offer + if self.arg[LIST_ITEM_TIME] != 0 or other.arg[LIST_ITEM_TIME] != 0: + if self.arg[LIST_ITEM_TIME] > 0 and other.arg[LIST_ITEM_TIME] > 0: + return ((self.arg[LIST_ITEM_TIME]-currentTime) <= (other.arg[LIST_ITEM_TIME]-currentTime)) + else: + return self.arg[LIST_ITEM_TIME] >= other.arg[LIST_ITEM_TIME] + # discount + if self.arg[LIST_ITEM_DISCOUNT] != 0 or other.arg[LIST_ITEM_DISCOUNT] != 0: + return self.arg[LIST_ITEM_DISCOUNT] >= other.arg[LIST_ITEM_DISCOUNT] + # added time + if self.arg[LIST_ITEM_ADDED_TIME] > currentTime-(60*60*24*3) or other.arg[LIST_ITEM_ADDED_TIME] > currentTime-(60*60*24*3): + return self.arg[LIST_ITEM_ADDED_TIME] >= other.arg[LIST_ITEM_ADDED_TIME] + return self.arg[LIST_ITEM_ID] >= other.arg[LIST_ITEM_ID] + +class ItemShopBanner(ui.ExpandedImageBox): + def __del__(self): + ui.ExpandedImageBox.__del__(self) + def Destroy(self): + self.bannerIndex = -1 + self.childrenImages = {} + def __init__(self): + ui.ExpandedImageBox.__init__(self) + self.Destroy() + def LoadData(self, bannerIndex): + self.bannerIndex=bannerIndex + if bannerIndex >= len(eventCategory): + return + self.LoadImage(IMG_DIR+eventCategory[bannerIndex][0][0]) + self.childrenImages["self"] = self + def OnUpdate(self): + pass + def OnRender(self, parent): + listboxHeight = parent.GetHeight() + (pgx,pgy) = parent.GetGlobalPosition() + for key, image in self.childrenImages.items(): + (jgx,jgy) = image.GetGlobalPosition() + imageHeight = image.GetHeight() + if jgy < pgy: + image.SetRenderingRect(0,ui.calculateRect(imageHeight-abs(jgy-pgy),imageHeight),0,0) + elif jgy+imageHeight > (pgy+listboxHeight-8): + calculate = (pgy+listboxHeight-8) - (jgy+imageHeight) + if calculate == 0: + return + image.SetRenderingRect(0.0,0.0,0.0,ui.calculateRect(imageHeight-abs(calculate),imageHeight)) + else: + image.SetRenderingRect(0,0,0,0) + +class ItemShopItem(ui.ExpandedImageBox): + def __del__(self): + ui.ExpandedImageBox.__del__(self) + def __init__(self): + ui.ExpandedImageBox.__init__(self) + self.Destroy() + self.buyCount=1 + self.LoadImage(IMG_DIR+"item_box.tga") + self.childrenImages["self"] = self + def Destroy(self): + self.data = [] + self.buyCount=0 + self.butButtonSet = False + self.childrenImages = {} + self.childrenTextLine = {} + + def LoadData(self, itemData): + self.data = itemData + self.SetItem(itemData[LIST_ITEM_VNUM]) + self.SetCount() + self.SetItemName() + self.SetBuyButton(itemData[LIST_ITEM_TIME], itemData[LIST_ITEM_MAX_SELLING_COUNT]) + self.SetPrice(itemData[LIST_ITEM_PRICE],itemData[LIST_ITEM_DISCOUNT]) + self.SetTime(itemData[LIST_ITEM_TIME]) + self.SetLastSellCount(itemData[LIST_ITEM_MAX_SELLING_COUNT]) + + if itemData[LIST_ITEM_TOP_SELLING_INDEX] >= 0 and itemData[LIST_ITEM_TOP_SELLING_INDEX] <= 10: + self.SetItemType(1) + elif itemData[LIST_ITEM_TIME] > 0 or itemData[LIST_ITEM_DISCOUNT] > 0: + self.SetItemType(3) + elif itemData[LIST_ITEM_ADDED_TIME] > app.GetGlobalTimeStamp()-(60*60*24*3): + self.SetItemType(2) + + def SetLastSellCount(self, maxSellingCount): + if maxSellingCount != -1: + self.ClearChildren("maxSelling") + maxSelling = MultiTextLine() + maxSelling.SetParent(self) + maxSelling.SetTextRange(20) + maxSelling.SetTextType("horizontal#right") + maxSelling.SetFontName("Tahoma:12") + maxSelling.SetText(localeInfo.ITEMSHOP_LAST_COUNT%maxSellingCount) + maxSelling.SetPosition(self.GetWidth()-5, 4) + maxSelling.Show() + self.childrenTextLine["maxSelling"] = maxSelling + + def ClearChildren(self, childrenName): + if self.childrenTextLine.has_key(childrenName): + self.childrenTextLine[childrenName].Hide() + self.childrenTextLine[childrenName].Destroy() + del self.childrenTextLine[childrenName] + if self.childrenImages.has_key(childrenName): + self.childrenImages[childrenName].Hide() + self.childrenImages[childrenName].Destroy() + del self.childrenImages[childrenName] + + def FormatTime(self, seconds): + if seconds <= 0: + if self.butButtonSet == False: + self.SetBuyButton(self.data[LIST_ITEM_TIME]) + return "|cffFF7B7B0h 0m 0s" + m, s = divmod(seconds, 60) + h, m = divmod(m, 60) + d, h = divmod(h, 24) + if d > 0: + return "|cffFF7B7B%dd %dh %dm %ds"%(d,h,m,s) + return "|cffFF7B7B%dh %dm %ds" % (h,m,s) + + def OnUpdate(self): + if self.childrenTextLine.has_key("timeText"): + self.childrenTextLine["timeText"].SetText(self.FormatTime(self.data[LIST_ITEM_TIME]-app.GetGlobalTimeStamp())) + + def SetTime(self, time): + self.ClearChildren("timeText") + if time != 0: + self.butButtonSet = False + + timeText = ui.TextLine() + timeText.SetParent(self) + timeText.AddFlag("not_pick") + timeText.SetPosition(168,65) + timeText.SetWindowHorizontalAlignLeft() + timeText.SetFontName("Tahoma:13") + timeText.Show() + self.childrenTextLine["timeText"] = timeText + + def SetBuyButton(self, time, maxSellingCount = -1): + self.ClearChildren("buyButton") + self.butButtonSet = False + buyButton = ui.ExpandedImageBox() + buyButton.SetParent(self) + if((time != 0 and app.GetGlobalTimeStamp() > time) or maxSellingCount == 0): + buyButton.LoadImage(IMG_DIR+"button_buy_disabled.tga") + self.butButtonSet = True + else: + buyButton.LoadImage(IMG_DIR+"buy_0.tga") + buyButton.SAFE_SetStringEvent("MOUSE_OVER_IN",self.OverInBuyBtn) + buyButton.SAFE_SetStringEvent("MOUSE_OVER_OUT",self.OverOutBuyBtn) + buyButton.SetEvent(ui.__mem_func__(self.ClickBuyBtn),"mouse_click") + buyButton.SetPosition(168,82) + buyButton.Show() + self.childrenImages["buyButton"] = buyButton + + buyBtnText = ui.TextLine() + buyBtnText.SetParent(buyButton) + buyBtnText.AddFlag("not_pick") + buyBtnText.SetHorizontalAlignCenter() + buyBtnText.SetVerticalAlignCenter() + buyBtnText.SetWindowHorizontalAlignCenter() + buyBtnText.SetWindowVerticalAlignCenter() + buyBtnText.SetText(localeInfo.ITEMSHOP_BUY) + buyBtnText.Show() + self.childrenTextLine["buyBtnText"] = buyBtnText + + def ClickBuyBtn(self, emptyArg): + time = self.data[LIST_ITEM_TIME] + if time != 0 and app.GetGlobalTimeStamp() > time: + return + + global buyQuestionDialog + if buyQuestionDialog == None: + buyQuestionDialog = BuyWindow() + + text = "" + + price = self.data[LIST_ITEM_PRICE]*self.buyCount + discount = self.data[LIST_ITEM_DISCOUNT] + if discount > 0: + price = int((float(price)/100.0)*float(100-discount)) + + item.SelectItem(self.data[LIST_ITEM_VNUM]) + if self.buyCount > 1: + text+=localeInfo.ITEMSHOP_BUY_TEXT_COUNT % (item.GetItemName(),self.buyCount) + else: + text+=localeInfo.ITEMSHOP_BUY_TEXT % item.GetItemName() + + text+="\n" + text+=localeInfo.ITEMSHOP_PRICE_NEW % price + + buyQuestionDialog.SetText(text) + buyQuestionDialog.SetAcceptEvent(self.AcceptBuy) + buyQuestionDialog.SetCancelEvent(self.CloseQuestionDialog) + buyQuestionDialog.SetCenterPosition() + buyQuestionDialog.SetTop() + buyQuestionDialog.Show() + + def CloseQuestionDialog(self): + global buyQuestionDialog + if buyQuestionDialog!= None: + buyQuestionDialog.Hide() + buyQuestionDialog.Destroy() + buyQuestionDialog=None + + def AcceptBuy(self): + net.SendChatPacket("/ishop buy %d %d"%(self.data[LIST_ITEM_ID],self.buyCount)) + self.CloseQuestionDialog() + + def EmptyFunction(self): + pass + + def OverOutBuyBtn(self): + if self.childrenImages.has_key("buyButton"): + self.childrenImages["buyButton"].LoadImage(IMG_DIR+"buy_0.tga") + + def OverInBuyBtn(self): + if self.childrenImages.has_key("buyButton"): + self.childrenImages["buyButton"].LoadImage(IMG_DIR+"buy_1.tga") + + def SetPrice(self, price, discount): + self.ClearChildren("lineImage") + self.ClearChildren("itemPrice") + + itemPrice = MultiTextLine() + itemPrice.AddFlag("not_pick") + itemPrice.SetParent(self) + itemPrice.SetTextRange(20) + itemPrice.SetPosition(95, 35) + itemPrice.SetTextType("horizontal#left") + itemPrice.SetFontName("Tahoma:13") + + price = price*self.buyCount + + text= "" + if discount > 0: + newPrice = int((float(price)/100.0)*float(100-discount)) + + text = localeInfo.ITEMSHOP_PRICE_ONLY_TEXT % NumberToMoneyFormat(price) + itemPriceEx = ui.TextLine() + itemPriceEx.SetParent(self) + itemPriceEx.SetText(text) + (xSize,ySize) = itemPriceEx.GetTextSize() + + text = localeInfo.ITEMSHOP_PRICE_WITH_DISCOUNT % (NumberToMoneyFormat(price),discount) + text+="\n" + text+=" " + text+=localeInfo.ITEMSHOP_PRICE_ONLY_TEXT % NumberToMoneyFormat(newPrice) + + lineImage = ui.ExpandedImageBox() + lineImage.SetParent(itemPrice) + lineImage.AddFlag("not_pick") + lineImage.LoadImage(IMG_DIR+"line.tga") + lineImage.SetDiffuseColor(1.0,0.0,0.0,0.9) + scaleCalc = float(xSize)*(1.0/10.0) + lineImage.SetScale(scaleCalc, 1.0) + lineImage.SetPosition(17,(ySize/2)+1) + lineImage.Show() + self.childrenImages["lineImage"] = lineImage + + self.SetItemType(3) + else: + text = localeInfo.ITEMSHOP_PRICE_NEW % NumberToMoneyFormat(price) + + itemPrice.SetText(text) + itemPrice.Show() + self.childrenTextLine["itemPrice"] = itemPrice + + def SetItemName(self): + self.ClearChildren("itemName") + itemName = ui.TextLine() + itemName.SetParent(self) + itemName.AddFlag("not_pick") + itemName.SetWindowHorizontalAlignLeft() + itemName.SetFontName("Tahoma:13") + itemName.SetPosition(95,15) + itemName.SetText("|cffF7BD48"+item.GetItemName()) + #itemName.SetFontColor(247,189,72) + itemName.Show() + self.childrenTextLine["itemName"] = itemName + + def SetCount(self): + self.ClearChildren("CountBg") + self.ClearChildren("CountText") + self.ClearChildren("CountLeft") + self.ClearChildren("CountRight") + if not item.IsFlag(item.ITEM_FLAG_STACKABLE): + return + + CountLeft = ui.ExpandedImageBox() + CountLeft.SetParent(self) + CountLeft.LoadImage(IMG_DIR+"count_left.tga") + CountLeft.SetPosition(70,85) + CountLeft.SetEvent(ui.__mem_func__(self.ClickCount),"mouse_click",0) + CountLeft.Show() + self.childrenImages["CountLeft"] = CountLeft + + CountBg = ui.ExpandedImageBox() + CountBg.SetParent(self) + CountBg.AddFlag("not_pick") + CountBg.LoadImage(IMG_DIR+"count_back.tga") + CountBg.SetPosition(70+CountLeft.GetWidth(),85) + CountBg.Show() + self.childrenImages["CountBg"] = CountBg + + CountText = ui.TextLine() + CountText.SetParent(CountBg) + CountText.AddFlag("not_pick") + CountText.SetHorizontalAlignCenter() + CountText.SetVerticalAlignCenter() + CountText.SetWindowHorizontalAlignCenter() + CountText.SetWindowVerticalAlignCenter() + CountText.SetText("1") + CountText.Show() + self.childrenTextLine["CountText"] = CountText + + CountRight = ui.ExpandedImageBox() + CountRight.SetParent(self) + CountRight.LoadImage(IMG_DIR+"count_right.tga") + CountRight.SetPosition(70+CountLeft.GetWidth()+CountBg.GetWidth(),85) + CountRight.SetEvent(ui.__mem_func__(self.ClickCount),"mouse_click",1) + CountRight.Show() + self.childrenImages["CountRight"] = CountRight + + def ClickCount(self,emptyArg, btnType): + value = 1 + if app.IsPressed(app.DIK_LCONTROL): + value += 4 + buyCount = self.buyCount + if btnType == 0: + buyCount -= value + if buyCount <= 0: + buyCount = 1 + else: + buyCount += value + if buyCount <= 0: + buyCount = 1 + elif buyCount > 20: + buyCount = 20 + self.buyCount = buyCount + + if self.childrenTextLine.has_key("CountText"): + self.childrenTextLine["CountText"].SetText(str(self.buyCount)) + + itemData = self.data + self.SetPrice(itemData[LIST_ITEM_PRICE],itemData[LIST_ITEM_DISCOUNT]) + + def SetItem(self, itemVnum): + self.ClearChildren("itemImage") + self.ClearChildren("itemCount") + item.SelectItem(itemVnum) + (width,height) = item.GetItemSize() + (xPos, yPos) = (36,46) + if height == 1: + xPos = 30 + elif height == 2: + yPos -= 20 + elif height == 3: + yPos -= 30 + xPos -= 5 + itemImage = ui.ExpandedImageBox() + itemImage.SetParent(self) + itemImage.LoadImage(item.GetIconImageFileName()) + itemImage.SetPosition(xPos,yPos) + itemImage.SAFE_SetStringEvent("MOUSE_OVER_IN",self.OverInItem,itemVnum) + itemImage.SAFE_SetStringEvent("MOUSE_OVER_OUT",self.OverOutItem) + if app.ENABLE_RENDER_TARGET: + itemImage.SetEvent(ui.__mem_func__(self.ClickItem), "mouse_click", itemVnum) + itemImage.Show() + self.childrenImages["itemImage"] = itemImage + + if app.ENABLE_RENDER_TARGET: + def ClickItem(self, emptyArg, itemVnum): + if app.IsCanOpenRender(): + interface = constInfo.GetInterfaceInstance() + if interface: + interface.OpenRenderTargetWindow(0, itemVnum) + + def OverInItem(self, itemVnum): + interface = constInfo.GetInterfaceInstance() + if interface: + if interface.tooltipItem: + interface.tooltipItem.SetItemToolTip(itemVnum) + def OverOutItem(self): + interface = constInfo.GetInterfaceInstance() + if interface: + if interface.tooltipItem: + interface.tooltipItem.HideToolTip() + def SetItemType(self, itemType): + self.ClearChildren("itemType") + typeImages = ["hot.tga","new.tga","offer.tga"] + if itemType == 0: + return + itemType-=1 + if itemType >= len(typeImages): + return + typeImage = ui.ExpandedImageBox() + typeImage.AddFlag("not_pick") + typeImage.SetParent(self) + typeImage.LoadImage(IMG_DIR+typeImages[itemType]) + typeImage.SetPosition(0,0) + typeImage.Show() + self.childrenImages["typeImage"] = typeImage + + def OnRender(self, parent): + listboxHeight = parent.GetHeight() + (pgx,pgy) = parent.GetGlobalPosition() + for key, textline in self.childrenTextLine.items(): + (igx,igy) = textline.GetGlobalPosition() + if igy < pgy: + textline.Hide() + elif igy > (pgy+listboxHeight-25): + textline.Hide() + else: + textline.Show() + for key, image in self.childrenImages.items(): + (jgx,jgy) = image.GetGlobalPosition() + imageHeight = image.GetHeight() + if jgy < pgy: + image.SetRenderingRect(0,ui.calculateRect(imageHeight-abs(jgy-pgy),imageHeight),0,0) + elif jgy+imageHeight > (pgy+listboxHeight-8): + calculate = (pgy+listboxHeight-8) - (jgy+imageHeight) + if calculate == 0: + return + image.SetRenderingRect(0.0,0.0,0.0,ui.calculateRect(imageHeight-abs(calculate),imageHeight)) + else: + image.SetRenderingRect(0,0,0,0) + +class ItemWindow(ui.Window): + def __del__(self): + ui.Window.__del__(self) + def __init__(self, parent): + ui.Window.__init__(self) + self.children=[] + self.Destroy() + self.parent=proxy(parent) + self.SetSize(750,122) + def OnUpdate(self): + for children in self.children: + children.OnUpdate() + def Destroy(self): + for children in self.children: + children.Destroy() + children=None + self.children=[] + self.parent = None + def AppendWindow(self, window): + self.children.append(window) + self.OnRender() + def OnRender(self): + for children in self.children: + children.OnRender(self.parent) +class CategoryItem(ui.ExpandedImageBox): + def __del__(self): + ui.ExpandedImageBox.__del__(self) + def __init__(self): + ui.ExpandedImageBox.__init__(self) + self.Destroy() + self.categoryIndex=-1 + self.LoadImage(IMG_DIR+"category_no_selected.tga") + def Destroy(self): + self.parent=None + self.categoryIndex=0 + self.categoryText=None + def SetData(self, categoryIndex, categoryName, categoryListBox): + self.categoryIndex=categoryIndex + self.parent=proxy(categoryListBox) + categoryText = MultiTextLine() + categoryText.SetParent(self) + categoryText.SetPosition(self.GetWidth()/2,11) + categoryText.SetTextRange(15) + categoryText.SetTextType("horizontal#center") + categoryText.SetFontName("Tahoma:16") + categoryText.SetText(categoryName) + categoryText.Show() + self.categoryText = categoryText + def OnRender(self): + parent = self.parent + if parent == None: + return + listboxHeight = parent.GetHeight() + (pgx,pgy) = parent.GetGlobalPosition() + (igx,igy) = self.categoryText.GetGlobalPosition() + if igy < pgy: + self.categoryText.Hide() + elif igy > (pgy+listboxHeight-25): + self.categoryText.Hide() + else: + self.categoryText.Show() + (jgx,jgy) = self.GetGlobalPosition() + imageHeight = self.GetHeight() + if jgy < pgy: + self.SetRenderingRect(0,ui.calculateRect(imageHeight-abs(jgy-pgy),imageHeight),0,0) + elif jgy+imageHeight > (pgy+listboxHeight-4): + calculate = (pgy+listboxHeight-4) - (jgy+imageHeight) + if calculate == 0: + return + self.SetRenderingRect(0.0,0.0,0.0,ui.calculateRect(imageHeight-abs(calculate),imageHeight)) + else: + self.SetRenderingRect(0,0,0,0) +class ScrollBar(ui.Window): + SCROLLBAR_WIDTH = 13 + SCROLLBAR_MIDDLE_HEIGHT = 1 + SCROLLBAR_BUTTON_WIDTH = 17 + SCROLLBAR_BUTTON_HEIGHT = 17 + SCROLL_BTN_XDIST = 2 + SCROLL_BTN_YDIST = 2 + class MiddleBar(ui.DragButton): + def __init__(self): + ui.DragButton.__init__(self) + self.AddFlag("movable") + self.SetWindowName("scrollbar_middlebar") + def MakeImage(self): + top = ui.ExpandedImageBox() + top.SetParent(self) + top.LoadImage(IMG_DIR+"scroll_top.tga") + top.AddFlag("not_pick") + top.Show() + bottom = ui.ExpandedImageBox() + bottom.SetParent(self) + bottom.LoadImage(IMG_DIR+"scroll_bottom.tga") + bottom.AddFlag("not_pick") + bottom.Show() + middle = ui.ExpandedImageBox() + middle.SetParent(self) + middle.LoadImage(IMG_DIR+"scroll_mid.tga") + middle.AddFlag("not_pick") + middle.Show() + self.top = top + self.bottom = bottom + self.middle = middle + def SetSize(self, height): + minHeight = self.top.GetHeight() + self.bottom.GetHeight() + self.middle.GetHeight() + height = max(minHeight, height) + ui.DragButton.SetSize(self, 10, height) + scale = (height - minHeight) / 2 + extraScale = 0 + if (height - minHeight) % 2 == 1: + extraScale = 1 + self.middle.SetPosition(0, self.top.GetHeight() + scale) + self.bottom.SetPosition(0, height - self.bottom.GetHeight()) + + def __init__(self): + ui.Window.__init__(self) + + self.pageSize = 1 + self.curPos = 0.0 + self.eventScroll = None + self.eventArgs = None + self.lockFlag = False + + self.CreateScrollBar() + self.SetScrollBarSize(0) + + self.scrollStep = 0.03 + self.SetWindowName("NONAME_ScrollBar") + + def __del__(self): + ui.Window.__del__(self) + + def CreateScrollBar(self): + topImage = ui.ExpandedImageBox() + topImage.SetParent(self) + topImage.AddFlag("not_pick") + topImage.LoadImage(IMG_DIR+"scrollbar_top.tga") + topImage.Show() + bottomImage = ui.ExpandedImageBox() + bottomImage.SetParent(self) + bottomImage.AddFlag("not_pick") + bottomImage.LoadImage(IMG_DIR+"scrollbar_bottom.tga") + bottomImage.Show() + middleImage = ui.ExpandedImageBox() + middleImage.SetParent(self) + middleImage.AddFlag("not_pick") + middleImage.SetPosition(0, topImage.GetHeight()) + middleImage.LoadImage(IMG_DIR+"scrollbar_mid.tga") + middleImage.Show() + self.topImage = topImage + self.bottomImage = bottomImage + self.middleImage = middleImage + + middleBar = self.MiddleBar() + middleBar.SetParent(self) + middleBar.SetMoveEvent(ui.__mem_func__(self.OnMove)) + middleBar.Show() + middleBar.MakeImage() + middleBar.SetSize(0) # set min height + self.middleBar = middleBar + def Destroy(self): + self.eventScroll = None + self.eventArgs = None + def SetScrollEvent(self, event, *args): + self.eventScroll = event + self.eventArgs = args + def SetMiddleBarSize(self, pageScale): + self.middleBar.SetSize(int(pageScale * float(self.GetHeight() - self.SCROLL_BTN_YDIST*2))) + realHeight = self.GetHeight() - self.SCROLL_BTN_YDIST*2 - self.middleBar.GetHeight() + self.pageSize = realHeight + def SetScrollBarSize(self, height): + self.SetSize(self.SCROLLBAR_WIDTH, height) + self.pageSize = height - self.SCROLL_BTN_YDIST*2 - self.middleBar.GetHeight() + middleImageScale = float((height - self.SCROLL_BTN_YDIST*2) - self.middleImage.GetHeight()) / float(self.middleImage.GetHeight()) + self.middleImage.SetRenderingRect(0, 0, 0, middleImageScale) + self.bottomImage.SetPosition(0, height - self.bottomImage.GetHeight()) + self.middleBar.SetRestrictMovementArea(self.SCROLL_BTN_XDIST, self.SCROLL_BTN_YDIST, self.middleBar.GetWidth(), height - self.SCROLL_BTN_YDIST * 2) + self.middleBar.SetPosition(self.SCROLL_BTN_XDIST, self.SCROLL_BTN_YDIST) + def SetScrollStep(self, step): + self.scrollStep = step + def GetScrollStep(self): + return self.scrollStep + def GetPos(self): + return self.curPos + def OnUp(self): + self.SetPos(self.curPos-self.scrollStep) + def OnDown(self): + self.SetPos(self.curPos+self.scrollStep) + def SetPos(self, pos, moveEvent = True): + pos = max(0.0, pos) + pos = min(1.0, pos) + newPos = float(self.pageSize) * pos + self.middleBar.SetPosition(self.SCROLL_BTN_XDIST, int(newPos) + self.SCROLL_BTN_YDIST) + if moveEvent == True: + self.OnMove() + def OnMove(self): + if self.lockFlag: + return + if 0 == self.pageSize: + return + (xLocal, yLocal) = self.middleBar.GetLocalPosition() + self.curPos = float(yLocal - self.SCROLL_BTN_YDIST) / float(self.pageSize) + if self.eventScroll: + apply(self.eventScroll, self.eventArgs) + def OnMouseLeftButtonDown(self): + (xMouseLocalPosition, yMouseLocalPosition) = self.GetMouseLocalPosition() + newPos = float(yMouseLocalPosition) / float(self.GetHeight()) + self.SetPos(newPos) + def LockScroll(self): + self.lockFlag = True + def UnlockScroll(self): + self.lockFlag = False +#class ScrollBar(ui.Window): +# SCROLLBAR_WIDTH = 12 +# MIDDLE_BAR_POS = 5 +# MIDDLE_BAR_UPPER_PLACE = 4 +# MIDDLE_BAR_DOWNER_PLACE = 4 +# MIDDLE_BAR_PER_HEIGHT = 27 +# TEMP_SPACE = MIDDLE_BAR_UPPER_PLACE + MIDDLE_BAR_DOWNER_PLACE +# class MiddleBar(ui.DragButton): +# MIDDLE_BAR_PER_HEIGHT = 27 +# MIDDLE_BAR_WIDTH = 6 +# def __init__(self): +# ui.DragButton.__init__(self) +# self.AddFlag("movable") +# def MakeImage(self): +# top = ui.ImageBox() +# top.SetParent(self) +# top.LoadImage(IMG_DIR+"scroll_top.tga") +# top.SetPosition(0, 0) +# top.AddFlag("not_pick") +# top.Show() +# bottom = ui.ImageBox() +# bottom.SetParent(self) +# bottom.LoadImage(IMG_DIR+"scroll_bottom.tga") +# bottom.AddFlag("not_pick") +# bottom.Show() +# middle = ui.ExpandedImageBox() +# middle.SetParent(self) +# middle.LoadImage(IMG_DIR+"scroll_mid.tga") +# middle.SetPosition(0, self.MIDDLE_BAR_PER_HEIGHT) +# middle.AddFlag("not_pick") +# middle.Show() +# self.top = top +# self.bottom = bottom +# self.middle = middle +# def SetSize(self, height): +# height = max(self.MIDDLE_BAR_PER_HEIGHT * 3, height) +# ui.DragButton.SetSize(self, 10, height) +# self.bottom.SetPosition(0, height-self.MIDDLE_BAR_PER_HEIGHT) +# height -= self.MIDDLE_BAR_PER_HEIGHT*3 +# self.middle.SetRenderingRect(0, 0, 0, float(height)/float(self.MIDDLE_BAR_PER_HEIGHT)) +# def __init__(self): +# ui.Window.__init__(self) +# self.pageSize = 1 +# self.curPos = 0.0 +# self.eventScroll = lambda *arg: None +# self.lockFlag = FALSE +# self.scrollStep = 0.20 +# self.CreateScrollBar() +# def __del__(self): +# ui.Window.__del__(self) +# def CreateScrollBar(self): +# barSlot = ui.Bar3D() +# barSlot.SetParent(self) +# barSlot.AddFlag("not_pick") +# barSlot.Show() +# middleBar = self.MiddleBar() +# middleBar.SetParent(self) +# middleBar.SetMoveEvent(ui.__mem_func__(self.OnMove)) +# middleBar.Show() +# middleBar.MakeImage() +# middleBar.SetSize(60) +# self.middleBar = middleBar +# self.barSlot = barSlot +# self.SCROLLBAR_MIDDLE_HEIGHT = self.middleBar.GetHeight() +# def Destroy(self): +# self.middleBar = None +# self.eventScroll = lambda *arg: None +# def SetScrollEvent(self, event): +# self.eventScroll = event +# def SetMiddleBarSize(self, pageScale): +# realHeight = self.GetHeight() +# self.SCROLLBAR_MIDDLE_HEIGHT = int(pageScale * float(realHeight)) +# self.middleBar.SetSize(self.SCROLLBAR_MIDDLE_HEIGHT) +# self.pageSize = self.GetHeight() - self.SCROLLBAR_MIDDLE_HEIGHT - (self.TEMP_SPACE) +# def SetScrollBarSize(self, height): +# self.pageSize = height - self.SCROLLBAR_MIDDLE_HEIGHT - (self.TEMP_SPACE) +# self.SetSize(self.SCROLLBAR_WIDTH, height) +# self.middleBar.SetRestrictMovementArea(self.MIDDLE_BAR_POS, self.MIDDLE_BAR_UPPER_PLACE, self.MIDDLE_BAR_POS+2, height - self.TEMP_SPACE) +# self.middleBar.SetPosition(self.MIDDLE_BAR_POS, 0) +# self.UpdateBarSlot() +# def UpdateBarSlot(self): +# self.barSlot.SetPosition(0, 2) +# self.barSlot.SetSize(self.GetWidth() - 2, self.GetHeight() - 2) +# def GetPos(self): +# return self.curPos +# def SetPos(self, pos): +# pos = max(0.0, pos) +# pos = min(1.0, pos) +# newPos = float(self.pageSize) * pos +# self.middleBar.SetPosition(self.MIDDLE_BAR_POS, int(newPos) + self.MIDDLE_BAR_UPPER_PLACE) +# self.OnMove() +# def SetScrollStep(self, step): +# self.scrollStep = step +# def GetScrollStep(self): +# return self.scrollStep +# def OnUp(self): +# self.SetPos(self.curPos-self.scrollStep) +# def OnDown(self): +# self.SetPos(self.curPos+self.scrollStep) +# def OnMove(self): +# if self.lockFlag: +# return +# if 0 == self.pageSize: +# return +# (xLocal, yLocal) = self.middleBar.GetLocalPosition() +# self.curPos = float(yLocal - self.MIDDLE_BAR_UPPER_PLACE) / float(self.pageSize) +# self.eventScroll() +# def OnMouseLeftButtonDown(self): +# (xMouseLocalPosition, yMouseLocalPosition) = self.GetMouseLocalPosition() +# pickedPos = yMouseLocalPosition - self.SCROLLBAR_MIDDLE_HEIGHT/2 +# newPos = float(pickedPos) / float(self.pageSize) +# self.SetPos(newPos) +# def LockScroll(self): +# self.lockFlag = TRUE +# def UnlockScroll(self): +# self.lockFlag = FALSE +def NumberToMoneyFormat(n): + if n <= 0 : + return "0" + return "%s" % ('.'.join([ i-3<0 and str(n)[:i] or str(n)[i-3:i] for i in range(len(str(n))%3, len(str(n))+1, 3) if i ])) +class MultiTextLine(ui.Window): + def __del__(self): + ui.Window.__del__(self) + def Destroy(self): + self.children = [] + self.rangeText = 0 + def __init__(self): + ui.Window.__init__(self) + self.children = [] + self.rangeText = 15 + self.textType = "" + self.fontName = "" + self.outline = False + self.rgb = (0,0,0) + def SetFontColor(self, r, g, b): + self.rgb = (r, g, b) + for text in self.children: + if self.rgb[0] != 0: + text.SetFontColor(self.rgb[0],self.rgb[1],self.rgb[2]) + def SetOutline(self, flag): + self.outline = flag + for text in self.children: + if self.outline: + text.SetOutline() + def SetTextType(self, textType): + self.textType = textType + for text in self.children: + self.AddTextType(self.textType.split("#"),text) + def SetFontName(self, fontName): + self.fontName = fontName + for text in self.children: + text.SetFontName(fontName) + def GetTextSize(self, index = 0): + if len(self.children) == 0: + return (0,0) + elif index >= len(self.children): + return (0,0) + return self.children[index].GetTextSize() + + def SetTextRange(self, range): + self.rangeText = range + yPosition = 0 + for text in self.children: + text.SetPosition(0,yPosition) + yPosition+=self.rangeText + def AddTextType(self, typeArg, text): + if len(typeArg) > 1: + if typeArg[0] == "vertical": + if typeArg[1] == "top": + text.SetVerticalAlignTop() + elif typeArg[1] == "bottom": + text.SetVerticalAlignBottom() + elif typeArg[1] == "center": + text.SetVerticalAlignCenter() + elif typeArg[0] == "horizontal": + if typeArg[1] == "left": + text.SetHorizontalAlignLeft() + elif typeArg[1] == "right": + text.SetHorizontalAlignRight() + elif typeArg[1] == "center": + text.SetHorizontalAlignCenter() + def SetText(self, cmd): + if len(self.children) > 1: + self.children=[] + multi_arg = cmd.split("\n") + yPosition = 0 + for text in multi_arg: + childText = ui.TextLine() + childText.SetParent(self) + childText.SetPosition(0,yPosition) + if self.rgb[0] != 0: + childText.SetFontColor(self.rgb[0],self.rgb[1],self.rgb[2]) + if self.textType != "": + self.AddTextType(self.textType.split("#"),childText) + if self.fontName != "": + childText.SetFontName(self.fontName) + if self.outline: + childText.SetOutline() + childText.SetText(str(text)) + childText.Show() + self.children.append(childText) + yPosition+=self.rangeText +class ListBox(ui.Window): + def __init__(self, isHorizontal = False): + ui.Window.__init__(self) + self.viewItemCount=10 + self.basePos=0 + self.itemHeight=16 + self.itemStep=20 + self.itemList=[] + self.itemWidth=100 + self.scrollBar=None + self.isHorizontal= isHorizontal + def __del__(self): + ui.Window.__del__(self) + def __GetItemCount(self): + return len(self.itemList) + def SetItemStep(self, itemStep): + self.itemStep=itemStep + def SetItemSize(self, itemWidth, itemHeight): + self.itemWidth=itemWidth + self.itemHeight=itemHeight + def SetViewItemCount(self, viewItemCount): + self.viewItemCount=viewItemCount + def RemoveAllItems(self): + for item in self.itemList: + item.Destroy() + self.itemList=[] + if self.scrollBar: + self.scrollBar.SetPos(0) + def GetItems(self): + return self.itemList + def RemoveItem(self, delItem): + self.itemList.remove(delItem) + def AppendItem(self, newItem): + self.itemList.append(newItem) + if app.ENABLE_MOUSEWHEEL_EVENT: + newItem.SetMouseWheelScrollEvent(self.OnMouseWheelScroll_ScrollBar) + def SetScrollBar(self, scrollBar): + scrollBar.SetScrollEvent(ui.__mem_func__(self.__OnScroll)) + self.scrollBar=scrollBar + if app.ENABLE_MOUSEWHEEL_EVENT: + self.SetMouseWheelScrollEvent(self.OnMouseWheelScroll_ScrollBar) + if app.ENABLE_MOUSEWHEEL_EVENT: + def OnMouseWheelScroll_ScrollBar(self,mode): + if self.scrollBar: + if mode == "UP": + self.scrollBar.OnUp() + else: + self.scrollBar.OnDown() + def OnMouseWheel(self, nLen): + if self.scrollBar: + if self.scrollBar.IsShow(): + if nLen > 0: + self.scrollBar.OnUp() + else: + self.scrollBar.OnDown() + return True + return False + def __OnScroll(self): + self.SetBasePos(int(self.scrollBar.GetPos()*self.__GetScrollLen())) + def __GetScrollLen(self): + if self.__GetItemCount() == 0: + return 0 + (lx,ly) = self.itemList[len(self.itemList)-1].exPos + return ly + def Render(self,basePos): + for item in self.itemList: + (ex,ey) = item.exPos + if self.isHorizontal: + item.SetPosition(ex-(basePos),ey) + else: + item.SetPosition(ex,ey-(basePos)) + item.OnRender() + def SetBasePos(self, basePos): + if self.basePos == basePos: + return + self.Render(basePos) + self.basePos=basePos + +class ImageBoxSpecial(ui.Window): + def __del__(self): + ui.Window.__del__(self) + def Destroy(self): + self.imageList=[] + self.waitingTime = 0.0 + self.sleepTime = 0.0 + self.alphaValue = 0.0 + self.increaseValue = 0.0 + self.minAlpha = 0.0 + self.maxAlpha = 0.0 + self.alphaStatus = False + self.imageIndex = 0 + self.img = None + self.numberText = None + + def __init__(self): + ui.Window.__init__(self) + self.Destroy() + self.waitingTime = 2.0 + self.alphaValue = 0.3 + self.increaseValue = 0.05 + self.minAlpha = 0.3 + self.maxAlpha = 1.0 + def SetImage(self, folder, itemVnum, itemCount): + (x, y) = (0,0) + if self.img != None: + (x, y) = self.img.GetLocalPosition() + if self.img == None: + img = ui.ImageBox() + img.SetParent(self) + img.SAFE_SetStringEvent("MOUSE_OVER_OUT",self.OverOutItem) + img.SAFE_SetStringEvent("MOUSE_OVER_IN",self.OverInItem) + self.img = img + if self.numberText == None: + numberText = ui.NumberLine() + numberText.SetParent(self.img) + numberText.SetPosition(20,20) + self.numberText = numberText + + self.numberText.SetNumber(str(itemCount)) + self.numberText.Show() + + self.img.LoadImage(folder) + self.img.SetPosition(x, y) + self.img.Show() + + def OverOutItem(self): + interface = constInfo.GetInterfaceInstance() + if interface: + if interface.tooltipItem: + interface.tooltipItem.HideToolTip() + def OverInItem(self): + interface = constInfo.GetInterfaceInstance() + if interface: + if interface.tooltipItem: + interface.tooltipItem.SetItemToolTip(self.imageList[self.imageIndex][1]) + def Clear(self): + self.img = None + self.numberText = None + self.imageList = [] + def LoadImage(self, imageFolder, itemVnum, itemCount): + item_list = [imageFolder, itemVnum, itemCount] + if item_list in self.imageList: + return + self.imageList.append(item_list) + if self.img == None: + self.SetImage(imageFolder, itemVnum, itemCount) + def GetNextImage(self, listIndex): + if listIndex >= len(self.imageList): + if len(self.imageList) > 0: + return (0,self.imageList[0][0],self.imageList[0][1],self.imageList[0][2]) + return (0,"",0,0) + return (listIndex, self.imageList[listIndex][0],self.imageList[listIndex][0], self.imageList[listIndex][2]) + def OnUpdate(self): + if len(self.imageList) <= 1: + self.imageIndex=0 + return + elif self.sleepTime > app.GetTime(): + return + if self.alphaStatus == True: + self.alphaValue -= self.increaseValue + if self.alphaValue < self.minAlpha: + self.alphaValue = self.minAlpha + self.alphaStatus = False + (imageIndex, imageFolder, itemVnum, itemCount) = self.GetNextImage(self.imageIndex+1) + if imageFolder != "": + self.SetImage(imageFolder, itemVnum, itemCount) + self.imageIndex = imageIndex + else: + self.alphaValue += self.increaseValue + if self.alphaValue > self.maxAlpha: + self.alphaStatus = True + self.sleepTime = app.GetTime()+self.waitingTime + if self.img != None: + self.img.SetAlpha(self.alphaValue) + +class MessageWindow(ui.BoardWithTitleBar): + def __del__(self): + ui.BoardWithTitleBar.__del__(self) + def __init__(self): + ui.BoardWithTitleBar.__init__(self) + self.Destroy() + def Destroy(self): + self.children = {} + def LoadMessage(self, itemVnum, itemCount): + self.SetTitleName(localeInfo.WHEEL_REWARD_TITLE) + self.SetCloseEvent(self.Close) + self.SetSize(210,180) + self.AddFlag("attach") + self.AddFlag("movable") + self.AddFlag("float") + self.SetCenterPosition() + + item.SelectItem(itemVnum) + + multiText = MultiTextLine() + multiText.SetParent(self) + multiText.SetTextType("horizontal#center") + multiText.SetPosition(95,45) + if itemCount > 1: + text = "%s\nx%d%s\n%s"%(localeInfo.WHEEL_REWARD_TEXT, itemCount,item.GetItemName(), localeInfo.WHEEL_REWARD_TEXT_1) + else: + text = "%s\n%s\n%s"%(localeInfo.WHEEL_REWARD_TEXT,item.GetItemName(), localeInfo.WHEEL_REWARD_TEXT_1) + multiText.SetText(text) + multiText.Show() + self.children["multiText"] = multiText + + itemIcon = ui.ImageBox() + itemIcon.SetParent(self) + itemIcon.LoadImage(item.GetIconImageFileName()) + itemIcon.SetPosition(105-16,95) + itemIcon.Show() + self.children["itemIcon"] = itemIcon + + itemCountNumber = ui.NumberLine() + itemCountNumber.SetParent(itemIcon) + itemCountNumber.SetNumber(str(itemCount)) + itemCountNumber.SetPosition(20,20) + itemCountNumber.Show() + self.children["itemCount"] = itemCountNumber + + okBtn = ui.Button() + okBtn.SetParent(self) + okBtn.SetUpVisual("d:/ymir work/ui/public/middle_button_01.sub") + okBtn.SetOverVisual("d:/ymir work/ui/public/middle_button_02.sub") + okBtn.SetDownVisual("d:/ymir work/ui/public/middle_button_03.sub") + okBtn.SetText(localeInfo.UI_OK) + okBtn.SetEvent(ui.__mem_func__(self.Close)) + okBtn.SetPosition(105-(okBtn.GetWidth()/2),135) + okBtn.Show() + self.children["okBtn"] = okBtn + + self.Show() + + def Close(self): + self.Destroy() + self.Hide() + def OnPressEscapeKey(self): + self.Close() + return True + +)PY"; diff --git a/src/platform/ScriptLib/Ava2ItemShopScript.inc b/src/platform/ScriptLib/Ava2ItemShopScript.inc new file mode 100644 index 00000000..65fcc7be --- /dev/null +++ b/src/platform/ScriptLib/Ava2ItemShopScript.inc @@ -0,0 +1,248 @@ +// Native shop platform glue; original AVA2 source is kept byte-equivalent after encoding normalization. +static const char c_szAva2ShopSupportScript[]=R"PY(# -*- coding: utf-8 -*- +import localeInfo,app,item +item.ITEM_FLAG_STACKABLE=1<<2 +app.ENABLE_RENDER_TARGET=True +app.ENABLE_MOUSEWHEEL_EVENT=True +import ui +ui.Window.SetMouseWheelScrollEvent=lambda self,event:setattr(self,'onMouseWheelScrollEvent',event) +from mt_biolog import L +LOCALE={'CATEGORY_0_NAME': 'Offers', 'CATEGORY_0_SUB_0_NAME': 'Battle pass', 'CATEGORY_0_SUB_1_NAME': 'Special packs', 'CATEGORY_0_SUB_2_NAME': 'Special Offers', 'CATEGORY_1_NAME': 'Special Objects', 'CATEGORY_2_NAME': 'Cosmetics', 'CATEGORY_2_SUB_0_NAME': 'Weapons Skins', 'CATEGORY_2_SUB_1_NAME': 'Body Costume', 'CATEGORY_2_SUB_2_NAME': 'Hairstyles', 'CATEGORY_2_SUB_3_NAME': 'Sash Skin', 'CATEGORY_2_SUB_4_NAME': 'Mount Skin', 'CATEGORY_3_NAME': 'Pets and mounts', 'CATEGORY_3_SUB_0_NAME': 'Mounts', 'CATEGORY_3_SUB_1_NAME': 'Leveable pets', 'CATEGORY_3_SUB_2_NAME': 'Normal pets', 'CATEGORY_4_NAME': 'Dungeons', 'CATEGORY_5_NAME': 'Reinforce Costume', 'CATEGORY_5_SUB_0_NAME': 'Weapon Skin', 'CATEGORY_5_SUB_1_NAME': 'Body Costume', 'CATEGORY_5_SUB_2_NAME': 'Hairstyles', 'CATEGORY_5_SUB_3_NAME': 'Mount Skin', 'CATEGORY_5_SUB_4_NAME': 'Sash Skin', 'CATEGORY_5_SUB_5_NAME': 'Effects', 'CATEGORY_6_NAME': 'Alchemy', 'CATEGORY_7_NAME': 'Equipment', 'ITEMSHOP_BUY': 'Comprar', 'ITEMSHOP_BUY_COIN': 'Home', 'ITEMSHOP_BUY_TEXT': 'Wanna buy |cffF7BD48%s|r ?', 'ITEMSHOP_BUY_TEXT_COUNT': 'Wanna buy |cffF7BD48%sx%d|r ?', 'ITEMSHOP_DRAGONCOINT': 'Dragon Coins', 'ITEMSHOP_HOTITEMS': '|Eishop/hot|ePOPULAR', 'ITEMSHOP_ITEMSEARCH_DEFAULT_TEXT': 'Search the itemshop ...', 'ITEMSHOP_LAST_COUNT': 'Remaining amount: %d', 'ITEMSHOP_OFFERS': '|Eishop/offer|e OFFERS', 'ITEMSHOP_PRICE_NEW': '|Eishop/mini_coin|e %s Coins', 'ITEMSHOP_PRICE_ONLY_TEXT': '%s Coins', 'ITEMSHOP_PRICE_WITH_DISCOUNT': '|Eishop/mini_coin|e |cffFF7B7B%s Coins (%d%%)', 'ITEMSHOP_PURCHASES': 'SHOPPING', 'ITEMSHOP_WHEEL': '|Eishop/wheel_icon|e Roulette', 'ITEMSHOP_WHEEL_BACK_ISHOP': 'Itemhop go back', 'ITEMSHOP_WHEEL_COIN_TEXT': ' |Eishop/coin|e Price: 10 Coins', 'ITEMSHOP_WHEEL_COIN_TEXT_INFO': 'You will use |cffF7BD48Coins|r to spin.', 'ITEMSHOP_WHEEL_PURCHASE': '|Eishop/wheel_icon|e |cffF7BD48Fortune roulette|r', 'ITEMSHOP_WHEEL_SKIP_ANIMATION': 'Skip animation', 'ITEMSHOP_WHEEL_TICKET_TEXT': '|Eishop/wheel_ticket|e x1 ticket', 'ITEMSHOP_WHEEL_TICKET_TEXT_INFO': 'Your are using |cffF7BD48Roulette ticket|r to spin.', 'PURCHASES_ACCOUNTID': 'ID account', 'PURCHASES_DATE': 'Date', 'PURCHASES_IP': 'IP', 'PURCHASES_ITEMBOUGHT': 'Purchased object', 'PURCHASES_PRICE': 'Price', 'PURCHASES_PRICE_TEXT': '|Eishop/mini_coin|e |cfff7bd48%s dragon coins', 'UI_CANCEL': 'Cancel', 'UI_OK': 'OK', 'WHEEL_REWARD_TEXT': 'You have received', 'WHEEL_REWARD_TEXT_1': 'In your inventory', 'WHEEL_REWARD_TITLE': 'Roulette reward', 'YES': 'Buy'} +ZH={'YES':'确认','ITEMSHOP_BUY_COIN': '充值', 'ITEMSHOP_WHEEL': '幸运转盘', 'ITEMSHOP_PURCHASES': '购买记录', 'ITEMSHOP_HOTITEMS': '热销商品', 'ITEMSHOP_OFFERS': '限时优惠', 'ITEMSHOP_ITEMSEARCH_DEFAULT_TEXT': '搜索道具名称', 'ITEMSHOP_DRAGONCOINT': '龙币', 'ITEMSHOP_BUY': '购买', 'ITEMSHOP_BUY_TEXT': '购买 %s?', 'ITEMSHOP_BUY_TEXT_COUNT': '购买 %s × %d?', 'ITEMSHOP_PRICE_NEW': '价格:%s 龙币', 'ITEMSHOP_PRICE_ONLY_TEXT': '%s 龙币', 'ITEMSHOP_PRICE_WITH_DISCOUNT': '原价 %s(优惠 %d%%)', 'ITEMSHOP_LAST_COUNT': '剩余:%d', 'PURCHASES_PRICE_TEXT': '支付:%s 龙币', 'PURCHASES_DATE': '购买时间', 'PURCHASES_ACCOUNTID': '角色', 'PURCHASES_IP': '登录地址', 'PURCHASES_ITEMBOUGHT': '购买道具', 'PURCHASES_PRICE': '支付金额', 'ITEMSHOP_WHEEL_BACK_ISHOP': '返回商城'} +ZH.update({'CATEGORY_0_NAME': '精选优惠', 'CATEGORY_0_SUB_0_NAME': '战令', 'CATEGORY_0_SUB_1_NAME': '超值礼包', 'CATEGORY_0_SUB_2_NAME': '特别优惠', 'CATEGORY_1_NAME': '特殊道具', 'CATEGORY_2_NAME': '外观', 'CATEGORY_2_SUB_0_NAME': '武器外观', 'CATEGORY_2_SUB_1_NAME': '服装', 'CATEGORY_2_SUB_2_NAME': '发型', 'CATEGORY_2_SUB_3_NAME': '披风外观', 'CATEGORY_2_SUB_4_NAME': '坐骑外观', 'CATEGORY_3_NAME': '宠物与坐骑', 'CATEGORY_3_SUB_0_NAME': '坐骑', 'CATEGORY_3_SUB_1_NAME': '成长宠物', 'CATEGORY_3_SUB_2_NAME': '普通宠物', 'CATEGORY_4_NAME': '副本', 'CATEGORY_5_NAME': '外观强化', 'CATEGORY_5_SUB_0_NAME': '武器外观', 'CATEGORY_5_SUB_1_NAME': '服装', 'CATEGORY_5_SUB_2_NAME': '发型', 'CATEGORY_5_SUB_3_NAME': '坐骑外观', 'CATEGORY_5_SUB_4_NAME': '披风外观', 'CATEGORY_5_SUB_5_NAME': '特效', 'CATEGORY_6_NAME': '龙魂炼金', 'CATEGORY_7_NAME': '装备'}) +for key,value in LOCALE.items(): + if not hasattr(localeInfo,key):setattr(localeInfo,key,L(value)) +for key,value in ZH.items():setattr(localeInfo,key,L(value)) +)PY"; +static const char c_szAva2ItemShopScript[]=R"PY(# -*- coding: utf-8 -*- +import app,chat,constInfo,game,net,os,struct,types,ui +import uiItemShopNew as native +from mt_biolog import L +# AVA2 ui.py calculateRect, retained for the native list's clipping rectangles. +def calculateRect(curValue,maxValue): + try:return -1.0+float(curValue)/float(maxValue) + except:return 0.0 +ui.calculateRect=calculateRect +window=None;pending=None;_serial=0;_next=0;_waiting=False;_requested=0;_queued=False;_logAt=0 +_product=struct.Struct('7 or subcount>10 or category in groups:raise ValueError('shop category') + groups.add(category);subs=set() + for unused2 in range(subcount): + sub,count=read('9 or sub in subs:raise ValueError('shop subcategory') + subs.add(sub) + for unused3 in range(count): + p=read(_product.format) + if p[0] in seen or not p[0] or not p[1] or not 0<=p[2]<=1000000000000 or p[4]>100 or p[7]<0 or p[8]<0 or p[9]<0 or p[10]<-1:raise ValueError('shop product') + seen.add(p[0]);rows.append((category,sub,p)) + result=(coins,revision,rows) + elif op==1: + count,=read('9 or coins<0 or any(c not in bytearray(b'0123456789abcdefABCDEF') for c in bytearray(token)):raise ValueError('shop result') + result=(token,status,coins) + elif op==8:result=None + else:raise ValueError('unknown shop message') + if read.offset!=len(raw):raise ValueError('trailing shop data') + return op,result + +def Request(): + global _waiting,_requested,_next,_queued + now=app.GetTime();_waiting=True;_requested=now;_queued=now<_next + if not _queued:net.SendChatPacket('/ishop data -1');_next=now+1.1 + +def Toggle(): + global window + if window and window.IsShow():window.Close();return + if window is None: + window=native.ItemShopWindow();window.SetCenterPosition() + # Explicit refresh on every reopen; no stale balance, stock or expired offers. + window.children['sendPacketData']=1;window.Show();window.SetTop();window.children['LoadingImage'].Show();Request() + +# Original ItemShopUpdateItem assigned to a loop variable, leaving stored rows unchanged. +def UpdateItem(itemID,itemVnum,itemPrice,discount,expiry,top,added,sold,stock): + for categories in native.itemshopData.values(): + for rows in categories: + for index,row in enumerate(rows): + if row[0]==itemID:rows[index]=[itemID,itemVnum,itemPrice,discount,expiry,top,added,sold,stock] +native.ItemShopUpdateItem=UpdateItem + +def Total(unit,count,discount):return unit*count*(100-discount)//100 + +_setPrice=native.ItemShopItem.SetPrice +def SetPrice(self,unit,discount): + _setPrice(self,unit,discount) + price=unit*self.buyCount + if discount: + text=native.localeInfo.ITEMSHOP_PRICE_WITH_DISCOUNT%(native.NumberToMoneyFormat(price),discount) + text+='\n '+native.localeInfo.ITEMSHOP_PRICE_ONLY_TEXT%native.NumberToMoneyFormat(Total(unit,self.buyCount,discount)) + self.childrenTextLine['itemPrice'].SetText(text) +native.ItemShopItem.SetPrice=SetPrice +_setCoins=native.ItemShopWindow.SetDragonCoin +def SetCoins(self,value): + _setCoins(self,value);self.MoneyRange=abs(self.MoneyRange) +native.ItemShopWindow.SetDragonCoin=SetCoins + +_buyClick=native.ItemShopItem.ClickBuyBtn +def BuyClick(self,*args): + unit=self.data[native.LIST_ITEM_PRICE];discount=self.data[native.LIST_ITEM_DISCOUNT] + total=Total(unit,self.buyCount,discount) + self.shopQuote=(self.data[native.LIST_ITEM_ID],self.buyCount,total,self.data[native.LIST_ITEM_VNUM]) + _buyClick(self,*args) + if native.buyQuestionDialog: + native.item.SelectItem(self.shopQuote[3]) + if self.buyCount>1:text=native.localeInfo.ITEMSHOP_BUY_TEXT_COUNT%(native.item.GetItemName(),self.buyCount) + else:text=native.localeInfo.ITEMSHOP_BUY_TEXT%native.item.GetItemName() + text+='\n'+native.localeInfo.ITEMSHOP_PRICE_NEW%total + native.buyQuestionDialog.SetText(text);native.buyQuestionDialog.SetCenterPosition() +native.ItemShopItem.ClickBuyBtn=BuyClick + +def AcceptBuy(self): + global pending,_serial + if pending or not getattr(self,'shopQuote',None):return + _serial+=1 + token=os.urandom(16).encode('hex') + product,count,total,vnum=self.shopQuote + pending=(token,product,count,app.GetTime(),0,total,vnum) + net.SendChatPacket('/ishop buy %d %d %s %d %d'%(pending[1],pending[2],pending[0],pending[5],pending[6]));self.CloseQuestionDialog() +native.ItemShopItem.AcceptBuy=AcceptBuy +# The source's wheel uses separate game services and reward configuration. +# Keep its entry unavailable until that service has been ported and validated. +def Wheel(self):chat.AppendChat(chat.CHAT_TYPE_INFO,L('幸运转盘尚未开放。')) +def Recharge(self):chat.AppendChat(chat.CHAT_TYPE_INFO,L('充值服务尚未开放。')) +native.ItemShopWindow.WheelBtn=Wheel;native.ItemShopWindow.BuyDragonCoin=Recharge +# Never open the vendor's external website. +native.ItemShopWindow.OpenWeb=lambda self,*args:None + +def Receive(self,raw): + global window,pending,_waiting,_logAt + try:op,value=Parse(raw) + except (ValueError,struct.error,TypeError): + chat.AppendChat(chat.CHAT_TYPE_INFO,L('商城数据无效,请重新打开。'));return + if op==8: + _waiting=False;_logAt=0 + if window:window.CloseLoading();window.children.pop('sendPacketDataLog',None) + chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[6]));return + if op==0: + coins,revision,rows=value;native.itemshopData.clear();native.UPDATE_TIME=revision + for category,sub,p in rows:native.ItemShopAppendItem(category,sub,p[0],p[1],p[2],p[4],p[5],p[3],p[6],p[7],p[10]) + _waiting=False + if window:window.SetDragonCoin(coins);window.CloseLoading();window.LoadFirstOpening() + elif op==1: + _logAt=0 + native.ItemShopLogClear() + for p in value:native.ItemShopAppendLog(p[2].split('\0',1)[0],p[3],p[1].split('\0',1)[0],p[4].split('\0',1)[0],p[6],p[7],p[8]) + if window:window.children['sendPacketDataLog']=1;window.CloseLoading();window.RefreshPurchasesWindow() + elif op==7: + token,status,coins=value + if not pending or pending[0]!=token:return + if status==8:return # Commit outcome uncertain: retry the same durable token. + pending=None + if window:window.SetDragonCoin(coins);window.children.pop('sendPacketDataLog',None) + chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS.get(status,'购买成功,道具已发往商城仓库。'))) + Request() + +_openLog=native.ItemShopWindow.OpenPurchasesWindow +def OpenLog(self): + global _logAt + if 'sendPacketDataLog' not in self.children:_logAt=app.GetTime() + _openLog(self) +native.ItemShopWindow.OpenPurchasesWindow=OpenLog + +def Tick(): + global pending,_waiting,_queued,_logAt + now=app.GetTime() + if _queued and now>=_next:Request() + if _logAt and now-_logAt>=10: + _logAt=0 + if window:window.CloseLoading();window.children.pop('sendPacketDataLog',None) + chat.AppendChat(chat.CHAT_TYPE_INFO,L('购买记录请求超时,请重新打开。')) + if pending and now-pending[3]>=5: + # Re-send exactly the same durable order token; never create a replacement payment. + token,product,count,unused,attempt,total,vnum=pending + if attempt<3:net.SendChatPacket('/ishop buy %d %d %s %d %d'%(product,count,token,total,vnum));pending=(token,product,count,now,attempt+1,total,vnum) + elif attempt==3: + pending=(token,product,count,now,4,total,vnum);chat.AppendChat(chat.CHAT_TYPE_INFO,L('订单处理中,请查看购买记录;重新登录前不会再次扣款。')) + if _waiting and now-_requested>=10: + _waiting=False + if window:window.CloseLoading() + chat.AppendChat(chat.CHAT_TYPE_INFO,L('商城请求超时,请重新打开。')) + +def HandleWheel(delta): + if not window or not window.IsShow() or not window.IsIn():return False + for key in ('itemListBox','categoryListBox','PurchasesListBox'): + box=window.children.get(key) + if box and box.IsShow() and box.IsIn():box.OnMouseWheel(delta);return True + return True + +def Clear(): + global window,pending,_waiting,_queued,_logAt,_next + if window:window.Close();window.Destroy();window=None + pending=None;_waiting=False;_queued=False;_logAt=0;_next=0;native.itemshopData.clear();native.ItemShopLogClear();native.UPDATE_TIME=-1 +_open=game.GameWindow.Open;_close=game.GameWindow.Close;_update=game.GameWindow.OnUpdate + +def Open(self): + _open(self);Clear() + self.interface.OpenItemMall=Toggle;self.interface.OpenItemShopWindow=Toggle;self.interface.OpenItemShopMainWindow=Toggle + self.onPressKeyDict[app.DIK_F9]=Toggle + # Existing classic cash-shop button now opens the native AVA2 catalogue. + if getattr(self.interface,'wndTaskBar',None): + task=self.interface.wndTaskBar + if hasattr(task,'SetItemShopEvent'):task.SetItemShopEvent(Toggle) + for name in ('rampageGauge1','rampageGauge2'): + gauge=getattr(task,name,None) + if gauge:gauge.OnMouseLeftButtonUp=Toggle +def Close(self):Clear();return _close(self) +def Update(self):_update(self);Tick() +game.GameWindow.Open=Open;game.GameWindow.Close=Close;game.GameWindow.OnUpdate=Update +game.GameWindow.BINARY_Ava2ItemShop=Receive +)PY"; diff --git a/src/platform/ScriptLib/MinimapOuterRingScript.inc b/src/platform/ScriptLib/MinimapOuterRingScript.inc index 65551498..d452ca9f 100644 --- a/src/platform/ScriptLib/MinimapOuterRingScript.inc +++ b/src/platform/ScriptLib/MinimapOuterRingScript.inc @@ -8,6 +8,10 @@ import wndMgr import mt_dungeons import mt_battlepass import mt_biolog +import player + +# Source literals are UTF-8; classic text widgets consume the active locale code page. +L = player.AutoHuntLocalize class MapTextToolTip(ui.Window): @@ -25,7 +29,7 @@ class MapTextToolTip(ui.Window): ui.Window.__del__(self) def SetText(self, text): - self.textLine.SetText(text) + self.textLine.SetText(L(text)) def SetTooltipPosition(self, PosX, PosY): self.textLine.SetPosition(PosX - 5, PosY) @@ -146,7 +150,7 @@ class MinimapOuterRing(object): btnSwitch.SetDownVisual("d:/ymir work/ui/game/new_inventory/switch_2.tga") btnSwitch.SetPosition(37, 0) if hasattr(btnSwitch, 'SetToolTipText'): - btnSwitch.SetToolTipText("自动洗练") + btnSwitch.SetToolTipText(L("自动洗练")) btnSwitch.SetEvent(lambda: interface.ToggleSwitchbotWindow()) btnSwitch.Show() wndExpandedTaskBar.btnSwitchbot = btnSwitch @@ -165,7 +169,7 @@ class MinimapOuterRing(object): btnWiki.SetDownVisual("d:/ymir work/ui/game/new_inventory/wiki_2.tga") btnWiki.SetPosition(74, 0) if hasattr(btnWiki, 'SetToolTipText'): - btnWiki.SetToolTipText("游戏百科") + btnWiki.SetToolTipText(L("游戏百科")) btnWiki.SetEvent(wiki_toggle) btnWiki.Show() wndExpandedTaskBar.btnWiki = btnWiki diff --git a/src/platform/ScriptLib/MobileHUDScript.inc b/src/platform/ScriptLib/MobileHUDScript.inc index 0978bf06..fa506570 100644 --- a/src/platform/ScriptLib/MobileHUDScript.inc +++ b/src/platform/ScriptLib/MobileHUDScript.inc @@ -33,6 +33,7 @@ class RoundAction(ui.Window): self.action = action self.down = False self.active = False + self.visualScale = 1.0 self.label = _Text(self, text) self.label.SetHorizontalAlignCenter() self.label.SetVerticalAlignCenter() @@ -51,22 +52,25 @@ class RoundAction(ui.Window): self.SetSize(int(size), int(size)) self.label.SetPosition(int(size/2), int(size/2)) if self.icon: - edge = size * .62 + edge = size * .62 * self.visualScale self.icon.SetScale(edge / max(1, self.iconSize[0]), edge / max(1, self.iconSize[1])) self.icon.SetPosition(int((size-edge)/2), int((size-edge)/2)) def OnRender(self): x, y = self.GetGlobalPosition() - r = self.GetWidth()/2.0 + diameter = max(1, int(self.GetWidth()*self.visualScale)) + x += (self.GetWidth()-diameter)/2.0 + y += (self.GetHeight()-diameter)/2.0 + r = diameter/2.0 if getattr(self, "active", False): grp.SetColor(0xEE207028 if self.down else 0xCC185820) else: grp.SetColor(0xE0664B2D if self.down else 0xBB281A16) # Horizontal strips fill a round button without requiring extra image assets. - for row in xrange(0, self.GetHeight(), 3): + for row in xrange(0, diameter, 3): dy = min(r, row + 1.5 - r) half = math.sqrt(max(0, r*r - dy*dy)) - grp.RenderBar(x+r-half, y+row, half*2, min(3, self.GetHeight()-row)) + grp.RenderBar(x+r-half, y+row, half*2, min(3, diameter-row)) if getattr(self, "active", False): grp.SetColor(0xFFB0FFB0 if self.down else 0xFF80FF90) else: @@ -214,10 +218,27 @@ class HUD(ui.Window): self.btnAutoHunt, RoundAction(self, "帮助", interface.OpenHelpWindow), RoundAction(self, "聊天", interface.ToggleChat)] + import mt_itemshop + self.shop = RoundAction(self, "商城", mt_itemshop.Toggle) + self.menuExpanded = False + self.more = RoundAction(self, "更多", self.ToggleMore) + # Secondary menu art is 28% smaller; hit rectangles remain comfortably tappable. + for button in self.top + self.side + [self.shop, self.more]: + button.visualScale = .72 + for button in self.side: + button.Hide() self.dimensions = None self.OnUpdate() self.Show() + def ToggleMore(self): + self.menuExpanded = not self.menuExpanded + self.more.label.SetText(L("收起" if self.menuExpanded else "更多")) + self.more.active = self.menuExpanded + for button in self.side: + if self.menuExpanded: button.Show() + else: button.Hide() + def Show(self): ui.Window.Show(self) self.SetTop() @@ -228,24 +249,27 @@ class HUD(ui.Window): dimensions = (w, h, target) if dimensions != self.dimensions: self.dimensions = dimensions - s = max(target/52.0, min(1.35, max(.65, min(h/600.0, w/800.0)))) + # Keep spacing compact while preserving the device's minimum hit target. + s = min(1.1, max(.65, min(h/600.0, w/800.0))) self.SetSize(w, h) self.status.Place(s) self.experience.SetPosition(int(12*s), int(h-self.experience.GetHeight()-6*s)) self.experienceText.SetPosition(self.experience.GetWidth()+6, 10) - size, gap = max(target, 48*s), 8*s - for i, button in enumerate(self.top): - button.Place(w-12*s-(4-i)*(size+gap), 10*s, size) - for i, button in enumerate(self.side): - if h < 520 or s > 1.25: - button.Place(12*s+i*(size+gap), 140*s, size) - else: - button.Place(12*s, 140*s+i*(size+gap), size) - self.window.affectShower.SetPosition(int(18*s), int(104*s)) + size, gap = max(target, 48*s), 6*s minimap = self.window.interface.wndMiniMap minimap.SetWindowHorizontalAlignLeft() minimap.SetWindowVerticalAlignTop() - minimap.SetPosition(int(w-minimap.GetWidth()-12*s), int(72*s)) + minimap.SetPosition(int(w-minimap.GetWidth()-12*s), int(10*s)) + # Compact two-column menu beside the map, outside the combat/thumb regions. + menuX = w-minimap.GetWidth()-30*s-2*size-gap + for i, button in enumerate(self.top): + button.Place(menuX+(i%2)*(size+gap), 10*s+(i//2)*(size+gap), size) + moreY = 10*s+2*(size+gap) + self.shop.Place(menuX, moreY, size) + self.more.Place(menuX+size+gap, moreY, size) + for i, button in enumerate(self.side): + button.Place(menuX+(i%2)*(size+gap), moreY+(1+i//2)*(size+gap), size) + self.window.affectShower.SetPosition(int(18*s), int(104*s)) chat = self.window.interface.wndChat chat.SetPosition(int(180*s), int(h-86*s)) chat.Refresh() @@ -275,7 +299,7 @@ class HUD(ui.Window): self.experience.Hide() self.experience.SetParent(self.taskbar) self.experience.SetPosition(*self.experiencePosition) - for button in self.top + self.side: + for button in self.top + self.side + [self.shop, self.more]: button.action = None self.window = None diff --git a/src/platform/ScriptLib/PythonBoot.cpp b/src/platform/ScriptLib/PythonBoot.cpp index 4292f69c..bf50a7c1 100644 --- a/src/platform/ScriptLib/PythonBoot.cpp +++ b/src/platform/ScriptLib/PythonBoot.cpp @@ -418,6 +418,15 @@ void UIMouseButton(int button, bool pressed, int x, int y) void UIMouseWheel(int nLen) { + // AVA2 native shop consumes wheel input inside its list, before camera zoom. + PyObject* shop=PyDict_GetItemString(PyImport_GetModuleDict(),"mt_itemshop"); + if(shop) { + PyObject* result=PyObject_CallMethod(shop,const_cast("HandleWheel"),const_cast("i"),nLen); + const bool handled=result && PyObject_IsTrue(result)>0; + Py_XDECREF(result);if(PyErr_Occurred())PyErr_Clear(); + if(handled)return; + } + CCameraManager& rkCmrMgr = CCameraManager::Instance(); CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera(); if (pkCmrCur) @@ -681,6 +690,15 @@ void CameraRotateBy(float rollDeg, float pitchDeg) pkCmrCur->RotateEyeAroundTarget(pitchDeg, rollDeg); } +void CameraZoomBy(float distanceRatio) +{ + CCamera* camera = CCameraManager::Instance().GetCurrentCamera(); + if (!camera || camera->IsLock() || !std::isfinite(distanceRatio) || distanceRatio <= 0.0f) + return; + camera->SetDistance(camera->GetDistance() * std::clamp(distanceRatio, 0.5f, 2.0f)); + // The normal CCamera::Update still enforces its configured min/max and terrain collision. +} + void SetTouchInput(bool touch) { g_touch_input = touch; @@ -1051,6 +1069,8 @@ namespace PythonBoot #include "Ava2WikiSource.inc" #include "Ava2DropItemSource.inc" #include "Ava2NativeInterfacesScript.inc" +#include "Ava2ItemShopNewSource.inc" +#include "Ava2ItemShopScript.inc" #include "AttrLockSnapshotsScript.inc" #include "LiveEndpointScript.inc" #include "NativeChannelScript.inc" @@ -1170,6 +1190,9 @@ bool RunMainScript(const char* lpCmdLine, std::string* error) install_script_module("uiWiki",c_szAva2WikiSource); install_script_module("uiDropItem",c_szAva2DropItemSource); install_script_module("mt_ava2_native_interfaces",c_szAva2NativeInterfacesScript); + install_script_module("mt_ava2_shop_support",c_szAva2ShopSupportScript); + install_script_module("uiItemShopNew",c_szAva2ItemShopNewSource); + install_script_module("mt_itemshop",c_szAva2ItemShopScript); install_script_module("mt_minimap_buttons", c_szMinimapOuterRingScript); if (g_touch_input) install_script_module("mt_mobile_hud", c_szMobileHUDScript); diff --git a/src/platform/ScriptLib/PythonBoot.h b/src/platform/ScriptLib/PythonBoot.h index 9402be11..877b5814 100644 --- a/src/platform/ScriptLib/PythonBoot.h +++ b/src/platform/ScriptLib/PythonBoot.h @@ -102,6 +102,8 @@ bool UIIsAttaching(); void UIDeattachObject(); // Turns the camera around the player immediately, without CCamera::Drag's decaying velocity. void CameraRotateBy(float rollDeg, float pitchDeg); +// PORT mobile pinch: immediate proportional zoom; native camera update retains distance/collision limits. +void CameraZoomBy(float distanceRatio); bool IsPointInsideActiveUI(int x, int y); // Touch hosts: hide 40250's on-screen login keypad (the system keyboard types instead). // Also drops the mouse arrow: touch hosts run 40250's hardware-cursor mode with no OS cursor, so diff --git a/src/port/UserInterface/PythonNetworkStream.cpp b/src/port/UserInterface/PythonNetworkStream.cpp index 48e8397b..54b07346 100644 --- a/src/port/UserInterface/PythonNetworkStream.cpp +++ b/src/port/UserInterface/PythonNetworkStream.cpp @@ -188,7 +188,8 @@ class CMainPacketHeaderMap : public CNetworkPacketHeaderMap Set(HEADER_GC_SASH, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketSash), STATIC_SIZE_PACKET)); // PORT: AVA2 sash Set(HEADER_GC_CHESTDROP, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCChestDrop), DYNAMIC_SIZE_PACKET)); Set(HEADER_GC_AVA2_DROP,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Drop),STATIC_SIZE_PACKET)); - Set(HEADER_GC_AVA2_EVENTS,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET)); + Set(93,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET)); + Set(HEADER_GC_AVA2_EVENTS,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET)); Set(HEADER_GC_SWITCHBOT, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCSwitchbot), DYNAMIC_SIZE_PACKET)); // PORT: AVA2 switchbot } @@ -545,6 +546,15 @@ bool CPythonNetworkStream::CheckPacket(TPacketHeader * pRetHeader) return false; } + // Native shop/calendar use DWORD lengths. Wait for the entire frame before dispatch. + if(header==93 || header==HEADER_GC_AVA2_EVENTS) { + TPacketGCAva2Events p; + if(!Peek(sizeof(p),&p))return false; + const unsigned minimum=sizeof(p)+(header==93?1:6); + if(p.size32768) { ClearRecvBuffer();PostQuitMessage(0);return false; } + if(!Peek(p.size))return false; + *pRetHeader=header;return true; + } // AVA2 chest preview uses a DWORD length, unlike the base WORD dynamic header. if(header==HEADER_GC_CHESTDROP) { TPacketGCChestDrop p; diff --git a/src/port/UserInterface/PythonNetworkStream.h b/src/port/UserInterface/PythonNetworkStream.h index ffb3fe83..92eb8058 100644 --- a/src/port/UserInterface/PythonNetworkStream.h +++ b/src/port/UserInterface/PythonNetworkStream.h @@ -562,6 +562,7 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton32768)return false; + std::vector data(p.size-sizeof(p)); + if (!Recv(data.size(),data.data()))return false; + PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_GAME],"BINARY_Ava2ItemShop",Py_BuildValue("(s#)",data.data(),int(data.size()))); + return true; +} diff --git a/tests/port/port_login_flow_test.cpp b/tests/port/port_login_flow_test.cpp index f4475178..2d966142 100644 --- a/tests/port/port_login_flow_test.cpp +++ b/tests/port/port_login_flow_test.cpp @@ -352,6 +352,7 @@ int main(int argc, char** argv) // by port. TChannelStatus::nPort is a short, so the fake server's ephemeral state port (> 32767) // never matches its own channel; offline the proof is the second channel (13002) it also lists. // Live the game port answers for the channels the db knows, the game port among them. + if (!std::getenv("MT_TEST_PINCH")) { const int state_port = server ? server->StatePort() : game_port; const int key = server ? 2 : 1; @@ -501,6 +502,69 @@ int main(int argc, char** argv) return g_failures ? 1 : 0; } + if (mobile_test && std::getenv("MT_TEST_PINCH")) { + CHECK(pump_until(5, [] { return py_true("not _stream.curtain.IsShow()"); })); + CHECK(py("import mt_mobile_hud; _hud=mt_mobile_hud.g_hud\n" + "assert not _hud.menuExpanded and all(not b.IsShow() for b in _hud.side)\n" + "assert _hud.shop.IsShow() and _hud.more.IsShow()\n" + "_hud.ToggleMore()\n" + "assert _hud.menuExpanded and all(b.IsShow() for b in _hud.side)\n" + "_hud.ToggleMore()\n" + "assert not _hud.menuExpanded and all(not b.IsShow() for b in _hud.side)")); + TouchController touch; + touch.set_enabled(true); + touch.update_screen_size(800, 600); + // PORT scene pinch: start across both halves, spread closer, close farther. + CHECK(!PythonBoot::IsPointInsideActiveUI(480, 240)); + CHECK(!PythonBoot::IsPointInsideActiveUI(320, 240)); + auto* camera = CCameraManager::Instance().GetCurrentCamera(); + const float originalDistance = camera->GetDistance(); + CHECK(touch.on_finger_down(201, 0.4f, 0.4f)); + CHECK(touch.on_finger_down(202, 0.6f, 0.4f)); + const float beforePinch = camera->GetDistance(); + touch.on_finger_motion(202, 0.7f, 0.4f); + CHECK(camera->GetDistance() < beforePinch * 0.8f); + const float closeDistance = camera->GetDistance(); + touch.on_finger_motion(202, 0.6f, 0.4f); + CHECK(camera->GetDistance() > closeDistance * 1.2f); + CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f); + touch.on_finger_up(201, 0.4f, 0.4f); // remaining finger becomes look, never tap + touch.on_finger_motion(202, 0.62f, 0.4f); + CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f); + touch.on_finger_up(202, 0.62f, 0.4f); + touch.update(); + CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f); + + // Reverse ownership order; right scene finger plus left scene finger also pinches. + touch.on_finger_down(203, 0.6f, 0.4f); + touch.on_finger_down(204, 0.4f, 0.4f); + touch.on_finger_motion(204, 0.3f, 0.4f); + CHECK(camera->GetDistance() < beforePinch * 0.8f); + touch.on_finger_up(204, 0.3f, 0.4f); + touch.on_finger_up(203, 0.6f, 0.4f); + camera->SetDistance(originalDistance); + touch.on_finger_down(207, 0.6f, 0.4f); + touch.on_finger_down(208, 0.4f, 0.4f); + touch.cancel_gestures(); + touch.on_finger_motion(208, 0.2f, 0.4f); + CHECK(std::abs(camera->GetDistance() - originalDistance) < 1.0f); + + // A moving joystick is not stolen by a second thumb looking around. + touch.on_finger_down(205, 0.3f, 0.45f); + touch.on_finger_motion(205, 0.35f, 0.45f); + touch.on_finger_down(206, 0.6f, 0.4f); + touch.on_finger_motion(206, 0.7f, 0.4f); + CHECK(std::abs(camera->GetDistance() - originalDistance) < 1.0f); + touch.on_finger_up(205, 0.35f, 0.45f); + touch.on_finger_up(206, 0.7f, 0.4f); + CHECK(py("import app; app.Exit()")); + pump_until(2, [] { return !PythonBoot::IsAppLooping(); }); + PythonBoot::Stop(); + if (server) server->Stop(); + std::printf("mobile scene pinch: %s\n", g_failures ? "FAILED" : "PASS"); + return g_failures ? 1 : 0; + } + if (mobile_test) { // Input remains blocked by the original phase curtain until its fade finishes. CHECK(pump_until(5, [] { return py_true("not _stream.curtain.IsShow()"); })); @@ -511,7 +575,7 @@ int main(int argc, char** argv) "_hud.window.interface.wndInventory.Hide()")); CHECK(py_true("_hud.IsShow()")); CHECK(py_true("not ui.Window.IsShow(_hud.taskbar)")); - CHECK(py_true("len(_hud.top) == 4 and len(_hud.side) == 3")); + CHECK(py_true("len(_hud.top) == 4 and len(_hud.side) == 4")); CHECK(py_true("all(button.GetWidth() >= 48 for button in _hud.top + _hud.side)")); CHECK(py_true("_hud.status.values[0] == player.GetStatus(player.HP)")); CHECK(py_true("_hud.experience is _hud.taskbar.expGaugeBoard and _hud.experience.IsShow()")); @@ -1650,6 +1714,8 @@ int main(int argc, char** argv) CHECK(kept_origin); touch.on_finger_up(101, 0.325f, 0.46666667f); + + } CHECK(py("import app\napp.Exit()")); diff --git a/tests/wiki/test_itemshop.py b/tests/wiki/test_itemshop.py new file mode 100644 index 00000000..446e43b7 --- /dev/null +++ b/tests/wiki/test_itemshop.py @@ -0,0 +1,75 @@ +"""Execute the shipping shop decoder and purchase callbacks with real native layouts.""" +import ast,struct,types,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] +SRC=(ROOT/'src/platform/ScriptLib/Ava2ItemShopScript.inc').read_text().split('c_szAva2ItemShopScript[]=R"PY(',1)[1].split(')PY";',1)[0] +class Wire(unittest.TestCase): + def setUp(self): + tree=ast.parse(SRC);fn=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='Parse') + self.ns={'struct':struct,'_product':struct.Struct('','exec'),self.ns) + def catalogue(self,discount=25,product=1): + row=self.ns['_product'].pack(product,71084,99,0,discount,0,0,0,2,8,4) + return struct.pack('','exec'),self.ns) + def setUp(self): + self.sent=[];self.now=0 + class Token: + def encode(self,encoding):assert encoding=='hex';return 'a'*32 + self.ns=dict(pending=None,_serial=0,_next=0,_waiting=False,_queued=False,_requested=0,_logAt=0,window=None, + os=types.SimpleNamespace(urandom=lambda size:Token()),app=types.SimpleNamespace(GetTime=lambda:self.now), + net=types.SimpleNamespace(SendChatPacket=self.sent.append),chat=types.SimpleNamespace(CHAT_TYPE_INFO=1,AppendChat=lambda *args:None),L=lambda s:s) + def test_displayed_discount_matches_server_integer_total(self): + self.functions('Total') + self.assertEqual(self.ns['Total'](58,1,50),29) + self.assertEqual(self.ns['Total'](99,2,25),148) + def test_confirmed_quote_is_frozen_and_double_accept_is_blocked(self): + self.functions('AcceptBuy') + item=types.SimpleNamespace(shopQuote=(1,2,148,71084),data=[999],buyCount=20,CloseQuestionDialog=lambda:None) + self.ns['AcceptBuy'](item);self.ns['AcceptBuy'](item) + self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084']) + def test_retry_preserves_order_and_never_creates_second_payment(self): + self.functions('Tick');self.ns['pending']=('a'*32,1,2,0,0,148,71084) + for now in [5,10,15,20,25]:self.now=now;self.ns['Tick']() + self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084']*3) + self.assertEqual(self.ns['pending'][4],4) + def test_catalogue_refresh_is_queued_past_command_throttle(self): + self.functions('Request','Tick');self.ns['Request']();self.now=.5;self.ns['Request']() + self.assertEqual(len(self.sent),1);self.assertTrue(self.ns['_queued']) + self.now=1.2;self.ns['Tick']();self.assertEqual(self.sent,['/ishop data -1']*2) + def test_image_and_button_callbacks_keep_correct_event_arguments(self): + self.ns['_MISSING']=object();self.functions('EventTag');calls=[] + wrapped=self.ns['EventTag'](lambda self,event,category,sub:calls.append((event,category,sub)),3) + self.assertGreater(wrapped.__code__.co_argcount,1) # classic ui.__mem_func__ must retain image arguments + wrapped(None,2,1);wrapped(None,'button',2,1) + self.assertEqual(calls,[(None,2,1),('button',2,1)]) + def test_uncertain_commit_keeps_same_pending_order(self): + self.functions('Receive');pending=('a'*32,1,2,0,0,148,71084) + self.ns.update(pending=pending,Parse=lambda raw:(7,('a'*32,8,10000))) + self.ns['Receive'](None,b'');self.assertEqual(self.ns['pending'],pending) + +if __name__=='__main__':unittest.main() diff --git a/tests/wiki/test_minimap_buttons.py b/tests/wiki/test_minimap_buttons.py index 3c733c9e..83546323 100644 --- a/tests/wiki/test_minimap_buttons.py +++ b/tests/wiki/test_minimap_buttons.py @@ -29,6 +29,7 @@ class MockWidget(object): def SetDownVisual(self, v): self.visuals['down'] = v def SetEvent(self, ev): self.event = ev def SetText(self, t): self.text = t + def SetToolTipText(self, t): self.tooltip = t def SetOutline(self): pass def SetHorizontalAlignRight(self): pass def SetPackedFontColor(self, c): pass @@ -40,11 +41,15 @@ class MockWidget(object): class MinimapButtonsTests(unittest.TestCase): def setUp(self): - names = ('app', 'game', 'ui', 'wndMgr', 'mt_dungeons', 'mt_battlepass', 'mt_biolog') + names = ('app', 'game', 'ui', 'wndMgr', 'mt_dungeons', 'mt_battlepass', 'mt_biolog', 'player', 'mt_channel', 'mt_wiki') mods = {n: types.ModuleType(n) for n in names} mods['app'].DIK_F5 = 63 mods['app'].DIK_F6 = 64 mods['app'].DIK_F7 = 65 + mods['app'].DIK_F8 = 66 + mods['player'].AutoHuntLocalize = lambda text: text.encode('gbk') + mods['mt_channel'].Toggle = lambda: None + mods['mt_wiki'].Toggle = lambda: None self.toggles = {'dungeon': 0, 'battlepass': 0, 'biolog': 0} mods['mt_dungeons'].Toggle = lambda: self.toggles.__setitem__('dungeon', self.toggles['dungeon'] + 1) @@ -75,7 +80,10 @@ class MinimapButtonsTests(unittest.TestCase): self.wndMiniMap.ShowMiniMap = lambda: self.wndMiniMap.OpenWindow.Show() self.wndMiniMap.OnUpdate = lambda: None - self.gw.interface = types.SimpleNamespace(wndMiniMap=self.wndMiniMap) + self.expanded = MockWidget() + self.expanded.expandedTaskBarBoard = MockWidget() + self.gw.interface = types.SimpleNamespace( + wndMiniMap=self.wndMiniMap, wndExpandedTaskBar=self.expanded) self.game.GameWindow.Open(self.gw) self.ring = self.ns['g_ring'] @@ -96,17 +104,27 @@ class MinimapButtonsTests(unittest.TestCase): # Dungeon: (-10, 40) self.assertEqual(self.ring.btnDungeon.pos, (-10, 40)) self.assertEqual(self.ring.btnDungeon.visuals['up'], "d:/ymir work/ui/game/minimapa/dungeon_0.tga") - self.assertEqual(self.ring.tipDungeon.textLine.text, "[F5] 副本信息") + self.assertEqual(self.ring.tipDungeon.textLine.text, "[F5] 副本信息".encode("gbk")) # BattlePass: (0, 80) self.assertEqual(self.ring.btnBattlePass.pos, (0, 80)) self.assertEqual(self.ring.btnBattlePass.visuals['up'], "d:/ymir work/ui/game/battle_pass/battlepass_icon_0.tga") - self.assertEqual(self.ring.tipBattlePass.textLine.text, "[F6] 战斗通行证") + self.assertEqual(self.ring.tipBattlePass.textLine.text, "[F6] 战斗通行证".encode("gbk")) # Biolog: (15, 105) self.assertEqual(self.ring.btnBiolog.pos, (15, 105)) self.assertEqual(self.ring.btnBiolog.visuals['up'], "d:/ymir work/ui/game/minimapa/biolog_0.tga") - self.assertEqual(self.ring.tipBiolog.textLine.text, "[F7] 生物学家") + self.assertEqual(self.ring.tipBiolog.textLine.text, "[F7] 生物学家".encode("gbk")) + + def test_all_chinese_tooltips_use_locale_bytes(self): + expected = ((self.ring.tipDungeon, "[F5] 副本信息"), + (self.ring.tipBattlePass, "[F6] 战斗通行证"), + (self.ring.tipBiolog, "[F7] 生物学家"), + (self.ring.tipChannel, "[F8] 点击换线")) + for tooltip, label in expected: + self.assertEqual(tooltip.textLine.text.decode('gbk'), label) + self.assertEqual(self.expanded.btnSwitchbot.tooltip.decode('gbk'), "自动洗练") + self.assertEqual(self.expanded.btnWiki.tooltip.decode('gbk'), "游戏百科") def test_button_clicks_trigger_subsystems(self): self.ring.btnDungeon.event() diff --git a/tools/ava2-native/import_sources.py b/tools/ava2-native/import_sources.py index a428f15a..1d302d44 100644 --- a/tools/ava2-native/import_sources.py +++ b/tools/ava2-native/import_sources.py @@ -4,7 +4,7 @@ from pathlib import Path import hashlib,json ROOT=Path(__file__).resolve().parents[2] REF=ROOT.parent/'AVA2/1. Client DEV/pack_maker/root' -SOURCES={'BattlePassEx':'uibattlepassex.py','EventCalendarNew':'uieventcalendarnew.py','WikiUI':'wikiui.py','Wiki':'uiwiki.py','DropItem':'uidropitem.py'} +SOURCES={'ItemShopNew':'uiitemshopnew.py','BattlePassEx':'uibattlepassex.py','EventCalendarNew':'uieventcalendarnew.py','WikiUI':'wikiui.py','Wiki':'uiwiki.py','DropItem':'uidropitem.py'} manifest={} for label,name in SOURCES.items(): raw=(REF/name).read_bytes();s=raw.decode('cp1254').replace('\r\n','\n') diff --git a/tools/ava2-native/sources.json b/tools/ava2-native/sources.json index dfe9aada..60799ea4 100644 --- a/tools/ava2-native/sources.json +++ b/tools/ava2-native/sources.json @@ -1,4 +1,12 @@ { + "uiitemshopnew.py": { + "sha256": "b0e76028a37763bf021feaef31979040535174a60ec60c885877f9d19a07cb6d", + "module": "ItemShopNew", + "changes": [ + "CP1254 to UTF-8", + "CRLF to LF" + ] + }, "uibattlepassex.py": { "sha256": "c0ac6e2e3dfcd6c6c0716e5da4bfdf29169087109a7216d507f67d7ac3ed00d2", "module": "BattlePassEx", diff --git a/tools/ava2-native/stage_resources.py b/tools/ava2-native/stage_resources.py index d519cb33..d0fd9f57 100644 --- a/tools/ava2-native/stage_resources.py +++ b/tools/ava2-native/stage_resources.py @@ -7,7 +7,7 @@ def stage(pack_maker,assets): spec=importlib.util.spec_from_file_location('ava2_items',ROOT/'tools/server/ava2-items/make_items.py') module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) files=module.pack_index(pack_maker) - prefixes=('d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/','d:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/') + prefixes=('d:/ymir work/ui/game/ishop/','d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/','d:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/') count=0 for name,source in files.items(): if name.startswith(prefixes): diff --git a/tools/server/ava2-items/make_items.py b/tools/server/ava2-items/make_items.py index 93c6506d..253a77fa 100644 --- a/tools/server/ava2-items/make_items.py +++ b/tools/server/ava2-items/make_items.py @@ -315,7 +315,7 @@ def prepare(ava,proto_reader,locale,output,tool,packer,wrap=lambda text:text): target=assets/q;target.parent.mkdir(parents=True,exist_ok=True) if not target.exists():shutil.copy2(files[q],target);copied+=1 # Native AVA2 BattlePassEx, event manager, encyclopedia and drop finder. - native_prefixes=('d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/', + native_prefixes=('d:/ymir work/ui/game/ishop/','d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/', 'd:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/') for q in files: if q.startswith(native_prefixes):