From 802ba10e1a7044359515e9c0e7afbaa5d816d38d Mon Sep 17 00:00:00 2001 From: EJClaw Date: Mon, 12 Oct 2026 01:34:06 +0900 Subject: [PATCH] =?UTF-8?q?feat(bunsik):=20MVP=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=E2=80=94=20=EB=A7=B5,=20=EC=9A=94?= =?UTF-8?q?=EB=A6=AC=C2=B7=EC=84=9C=EB=B9=99,=20=EC=86=90=EB=8B=98=20NPC,?= =?UTF-8?q?=20=EC=97=85=EA=B7=B8=EB=A0=88=EC=9D=B4=EB=93=9C=2020=EA=B0=9C,?= =?UTF-8?q?=20=EC=84=B8=EC=9D=B4=EB=B8=8C,=20=EA=B2=B0=EC=A0=9C,=20?= =?UTF-8?q?=ED=95=9C/=EC=98=81=20UI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Shop.luau: 손님·주문·조리·서빙·구매 순수 로직(lune 단위 테스트, 시뮬레이터 공용) - 서버: World(부지 6칸), PlotBuilder(파트 모형), PlotController, Npc(트윈 이동), Data(ProfileStore), Receipts(결제 1회 = 지급 1회), Game - 클라이언트: Hud(돈·다음 업그레이드·목록·결제·언어·튜토리얼), 내 조리대 전용 버튼, 튜토리얼 화살표, 주인 전용 테스트 버튼 - 2단계 업그레이드 10개 추가, 파이썬 시뮬레이터를 실제 로직 기반 tools/sim.luau로 교체 - tools/cloud.py: 업로드, 원격 Luau 실행, 게임패스·개발자 상품 생성, 서버 인원 설정 - tests/cloud/integration.luau: 로블록스 서버 통합 테스트 514개 통과 - check.sh에 luau-lsp 타입 검사 추가, ProfileStore 고정 버전 포함 Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 9 +- SETUP.md | 1 + bunsik-tycoon/ECONOMY.md | 75 +- bunsik-tycoon/PLAYTEST.md | 33 + bunsik-tycoon/SPEC.md | 11 +- bunsik-tycoon/art/double_money.png | Bin 0 -> 36855 bytes bunsik-tycoon/art/money_boost.png | Bin 0 -> 20932 bytes bunsik-tycoon/default.project.json | 65 +- bunsik-tycoon/src/client/Guide.luau | 58 + bunsik-tycoon/src/client/Hud.luau | 466 ++++ bunsik-tycoon/src/client/Main.client.luau | 41 +- bunsik-tycoon/src/client/Stove.luau | 60 + bunsik-tycoon/src/server/Build.luau | 151 ++ bunsik-tycoon/src/server/Data.luau | 83 + bunsik-tycoon/src/server/Food.luau | 128 + bunsik-tycoon/src/server/Game.luau | 261 ++ bunsik-tycoon/src/server/Main.server.luau | 7 +- bunsik-tycoon/src/server/Npc.luau | 253 ++ bunsik-tycoon/src/server/PlotBuilder.luau | 521 ++++ bunsik-tycoon/src/server/PlotController.luau | 549 ++++ bunsik-tycoon/src/server/PlotLayout.luau | 52 + bunsik-tycoon/src/server/Receipts.luau | 64 + bunsik-tycoon/src/server/World.luau | 179 ++ bunsik-tycoon/src/shared/Economy.luau | 156 +- bunsik-tycoon/src/shared/Locale.luau | 127 + bunsik-tycoon/src/shared/Products.luau | 7 + bunsik-tycoon/src/shared/Shop.luau | 236 ++ bunsik-tycoon/src/shared/Sounds.luau | 8 + bunsik-tycoon/tests/Economy.spec.luau | 71 +- bunsik-tycoon/tests/Locale.spec.luau | 40 + bunsik-tycoon/tests/Receipts.spec.luau | 90 + bunsik-tycoon/tests/Shop.spec.luau | 112 + bunsik-tycoon/tests/Sim.spec.luau | 31 + bunsik-tycoon/tests/check.luau | 25 + bunsik-tycoon/tests/cloud/integration.luau | 339 +++ bunsik-tycoon/tools/art.py | 88 + bunsik-tycoon/tools/check.sh | 17 +- bunsik-tycoon/tools/cloud.py | 171 ++ bunsik-tycoon/tools/economy_sim.py | 93 - bunsik-tycoon/tools/sim.luau | 14 + bunsik-tycoon/tools/simlib.luau | 61 + bunsik-tycoon/vendor/ProfileStore.LICENSE.txt | 201 ++ bunsik-tycoon/vendor/ProfileStore.luau | 2243 +++++++++++++++++ rokit.toml | 1 + 45 files changed, 6997 insertions(+), 202 deletions(-) create mode 100644 bunsik-tycoon/PLAYTEST.md create mode 100644 bunsik-tycoon/art/double_money.png create mode 100644 bunsik-tycoon/art/money_boost.png create mode 100644 bunsik-tycoon/src/client/Guide.luau create mode 100644 bunsik-tycoon/src/client/Hud.luau create mode 100644 bunsik-tycoon/src/client/Stove.luau create mode 100644 bunsik-tycoon/src/server/Build.luau create mode 100644 bunsik-tycoon/src/server/Data.luau create mode 100644 bunsik-tycoon/src/server/Food.luau create mode 100644 bunsik-tycoon/src/server/Game.luau create mode 100644 bunsik-tycoon/src/server/Npc.luau create mode 100644 bunsik-tycoon/src/server/PlotBuilder.luau create mode 100644 bunsik-tycoon/src/server/PlotController.luau create mode 100644 bunsik-tycoon/src/server/PlotLayout.luau create mode 100644 bunsik-tycoon/src/server/Receipts.luau create mode 100644 bunsik-tycoon/src/server/World.luau create mode 100644 bunsik-tycoon/src/shared/Locale.luau create mode 100644 bunsik-tycoon/src/shared/Products.luau create mode 100644 bunsik-tycoon/src/shared/Shop.luau create mode 100644 bunsik-tycoon/src/shared/Sounds.luau create mode 100644 bunsik-tycoon/tests/Locale.spec.luau create mode 100644 bunsik-tycoon/tests/Receipts.spec.luau create mode 100644 bunsik-tycoon/tests/Shop.spec.luau create mode 100644 bunsik-tycoon/tests/Sim.spec.luau create mode 100644 bunsik-tycoon/tests/check.luau create mode 100644 bunsik-tycoon/tests/cloud/integration.luau create mode 100644 bunsik-tycoon/tools/art.py create mode 100644 bunsik-tycoon/tools/cloud.py delete mode 100644 bunsik-tycoon/tools/economy_sim.py create mode 100644 bunsik-tycoon/tools/sim.luau create mode 100644 bunsik-tycoon/tools/simlib.luau create mode 100644 bunsik-tycoon/vendor/ProfileStore.LICENSE.txt create mode 100644 bunsik-tycoon/vendor/ProfileStore.luau diff --git a/.gitignore b/.gitignore index a7b2c46..20f4b26 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ __pycache__/ build/ *.rbxl *.rbxlx +.cache/ diff --git a/README.md b/README.md index ed48168..abfd983 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,13 @@ 사용자 준비(계정·2단계 인증·나이 확인·Studio 설치): [SETUP.md](SETUP.md) -현재 단계: 분식집 Rojo 골격 완료, 사용자 계정 준비와 API 키 발급 대기. 다음은 테스트 플레이스 업로드와 원격 테스트 연결 +현재 단계: 분식집 MVP 완성, 비공개 게임에 올려 사용자 플레이 테스트 중([bunsik-tycoon/PLAYTEST.md](bunsik-tycoon/PLAYTEST.md)). 다음은 테스트 의견 반영, 아이콘·썸네일, 출시 준비 개발 도구 설치와 검사: ``` -rokit install # rojo, selene, stylua, lune (버전은 rokit.toml) -bunsik-tycoon/tools/check.sh # 스타일·린트·단위 테스트·빌드 +rokit install # rojo, selene, stylua, lune, luau-lsp (버전은 rokit.toml) +bunsik-tycoon/tools/check.sh # 스타일·린트·타입 검사·단위 테스트·빌드 +python3 bunsik-tycoon/tools/cloud.py publish bunsik-tycoon/build/BunsikTycoon.rbxl # 저장 버전 업로드 +python3 bunsik-tycoon/tools/cloud.py run bunsik-tycoon/tests/cloud/integration.luau --version N # 로블록스 서버 통합 테스트 +python3 bunsik-tycoon/tools/cloud.py publish bunsik-tycoon/build/BunsikTycoon.rbxl --published # 실제 서버에 반영 ``` diff --git a/SETUP.md b/SETUP.md index aa218c0..acf71a6 100644 --- a/SETUP.md +++ b/SETUP.md @@ -76,6 +76,7 @@ AI가 서버에서 게임을 올리고, 로블록스 서버에서 테스트를 - 키는 서버 `secrets.json`의 `roblox.opencloud/bunsik-tycoon`에 있습니다. 리포와 채팅에는 넣지 않습니다. - Bunsik Tycoon: universe `10770390863`, 루트 플레이스 `98118751156219`. - 서버에서 확인한 것: 게임 설정 읽기·수정, 게임패스·개발자 상품 목록, 에셋 읽기, Rojo 빌드 업로드(Saved 버전 4), 그 버전에서 Luau 원격 실행. 모두 성공했습니다. +- 2026-10-12 API로 만든 것: 게임패스 `Double Money (2배 수익)` 199 로벅스(ID 2026574937), 개발자 상품 `Money Boost (돈 부스트)` 25 로벅스(ID 3717970589), 서버 인원 6명, 게임 설명. ## 6. 나중에 할 것 (지금은 안 해도 됨) diff --git a/bunsik-tycoon/ECONOMY.md b/bunsik-tycoon/ECONOMY.md index 6a6c8af..8989d17 100644 --- a/bunsik-tycoon/ECONOMY.md +++ b/bunsik-tycoon/ECONOMY.md @@ -1,55 +1,70 @@ -# 분식집 타이쿤 — 첫 10분 경제 수치표 (초안) +# 분식집 타이쿤 — 경제 수치표 -목표: 첫 구매는 10초 안에, 그 뒤로는 40~90초마다 하나씩 사고, 10분 무렵 "실내 분식집 확장"(2단계)에 닿게 합니다. -숫자는 `tools/economy_sim.py`로 1초 단위 시뮬레이션을 돌려 맞췄습니다. 표를 고치면 시뮬레이터도 같이 고치고 다시 돌립니다. +목표: 첫 구매는 10초 안에, 그 뒤로는 40~90초마다 하나씩 사고, 10분 무렵 "실내 분식집 확장"(2단계)에 닿게 합니다. 2단계는 구매 간격 1.5~2.5분입니다. +숫자의 원본은 `src/shared/Economy.luau`입니다. 표의 시각은 시뮬레이터 `tools/sim.luau`가 **실제 게임 로직(`src/shared/Shop.luau`)**을 봇으로 돌려서 낸 값입니다(2026-10-12, 예전 파이썬 시뮬레이터는 게임 코드와 따로 놀 수 있어서 지웠습니다). + +``` +lune run tools/sim.luau # 기본 +lune run tools/sim.luau x2 # 2배 수익 게임패스 +lune run tests/Sim.spec.luau # 목표 범위 자동 검사(check.sh에 포함) +``` ## 기본 설정 | 항목 | 값 | 설명 | |---|---|---| | 처음 테이블 수 | 1 | 동시에 앉을 수 있는 손님 수 | -| 손님 간격 | 6초 | 빈자리가 없으면 그냥 지나감 | +| 손님 간격 | 6초 | 빈자리가 없으면 그냥 지나감. 접속하자마자 첫 손님 | +| 손님 입장 | 2.5초 | 입구에서 자리까지 걷는 시간(NPC 이동 시간과 같음) | | 조리 시간 | 2.5초 | 조리대에서 버튼을 누르고 있는 시간 | -| 왕복 시간 | 약 5초 | 조리대 → 테이블 → 조리대 | -| 식사 시간 | 6초 | 다 먹으면 자리가 빔 | +| 왕복 시간 | 약 5초 | 조리대 → 테이블 → 조리대(시뮬레이터 가정. 게임 속 걷기 속도는 20) | +| 식사 시간 | 6초 | 다 먹으면 자리가 빔. 돈은 접시를 놓는 순간 들어옴 | +| 한 번에 드는 접시 | 1 | 쟁반 2, 큰 쟁반 3 | | 시작 돈 | 0 | | ## 메뉴 가격 | 메뉴 | 한 접시 | 해금 | |---|---|---| -| 떡볶이 | 10 | 처음부터 | -| 김밥 | 20 | 구매 2번 | -| 순대 | 35 | 구매 6번 | +| 떡볶이 🌶️ | 10 | 처음부터 | +| 김밥 🍙 | 20 | 구매 2번 | +| 순대 🌭 | 35 | 구매 6번 | +| 어묵 🍢 | 50 | 구매 13번(2단계) | +| 튀김 🍤 | 70 | 구매 17번(2단계) | -손님은 해금된 메뉴를 돌아가며 주문합니다. +손님은 해금된 메뉴를 돌아가며 주문합니다. 양념 비법은 모든 메뉴 가격에 배율을 곱하고 소수점은 버립니다(순대 35 × 1.5 = 52). ## 구매 순서와 시점 -"도달 시각"은 쉬지 않고 최적으로 플레이했을 때의 값입니다. 실제 아이들은 1.3~1.5배쯤 걸릴 것으로 보고, 출시 전 플레이 테스트로 다시 맞춥니다. +"도달 시각"은 쉬지 않고 최적으로 플레이했을 때의 값입니다. 실제 아이들은 1.3~1.5배쯤 걸릴 것으로 보고, 사용자 플레이 테스트 뒤 다시 맞춥니다. | # | 구매 | 비용 | 효과 | 도달 시각 | 2배 게임패스 | |---|---|---|---|---|---| -| 1 | 테이블 2 | 10 | 테이블 1 → 2 | 0:08 | 0:08 | -| 2 | 김밥 해금 | 40 | 메뉴 추가(20) | 0:46 | 0:28 | -| 3 | 간판 Lv1 | 70 | 손님 간격 6 → 5초 | 1:32 | 0:46 | -| 4 | 화구 Lv1 | 90 | 조리 2.5 → 1.5초 | 2:22 | 1:12 | -| 5 | 테이블 3 | 120 | 테이블 2 → 3 | 3:23 | 1:42 | -| 6 | 순대 해금 | 160 | 메뉴 추가(35) | 4:33 | 2:25 | -| 7 | 양념 비법 Lv1 | 240 | 모든 메뉴 가격 1.5배 | 5:50 | 3:07 | -| 8 | 알바생 고용 | 360 | 조리 자동, 플레이어는 나르기만 | 7:14 | 3:49 | -| 9 | 테이블 4 | 480 | 테이블 3 → 4, 손님 간격 5 → 4초 | 8:31 | 4:26 | -| 10 | 실내 분식집 확장 | 600 | 2단계 진입(새 맵 구역, 다음 업그레이드 줄) | 10:01 | 5:11 | +| 1 | 테이블 2 | 10 | 테이블 1 → 2 | 0:05 | 0:05 | +| 2 | 김밥 해금 | 40 | 메뉴 추가(20) | 0:37 | 0:21 | +| 3 | 간판 Lv1 | 70 | 손님 간격 6 → 5초 | 1:18 | 0:37 | +| 4 | 화구 Lv1 | 90 | 조리 2.5 → 1.5초 | 2:05 | 0:59 | +| 5 | 테이블 3 | 120 | 테이블 2 → 3 | 3:05 | 1:26 | +| 6 | 순대 해금 | 160 | 메뉴 추가(35) | 4:19 | 2:07 | +| 7 | 양념 비법 Lv1 | 240 | 모든 메뉴 가격 1.5배 | 5:37 | 2:48 | +| 8 | 알바생 고용 | 360 | 알바생이 카운터에 접시를 만들어 둠, 플레이어는 나르기만 | 6:49 | 3:29 | +| 9 | 테이블 4 | 480 | 테이블 3 → 4, 손님 간격 5 → 4초 | 8:04 | 4:05 | +| 10 | 실내 분식집 확장 | 600 | 2단계: 건물, 새 업그레이드 줄 | 9:39 | 4:55 | +| 11 | 쟁반 | 700 | 접시 2개 들기 | 11:29 | 5:46 | +| 12 | 테이블 5 | 800 | 테이블 5 | 13:06 | 6:31 | +| 13 | 어묵 해금 | 950 | 메뉴 추가(50) | 15:06 | 7:31 | +| 14 | 간판 Lv2 | 1,150 | 손님 간격 4 → 3초 | 16:51 | 8:26 | +| 15 | 테이블 6 | 1,400 | 테이블 6 | 18:34 | 9:21 | +| 16 | 화구 Lv2 | 1,700 | 조리 1.5 → 1초 | 20:34 | 10:16 | +| 17 | 튀김 해금 | 2,000 | 메뉴 추가(70) | 22:59 | 11:26 | +| 18 | 양념 비법 Lv2 | 2,500 | 가격 배율 2배 | 25:20 | 12:36 | +| 19 | 큰 쟁반 | 3,000 | 접시 3개 들기 | 27:30 | 13:36 | +| 20 | 테이블 7·8 | 3,600 | 테이블 8, 손님 간격 2.5초 | 30:00 | 14:51 | -구매 간격은 8초 → 38초 → 46초 → … → 90초로 조금씩 늘어납니다. 비용은 한 단계에 약 1.3배씩 오릅니다. - -## 10분 이후 규칙 (2단계부터) - -- 같은 종류 업그레이드의 다음 레벨 비용은 이전 비용의 1.15배로 시작하고, 매출이 느는 속도에 맞춰 시뮬레이터로 조정합니다. -- 구매 간격 목표: 2단계는 1~2분, 3단계는 2~4분. -- 오프라인 수익과 체인점(리버스, 영구 수익 배율)은 2차 업데이트에서 넣습니다. +1단계 구매 간격은 5초 → 32초 → 41초 → … → 95초, 2단계는 97~150초입니다. 비용은 한 단계에 약 1.2~1.3배씩 오릅니다. +20개를 다 사면 "2호점은 다음 업데이트에서 열려요"가 나옵니다. 오프라인 수익과 체인점(리버스)은 2차 업데이트입니다. ## 게임패스·상품과의 관계 -- 2배 수익 게임패스는 진행 속도를 약 2배로 만듭니다(위 표의 오른쪽 열). 무과금 유저도 10분에 확장할 수 있으니, 결제하지 않아도 답답하지 않은 선입니다. -- 돈 부스트 팩(개발자 상품)은 "현재 1분 매출 × N분" 방식으로 줍니다. 고정 금액으로 주면 후반에는 쓸모가 없어지고 초반에는 밸런스를 깨기 때문입니다. +- 2배 수익 게임패스(199 로벅스)는 진행 속도를 약 2배로 만듭니다(위 표의 오른쪽 열). 무과금 유저도 10분에 확장할 수 있으니, 결제하지 않아도 답답하지 않은 선입니다. +- 돈 부스트 팩(25 로벅스)은 "지금 능력치로 1분 매출 × 10분"(최소 100원)을 줍니다. 처음엔 370원, 확장 직전엔 4,850원쯤입니다. 고정 금액으로 주면 후반에는 쓸모가 없어지고 초반에는 밸런스를 깨기 때문입니다. 20개를 다 산 뒤에는 쓸 곳이 없으므로 버튼을 숨깁니다. diff --git a/bunsik-tycoon/PLAYTEST.md b/bunsik-tycoon/PLAYTEST.md new file mode 100644 index 0000000..ee73198 --- /dev/null +++ b/bunsik-tycoon/PLAYTEST.md @@ -0,0 +1,33 @@ +# 분식집 타이쿤 — 직접 해 보기 안내 + +## 들어가는 법 + +1. `tkrmagid` 계정으로 로그인한 PC나 휴대폰에서 https://www.roblox.com/games/98118751156219/Bunsik-Tycoon 을 엽니다. +2. 초록색 플레이 버튼을 누릅니다. 게임은 비공개라서 주인 계정만 들어갈 수 있습니다. +3. 들어가면 바로 내 가게 자리(부지)로 옮겨집니다. + +## 해 볼 것 (15~20분) + +1. 튜토리얼: 노란 줄과 ⬇️ 화살표를 따라 조리대로 가서 버튼을 꾹 누르고(PC는 E 키), 접시를 손님 자리로 가져갑니다. 손님 근처에 가면 접시가 자동으로 놓입니다. +2. 돈이 생기면 아래 가운데 카드의 [사기] 버튼으로 다음 업그레이드를 삽니다. 오른쪽 [📋 업그레이드]에서 전체 목록을 봅니다. +3. 8번째 구매(알바생)부터는 알바생이 카운터(조리대 오른쪽)에 접시를 만들어 둡니다. 카운터 근처에 가면 접시를 자동으로 집습니다. +4. 10번째 구매(실내 분식집 확장)를 하면 건물이 생기고 2단계 업그레이드 10개가 열립니다. +5. 오른쪽 위 언어 버튼으로 한국어·영어를 바꿔 봅니다. +6. 나갔다가 다시 들어와서 돈과 업그레이드가 그대로인지 봅니다. + +## 개발자 테스트 버튼(주인 계정에만 보임) + +화면 왼쪽, `⚡ 돈 부스트` 버튼 아래의 `🛠 개발자 테스트` 상자: +- `+1,000원`: 돈을 바로 넣습니다. 뒤쪽 업그레이드를 빨리 확인할 때 씁니다. +- `2배 켜기/끄기`: 2배 수익 게임패스를 산 것처럼 켭니다(이번 접속에만 적용). +- `처음부터`: 돈·업그레이드·튜토리얼을 처음으로 되돌립니다. + +왼쪽의 `💰x2 2배 수익`, `⚡ 돈 부스트` 버튼은 진짜 결제 창이 뜹니다. 누르면 실제 로벅스가 나가니, 결제 테스트가 필요할 때만 쓰세요. + +## 알려 주시면 좋은 것 + +- 처음 1분 안에 무엇을 해야 하는지 바로 알 수 있었는지 +- 손님 걷기·앉기 모습, 접시가 손에 들리는 모습이 어색하지 않은지(서버에서는 화면을 볼 수 없어서 이 부분은 직접 봐 주셔야 합니다) +- 너무 빠르거나 느리다고 느낀 구간(몇 번째 업그레이드 근처인지) +- 휴대폰에서 버튼이 가려지거나 누르기 어려운 곳 +- 오류나 멈춤이 있었다면 그때 한 행동과 화면 캡처 diff --git a/bunsik-tycoon/SPEC.md b/bunsik-tycoon/SPEC.md index 9b9f539..cb91bf1 100644 --- a/bunsik-tycoon/SPEC.md +++ b/bunsik-tycoon/SPEC.md @@ -58,11 +58,8 @@ ## 8. 제작 일정 (마일스톤) 제작·테스트는 AI가 하고, 사용자는 마일스톤마다 직접 플레이해 보는 것만 한다고 보고 3주로 잡았습니다(원안 14일). - M0 (0주차): 사용자 계정 준비(2단계 인증, 나이 확인, 빈 게임 Publish 1회, API 키) + Rojo 골격(완료) -- M1 (1주차 전반): 부지 배정 + 맵 블록아웃 + 조리대/요리 + 돈 수금 -- M2 (1주차 후반): 손님 AI 동선·주문·지불 -- M3 (2주차 전반): 업그레이드 10개·실내 확장 + ProfileStore 세이브 -- M4 (2주차 후반): 게임패스·개발자 상품 + UI 다듬기 + 한국어·영어 -- M5 (3주차): 플레이 테스트·밸런싱 + 썸네일/아이콘 + 설문 작성 + 출시(16세 이상 공개) +- M1~M4: 맵·조리·손님·업그레이드 20개(1단계 10 + 2단계 10)·세이브·게임패스·개발자 상품·한국어/영어 UI(2026-10-12 완료, 비공개 게임 버전 6에 올림. 사용자 플레이 테스트 단계. 해 보는 법은 `PLAYTEST.md`) +- M5 (3주차): 사용자 플레이 테스트 반영·밸런싱 + 게임 아이콘/썸네일 + 설문 작성 + 출시(16세 이상 공개) - 출시 후 60일: 초중생 계정 공개 조건(조건 충족 유저의 고유 플레이 250회, 약 250명) 달성 ## 9. 기술 스택 @@ -105,8 +102,8 @@ - "화구" 업그레이드로 누르는 시간이 짧아지고, "알바생"을 고용하면 조리가 자동이 됩니다. ### C. 경제 수치 -- 첫 10분 표: `ECONOMY.md`. 첫 구매 0:08, 10번째 구매(실내 확장) 10:01. -- 시뮬레이터: `tools/economy_sim.py`. +- 첫 10분 표: `ECONOMY.md`. 첫 구매 0:05, 10번째 구매(실내 확장) 9:39. +- 시뮬레이터: `tools/sim.luau`(실제 게임 로직 Shop.luau를 봇이 플레이). 표는 1단계 10개 + 2단계 10개. ### D. 출시 대상과 언어 - 출시 직후 60일은 나이 확인을 마친 16세 이상만 볼 수 있습니다. 그동안 조건 충족 유저의 고유 플레이 250회(서로 다른 유저 약 250명)를 모아야 초중생 계정(Kids·Select)에 공개됩니다. diff --git a/bunsik-tycoon/art/double_money.png b/bunsik-tycoon/art/double_money.png new file mode 100644 index 0000000000000000000000000000000000000000..f5a6656100e7ad08b7b07ae71aff82ef4cd1a8ae GIT binary patch literal 36855 zcmWhzWmsEn3@y%Z7%s(~;WD7OkKqh=cO6i)$cDQPhC9Pyz;JhWcXxOD`u%D9^xmgU za`PtVoFq(HQ3f4_7zF?Tpv%chssaG8(2uYHWJKuO4S41W0ElUmlN3`2r=MoHrIYrj z-b1=;MCqFcltX1Jj83(u6 zG|Wn|f{b+a1(`5rGO<9uo=C~nWF-C z2T=IYJ{4qzhQh_`NCN*!#+Ax);z-ejh0;)~S`BLu!=WzJ<3y@H3}U$%sRj)Mr69ZD z$q7>pP-DmKNQ4u))Rl@EHP4wBZl%c5;Cy%neK%D?tIDD@iXa~joFZ^`&qa*0WTzTX zr+Eyeh>?_x$NZo%G=tISKOqu}&`Um^?+=$qe1$;PBNE@QYJI7Nagci<=P z+^%OgT%GuV;u!>SqnX3$%$ef${h+&}=A8{n(wxdWr;r?9$LJMC`Lm9|Gz-Ej&9Mjm- zFbHsCfTW|PfU0SWK!veTq6a40k|>-4GxJyk8+%7AP?j??#LW>f4FpUki5RtGu-V9@ z$ljP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=iClO~cBFR()`G_QsL`0Ae30BDTCpJ*}@d)h! zNXGq#y#i(#0wNDg5{X1&6lQvM?56k?Y-a!{D29N76`lc!L?V%xk6jghBC-;aK+71A zvwtz&m!ip41R04YlSD+25h=7}E0z9oWQC|it5G2OfTR`?2QJZMD~gOnlS@3J$cPlJ zvX#nS9kyKp&`RQxK|FH#AUSp)v?LN*R5#f)F;E($lGo4w2UM^9JxYzUU;qFB07*qo IM6N<$f+8~o0RR91 literal 0 HcmV?d00001 diff --git a/bunsik-tycoon/art/money_boost.png b/bunsik-tycoon/art/money_boost.png new file mode 100644 index 0000000000000000000000000000000000000000..04f8ac5041830e4a199314eebc5c2f29940547bb GIT binary patch literal 20932 zcmXV1cRbbq_kZ7kYu;-lnU~B|C|kHjMP^Bq8H%#EGVVngDYK9f$%xGCd9M=r$Sm2e z>^(E@c>iwS$L}xKPT_9;k=JWnF2AmJ^4lcgl5H##x33+Js}MOUpEGY_W*#M!?Oi-= z?-cpSQ2zY_>Cv&E!g!m>tKVA+&)x>9QmQR#+5S74(13Z{L*TgZawp{ZC!05KUjUu~ zVe&jF$~eh%2AEHVi#~q-B5sjT@U1+2P;uxyl<=k%=|`jqs+s4e+ZXJxnfWV?r1(hO-qauBS=etN<{E zLJ6&v3sEhmVheN=TRp{ff4I771#N$|3)m0RY(q+$vGmHwP!GTb#P$ z{9J;1_nC2kvpkc~isCPO&K1S@Yx91v4nN?R7|3yRc7{(pR#%$Gv+tq^1frsQ1_>%%_+#-$kGuVks z09e4ybC25`~SfF3m! z{T=}1!{>?mZ0w1Dxd?xMD%~mAB>Uw(t5PjrmTTwO5ZlRc6}3|vTy06C3PhO>1^PRk zNK}+|5|cLlFrV27e@%9`g1DknI}m^*-)-=>p=Nfu!8_f5U=1VwyhcN1WeBGE{ckzQ zP1l;rZuva5&F6p&(h;l|61st!TenOZfM*ZH!}3v(n{*i02_X@C9=-Db5R3jjF~~9J z7>9F#<_7i(aXRvhUj-Inl5`tw*07wq56&7LT#%b^+99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%?&D zMY?TV;bc>7NxzAj4uA;>T>$`qAKa@(AQR1rzefERoaOM3r56LG2PchHj3%3Eu#YBt z%%Z_QF66N3wtufb={Hf`0Wh)sS5J2Z5(xp#fe8QrVv(}5Q(EG$DNX>?)Iy*pM`r*4 z06=<5P58555DbJ81E~IWwlB5WRfCPR*<===&?2s1Qh@P literal 0 HcmV?d00001 diff --git a/bunsik-tycoon/default.project.json b/bunsik-tycoon/default.project.json index aa084bb..2edfa7e 100644 --- a/bunsik-tycoon/default.project.json +++ b/bunsik-tycoon/default.project.json @@ -3,38 +3,55 @@ "tree": { "$className": "DataModel", "ReplicatedStorage": { - "Shared": { "$path": "src/shared" } + "Shared": { + "$path": "src/shared" + }, + "Remotes": { + "$className": "Folder", + "Action": { + "$className": "RemoteEvent" + }, + "Notify": { + "$className": "RemoteEvent" + } + } }, "ServerScriptService": { - "Server": { "$path": "src/server" } + "Server": { + "$path": "src/server" + }, + "Vendor": { + "$className": "Folder", + "ProfileStore": { + "$path": "vendor/ProfileStore.luau" + } + } }, "StarterPlayer": { "StarterPlayerScripts": { - "Client": { "$path": "src/client" } + "Client": { + "$path": "src/client" + } + }, + "$properties": { + "CharacterWalkSpeed": 20, + "CameraMaxZoomDistance": 80 } }, "Workspace": { - "$properties": { "FilteringEnabled": true }, - "Baseplate": { - "$className": "Part", - "$properties": { - "Anchored": true, - "Locked": true, - "Size": [512, 20, 512], - "Position": [0, -10, 0], - "Material": "Grass", - "Color": [0.42, 0.62, 0.32] - } - }, - "SpawnLocation": { - "$className": "SpawnLocation", - "$properties": { - "Anchored": true, - "Size": [12, 1, 12], - "Position": [0, 0.5, 0], - "Duration": 0 - } + "$properties": { + "FilteringEnabled": true + } + }, + "Players": { + "$properties": { + "CharacterAutoLoads": true + } + }, + "Lighting": { + "$properties": { + "ClockTime": 14.5 } } } -} +} \ No newline at end of file diff --git a/bunsik-tycoon/src/client/Guide.luau b/bunsik-tycoon/src/client/Guide.luau new file mode 100644 index 0000000..90c42ad --- /dev/null +++ b/bunsik-tycoon/src/client/Guide.luau @@ -0,0 +1,58 @@ +--!strict +-- 튜토리얼 화살표: 캐릭터에서 목표(조리대, 손님 자리)까지 빛나는 줄과 위에서 통통 튀는 화살표. + +local RunService = game:GetService("RunService") + +local Guide = {} + +function Guide.start(player: Player) + local beam = Instance.new("Beam") + beam.Color = ColorSequence.new(Color3.fromRGB(255, 230, 60)) + beam.Width0 = 0.6 + beam.Width1 = 0.6 + beam.FaceCamera = true + beam.LightEmission = 1 + beam.Transparency = NumberSequence.new(0.2) + beam.Segments = 1 + local a0 = Instance.new("Attachment") + a0.Name = "GuideFrom" + local a1 = Instance.new("Attachment") + a1.Name = "GuideTo" + beam.Attachment0 = a0 + beam.Attachment1 = a1 + + local arrow = Instance.new("BillboardGui") + arrow.Name = "GuideArrow" + arrow.Size = UDim2.fromOffset(70, 70) + arrow.AlwaysOnTop = true + arrow.LightInfluence = 0 + local label = Instance.new("TextLabel") + label.Size = UDim2.fromScale(1, 1) + label.BackgroundTransparency = 1 + label.Text = "⬇️" + label.TextScaled = true + label.Parent = arrow + + RunService.RenderStepped:Connect(function() + local value = player:FindFirstChild("Guide") :: ObjectValue? + local target = value and value.Value :: BasePart? + local char = player.Character + local root = char and char:FindFirstChild("HumanoidRootPart") :: BasePart? + local tut = player:GetAttribute("Tut") + if target and root and (tut == 1 or tut == 2) then + a0.Parent = root + a1.Parent = target + beam.Parent = target + arrow.Adornee = target + arrow.StudsOffset = Vector3.new(0, 3 + math.abs(math.sin(os.clock() * 4)) * 1.5, 0) + arrow.Parent = target + else + beam.Parent = nil + arrow.Parent = nil + a0.Parent = nil + a1.Parent = nil + end + end) +end + +return Guide diff --git a/bunsik-tycoon/src/client/Hud.luau b/bunsik-tycoon/src/client/Hud.luau new file mode 100644 index 0000000..656cb52 --- /dev/null +++ b/bunsik-tycoon/src/client/Hud.luau @@ -0,0 +1,466 @@ +--!strict +-- 화면 UI: 돈, 다음 업그레이드, 업그레이드 목록, 2배 수익·돈 부스트 버튼, 언어 전환, 안내 문구, 알림. +-- 상태는 `state` 인스턴스(실제 게임에서는 Player)의 속성에서 읽습니다. 서버에서도 만들 수 있어서 원격 테스트로 검사합니다. + +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local TweenService = game:GetService("TweenService") + +local Shared = ReplicatedStorage:WaitForChild("Shared") +local Economy = require(Shared:WaitForChild("Economy")) +local Locale = require(Shared:WaitForChild("Locale")) +local Products = require(Shared:WaitForChild("Products")) + +local Hud = {} + +export type HudHandle = { + gui: ScreenGui, + refresh: () -> (), + notify: (key: string, args: { [string]: any }?) -> (), + setScale: (number) -> (), + destroy: () -> (), +} + +local ORANGE = Color3.fromRGB(255, 130, 50) +local GREEN = Color3.fromRGB(70, 190, 90) +local GRAY = Color3.fromRGB(150, 150, 150) +local DARK = Color3.fromRGB(45, 35, 35) +local CREAM = Color3.fromRGB(255, 248, 235) + +local function corner(parent: Instance, r: number) + local c = Instance.new("UICorner") + c.CornerRadius = UDim.new(0, r) + c.Parent = parent +end + +local function stroke(parent: Instance, color: Color3, thickness: number): UIStroke + local s = Instance.new("UIStroke") + s.Color = color + s.Thickness = thickness + s.ApplyStrokeMode = Enum.ApplyStrokeMode.Border + s.Parent = parent + return s +end + +local function frame(parent: Instance, name: string, size: UDim2, pos: UDim2, anchor: Vector2, color: Color3?): Frame + local f = Instance.new("Frame") + f.Name = name + f.Size = size + f.Position = pos + f.AnchorPoint = anchor + f.BackgroundColor3 = color or CREAM + f.BackgroundTransparency = if color then 0 else 1 + f.BorderSizePixel = 0 + f.Parent = parent + return f +end + +local function text(parent: Instance, name: string, size: UDim2, pos: UDim2, color: Color3?): TextLabel + local t = Instance.new("TextLabel") + t.Name = name + t.Size = size + t.Position = pos + t.BackgroundTransparency = 1 + t.TextColor3 = color or DARK + t.Font = Enum.Font.FredokaOne + t.TextScaled = true + t.AutoLocalize = false + t.Text = "" + t.Parent = parent + return t +end + +local function button( + parent: Instance, + name: string, + size: UDim2, + pos: UDim2, + anchor: Vector2, + color: Color3 +): TextButton + local b = Instance.new("TextButton") + b.Name = name + b.Size = size + b.Position = pos + b.AnchorPoint = anchor + b.BackgroundColor3 = color + b.TextColor3 = Color3.new(1, 1, 1) + b.Font = Enum.Font.FredokaOne + b.TextScaled = true + b.AutoLocalize = false + b.AutoButtonColor = true + b.Text = "" + b.Parent = parent + corner(b, 14) + stroke(b, Color3.fromRGB(255, 255, 255), 3) + local pad = Instance.new("UIPadding") + pad.PaddingTop = UDim.new(0.14, 0) + pad.PaddingBottom = UDim.new(0.14, 0) + pad.PaddingLeft = UDim.new(0, 8) + pad.PaddingRight = UDim.new(0, 8) + pad.Parent = b + return b +end + +local function attr(state: Instance, key: string, default: any): any + local v = state:GetAttribute(key) + if v == nil then + return default + end + return v +end + +function Hud.build(parent: Instance, state: Instance, send: (string, any?) -> ()): HudHandle + local gui = Instance.new("ScreenGui") + gui.Name = "BunsikHud" + gui.ResetOnSpawn = false + gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling + gui.Parent = parent + + local root = frame(gui, "Root", UDim2.fromScale(1, 1), UDim2.fromScale(0, 0), Vector2.zero) + local scale = Instance.new("UIScale") + scale.Parent = root + -- UIScale은 자식 크기를 키우므로, 기준 화면(1100x620) 크기의 루트에 붙이고 가운데에 둡니다. + root.Size = UDim2.fromOffset(1100, 620) + root.AnchorPoint = Vector2.new(0.5, 0.5) + root.Position = UDim2.fromScale(0.5, 0.5) + + -- 돈 + local money = frame(root, "Money", UDim2.fromOffset(300, 62), UDim2.new(0.5, 0, 0, 6), Vector2.new(0.5, 0), ORANGE) + corner(money, 31) + stroke(money, Color3.new(1, 1, 1), 4) + local moneyText = text(money, "Text", UDim2.new(1, -24, 1, -14), UDim2.fromOffset(12, 7), Color3.new(1, 1, 1)) + local carry = text(root, "Carry", UDim2.fromOffset(160, 28), UDim2.new(0.5, -80, 0, 72), DARK) + + -- 안내 문구(튜토리얼) + local hint = frame( + root, + "Hint", + UDim2.fromOffset(640, 54), + UDim2.new(0.5, 0, 0, 104), + Vector2.new(0.5, 0), + Color3.fromRGB(255, 235, 120) + ) + corner(hint, 14) + stroke(hint, ORANGE, 3) + local hintText = text(hint, "Text", UDim2.new(1, -20, 1, -10), UDim2.fromOffset(10, 5)) + + -- 알림 + local toasts = frame(root, "Toasts", UDim2.fromOffset(560, 200), UDim2.new(0.5, 0, 0, 166), Vector2.new(0.5, 0)) + local list = Instance.new("UIListLayout") + list.HorizontalAlignment = Enum.HorizontalAlignment.Center + list.Padding = UDim.new(0, 6) + list.Parent = toasts + + -- 다음 업그레이드 카드(아래 가운데) + local card = frame(root, "Next", UDim2.fromOffset(500, 96), UDim2.new(0.5, 0, 1, -8), Vector2.new(0.5, 1), CREAM) + corner(card, 18) + stroke(card, ORANGE, 4) + local cardTitle = text(card, "Title", UDim2.new(1, -170, 0, 40), UDim2.fromOffset(14, 8)) + cardTitle.TextXAlignment = Enum.TextXAlignment.Left + local cardCost = + text(card, "Cost", UDim2.new(1, -170, 0, 26), UDim2.fromOffset(14, 48), Color3.fromRGB(120, 90, 60)) + cardCost.TextXAlignment = Enum.TextXAlignment.Left + local barBg = frame( + card, + "Bar", + UDim2.new(1, -170, 0, 10), + UDim2.fromOffset(14, 78), + Vector2.zero, + Color3.fromRGB(230, 220, 200) + ) + corner(barBg, 5) + local barFill = frame(barBg, "Fill", UDim2.fromScale(0, 1), UDim2.fromScale(0, 0), Vector2.zero, GREEN) + corner(barFill, 5) + local buyBtn = button(card, "Buy", UDim2.fromOffset(140, 72), UDim2.new(1, -12, 0.5, 0), Vector2.new(1, 0.5), GREEN) + local buyStroke = buyBtn:FindFirstChildOfClass("UIStroke") :: UIStroke + + -- 업그레이드 목록 버튼과 창 + local listBtn = + button(root, "ListButton", UDim2.fromOffset(150, 56), UDim2.new(1, -10, 0.5, -40), Vector2.new(1, 0.5), ORANGE) + local panel = + frame(root, "Panel", UDim2.fromOffset(520, 430), UDim2.fromScale(0.5, 0.48), Vector2.new(0.5, 0.5), CREAM) + panel.Visible = false + corner(panel, 20) + stroke(panel, ORANGE, 4) + local panelTitle = text(panel, "Title", UDim2.new(1, -120, 0, 44), UDim2.fromOffset(16, 10)) + panelTitle.TextXAlignment = Enum.TextXAlignment.Left + local closeBtn = button( + panel, + "Close", + UDim2.fromOffset(90, 42), + UDim2.new(1, -12, 0, 10), + Vector2.new(1, 0), + Color3.fromRGB(220, 80, 70) + ) + local scroll = Instance.new("ScrollingFrame") + scroll.Name = "List" + scroll.Size = UDim2.new(1, -24, 1, -70) + scroll.Position = UDim2.fromOffset(12, 62) + scroll.BackgroundTransparency = 1 + scroll.BorderSizePixel = 0 + scroll.ScrollBarThickness = 8 + scroll.AutomaticCanvasSize = Enum.AutomaticSize.Y + scroll.CanvasSize = UDim2.new() + scroll.Parent = panel + local rows = Instance.new("UIListLayout") + rows.Padding = UDim.new(0, 6) + rows.SortOrder = Enum.SortOrder.LayoutOrder + rows.Parent = scroll + + -- 왼쪽: 2배 수익, 돈 부스트 + local passBtn = button( + root, + "Double", + UDim2.fromOffset(170, 64), + UDim2.new(0, 10, 0.5, -40), + Vector2.new(0, 0.5), + Color3.fromRGB(150, 80, 220) + ) + local boostBtn = button( + root, + "Boost", + UDim2.fromOffset(170, 64), + UDim2.new(0, 10, 0.5, 34), + Vector2.new(0, 0.5), + Color3.fromRGB(240, 170, 30) + ) + + -- 개발자(게임 주인)만 보는 테스트 버튼 + local dev = frame( + root, + "Dev", + UDim2.fromOffset(170, 150), + UDim2.new(0, 10, 0.5, 80), + Vector2.new(0, 0), + Color3.fromRGB(40, 40, 50) + ) + dev.BackgroundTransparency = 0.3 + corner(dev, 12) + local devTitle = text(dev, "Title", UDim2.new(1, -10, 0, 22), UDim2.fromOffset(5, 4), Color3.new(1, 1, 1)) + local devButtons: { [string]: TextButton } = {} + for i, key in { "devMoney", "devDouble", "devReset" } do + local b = button( + dev, + key, + UDim2.new(1, -16, 0, 34), + UDim2.fromOffset(8, 30 + (i - 1) * 39), + Vector2.zero, + Color3.fromRGB(90, 90, 110) + ) + devButtons[key] = b + end + + -- 오른쪽 위: 언어 + local langBtn = button( + root, + "Lang", + UDim2.fromOffset(120, 44), + UDim2.new(1, -10, 0, 6), + Vector2.new(1, 0), + Color3.fromRGB(80, 140, 230) + ) + + local function lang(): string + return attr(state, "Lang", "ko") + end + local function L(key: string, args: { [string]: any }?): string + return Locale.t(lang(), key, args) + end + local function pname(p: Economy.Purchase): string + return if lang() == "ko" then p.name else p.nameEn + end + + local pulse: Tween? = nil + local listKey = "" + + local function refresh() + local m = attr(state, "Money", 0) + local bought = attr(state, "Bought", 0) + local stats = Economy.statsAt(bought) + moneyText.Text = "💰 " .. L("money", { money = Locale.number(m) }) + local held = attr(state, "Carry", 0) + carry.Text = if held > 0 then `🍽️ {held}/{stats.carry}` else "" + + local nextP = Economy.PURCHASES[bought + 1] + if nextP then + cardTitle.Text = `{L("next")}: {pname(nextP)}` + cardCost.Text = L("money", { money = Locale.number(nextP.cost) }) + barFill.Size = UDim2.fromScale(math.clamp(m / nextP.cost, 0, 1), 1) + local can = m >= nextP.cost + buyBtn.Text = L("buy") + buyBtn.BackgroundColor3 = if can then GREEN else GRAY + buyBtn.Visible = true + else + cardTitle.Text = L("maxed") + cardCost.Text = "" + barFill.Size = UDim2.fromScale(1, 1) + buyBtn.Visible = false + end + + -- 튜토리얼 안내 + local tut = attr(state, "Tut", 0) + if tut == 1 or tut == 2 or tut == 3 then + hint.Visible = true + hintText.Text = L("tut" .. tut) + else + hint.Visible = false + end + if tut == 3 and not pulse then + buyStroke.Color = Color3.fromRGB(255, 220, 0) + local tw = TweenService:Create( + buyStroke, + TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true), + { Thickness = 9 } + ) + tw:Play() + pulse = tw + elseif tut ~= 3 and pulse then + pulse:Cancel() + pulse = nil + buyStroke.Thickness = 3 + buyStroke.Color = Color3.new(1, 1, 1) + end + + dev.Visible = attr(state, "Dev", false) == true + devTitle.Text = "🛠 " .. L("devTitle") + for key, b in devButtons do + b.Text = L(key) + end + + listBtn.Text = "📋 " .. L("shop") + langBtn.Text = L("language") + closeBtn.Text = L("close") + + local double = attr(state, "Double", false) + passBtn.Visible = Products.DOUBLE_MONEY_PASS ~= 0 + passBtn.Text = if double then "✅ " .. L("doubleOwned") else "💰x2 " .. L("double") + passBtn.Active = not double + passBtn.AutoButtonColor = not double + boostBtn.Visible = Products.MONEY_BOOST_PRODUCT ~= 0 and nextP ~= nil + boostBtn.Text = "⚡ " .. L("boost") .. "\n+" .. Locale.number(attr(state, "Boost", Economy.BOOST_MIN)) + + -- 업그레이드 목록(지금 단계 것만). 산 개수나 언어가 바뀔 때만 다시 그립니다. + local key = `{bought}:{lang()}` + if key == listKey then + return + end + listKey = key + local stage = stats.stage + panelTitle.Text = L(if stage >= 2 then "stage2" else "stage1") + for _, c in scroll:GetChildren() do + if c:IsA("Frame") then + c:Destroy() + end + end + local from = if stage >= 2 then 11 else 1 + local to = if stage >= 2 then #Economy.PURCHASES else 10 + for i = from, to do + local p = Economy.PURCHASES[i] + local row = + frame(scroll, "Row" .. i, UDim2.new(1, -12, 0, 46), UDim2.new(), Vector2.zero, Color3.new(1, 1, 1)) + row.LayoutOrder = i + corner(row, 10) + local done = i <= bought + local isNext = i == bought + 1 + row.BackgroundColor3 = if done + then Color3.fromRGB(215, 245, 215) + elseif isNext then Color3.fromRGB(255, 240, 200) + else Color3.fromRGB(240, 240, 240) + local status = if done then "✅" elseif isNext then "👉" else "🔒" + local name = text(row, "Name", UDim2.new(0.66, -10, 1, -12), UDim2.fromOffset(10, 6)) + name.TextXAlignment = Enum.TextXAlignment.Left + name.Text = `{status} {pname(p)}` + local cost = + text(row, "Cost", UDim2.new(0.34, -10, 1, -12), UDim2.new(0.66, 0, 0, 6), Color3.fromRGB(120, 90, 60)) + cost.TextXAlignment = Enum.TextXAlignment.Right + cost.Text = if done then L("bought") else L("money", { money = Locale.number(p.cost) }) + end + end + + local function notify(key: string, args: { [string]: any }?) + local toast = + frame(toasts, "Toast", UDim2.fromOffset(540, 46), UDim2.new(), Vector2.zero, Color3.fromRGB(45, 45, 60)) + corner(toast, 12) + local t = text(toast, "Text", UDim2.new(1, -20, 1, -10), UDim2.fromOffset(10, 5), Color3.new(1, 1, 1)) + t.Text = L(key, args) + task.delay(2.6, function() + TweenService:Create(toast, TweenInfo.new(0.4), { BackgroundTransparency = 1 }):Play() + TweenService:Create(t, TweenInfo.new(0.4), { TextTransparency = 1 }):Play() + task.wait(0.45) + toast:Destroy() + end) + end + + local conns: { RBXScriptConnection } = {} + table.insert( + conns, + buyBtn.Activated:Connect(function() + send("buy") + end) + ) + table.insert( + conns, + listBtn.Activated:Connect(function() + panel.Visible = not panel.Visible + end) + ) + table.insert( + conns, + closeBtn.Activated:Connect(function() + panel.Visible = false + end) + ) + table.insert( + conns, + langBtn.Activated:Connect(function() + send("lang", if lang() == "ko" then "en" else "ko") + end) + ) + table.insert( + conns, + passBtn.Activated:Connect(function() + if not attr(state, "Double", false) then + send("pass") + end + end) + ) + table.insert( + conns, + boostBtn.Activated:Connect(function() + send("boost") + end) + ) + local devKinds: { [string]: string } = { devMoney = "dev_money", devDouble = "dev_double", devReset = "dev_reset" } + for key, kind in devKinds do + table.insert( + conns, + devButtons[key].Activated:Connect(function() + send(kind) + end) + ) + end + table.insert(conns, state.AttributeChanged:Connect(refresh)) + refresh() + + return { + gui = gui, + refresh = refresh, + notify = notify, + setScale = function(s: number) + scale.Scale = s + end, + destroy = function() + for _, c in conns do + c:Disconnect() + end + gui:Destroy() + end, + } +end + +-- 화면 크기에 맞춘 UI 배율(기준 1100x620) +function Hud.scaleFor(viewport: Vector2): number + return math.clamp(math.min(viewport.X / 1100, viewport.Y / 620), 0.5, 1.4) +end + +return Hud diff --git a/bunsik-tycoon/src/client/Main.client.luau b/bunsik-tycoon/src/client/Main.client.luau index a80c12b..d9266bf 100644 --- a/bunsik-tycoon/src/client/Main.client.luau +++ b/bunsik-tycoon/src/client/Main.client.luau @@ -1,3 +1,42 @@ +-- 클라이언트 진입점: 화면 UI, 내 조리대 버튼, 튜토리얼 화살표. local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") -print(`[Bunsik] client ready for {Players.LocalPlayer.Name}`) +local Guide = require(script.Parent.Guide) +local Hud = require(script.Parent.Hud) +local Stove = require(script.Parent.Stove) + +local player = Players.LocalPlayer +local remotes = ReplicatedStorage:WaitForChild("Remotes") +local action = remotes:WaitForChild("Action") :: RemoteEvent +local notifyRemote = remotes:WaitForChild("Notify") :: RemoteEvent + +local function send(kind: string, arg: any?) + action:FireServer(kind, arg) +end + +-- 서버가 세이브를 불러오고 부지를 줄 때까지 기다립니다. +while not player:GetAttribute("Ready") do + player:GetAttributeChangedSignal("Ready"):Wait() +end + +local hud = Hud.build(player:WaitForChild("PlayerGui"), player, send) +local camera = workspace.CurrentCamera +local function rescale() + hud.setScale(Hud.scaleFor(camera.ViewportSize)) +end +camera:GetPropertyChangedSignal("ViewportSize"):Connect(rescale) +rescale() +notifyRemote.OnClientEvent:Connect(function(key, args) + if typeof(key) == "string" then + hud.notify(key, if typeof(args) == "table" then args else nil) + end +end) + +local plotIndex = player:GetAttribute("Plot") +local world = workspace:WaitForChild("BunsikWorld") +local plot = world:WaitForChild("Plots"):WaitForChild("Plot" .. tostring(plotIndex)) +local stove = plot:WaitForChild("Base"):WaitForChild("Stall"):WaitForChild("Stove") :: BasePart +Stove.attach(stove, player, send) + +Guide.start(player) diff --git a/bunsik-tycoon/src/client/Stove.luau b/bunsik-tycoon/src/client/Stove.luau new file mode 100644 index 0000000..3132ec0 --- /dev/null +++ b/bunsik-tycoon/src/client/Stove.luau @@ -0,0 +1,60 @@ +--!strict +-- 내 가게 조리대에만 "요리하기" 버튼(ProximityPrompt)을 만듭니다. 다른 사람 가게에서는 버튼이 안 보입니다. +-- 서버가 조리대 속성(CookMenu, CookTime)으로 알려 준 상태를 그대로 보여 주고, 다 누르면 서버에 "cook"을 보냅니다. + +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Shared = ReplicatedStorage:WaitForChild("Shared") +local Economy = require(Shared:WaitForChild("Economy")) +local Locale = require(Shared:WaitForChild("Locale")) +local Sounds = require(Shared:WaitForChild("Sounds")) + +local Stove = {} + +function Stove.attach(stove: BasePart, state: Instance, send: (string, any?) -> ()): ProximityPrompt + local prompt = Instance.new("ProximityPrompt") + prompt.Name = "CookPrompt" + prompt.KeyboardKeyCode = Enum.KeyCode.E + prompt.MaxActivationDistance = 10 + prompt.RequiresLineOfSight = false + prompt.Exclusivity = Enum.ProximityPromptExclusivity.OneGlobally + + local sizzle = Instance.new("Sound") + sizzle.SoundId = Sounds.SIZZLE + sizzle.Volume = 0.6 + sizzle.Looped = true + sizzle.Parent = stove + + local function refresh() + local lang = (state:GetAttribute("Lang") :: string?) or "ko" + local menu = stove:GetAttribute("CookMenu") + prompt.HoldDuration = (stove:GetAttribute("CookTime") :: number?) or 2.5 + prompt.ObjectText = Locale.t(lang, "stoveObject") + if typeof(menu) == "string" and Economy.MENUS[menu] then + local m = Economy.MENUS[menu] + local name = if lang == "ko" then m.name else m.nameEn + prompt.ActionText = `{m.icon} ` .. Locale.t(lang, "cookAction", { menu = name }) + prompt.Enabled = true + else + prompt.Enabled = false + end + end + + stove.AttributeChanged:Connect(refresh) + state:GetAttributeChangedSignal("Lang"):Connect(refresh) + prompt.PromptButtonHoldBegan:Connect(function() + sizzle:Play() + end) + prompt.PromptButtonHoldEnded:Connect(function() + sizzle:Stop() + end) + prompt.Triggered:Connect(function() + sizzle:Stop() + send("cook") + end) + refresh() + prompt.Parent = stove + return prompt +end + +return Stove diff --git a/bunsik-tycoon/src/server/Build.luau b/bunsik-tycoon/src/server/Build.luau new file mode 100644 index 0000000..c36c6eb --- /dev/null +++ b/bunsik-tycoon/src/server/Build.luau @@ -0,0 +1,151 @@ +--!strict +-- 파트로 모형을 만드는 작은 도구. Union은 Place Publishing API로 못 올리므로 Part 조합만 씁니다. + +local Build = {} + +export type PartProps = { + size: Vector3, + cf: CFrame, + color: Color3?, + material: Enum.Material?, + shape: Enum.PartType?, + transparency: number?, + collide: boolean?, + name: string?, + wedge: boolean?, + neon: boolean?, + reflectance: number?, +} + +function Build.part(parent: Instance, p: PartProps): BasePart + local part: BasePart + if p.wedge then + part = Instance.new("WedgePart") + else + local np = Instance.new("Part") + if p.shape then + np.Shape = p.shape + end + part = np + end + part.Anchored = true + part.Size = p.size + part.CFrame = p.cf + part.Color = p.color or Color3.fromRGB(200, 200, 200) + part.Material = if p.neon then Enum.Material.Neon else (p.material or Enum.Material.SmoothPlastic) + part.Transparency = p.transparency or 0 + part.CanCollide = if p.collide == nil then true else p.collide + part.Reflectance = p.reflectance or 0 + part.TopSurface = Enum.SurfaceType.Smooth + part.BottomSurface = Enum.SurfaceType.Smooth + part.CastShadow = (p.transparency or 0) < 0.5 + part.Name = p.name or "Part" + part.Parent = parent + return part +end + +-- 원기둥(세로로 세운). Roblox 원기둥은 X축이 높이라서 Z축으로 90도 돌립니다. +function Build.cylinder( + parent: Instance, + cf: CFrame, + height: number, + diameter: number, + color: Color3, + extra: { [string]: any }? +): BasePart + local props: PartProps = { + size = Vector3.new(height, diameter, diameter), + cf = cf * CFrame.Angles(0, 0, math.rad(90)), + color = color, + shape = Enum.PartType.Cylinder, + } + if extra then + for k, v in extra do + (props :: any)[k] = v + end + end + return Build.part(parent, props) +end + +function Build.model(parent: Instance, name: string): Model + local m = Instance.new("Model") + m.Name = name + m.Parent = parent + return m +end + +-- 판(Part) 한 면에 글자를 씁니다. +function Build.label(part: BasePart, face: Enum.NormalId, text: string, color: Color3?, bg: Color3?): TextLabel + local gui = Instance.new("SurfaceGui") + gui.Face = face + gui.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud + gui.PixelsPerStud = 40 + gui.LightInfluence = 0 + gui.Parent = part + local label = Instance.new("TextLabel") + label.Size = UDim2.fromScale(1, 1) + label.BackgroundTransparency = if bg then 0 else 1 + label.BackgroundColor3 = bg or Color3.new(1, 1, 1) + label.TextColor3 = color or Color3.new(1, 1, 1) + label.Font = Enum.Font.FredokaOne + label.TextScaled = true + label.Text = text + label.AutoLocalize = false + label.Parent = gui + local pad = Instance.new("UIPadding") + pad.PaddingTop = UDim.new(0.08, 0) + pad.PaddingBottom = UDim.new(0.08, 0) + pad.PaddingLeft = UDim.new(0.04, 0) + pad.PaddingRight = UDim.new(0.04, 0) + pad.Parent = label + return label +end + +-- 머리 위 말풍선 +function Build.billboard(adornee: Instance, text: string, size: UDim2, offset: Vector3, color: Color3?): BillboardGui + local gui = Instance.new("BillboardGui") + gui.Size = size + gui.StudsOffset = offset + gui.AlwaysOnTop = false + gui.LightInfluence = 0 + gui.MaxDistance = 120 + gui.Adornee = adornee :: any + gui.Parent = adornee + local label = Instance.new("TextLabel") + label.Name = "Text" + label.Size = UDim2.fromScale(1, 1) + label.BackgroundColor3 = Color3.new(1, 1, 1) + label.BackgroundTransparency = if color then 1 else 0.05 + label.TextColor3 = color or Color3.fromRGB(40, 30, 30) + label.Font = Enum.Font.FredokaOne + label.TextScaled = true + label.AutoLocalize = false + label.Text = text + label.Parent = gui + if not color then + local corner = Instance.new("UICorner") + corner.CornerRadius = UDim.new(0.3, 0) + corner.Parent = label + local stroke = Instance.new("UIStroke") + stroke.Thickness = 3 + stroke.Color = Color3.fromRGB(255, 140, 60) + stroke.Parent = label + end + return gui +end + +-- 모델 전체를 하나로 묶습니다(첫 파트 기준). 손에 들기, 트윈 이동용. +function Build.weldAll(model: Model, root: BasePart) + for _, d in model:GetDescendants() do + if d:IsA("BasePart") and d ~= root then + local w = Instance.new("WeldConstraint") + w.Part0 = root + w.Part1 = d + w.Parent = d + d.Anchored = false + end + end + model.PrimaryPart = root +end + +return Build diff --git a/bunsik-tycoon/src/server/Data.luau b/bunsik-tycoon/src/server/Data.luau new file mode 100644 index 0000000..4f468d8 --- /dev/null +++ b/bunsik-tycoon/src/server/Data.luau @@ -0,0 +1,83 @@ +--!strict +-- 세이브 데이터(ProfileStore). 세션 잠금으로 서버 이동 때 덮어쓰기·복사를 막습니다. + +local Players = game:GetService("Players") +local RunService = game:GetService("RunService") +local ServerScriptService = game:GetService("ServerScriptService") + +local ProfileStore = require(ServerScriptService.Vendor.ProfileStore) + +local Data = {} + +Data.TEMPLATE = { + Money = 0, + Bought = 0, + PurchaseIdCache = {} :: { string }, + TutorialDone = false, + Lang = "", + Served = 0, + Earned = 0, + Version = 1, +} + +export type SaveData = typeof(Data.TEMPLATE) + +-- 데이터 구조를 바꾸면 store 이름을 올리지 말고 Version과 Reconcile로 이전합니다. +local STORE_NAME = "PlayerData_v1" + +local store = ProfileStore.New(STORE_NAME, Data.TEMPLATE) +-- Studio 테스트는 실제 저장소를 건드리지 않습니다. +local activeStore = if RunService:IsStudio() then store.Mock else store + +local profiles: { [Player]: any } = {} + +function Data.keyFor(userId: number): string + return "Player_" .. userId +end + +-- 플레이어 데이터를 불러옵니다. 실패하거나 그 사이 나가면 nil. +function Data.load(player: Player): any + local profile = activeStore:StartSessionAsync(Data.keyFor(player.UserId), { + Cancel = function() + return player.Parent ~= Players + end, + }) + if profile == nil then + return nil + end + profile:AddUserId(player.UserId) + profile:Reconcile() + profile.OnSessionEnd:Connect(function() + profiles[player] = nil + if player.Parent == Players then + player:Kick( + "세이브 세션이 다른 서버로 넘어갔어요. 다시 접속해 주세요 / Your save session moved. Please rejoin" + ) + end + end) + if player.Parent ~= Players then + profile:EndSession() + return nil + end + profiles[player] = profile + return profile +end + +function Data.get(player: Player): any + return profiles[player] +end + +function Data.release(player: Player) + local profile = profiles[player] + profiles[player] = nil + if profile then + profile:EndSession() + end +end + +-- 테스트용: 실제 저장소 대신 Mock 저장소를 씁니다. +function Data.useMock() + activeStore = store.Mock +end + +return Data diff --git a/bunsik-tycoon/src/server/Food.luau b/bunsik-tycoon/src/server/Food.luau new file mode 100644 index 0000000..12f4b8d --- /dev/null +++ b/bunsik-tycoon/src/server/Food.luau @@ -0,0 +1,128 @@ +--!strict +-- 메뉴별 접시 모형(파트 조합). 원점은 접시 바닥 가운데입니다. + +local Build = require(script.Parent.Build) + +local Food = {} + +local PLATE = Color3.fromRGB(250, 250, 245) + +local function rc(r: number, g: number, b: number): Color3 + return Color3.fromRGB(r, g, b) +end + +local builders: { [string]: (Model, CFrame) -> () } = { + Tteokbokki = function(m, top) + Build.cylinder(m, top * CFrame.new(0, 0.05, 0), 0.1, 2, rc(200, 40, 25), { collide = false }) + for i = 0, 6 do + local a = i * math.pi * 2 / 7 + local r = if i % 2 == 0 then 0.55 else 0.35 + Build.part(m, { + size = Vector3.new(0.9, 0.28, 0.28), + cf = top * CFrame.new(math.cos(a) * r, 0.22, math.sin(a) * r) * CFrame.Angles(0, a * 1.7, 0), + color = rc(235, 90, 50), + collide = false, + }) + end + Build.part(m, { + size = Vector3.new(0.5, 0.12, 0.25), + cf = top * CFrame.new(0.1, 0.4, -0.1) * CFrame.Angles(0, 0.6, 0), + color = rc(240, 220, 160), + collide = false, + }) + end, + Gimbap = function(m, top) + for i = 0, 5 do + local x = -0.75 + i * 0.3 + local cf = top * CFrame.new(x, 0.32, 0) * CFrame.Angles(0, 0, math.rad(80)) + Build.part(m, { + size = Vector3.new(0.25, 0.62, 0.62), + cf = cf, + color = rc(25, 35, 25), + shape = Enum.PartType.Cylinder, + collide = false, + }) + Build.part(m, { + size = Vector3.new(0.27, 0.5, 0.5), + cf = cf, + color = rc(250, 248, 240), + shape = Enum.PartType.Cylinder, + collide = false, + }) + Build.part(m, { + size = Vector3.new(0.29, 0.2, 0.2), + cf = cf, + color = if i % 2 == 0 then rc(250, 200, 40) else rc(240, 120, 40), + shape = Enum.PartType.Cylinder, + collide = false, + }) + end + end, + Sundae = function(m, top) + for i = 0, 5 do + local a = i * math.pi * 2 / 6 + Build.part(m, { + size = Vector3.new(0.22, 0.55, 0.55), + cf = top * CFrame.new(math.cos(a) * 0.55, 0.3, math.sin(a) * 0.55) * CFrame.Angles(0, -a, math.rad(70)), + color = rc(70, 35, 45), + shape = Enum.PartType.Cylinder, + material = Enum.Material.Pebble, + collide = false, + }) + end + Build.part(m, { + size = Vector3.new(0.4, 0.4, 0.4), + cf = top * CFrame.new(0, 0.25, 0), + color = rc(230, 200, 120), + shape = Enum.PartType.Ball, + collide = false, + }) + end, + Eomuk = function(m, top) + for i = -1, 1 do + local base = top * CFrame.new(i * 0.55, 0.2, 0) + Build.part(m, { + size = Vector3.new(0.08, 1.8, 0.08), + cf = base * CFrame.new(0, 0.7, 0), + color = rc(190, 150, 100), + collide = false, + }) + for j = 0, 2 do + Build.part(m, { + size = Vector3.new(0.45, 0.28, 0.12), + cf = base * CFrame.new(if j % 2 == 0 then 0.06 else -0.06, 0.2 + j * 0.3, 0), + color = rc(225, 185, 120), + collide = false, + }) + end + end + end, + Twigim = function(m, top) + for i = 0, 3 do + local a = i * math.pi / 2 + 0.4 + Build.part(m, { + size = Vector3.new(1.0, 0.32, 0.4), + cf = top + * CFrame.new(math.cos(a) * 0.4, 0.22 + (i % 2) * 0.12, math.sin(a) * 0.4) + * CFrame.Angles(0, a, 0), + color = rc(230, 170, 60), + material = Enum.Material.Sand, + collide = false, + }) + end + end, +} + +-- cf: 접시 바닥 가운데 위치 +function Food.dish(menu: string, cf: CFrame, parent: Instance): Model + local m = Instance.new("Model") + m.Name = "Dish_" .. menu + local plate = Build.cylinder(m, cf * CFrame.new(0, 0.1, 0), 0.2, 2.4, PLATE, { collide = false, name = "Plate" }) + local build = builders[menu] or builders.Tteokbokki + build(m, cf * CFrame.new(0, 0.2, 0)) + m.PrimaryPart = plate + m.Parent = parent + return m +end + +return Food diff --git a/bunsik-tycoon/src/server/Game.luau b/bunsik-tycoon/src/server/Game.luau new file mode 100644 index 0000000..b004763 --- /dev/null +++ b/bunsik-tycoon/src/server/Game.luau @@ -0,0 +1,261 @@ +--!strict +-- 서버 시작: 맵, 플레이어 입장·퇴장, 부지 배정, 리모트, 결제를 연결합니다. + +local MarketplaceService = game:GetService("MarketplaceService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local Shared = ReplicatedStorage.Shared +local Economy = require(Shared.Economy) +local Locale = require(Shared.Locale) +local Products = require(Shared.Products) + +local Data = require(script.Parent.Data) +local Npc = require(script.Parent.Npc) +local PlotBuilder = require(script.Parent.PlotBuilder) +local PlotController = require(script.Parent.PlotController) +local PlotLayout = require(script.Parent.PlotLayout) +local Receipts = require(script.Parent.Receipts) +local World = require(script.Parent.World) + +local Game = {} + +local slots: { World.Slot } = {} +local slotOwner: { [number]: Player } = {} +local controllers: { [Player]: PlotController.PlotController } = {} +local actionTimes: { [Player]: { number } } = {} + +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local ActionRemote = Remotes:WaitForChild("Action") :: RemoteEvent +local NotifyRemote = Remotes:WaitForChild("Notify") :: RemoteEvent + +local function freeSlot(): World.Slot? + for _, s in slots do + if not slotOwner[s.index] then + return s + end + end + return nil +end + +local function placeCharacter(player: Player, slot: World.Slot) + local char = player.Character + if not char then + return + end + local root = char:WaitForChild("HumanoidRootPart", 5) :: BasePart? + if not root then + return + end + local pos = PlotBuilder.world(slot.cf, PlotLayout.PLAYER_SPAWN) + Vector3.new(0, 4, 0) + local look = PlotBuilder.world(slot.cf, PlotLayout.STOVE) + char:PivotTo(CFrame.lookAt(pos, Vector3.new(look.X, pos.Y, look.Z))) +end + +local function checkPass(player: Player, controller: PlotController.PlotController) + if Products.DOUBLE_MONEY_PASS == 0 then + return + end + local ok, owns = pcall(function() + return MarketplaceService:UserOwnsGamePassAsync(player.UserId, Products.DOUBLE_MONEY_PASS) + end) + if ok and owns then + controller:setDouble(true) + end +end + +-- 게임 주인(개발자)만 쓰는 테스트 버튼. 결제 없이 기능을 확인할 수 있게 합니다. +local function isDev(player: Player): boolean + return game.CreatorType == Enum.CreatorType.User and player.UserId == game.CreatorId +end + +local function makeController(player: Player, slot: World.Slot, data: any, lang: string): PlotController.PlotController + return PlotController.new(slot, player, { + userId = player.UserId, + displayName = player.DisplayName, + data = data, + now = os.clock(), + lang = lang, + notify = function(key, args) + NotifyRemote:FireClient(player, key, args) + end, + }) +end + +local function onPlayerAdded(player: Player) + local profile = Data.load(player) + if not profile then + if player.Parent == Players then + player:Kick(Locale.t("ko", "saveFail") .. " / " .. Locale.t("en", "saveFail")) + end + return + end + local slot = freeSlot() + if not slot then + Data.release(player) + player:Kick("서버가 꽉 찼어요 / Server is full") + return + end + slotOwner[slot.index] = player + local data = profile.Data + local lang = if data.Lang ~= "" then data.Lang else Locale.pick(player.LocaleId) + player:SetAttribute("Lang", lang) + local controller = makeController(player, slot, data, lang) + controllers[player] = controller + player:SetAttribute("Dev", isDev(player)) + player:SetAttribute("Ready", true) + + player.CharacterAdded:Connect(function() + task.defer(function() + placeCharacter(player, slot) + local current = controllers[player] + if current then + current:rebuildHand() + end + end) + end) + if player.Character then + task.defer(placeCharacter, player, slot) + end + task.spawn(checkPass, player, controller) +end + +local function onPlayerRemoving(player: Player) + local controller = controllers[player] + controllers[player] = nil + actionTimes[player] = nil + if controller then + slotOwner[controller.slot.index] = nil + controller:destroy() + end + Data.release(player) +end + +-- 초당 10회 넘는 요청은 무시합니다. +local function allowAction(player: Player): boolean + local now = os.clock() + local list = actionTimes[player] or {} + actionTimes[player] = list + while list[1] and now - list[1] > 1 do + table.remove(list, 1) + end + if #list >= 10 then + return false + end + table.insert(list, now) + return true +end + +local function onAction(player: Player, kind: any, arg: any) + if typeof(kind) ~= "string" or not allowAction(player) then + return + end + local controller = controllers[player] + if not controller then + return + end + if kind == "cook" then + -- 버튼을 누르고 있는 시간만큼은 지나야 다음 접시를 만들 수 있습니다. + local now = os.clock() + if now - controller.lastCook >= controller.shop.stats.cook * 0.8 then + controller.shop.now = now + controller:cook() + end + elseif kind == "buy" then + local ok, err = controller:buy() + if not ok and err == "money" then + local p = Economy.PURCHASES[controller.shop.bought + 1] + if p then + controller:notify("notEnough", { need = Locale.number(p.cost - controller.shop.money) }) + end + end + elseif kind == "lang" then + if typeof(arg) == "string" and table.find(Locale.LANGS, arg) then + controller.data.Lang = arg + player:SetAttribute("Lang", arg) + controller:setLang(arg) + end + elseif kind == "pass" then + if Products.DOUBLE_MONEY_PASS ~= 0 and controller.shop.moneyMult == 1 then + MarketplaceService:PromptGamePassPurchase(player, Products.DOUBLE_MONEY_PASS) + end + elseif kind == "dev_money" and isDev(player) then + controller:addMoney(1000) + elseif kind == "dev_double" and isDev(player) then + controller:setDouble(controller.shop.moneyMult == 1) + elseif kind == "dev_reset" and isDev(player) then + local data = controller.data + data.Money = 0 + data.Bought = 0 + data.TutorialDone = false + data.Served = 0 + data.Earned = 0 + local slot = controller.slot + controller:destroy() + local fresh = makeController(player, slot, data, controller.lang) + controllers[player] = fresh + placeCharacter(player, slot) + fresh:notify("devResetDone") + elseif kind == "boost" then + if Products.MONEY_BOOST_PRODUCT ~= 0 and Economy.PURCHASES[controller.shop.bought + 1] then + MarketplaceService:PromptProductPurchase(player, Products.MONEY_BOOST_PRODUCT) + end + end +end + +-- 개발자 상품 지급(결제 1회 = 지급 1회) +function Game.processReceipt(info: { [string]: any }): Enum.ProductPurchaseDecision + local player = Players:GetPlayerByUserId(info.PlayerId) + local profile = player and Data.get(player) + local controller = player and controllers[player] + local decision = Receipts.process(profile, tostring(info.PurchaseId), function() + if info.ProductId ~= Products.MONEY_BOOST_PRODUCT or not controller then + return false + end + local amount = Economy.boostAmount(controller.shop.stats) + controller:addMoney(amount) + controller:notify("boostGot", { amount = Locale.number(amount) }) + return true + end) + if decision == "Granted" then + return Enum.ProductPurchaseDecision.PurchaseGranted + end + return Enum.ProductPurchaseDecision.NotProcessedYet +end + +function Game.start() + slots = World.build() + task.spawn(Npc.preload) + + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(onPlayerRemoving) + for _, p in Players:GetPlayers() do + task.spawn(onPlayerAdded, p) + end + ActionRemote.OnServerEvent:Connect(onAction) + + MarketplaceService.ProcessReceipt = Game.processReceipt + MarketplaceService.PromptGamePassPurchaseFinished:Connect(function(player, passId, purchased) + local controller = controllers[player] + if purchased and passId == Products.DOUBLE_MONEY_PASS and controller then + controller:setDouble(true) + end + end) + + local acc = 0 + RunService.Heartbeat:Connect(function(dt) + acc += dt + if acc < 0.1 then + return + end + acc = 0 + local now = os.clock() + for _, c in controllers do + c:update(now) + end + end) + print(`[Bunsik] server ready, {#Economy.PURCHASES} purchases, {#slots} plots`) +end + +return Game diff --git a/bunsik-tycoon/src/server/Main.server.luau b/bunsik-tycoon/src/server/Main.server.luau index d144ba3..8b8aef0 100644 --- a/bunsik-tycoon/src/server/Main.server.luau +++ b/bunsik-tycoon/src/server/Main.server.luau @@ -1,5 +1,2 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") - -local Economy = require(ReplicatedStorage.Shared.Economy) - -print(`[Bunsik] server ready, {#Economy.PURCHASES} purchases loaded`) +-- 서버 진입점. 실제 로직은 Game 모듈에 있습니다(원격 테스트에서 모듈을 직접 불러 씁니다). +require(script.Parent.Game).start() diff --git a/bunsik-tycoon/src/server/Npc.luau b/bunsik-tycoon/src/server/Npc.luau new file mode 100644 index 0000000..8924630 --- /dev/null +++ b/bunsik-tycoon/src/server/Npc.luau @@ -0,0 +1,253 @@ +--!strict +-- 손님·알바생 NPC. 로블록스 기본 아바타(R15)를 서버 시작 때 몇 개 만들어 두고 복제해서 씁니다. +-- 물리로 걷게 하면 테이블에 걸리거나 늦게 도착하므로, 몸을 고정(Anchored)하고 트윈으로 옮깁니다. + +local Players = game:GetService("Players") +local TweenService = game:GetService("TweenService") + +local Npc = {} + +local ANIM: { [string]: string } = { + walk = "rbxassetid://507777826", + idle = "rbxassetid://507766388", + sit = "rbxassetid://2506281703", +} + +local SKIN = { + Color3.fromRGB(255, 220, 190), + Color3.fromRGB(240, 200, 160), + Color3.fromRGB(205, 160, 120), + Color3.fromRGB(150, 105, 75), +} +local SHIRT = { + Color3.fromRGB(230, 70, 70), + Color3.fromRGB(70, 130, 230), + Color3.fromRGB(250, 200, 60), + Color3.fromRGB(90, 190, 110), + Color3.fromRGB(180, 100, 220), + Color3.fromRGB(255, 150, 190), + Color3.fromRGB(250, 250, 250), +} +local PANTS = { + Color3.fromRGB(40, 50, 90), + Color3.fromRGB(60, 60, 60), + Color3.fromRGB(120, 90, 60), + Color3.fromRGB(30, 90, 140), +} + +local template: Model? = nil +local loading = false + +local function makeBlockNpc(): Model + -- 아바타를 못 불러올 때 쓰는 간단한 블록 사람 + local m = Instance.new("Model") + m.Name = "Npc" + local root = Instance.new("Part") + root.Name = "HumanoidRootPart" + root.Size = Vector3.new(2, 2, 1) + root.Transparency = 1 + root.Parent = m + local function piece(name: string, size: Vector3, offset: Vector3) + local p = Instance.new("Part") + p.Name = name + p.Size = size + p.CFrame = CFrame.new(offset) + p.Parent = m + end + piece("UpperTorso", Vector3.new(2, 2, 1), Vector3.zero) + piece("Head", Vector3.new(1.2, 1.2, 1.2), Vector3.new(0, 1.6, 0)) + piece("LeftUpperLeg", Vector3.new(0.9, 2, 1), Vector3.new(-0.5, -2, 0)) + piece("RightUpperLeg", Vector3.new(0.9, 2, 1), Vector3.new(0.5, -2, 0)) + m.PrimaryPart = root + local h = Instance.new("Humanoid") + h.Parent = m + for _, p in m:GetChildren() do + if p:IsA("BasePart") and p ~= root then + local w = Instance.new("WeldConstraint") + w.Part0 = root + w.Part1 = p + w.Parent = p + end + end + return m +end + +-- 서버 시작 때 한 번 호출. 실패하면 블록 사람으로 대신합니다. +function Npc.preload() + if template then + return + end + if loading then + -- 다른 곳에서 이미 만드는 중이면 끝날 때까지 기다립니다. + while loading do + task.wait() + end + return + end + loading = true + local ok, model = pcall(function() + local desc = Instance.new("HumanoidDescription") + return Players:CreateHumanoidModelFromDescription(desc, Enum.HumanoidRigType.R15) + end) + if ok and model then + template = model + else + warn("[Bunsik] NPC 아바타 생성 실패, 블록 NPC 사용:", model) + template = makeBlockNpc() + end + loading = false +end + +local function pick(list: { T }, rng: Random): T + return list[rng:NextInteger(1, #list)] +end + +local function colorize(m: Model, rng: Random, shirtOverride: Color3?) + local skin = pick(SKIN, rng) + local shirt = shirtOverride or pick(SHIRT, rng) + local pants = pick(PANTS, rng) + for _, p in m:GetDescendants() do + if p:IsA("BasePart") then + local n = p.Name + if n == "Head" or string.find(n, "Hand") then + p.Color = skin + elseif string.find(n, "Torso") or string.find(n, "UpperArm") or string.find(n, "LowerArm") then + p.Color = shirt + elseif string.find(n, "Leg") or string.find(n, "Foot") then + p.Color = pants + end + end + end + local bc = m:FindFirstChildOfClass("BodyColors") + if bc then + bc:Destroy() + end +end + +export type Handle = { + model: Model, + root: BasePart, + humanoid: Humanoid, + tracks: { [string]: AnimationTrack }, + tween: Tween?, +} + +function Npc.spawn(parent: Instance, cf: CFrame, rng: Random, shirt: Color3?): Handle + if not template then + Npc.preload() + end + local m = (template :: Model):Clone() + m.Name = "Customer" + colorize(m, rng, shirt) + local root = m:FindFirstChild("HumanoidRootPart") :: BasePart + for _, p in m:GetDescendants() do + if p:IsA("BasePart") then + p.CanCollide = false + p.CanQuery = false + p.CanTouch = false + p.Massless = true + end + end + root.Anchored = true + local humanoid = m:FindFirstChildOfClass("Humanoid") :: Humanoid + humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None + humanoid.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff + humanoid.BreakJointsOnDeath = false + humanoid:SetStateEnabled(Enum.HumanoidStateType.Dead, false) + m:PivotTo(cf) + m.Parent = parent + local h: Handle = { model = m, root = root, humanoid = humanoid, tracks = {}, tween = nil } + local animator: Animator = humanoid:FindFirstChildOfClass("Animator") or Instance.new("Animator") + animator.Parent = humanoid + for name: string, id: string in ANIM do + local a = Instance.new("Animation") + a.AnimationId = id + local ok, track = pcall(function() + return animator:LoadAnimation(a) + end) + if ok and track then + track.Looped = true + h.tracks[name] = track + end + end + Npc.play(h, "idle") + return h +end + +function Npc.play(h: Handle, name: string) + for n, t in h.tracks do + if n ~= name and t.IsPlaying then + t:Stop(0.15) + end + end + local t = h.tracks[name] + if t and not t.IsPlaying then + t:Play(0.15) + end +end + +-- 높이(엉덩이 높이)를 맞춘 서 있는 자세 위치 +function Npc.standCFrame(h: Handle, floorPos: Vector3, lookAt: Vector3): CFrame + local hip = h.humanoid.HipHeight + h.root.Size.Y / 2 + local pos = floorPos + Vector3.new(0, hip, 0) + local look = Vector3.new(lookAt.X, pos.Y, lookAt.Z) + if (look - pos).Magnitude < 0.01 then + look = pos + Vector3.new(0, 0, -1) + end + return CFrame.lookAt(pos, look) +end + +-- 바닥 지점들을 차례로 걸어갑니다. 전체 걸리는 시간(초)을 맞춰 줍니다. +function Npc.walk(h: Handle, points: { Vector3 }, duration: number, onDone: (() -> ())?) + if h.tween then + h.tween:Cancel() + end + local total = 0 + for i = 2, #points do + total += (points[i] - points[i - 1]).Magnitude + end + Npc.play(h, "walk") + local alive = true + h.model.Destroying:Connect(function() + alive = false + end) + task.spawn(function() + for i = 2, #points do + if not alive then + return + end + local seg = (points[i] - points[i - 1]).Magnitude + local t = if total > 0 then duration * seg / total else 0 + local target = Npc.standCFrame(h, points[i], points[i] + (points[i] - points[i - 1])) + if t > 0.01 then + local tw = TweenService:Create(h.root, TweenInfo.new(t, Enum.EasingStyle.Linear), { CFrame = target }) + h.tween = tw + tw:Play() + tw.Completed:Wait() + else + h.root.CFrame = target + end + end + h.tween = nil + if alive then + Npc.play(h, "idle") + if onDone then + onDone() + end + end + end) +end + +function Npc.sit(h: Handle, seat: CFrame) + if h.tween then + h.tween:Cancel() + h.tween = nil + end + -- 앉은 자세에서 엉덩이가 의자 위에 오도록 살짝 낮춥니다. + h.root.CFrame = seat * CFrame.new(0, h.root.Size.Y / 2 + 0.6, 0) + if h.tracks.sit then + Npc.play(h, "sit") + end +end + +return Npc diff --git a/bunsik-tycoon/src/server/PlotBuilder.luau b/bunsik-tycoon/src/server/PlotBuilder.luau new file mode 100644 index 0000000..9aac9b4 --- /dev/null +++ b/bunsik-tycoon/src/server/PlotBuilder.luau @@ -0,0 +1,521 @@ +--!strict +-- 부지 모형: 기본(바닥·포장마차·조리대)과 업그레이드(테이블·간판·화구·실내 확장 등)를 파트로 짓습니다. + +local Build = require(script.Parent.Build) +local PlotLayout = require(script.Parent.PlotLayout) +local Economy = require(game:GetService("ReplicatedStorage").Shared.Economy) + +local PlotBuilder = {} + +export type BaseRefs = { + stove: BasePart, + counter: BasePart, + nameLabel: TextLabel, + menuLabel: TextLabel, + upgrades: Model, + dynamic: Folder, +} + +local function rgb(r: number, g: number, b: number): Color3 + return Color3.fromRGB(r, g, b) +end + +local Y = PlotLayout.FLOOR_Y + +-- 바닥과 포장마차. 부지마다 한 번만 짓습니다. +function PlotBuilder.buildBase(plot: Model, cf: CFrame): BaseRefs + local base = Build.model(plot, "Base") + local function at(x: number, y: number, z: number): CFrame + return cf * CFrame.new(x, y, z) + end + + -- 바닥, 길가 연석, 옆·뒤 울타리(나무 화단) + Build.part(base, { + name = "Floor", + size = Vector3.new(72, 0.4, 80), + cf = at(0, Y - 0.2, 0), + color = rgb(214, 205, 190), + material = Enum.Material.Concrete, + }) + for _, side in { -1, 1 } do + Build.part(base, { + size = Vector3.new(2, 2.4, 80), + cf = at(side * 35, Y + 1.2, 0), + color = rgb(90, 160, 80), + material = Enum.Material.LeafyGrass, + }) + end + Build.part(base, { + size = Vector3.new(72, 2.4, 2), + cf = at(0, Y + 1.2, -39), + color = rgb(90, 160, 80), + material = Enum.Material.LeafyGrass, + }) + -- 입구 기둥과 이름판 + for _, side in { -1, 1 } do + Build.part(base, { + size = Vector3.new(1.2, 11, 1.2), + cf = at(side * 8, Y + 5.5, 37), + color = rgb(120, 80, 50), + material = Enum.Material.Wood, + }) + end + local board = Build.part(base, { + name = "NameBoard", + size = Vector3.new(17, 3, 0.6), + cf = at(0, Y + 10, 37), + color = rgb(255, 245, 225), + material = Enum.Material.Wood, + }) + local nameLabel = Build.label(board, Enum.NormalId.Front, "", rgb(160, 50, 30)) + -- 앞뒤 둘 다 보이게: 앞면(+Z)은 길에서, 뒷면은 가게 안에서 + local backLabel = Build.label(board, Enum.NormalId.Back, "", rgb(160, 50, 30)) + nameLabel:GetPropertyChangedSignal("Text"):Connect(function() + backLabel.Text = nameLabel.Text + end) + + -- 포장마차: 수레 몸통, 조리대 상판 + local stall = Build.model(base, "Stall") + local sz = PlotLayout.STALL_Z + Build.part(stall, { + size = Vector3.new(18, 3.4, 4), + cf = at(0, Y + 1.7, sz), + color = rgb(160, 105, 60), + material = Enum.Material.Wood, + }) + Build.part(stall, { + size = Vector3.new(18.6, 0.4, 4.6), + cf = at(0, Y + 3.6, sz), + color = rgb(200, 205, 210), + material = Enum.Material.Metal, + }) + for _, x in { -7.5, 7.5 } do + Build.cylinder(stall, at(x, Y + 0.6, sz + 2), 0.5, 1.4, rgb(40, 40, 40), { collide = false }) + end + + -- 화구(프롬프트가 붙는 곳) + local stove = Build.part(stall, { + name = "Stove", + size = Vector3.new(5, 0.6, 3.4), + cf = at(PlotLayout.STOVE.X, Y + 4.1, sz), + color = rgb(60, 60, 65), + material = Enum.Material.DiamondPlate, + }) + Build.cylinder(stall, at(PlotLayout.STOVE.X, Y + 4.6, sz), 0.4, 4, rgb(30, 30, 30), { collide = false }) + Build.cylinder(stall, at(PlotLayout.STOVE.X, Y + 4.8, sz), 0.1, 3.5, rgb(205, 45, 25), { collide = false }) + for i = 0, 8 do + local a = i * 0.7 + Build.part(stall, { + size = Vector3.new(1.1, 0.35, 0.35), + cf = at( + PlotLayout.STOVE.X + math.cos(a) * (0.4 + (i % 3) * 0.45), + Y + 5, + sz + math.sin(a) * (0.4 + (i % 3) * 0.45) + ) * CFrame.Angles(0, a * 2, 0), + color = rgb(235, 90, 50), + collide = false, + }) + end + local steam = Instance.new("Smoke") + steam.Color = Color3.new(1, 1, 1) + steam.Opacity = 0.08 + steam.RiseVelocity = 3 + steam.Size = 1.5 + steam.Parent = stove + + -- 알바생이 만든 접시를 두는 카운터 + local counter = Build.part(stall, { + name = "Counter", + size = Vector3.new(6, 0.3, 3.4), + cf = at(PlotLayout.COUNTER.X, Y + 3.95, sz), + color = rgb(235, 215, 175), + material = Enum.Material.Wood, + }) + + -- 천막: 기둥 4개, 주황 지붕(박공), 앞 가림막 + for _, x in { -10, 10 } do + for _, z in { sz - 5, sz + 6 } do + Build.part(stall, { + size = Vector3.new(0.5, 11, 0.5), + cf = at(x, Y + 5.5, z), + color = rgb(170, 170, 175), + material = Enum.Material.Metal, + }) + end + end + local roofCf = at(0, Y + 11.2, sz + 0.5) + Build.part(stall, { + size = Vector3.new(22, 0.3, 12.6), + cf = roofCf, + color = rgb(240, 110, 40), + material = Enum.Material.Fabric, + }) + Build.part(stall, { + size = Vector3.new(22, 2.6, 6.3), + cf = roofCf * CFrame.new(0, 1.45, 3.15), + color = rgb(240, 110, 40), + material = Enum.Material.Fabric, + wedge = true, + }) + Build.part(stall, { + size = Vector3.new(22, 2.6, 6.3), + cf = roofCf * CFrame.new(0, 1.45, -3.15) * CFrame.Angles(0, math.pi, 0), + color = rgb(240, 110, 40), + material = Enum.Material.Fabric, + wedge = true, + }) + local valance = Build.part(stall, { + size = Vector3.new(22, 1.8, 0.2), + cf = at(0, Y + 10.2, sz + 6.3), + color = rgb(255, 230, 90), + material = Enum.Material.Fabric, + }) + Build.label(valance, Enum.NormalId.Front, "떡볶이 · 김밥 · 순대 BUNSIK", rgb(200, 40, 30)) + -- 뒤쪽 투명 비닐 가림막 + Build.part(stall, { + size = Vector3.new(20, 9, 0.1), + cf = at(0, Y + 5.8, sz - 5.2), + color = rgb(255, 200, 150), + transparency = 0.6, + material = Enum.Material.Glass, + }) + -- 메뉴판 + local menuBoard = Build.part(stall, { + name = "MenuBoard", + size = Vector3.new(9, 4.2, 0.3), + cf = at(0, Y + 7.6, sz - 4.8), + color = rgb(40, 60, 45), + material = Enum.Material.Wood, + }) + local menuLabel = Build.label(menuBoard, Enum.NormalId.Front, "", rgb(255, 250, 230)) + menuLabel.TextXAlignment = Enum.TextXAlignment.Left + menuLabel.Font = Enum.Font.GothamBold + -- 앞 처마에 매단 전구 + for i = -4, 4 do + local bulb = Build.part(stall, { + size = Vector3.new(0.6, 0.6, 0.6), + cf = at(i * 2.4, Y + 9.1, sz + 6.4), + color = rgb(255, 210, 120), + shape = Enum.PartType.Ball, + neon = true, + collide = false, + }) + if i % 2 == 0 then + local light = Instance.new("PointLight") + light.Color = rgb(255, 200, 130) + light.Range = 10 + light.Brightness = 0.6 + light.Parent = bulb + end + end + + local upgrades = Build.model(plot, "Upgrades") + local dynamic = Instance.new("Folder") + dynamic.Name = "Dynamic" + dynamic.Parent = plot + + return { + stove = stove, + counter = counter, + nameLabel = nameLabel, + menuLabel = menuLabel, + upgrades = upgrades, + dynamic = dynamic, + } +end + +-- 테이블 한 개와 의자 +local function buildTable(parent: Instance, cf: CFrame, seat: number) + local m = Build.model(parent, "Table" .. seat) + local t = PlotLayout.TABLES[seat] + local s = PlotLayout.stool(seat) + local tableTop = cf * CFrame.new(t.X, Y + 2.6, t.Z) + Build.cylinder(m, cf * CFrame.new(t.X, Y + 1.25, t.Z), 2.5, 0.6, rgb(160, 160, 165)) + Build.cylinder(m, cf * CFrame.new(t.X, Y + 0.1, t.Z), 0.2, 2.6, rgb(160, 160, 165)) + Build.cylinder(m, tableTop, 0.3, 5, if seat % 2 == 0 then rgb(225, 60, 50) else rgb(240, 120, 40)) + local stoolColor = if seat % 2 == 0 then rgb(60, 120, 225) else rgb(225, 60, 50) + Build.cylinder(m, cf * CFrame.new(s.X, Y + 0.9, s.Z), 1.8, 2, stoolColor) +end + +-- 실내 분식집 건물(2단계) +local function buildIndoor(parent: Instance, cf: CFrame) + local m = Build.model(parent, "Expand") + local function at(x: number, y: number, z: number): CFrame + return cf * CFrame.new(x, y, z) + end + local wall = rgb(250, 236, 205) + local trim = rgb(190, 75, 55) + local H = 14 + Build.part(m, { + size = Vector3.new(68, 0.1, 58), + cf = at(0, Y + 0.05, -9), + color = rgb(235, 225, 205), + material = Enum.Material.Marble, + collide = false, + }) + -- 뒤, 옆 벽 + Build.part(m, { size = Vector3.new(70, H, 1), cf = at(0, Y + H / 2, -38.5), color = wall }) + for _, side in { -1, 1 } do + Build.part(m, { size = Vector3.new(1, H, 58), cf = at(side * 34.5, Y + H / 2, -9), color = wall }) + -- 옆 창문 + Build.part(m, { + size = Vector3.new(1.1, 5, 30), + cf = at(side * 34.5, Y + 7, -6), + color = rgb(170, 220, 255), + material = Enum.Material.Glass, + transparency = 0.5, + }) + Build.part(m, { size = Vector3.new(1.2, 2.2, 58), cf = at(side * 34.5, Y + 1.1, -9), color = trim }) + end + -- 앞 벽(가운데 문, 양쪽 큰 창) + for _, side in { -1, 1 } do + Build.part(m, { + size = Vector3.new(29, H, 1), + cf = at(side * 20.5, Y + H / 2, 20.5), + color = wall, + }) + Build.part(m, { + size = Vector3.new(20, 6, 1.1), + cf = at(side * 20.5, Y + 6.5, 20.5), + color = rgb(170, 220, 255), + material = Enum.Material.Glass, + transparency = 0.45, + }) + Build.part(m, { size = Vector3.new(29, 2.2, 1.2), cf = at(side * 20.5, Y + 1.1, 20.5), color = trim }) + end + Build.part(m, { size = Vector3.new(12, 4, 1), cf = at(0, Y + H - 2, 20.5), color = wall }) + -- 문 위 차양 + Build.part(m, { + size = Vector3.new(14, 0.4, 4), + cf = at(0, Y + 10.5, 22.5) * CFrame.Angles(math.rad(-12), 0, 0), + color = rgb(240, 110, 40), + material = Enum.Material.Fabric, + }) + -- 천장 들보와 조명 + for i = 0, 4 do + local z = -34 + i * 13 + Build.part(m, { + size = Vector3.new(68, 0.8, 0.8), + cf = at(0, Y + H - 0.4, z), + color = rgb(140, 95, 60), + material = Enum.Material.Wood, + }) + for _, x in { -18, 0, 18 } do + local lamp = Build.part(m, { + size = Vector3.new(1.4, 1.4, 1.4), + cf = at(x, Y + H - 1.6, z), + color = rgb(255, 225, 150), + shape = Enum.PartType.Ball, + neon = true, + collide = false, + }) + local light = Instance.new("PointLight") + light.Color = rgb(255, 220, 160) + light.Range = 16 + light.Brightness = 0.8 + light.Parent = lamp + end + end + -- 지붕 간판 + local sign = Build.part(m, { + name = "RoofSign", + size = Vector3.new(30, 5, 1), + cf = at(0, Y + H + 2.5, 20.5), + color = rgb(200, 40, 30), + }) + Build.label(sign, Enum.NormalId.Front, "분식천국 BUNSIK HEAVEN", rgb(255, 240, 200)) + -- 화분 + for _, x in { -30, 30 } do + Build.cylinder(m, at(x, Y + 1, 16), 2, 2.4, rgb(180, 110, 70)) + Build.part(m, { + size = Vector3.new(3.2, 3.2, 3.2), + cf = at(x, Y + 3.4, 16), + color = rgb(70, 150, 70), + shape = Enum.PartType.Ball, + material = Enum.Material.LeafyGrass, + }) + end +end + +-- 산 업그레이드에 맞게 Upgrades 모형을 다시 짓습니다. +function PlotBuilder.buildUpgrades(refs: BaseRefs, cf: CFrame, bought: number) + local up = refs.upgrades + up:ClearAllChildren() + local stats = Economy.statsAt(bought) + local function has(id: string): boolean + for i = 1, bought do + if Economy.PURCHASES[i].id == id then + return true + end + end + return false + end + local function at(x: number, y: number, z: number): CFrame + return cf * CFrame.new(x, y, z) + end + local sz = PlotLayout.STALL_Z + + for seat = 1, stats.seats do + buildTable(up, cf, seat) + end + + if stats.stage >= 2 then + buildIndoor(up, cf) + end + + if has("Sign1") then + local m = Build.model(up, "Sign1") + local sign = Build.part(m, { + size = Vector3.new(12, 3.2, 0.6), + cf = at(0, Y + 15.6, sz + 3), + color = rgb(255, 80, 120), + neon = true, + }) + Build.label(sign, Enum.NormalId.Front, "분식 BUNSIK", rgb(255, 255, 255)) + local light = Instance.new("PointLight") + light.Color = rgb(255, 120, 160) + light.Range = 18 + light.Parent = sign + for _, x in { -4, 4 } do + Build.part(m, { + size = Vector3.new(0.3, 2.4, 0.3), + cf = at(x, Y + 13.4, sz + 3), + color = rgb(120, 120, 120), + }) + end + end + if has("Sign2") then + local m = Build.model(up, "Sign2") + for _, x in { -22, 22 } do + local post = Build.part(m, { + size = Vector3.new(1, 18, 1), + cf = at(x, Y + 9, 30), + color = rgb(80, 80, 85), + material = Enum.Material.Metal, + }) + local balloon = Build.part(m, { + size = Vector3.new(4, 4, 4), + cf = at(x, Y + 20, 30), + color = if x < 0 then rgb(255, 90, 90) else rgb(255, 200, 60), + shape = Enum.PartType.Ball, + neon = true, + collide = false, + }) + local sparkle = Instance.new("Sparkles") + sparkle.SparkleColor = rgb(255, 230, 150) + sparkle.Parent = balloon + local _ = post + end + local banner = Build.part(m, { + size = Vector3.new(40, 3, 0.4), + cf = at(0, Y + 16, 30), + color = rgb(255, 240, 120), + neon = true, + }) + Build.label(banner, Enum.NormalId.Front, "★ 오늘도 맛있는 분식 ★ OPEN", rgb(200, 40, 30)) + end + if has("Stove1") then + local m = Build.model(up, "Stove1") + local burner = Build.part(m, { + size = Vector3.new(1, 0.2, 1), + cf = at(PlotLayout.STOVE.X, Y + 4.4, sz + 1.4), + color = rgb(30, 30, 30), + collide = false, + }) + local fire = Instance.new("Fire") + fire.Size = if has("Stove2") then 4 else 2.5 + fire.Heat = 1 + fire.Color = if has("Stove2") then rgb(80, 160, 255) else rgb(255, 140, 40) + fire.SecondaryColor = if has("Stove2") then rgb(200, 230, 255) else rgb(255, 220, 80) + fire.Parent = burner + end + if has("Stove2") then + local m = Build.model(up, "Stove2") + Build.cylinder( + m, + at(PlotLayout.STOVE.X - 4.5, Y + 4.9, sz), + 1.2, + 2.6, + rgb(190, 190, 195), + { material = Enum.Material.Metal } + ) + local fire = Instance.new("Fire") + fire.Size = 3 + fire.Color = rgb(80, 160, 255) + fire.SecondaryColor = rgb(200, 230, 255) + fire.Parent = Build.part(m, { + size = Vector3.new(1, 0.2, 1), + cf = at(PlotLayout.STOVE.X - 4.5, Y + 4.2, sz), + transparency = 1, + collide = false, + }) + end + for _, id in { "Sauce1", "Sauce2" } do + if has(id) then + local m = Build.model(up, id) + local x = if id == "Sauce1" then -8.4 else -6.6 + local pot = Build.cylinder( + m, + at(x, Y + 4.9, sz - 1), + 2, + 1.8, + if id == "Sauce1" then rgb(180, 40, 30) else rgb(230, 180, 40), + { + material = Enum.Material.Metal, + } + ) + Build.cylinder(m, at(x, Y + 5.95, sz - 1), 0.1, 1.5, rgb(210, 30, 20)) + if id == "Sauce2" then + local sp = Instance.new("Sparkles") + sp.SparkleColor = rgb(255, 220, 90) + sp.Parent = pot + end + end + end + for _, id in { "Tray1", "Tray2" } do + if has(id) then + local m = Build.model(up, id) + Build.part(m, { + size = Vector3.new(2.6, 0.15, 1.8), + cf = at(8.6, Y + 4.2 + (if id == "Tray2" then 0.2 else 0), sz + 1), + color = if id == "Tray1" then rgb(120, 170, 230) else rgb(250, 200, 70), + collide = false, + }) + end + end + + -- 메뉴판 글자 + local lines = {} + for _, key in Economy.MENU_ORDER do + if table.find(stats.menus, key) then + local m = Economy.MENUS[key] + table.insert(lines, `{m.icon} {m.name} {Economy.dishPrice(key, stats, 1)}원`) + end + end + refs.menuLabel.Text = table.concat(lines, "\n") + refs.menuLabel.TextScaled = true +end + +-- 손님 의자 위(앉는 위치)와 테이블 위 접시 위치(월드 좌표) +function PlotBuilder.seatCFrame(cf: CFrame, seat: number): CFrame + local s = PlotLayout.stool(seat) + local t = PlotLayout.TABLES[seat] + local pos = (cf * CFrame.new(s.X, Y + 1.8, s.Z)).Position + local look = (cf * CFrame.new(t.X, Y + 1.8, t.Z)).Position + return CFrame.lookAt(pos, look) +end + +function PlotBuilder.dishCFrame(cf: CFrame, seat: number): CFrame + local t = PlotLayout.TABLES[seat] + return cf * CFrame.new(t.X, Y + 2.75, t.Z + 1.2) +end + +function PlotBuilder.counterSlot(cf: CFrame, i: number): CFrame + return cf * CFrame.new(PlotLayout.COUNTER.X - 2 + (i - 1) * 2, Y + 4.1, PlotLayout.STALL_Z) +end + +function PlotBuilder.world(cf: CFrame, v: Vector3): Vector3 + return (cf * CFrame.new(v.X, Y + v.Y, v.Z)).Position +end + +return PlotBuilder diff --git a/bunsik-tycoon/src/server/PlotController.luau b/bunsik-tycoon/src/server/PlotController.luau new file mode 100644 index 0000000..2c14590 --- /dev/null +++ b/bunsik-tycoon/src/server/PlotController.luau @@ -0,0 +1,549 @@ +--!strict +-- 플레이어 한 명의 가게를 움직입니다: Shop 로직의 이벤트를 받아 손님 NPC, 접시, 효과를 그리고, +-- 조리대 버튼·자동 서빙·구매를 처리합니다. 실제 Player 대신 Folder를 넣어도 돌아가서 원격 테스트에 씁니다. + +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local TweenService = game:GetService("TweenService") + +local Shared = ReplicatedStorage.Shared +local Economy = require(Shared.Economy) +local Shop = require(Shared.Shop) +local Locale = require(Shared.Locale) +local Sounds = require(Shared.Sounds) + +local Build = require(script.Parent.Build) +local Food = require(script.Parent.Food) +local Npc = require(script.Parent.Npc) +local PlotBuilder = require(script.Parent.PlotBuilder) +local PlotLayout = require(script.Parent.PlotLayout) + +local SERVE_RANGE = 8.5 +local PICKUP_RANGE = 8 + +export type Slot = { + index: number, + cf: CFrame, + model: Model, + refs: PlotBuilder.BaseRefs, +} + +type CustomerView = { + npc: Npc.Handle, + bubble: BillboardGui, + dish: Model?, +} + +export type Options = { + userId: number, + displayName: string, + data: any, -- 세이브 데이터(Data.TEMPLATE 모양) + now: number, + getCharacter: (() -> Model?)?, + notify: ((key: string, args: { [string]: any }?) -> ())?, + lang: string?, +} + +local PlotController = {} +PlotController.__index = PlotController + +export type PlotController = typeof(setmetatable( + {} :: { + slot: Slot, + owner: Instance, + opts: Options, + data: any, + shop: Shop.Shop, + views: { [number]: CustomerView }, + handModels: { Model }, + counterModels: { Model }, + lastCook: number, + coin: Sound, + buySound: Sound, + helper: Npc.Handle?, + guide: BasePart, + guideValue: ObjectValue, + rng: Random, + lang: string, + tut: number, + destroyed: boolean, + connections: { RBXScriptConnection }, + }, + PlotController +)) + +local function makeSound(parent: Instance, id: string, volume: number, looped: boolean?): Sound + local s = Instance.new("Sound") + s.SoundId = id + s.Volume = volume + s.Looped = looped == true + s.RollOffMaxDistance = 80 + s.Parent = parent + return s +end + +function PlotController.new(slot: Slot, owner: Instance, opts: Options): PlotController + local data = opts.data + local self = setmetatable({ + slot = slot, + owner = owner, + opts = opts, + data = data, + shop = Shop.new(data.Money, data.Bought, opts.now), + views = {}, + handModels = {}, + counterModels = {}, + lastCook = 0, + coin = makeSound(slot.refs.stove, Sounds.COIN, 0.7), + buySound = makeSound(slot.refs.stove, Sounds.BUY, 0.8), + helper = nil :: Npc.Handle?, + guide = Instance.new("Part") :: BasePart, + guideValue = Instance.new("ObjectValue"), + rng = Random.new(opts.userId + slot.index), + lang = opts.lang or "ko", + tut = if data.TutorialDone then 0 else 1, + destroyed = false, + connections = {}, + }, PlotController) + + slot.model:SetAttribute("OwnerId", opts.userId) + slot.refs.nameLabel.Text = Locale.t("ko", "plotOwner", { name = opts.displayName }) + + -- 튜토리얼 화살표가 가리킬 보이지 않는 표시 + local guide = self.guide + guide.Name = "Guide" + guide.Anchored = true + guide.CanCollide = false + guide.CanQuery = false + guide.CanTouch = false + guide.Transparency = 1 + guide.Size = Vector3.new(1, 1, 1) + guide.Parent = slot.refs.dynamic + self.guideValue.Name = "Guide" + self.guideValue.Parent = owner + + -- 조리 버튼(ProximityPrompt)은 주인 화면에만 클라이언트가 만듭니다. 서버는 조리대 속성으로 상태만 알려 줍니다. + slot.refs.stove:SetAttribute("OwnerId", opts.userId) + + PlotBuilder.buildUpgrades(slot.refs, slot.cf, self.shop.bought) + self:refreshHelper() + self:refreshPrompt() + self:sync() + return self +end + +function PlotController.isOwner(self: PlotController, player: Player): boolean + return player.UserId == self.opts.userId +end + +function PlotController.character(self: PlotController): Model? + if self.opts.getCharacter then + return self.opts.getCharacter() + end + if self.owner:IsA("Player") then + return self.owner.Character + end + return nil +end + +function PlotController.notify(self: PlotController, key: string, args: { [string]: any }?) + if self.opts.notify then + self.opts.notify(key, args) + end +end + +function PlotController.setLang(self: PlotController, lang: string) + self.lang = lang + self:refreshPrompt() +end + +-- 화면에 필요한 값을 Player 속성으로 내보내고 세이브 데이터에 적습니다. +function PlotController.sync(self: PlotController) + local shop = self.shop + self.data.Money = shop.money + self.data.Bought = shop.bought + self.data.Served = (self.data.Served or 0) + local o = self.owner + o:SetAttribute("Money", shop.money) + o:SetAttribute("Bought", shop.bought) + o:SetAttribute("Stage", shop.stats.stage) + o:SetAttribute("Double", shop.moneyMult > 1) + o:SetAttribute("Boost", Economy.boostAmount(shop.stats)) + o:SetAttribute("Tut", self.tut) + o:SetAttribute("Plot", self.slot.index) + o:SetAttribute("Carry", #shop.hand) +end + +-- 조리대 속성: CookMenu(만들 메뉴, 없으면 ""), CookTime(누르는 시간), HandFull +function PlotController.refreshPrompt(self: PlotController) + local shop = self.shop + local stove = self.slot.refs.stove + local full = Shop.handFull(shop) + local menu = if full then nil else Shop.nextCookMenu(shop) + stove:SetAttribute("CookMenu", menu or "") + stove:SetAttribute("CookTime", shop.stats.cook) + stove:SetAttribute("HandFull", full) +end + +function PlotController.refreshHelper(self: PlotController) + if self.shop.stats.helper and not self.helper then + local pos = PlotBuilder.world(self.slot.cf, PlotLayout.HELPER) + local look = PlotBuilder.world(self.slot.cf, PlotLayout.STOVE) + local h = Npc.spawn(self.slot.refs.dynamic, CFrame.new(pos), self.rng, Color3.fromRGB(250, 250, 250)) + h.model.Name = "Helper" + h.root.CFrame = Npc.standCFrame(h, pos, look) + local tag = Build.billboard( + h.root, + "👩‍🍳", + UDim2.fromOffset(60, 60), + Vector3.new(0, 3.5, 0), + Color3.new(1, 1, 1) + ) + tag.Name = "HelperTag" + self.helper = h + end +end + +-- 손에 든 접시 모형을 캐릭터 앞에 붙입니다. +function PlotController.layoutHand(self: PlotController) + local char = self:character() + local root = char and char:FindFirstChild("HumanoidRootPart") :: BasePart? + for i, m in self.handModels do + local plate = m.PrimaryPart :: BasePart + for _, d in m:GetDescendants() do + if d:IsA("WeldConstraint") then + d:Destroy() + end + end + if root then + m:PivotTo(root.CFrame * CFrame.new(0, -0.4 + (i - 1) * 0.6, -1.9)) + Build.weldAll(m, plate) + for _, d in m:GetDescendants() do + if d:IsA("BasePart") then + d.Massless = true + d.CanCollide = false + end + end + plate.Anchored = false + local w = Instance.new("WeldConstraint") + w.Part0 = root + w.Part1 = plate + w.Parent = plate + m.Parent = char + else + -- 캐릭터가 없을 때(테스트)는 조리대 위에 둡니다. + for _, d in m:GetDescendants() do + if d:IsA("BasePart") then + d.Anchored = true + end + end + m.Parent = self.slot.refs.dynamic + m:PivotTo(PlotBuilder.counterSlot(self.slot.cf, 1) * CFrame.new(0, 1 + i * 0.6, 1.4)) + end + end +end + +-- 캐릭터가 다시 생기면(리스폰) 손에 든 접시 모형을 다시 만듭니다. +function PlotController.rebuildHand(self: PlotController) + for _, m in self.handModels do + m:Destroy() + end + table.clear(self.handModels) + for _, menu in self.shop.hand do + table.insert(self.handModels, Food.dish(menu, PlotBuilder.counterSlot(self.slot.cf, 1), self.slot.refs.dynamic)) + end + self:layoutHand() +end + +function PlotController.layoutCounter(self: PlotController) + for i, m in self.counterModels do + m:PivotTo(PlotBuilder.counterSlot(self.slot.cf, i)) + end +end + +function PlotController.setTut(self: PlotController, step: number) + if self.tut == step then + return + end + self.tut = step + if step == 0 then + self.data.TutorialDone = true + self:notify("tutDone") + end + self.owner:SetAttribute("Tut", step) +end + +function PlotController.updateGuide(self: PlotController) + local target: Vector3? = nil + if self.tut == 1 then + target = self.slot.refs.stove.Position + Vector3.new(0, 1, 0) + elseif self.tut == 2 then + -- 든 접시를 기다리는 손님 자리 + for id, c in self.shop.customers do + if c.state ~= "eating" and table.find(self.shop.hand, c.menu) then + local v = self.views[id] + if v then + target = PlotBuilder.seatCFrame(self.slot.cf, c.seat).Position + Vector3.new(0, 1, 0) + end + break + end + end + end + if target then + self.guide.Position = target + self.guideValue.Value = self.guide + else + self.guideValue.Value = nil + end +end + +function PlotController.cook(self: PlotController): string? + local menu = Shop.cook(self.shop) + if not menu then + return nil + end + self.lastCook = self.shop.now + local dish = Food.dish(menu, PlotBuilder.counterSlot(self.slot.cf, 1), self.slot.refs.dynamic) + table.insert(self.handModels, dish) + self:layoutHand() + if self.tut == 1 then + self:setTut(2) + end + self:refreshPrompt() + self:sync() + return menu +end + +function PlotController.pickup(self: PlotController): number + local n = Shop.pickup(self.shop) + for _ = 1, n do + local m = table.remove(self.counterModels, 1) + if m then + table.insert(self.handModels, m) + end + end + if n > 0 then + self:layoutHand() + self:layoutCounter() + if self.tut == 1 then + self:setTut(2) + end + self:refreshPrompt() + self:sync() + end + return n +end + +local function floatText(parent: BasePart, text: string) + local gui = + Build.billboard(parent, text, UDim2.fromOffset(140, 60), Vector3.new(0, 2, 0), Color3.fromRGB(255, 215, 40)) + gui.AlwaysOnTop = true + local label = gui:FindFirstChild("Text") :: TextLabel + local stroke = Instance.new("UIStroke") + stroke.Thickness = 3 + stroke.Color = Color3.fromRGB(120, 60, 0) + stroke.Parent = label + TweenService:Create(gui, TweenInfo.new(1.2, Enum.EasingStyle.Quad), { StudsOffset = Vector3.new(0, 6, 0) }):Play() + TweenService:Create(label, TweenInfo.new(1.2, Enum.EasingStyle.Quad, Enum.EasingDirection.In), { + TextTransparency = 1, + }):Play() + task.delay(1.3, function() + gui:Destroy() + end) +end + +function PlotController.serve(self: PlotController, id: number): number? + local c = self.shop.customers[id] + local earn = Shop.serve(self.shop, id) + if not earn or not c then + return nil + end + local view = self.views[id] + -- 손에 든 같은 메뉴 접시 모형을 테이블로 옮깁니다. + for i, m in self.handModels do + if m.Name == "Dish_" .. c.menu then + table.remove(self.handModels, i) + for _, d in m:GetDescendants() do + if d:IsA("WeldConstraint") then + d:Destroy() + elseif d:IsA("BasePart") then + d.Anchored = true + end + end + m.Parent = self.slot.refs.dynamic + m:PivotTo(PlotBuilder.dishCFrame(self.slot.cf, c.seat)) + if view then + view.dish = m + end + break + end + end + self:layoutHand() + if view then + local label = view.bubble:FindFirstChild("Text") :: TextLabel? + if label then + label.Text = "😋" + end + floatText(view.npc.root, "+" .. Locale.number(earn)) + end + self.coin:Play() + self.data.Served = (self.data.Served or 0) + 1 + self.data.Earned = (self.data.Earned or 0) + earn + if self.tut == 2 then + self:setTut(3) + end + self:refreshPrompt() + self:sync() + return earn +end + +function PlotController.onEvent(self: PlotController, e: Shop.Event) + local cf = self.slot.cf + if e.kind == "spawn" then + local path = {} + for _, p in PlotLayout.pathTo(e.seat) do + table.insert(path, PlotBuilder.world(cf, p)) + end + local npc = Npc.spawn(self.slot.refs.dynamic, CFrame.new(path[1]), self.rng) + npc.root.CFrame = Npc.standCFrame(npc, path[1], path[2]) + local icon = Economy.MENUS[e.menu].icon + local bubble = Build.billboard(npc.root, icon, UDim2.fromOffset(70, 70), Vector3.new(0, 4, 0)) + bubble.Name = "Order" + self.views[e.id] = { npc = npc, bubble = bubble, dish = nil } + Npc.walk(npc, path, Economy.WALK_IN) + elseif e.kind == "seated" then + local c = self.shop.customers[e.id] + local v = self.views[e.id] + if c and v then + Npc.sit(v.npc, PlotBuilder.seatCFrame(cf, c.seat)) + end + elseif e.kind == "leave" then + local v = self.views[e.id] + self.views[e.id] = nil + if v then + if v.dish then + v.dish:Destroy() + end + v.bubble:Destroy() + local path = PlotLayout.pathTo(e.seat) + local back = {} + for i = #path, 1, -1 do + table.insert(back, PlotBuilder.world(cf, path[i])) + end + Npc.walk(v.npc, back, Economy.WALK_IN, function() + v.npc.model:Destroy() + end) + task.delay(Economy.WALK_IN + 1, function() + if v.npc.model.Parent then + v.npc.model:Destroy() + end + end) + end + elseif e.kind == "counter" then + local i = #self.counterModels + 1 + local m = Food.dish(e.menu, PlotBuilder.counterSlot(cf, i), self.slot.refs.dynamic) + table.insert(self.counterModels, m) + self:layoutCounter() + end +end + +-- 매 프레임(0.1초 간격) 호출합니다. +function PlotController.update(self: PlotController, now: number) + if self.destroyed then + return + end + local events = Shop.tick(self.shop, now) + for _, e in events do + self:onEvent(e) + end + local char = self:character() + local root = char and char:FindFirstChild("HumanoidRootPart") :: BasePart? + if root then + local pos = root.Position + if #self.shop.counter > 0 and not Shop.handFull(self.shop) then + local counterPos = self.slot.refs.counter.Position + if (Vector3.new(pos.X, counterPos.Y, pos.Z) - counterPos).Magnitude < PICKUP_RANGE then + self:pickup() + end + end + if #self.shop.hand > 0 then + for id, c in self.shop.customers do + if c.state == "waiting" and table.find(self.shop.hand, c.menu) then + local seat = PlotBuilder.seatCFrame(self.slot.cf, c.seat).Position + if (Vector3.new(pos.X, seat.Y, pos.Z) - seat).Magnitude < SERVE_RANGE then + self:serve(id) + end + end + end + end + end + if #events > 0 then + self:refreshPrompt() + end + self:updateGuide() +end + +function PlotController.buy(self: PlotController): (boolean, string?) + local before = self.shop.stats + local p, err = Shop.buyNext(self.shop) + if not p then + return false, err + end + PlotBuilder.buildUpgrades(self.slot.refs, self.slot.cf, self.shop.bought) + local fresh = self.slot.refs.upgrades:FindFirstChild(p.id) + if fresh then + local hl = Instance.new("Highlight") + hl.FillColor = Color3.fromRGB(255, 230, 120) + hl.OutlineColor = Color3.fromRGB(255, 255, 255) + hl.FillTransparency = 0.4 + hl.Parent = fresh + task.delay(2.5, function() + hl:Destroy() + end) + end + self.buySound:Play() + self:refreshHelper() + self:refreshPrompt() + if self.tut == 3 then + self:setTut(0) + end + local name = if self.lang == "ko" then p.name else p.nameEn + if self.shop.stats.stage > before.stage then + self:notify("expanded") + else + self:notify("purchased", { name = name }) + end + self:sync() + return true, nil +end + +function PlotController.addMoney(self: PlotController, amount: number) + Shop.addMoney(self.shop, amount) + self:sync() +end + +function PlotController.setDouble(self: PlotController, on: boolean) + self.shop.moneyMult = if on then 2 else 1 + self:sync() +end + +function PlotController.destroy(self: PlotController) + self.destroyed = true + for _, c in self.connections do + c:Disconnect() + end + self.slot.refs.stove:SetAttribute("OwnerId", nil) + self.slot.refs.stove:SetAttribute("CookMenu", nil) + self.coin:Destroy() + self.buySound:Destroy() + self.guideValue:Destroy() + for _, m in self.handModels do + m:Destroy() + end + self.slot.refs.dynamic:ClearAllChildren() + self.slot.refs.upgrades:ClearAllChildren() + self.slot.refs.nameLabel.Text = Locale.t("ko", "plotEmpty") .. " / " .. Locale.t("en", "plotEmpty") + self.slot.refs.menuLabel.Text = "" + self.slot.model:SetAttribute("OwnerId", nil) +end + +return PlotController diff --git a/bunsik-tycoon/src/server/PlotLayout.luau b/bunsik-tycoon/src/server/PlotLayout.luau new file mode 100644 index 0000000..997a1b8 --- /dev/null +++ b/bunsik-tycoon/src/server/PlotLayout.luau @@ -0,0 +1,52 @@ +--!strict +-- 부지 한 칸의 배치 좌표(부지 기준 상대 좌표, 단위 stud). +-- 부지 원점은 바닥 가운데, +Z가 길(입구) 쪽입니다. 포장마차는 -Z 쪽 끝에 있습니다. + +local PlotLayout = {} + +PlotLayout.SIZE = Vector3.new(72, 0, 80) +PlotLayout.FLOOR_Y = 0.2 -- 부지 바닥 윗면 높이 + +-- 조리대(플레이어가 서서 누르는 곳은 조리대 앞 +Z 쪽) +PlotLayout.STALL_Z = -26 +PlotLayout.STOVE = Vector3.new(-3, 0, -26) +PlotLayout.COUNTER = Vector3.new(5.5, 0, -26) +PlotLayout.HELPER = Vector3.new(-3, 0, -30) + +-- 손님 입구와 통로 +PlotLayout.ENTRANCE = Vector3.new(0, 0, 32) +PlotLayout.PLAYER_SPAWN = Vector3.new(0, 0, -16) + +-- 테이블 위치(1~4: 포장마차 앞, 5~8: 실내 확장 뒤 양옆) +PlotLayout.TABLES = { + Vector3.new(-9, 0, -10), + Vector3.new(9, 0, -10), + Vector3.new(-9, 0, 4), + Vector3.new(9, 0, 4), + Vector3.new(-25, 0, -10), + Vector3.new(25, 0, -10), + Vector3.new(-25, 0, 4), + Vector3.new(25, 0, 4), +} + +PlotLayout.STOOL_OFFSET = 3.5 -- 의자는 테이블에서 +Z 쪽으로 +PlotLayout.LANE_OFFSET = 3 -- 걷는 통로는 의자 뒤로 + +function PlotLayout.stool(seat: number): Vector3 + local t = PlotLayout.TABLES[seat] + return t + Vector3.new(0, 0, PlotLayout.STOOL_OFFSET) +end + +-- 입구 -> 가운데 통로 -> 줄 통로 -> 의자 순서로 걷는 길(상대 좌표) +function PlotLayout.pathTo(seat: number): { Vector3 } + local stool = PlotLayout.stool(seat) + local laneZ = stool.Z + PlotLayout.LANE_OFFSET + return { + PlotLayout.ENTRANCE, + Vector3.new(0, 0, laneZ), + Vector3.new(stool.X, 0, laneZ), + stool, + } +end + +return PlotLayout diff --git a/bunsik-tycoon/src/server/Receipts.luau b/bunsik-tycoon/src/server/Receipts.luau new file mode 100644 index 0000000..7a438f8 --- /dev/null +++ b/bunsik-tycoon/src/server/Receipts.luau @@ -0,0 +1,64 @@ +--!strict +-- 개발자 상품 결제 처리: 결제 한 번에 정확히 한 번만 지급합니다(DECISIONS.md 2절). +-- 로블록스 API에 직접 기대지 않게 프로필과 지급 함수를 받아서, lune 단위 테스트로도 검증합니다. + +local Receipts = {} + +Receipts.CACHE_SIZE = 100 + +-- Enum.ProductPurchaseDecision 대신 문자열을 돌려주고, 호출하는 쪽에서 Enum으로 바꿉니다. +export type Decision = "Granted" | "NotProcessedYet" + +export type ProfileLike = { + Data: { PurchaseIdCache: { string }? }, + LastSavedData: { PurchaseIdCache: { string }? }, + IsActive: (self: any) -> boolean, + Save: (self: any) -> (), + OnAfterSave: { Wait: (self: any) -> () }, +} + +local function isSaved(profile: ProfileLike, purchaseId: string): boolean + local saved = profile.LastSavedData and profile.LastSavedData.PurchaseIdCache + return saved ~= nil and table.find(saved, purchaseId) ~= nil +end + +-- profile이 nil이면(아직 로드 안 됨, 이미 나감) 나중에 다시 시도하게 합니다. +function Receipts.process(profile: ProfileLike?, purchaseId: string, grant: () -> boolean): Decision + if profile == nil or not profile:IsActive() then + return "NotProcessedYet" + end + local cache = profile.Data.PurchaseIdCache + if cache == nil then + return "NotProcessedYet" + end + if table.find(cache, purchaseId) == nil then + local ok, granted = pcall(grant) + if not ok or granted ~= true then + if not ok then + warn("[Bunsik] 상품 지급 오류:", granted) + end + return "NotProcessedYet" + end + while #cache >= Receipts.CACHE_SIZE do + table.remove(cache, 1) + end + table.insert(cache, purchaseId) + end + -- 지급과 PurchaseId가 같이 저장된 것을 확인한 뒤에만 완료로 알립니다. + if isSaved(profile, purchaseId) then + return "Granted" + end + while profile:IsActive() do + local last = profile.LastSavedData + profile:Save() + if profile.LastSavedData == last then + profile.OnAfterSave:Wait() + end + if isSaved(profile, purchaseId) then + return "Granted" + end + end + return "NotProcessedYet" +end + +return Receipts diff --git a/bunsik-tycoon/src/server/World.luau b/bunsik-tycoon/src/server/World.luau new file mode 100644 index 0000000..051716f --- /dev/null +++ b/bunsik-tycoon/src/server/World.luau @@ -0,0 +1,179 @@ +--!strict +-- 맵: 가운데 "분식 거리"와 양쪽에 부지 6칸. 모두 코드로 지어서 리포가 원본이 됩니다. + +local Lighting = game:GetService("Lighting") + +local Build = require(script.Parent.Build) +local PlotBuilder = require(script.Parent.PlotBuilder) +local Locale = require(game:GetService("ReplicatedStorage").Shared.Locale) + +local World = {} + +World.PLOT_COUNT = 6 +World.STREET_HALF = 14 -- 길 폭의 절반 +local PLOT_X = { -80, 0, 80 } +local PLOT_Z = 14 + 40 + 2 -- 길 가장자리 + 부지 반 길이 + 여유 + +local function rgb(r: number, g: number, b: number): Color3 + return Color3.fromRGB(r, g, b) +end + +-- i번째 부지의 기준 좌표. 입구(+Z)가 길을 봅니다. +function World.plotCFrame(i: number): CFrame + local col = ((i - 1) % 3) + 1 + local north = i <= 3 + local x = PLOT_X[col] + if north then + return CFrame.new(x, 0, -PLOT_Z) + end + return CFrame.new(x, 0, PLOT_Z) * CFrame.Angles(0, math.pi, 0) +end + +local function setupLighting() + Lighting.ClockTime = 14.5 + Lighting.Brightness = 2.2 + Lighting.Ambient = rgb(120, 115, 110) + Lighting.OutdoorAmbient = rgb(150, 145, 140) + Lighting.EnvironmentDiffuseScale = 0.5 + Lighting.EnvironmentSpecularScale = 0.5 + Lighting.GlobalShadows = true + if not Lighting:FindFirstChildOfClass("Atmosphere") then + local a = Instance.new("Atmosphere") + a.Density = 0.25 + a.Color = rgb(200, 220, 255) + a.Decay = rgb(120, 140, 170) + a.Parent = Lighting + end + if not Lighting:FindFirstChildOfClass("Sky") then + Instance.new("Sky").Parent = Lighting + end +end + +export type Slot = { + index: number, + cf: CFrame, + model: Model, + refs: PlotBuilder.BaseRefs, +} + +-- 맵을 짓고 부지 목록을 돌려줍니다. 여러 번 불러도 한 번만 짓습니다. +function World.build(): { Slot } + local existing = workspace:FindFirstChild("BunsikWorld") + if existing then + existing:Destroy() + end + setupLighting() + local root = Instance.new("Folder") + root.Name = "BunsikWorld" + root.Parent = workspace + + -- 잔디 바닥, 길, 인도, 차선 + Build.part(root, { + name = "Ground", + size = Vector3.new(400, 2, 260), + cf = CFrame.new(0, -1, 0), + color = rgb(110, 170, 90), + material = Enum.Material.Grass, + }) + Build.part(root, { + name = "Street", + size = Vector3.new(260, 0.2, World.STREET_HALF * 2), + cf = CFrame.new(0, 0.1, 0), + color = rgb(70, 70, 75), + material = Enum.Material.Asphalt, + }) + for i = -6, 6 do + Build.part(root, { + size = Vector3.new(8, 0.05, 0.6), + cf = CFrame.new(i * 18, 0.22, 0), + color = rgb(250, 240, 200), + collide = false, + }) + end + -- 가로등 + for i = -3, 3 do + for _, side in { -1, 1 } do + local x = i * 40 + 20 * side + local z = side * (World.STREET_HALF - 1) + Build.part(root, { + size = Vector3.new(0.6, 14, 0.6), + cf = CFrame.new(x, 7, z), + color = rgb(60, 60, 65), + material = Enum.Material.Metal, + }) + local lamp = Build.part(root, { + size = Vector3.new(1.6, 1.6, 1.6), + cf = CFrame.new(x, 14.5, z), + color = rgb(255, 240, 200), + shape = Enum.PartType.Ball, + neon = true, + collide = false, + }) + local light = Instance.new("PointLight") + light.Range = 24 + light.Brightness = 0.7 + light.Color = rgb(255, 230, 180) + light.Parent = lamp + end + end + -- 거리 입구 아치 + for _, x in { -128, 128 } do + for _, side in { -1, 1 } do + Build.part(root, { + size = Vector3.new(2, 20, 2), + cf = CFrame.new(x, 10, side * World.STREET_HALF), + color = rgb(200, 50, 40), + }) + end + local arch = Build.part(root, { + name = "Arch", + size = Vector3.new(2, 5, World.STREET_HALF * 2 + 4), + cf = CFrame.new(x, 21, 0), + color = rgb(255, 215, 80), + }) + local face = if x < 0 then Enum.NormalId.Right else Enum.NormalId.Left + Build.label(arch, face, "분식 거리 · BUNSIK STREET", rgb(190, 40, 30)) + end + -- 바깥 나무 + local rng = Random.new(7) + for _ = 1, 40 do + local x = rng:NextNumber(-190, 190) + local z = (if rng:NextNumber() < 0.5 then -1 else 1) * rng:NextNumber(102, 125) + Build.cylinder(root, CFrame.new(x, 3, z), 6, 1.6, rgb(120, 80, 50)) + Build.part(root, { + size = Vector3.new(9, 9, 9), + cf = CFrame.new(x, 9, z), + color = rgb(70 + rng:NextInteger(0, 30), 150, 70), + shape = Enum.PartType.Ball, + material = Enum.Material.LeafyGrass, + }) + end + + -- 시작 지점(길 가운데). 들어오면 바로 자기 부지로 옮겨집니다. + local spawn = Instance.new("SpawnLocation") + spawn.Name = "Spawn" + spawn.Anchored = true + spawn.Size = Vector3.new(10, 0.4, 10) + spawn.CFrame = CFrame.new(0, 0.3, 0) + spawn.Duration = 0 + spawn.Transparency = 1 + spawn.CanCollide = false + spawn.Parent = root + + local plots = Instance.new("Folder") + plots.Name = "Plots" + plots.Parent = root + local slots: { Slot } = {} + for i = 1, World.PLOT_COUNT do + local cf = World.plotCFrame(i) + local model = Instance.new("Model") + model.Name = "Plot" .. i + model.Parent = plots + local refs = PlotBuilder.buildBase(model, cf) + refs.nameLabel.Text = Locale.t("ko", "plotEmpty") .. " / " .. Locale.t("en", "plotEmpty") + table.insert(slots, { index = i, cf = cf, model = model, refs = refs }) + end + return slots +end + +return World diff --git a/bunsik-tycoon/src/shared/Economy.luau b/bunsik-tycoon/src/shared/Economy.luau index 36cb290..cd3805d 100644 --- a/bunsik-tycoon/src/shared/Economy.luau +++ b/bunsik-tycoon/src/shared/Economy.luau @@ -1,5 +1,6 @@ --!strict --- 분식집 첫 10분 경제 수치. ECONOMY.md 표, tools/economy_sim.py 와 같은 숫자여야 합니다. +-- 분식집 경제 수치. ECONOMY.md 표와 같은 숫자여야 합니다. +-- 숫자를 바꾸면 `lune run tools/sim.luau` 로 구매 시점을 다시 확인합니다. export type Effect = { seats: number?, -- 테이블 수 @@ -8,19 +9,44 @@ export type Effect = { price: number?, -- 가격 배율 helper: boolean?, -- 알바생(조리 자동) menu: string?, -- 해금할 메뉴 + carry: number?, -- 한 번에 드는 접시 수 + stage: number?, -- 가게 단계(2 = 실내 분식집) } export type Purchase = { id: string, name: string, + nameEn: string, cost: number, effect: Effect, } +export type Menu = { + name: string, + nameEn: string, + price: number, + icon: string, +} + +export type Stats = { + seats: number, + spawn: number, + cook: number, + price: number, + helper: boolean, + menus: { string }, + carry: number, + stage: number, +} + local Economy = {} -Economy.WALK = 5 -- 조리대 -> 테이블 -> 조리대 왕복(초) +Economy.WALK = 5 -- 조리대 -> 테이블 -> 조리대 왕복(초, 시뮬레이터 가정) Economy.EAT = 6 -- 식사 시간(초) +Economy.WALK_IN = 2.5 -- 손님이 입구에서 자리까지 걷는 시간(초) +Economy.COUNTER_MAX = 3 -- 알바생이 미리 만들어 두는 접시 최대 수 +Economy.BOOST_MINUTES = 10 -- 돈 부스트 팩: 현재 1분 매출 x 10분 +Economy.BOOST_MIN = 100 -- 돈 부스트 팩 최소 지급액 Economy.START = { money = 0, @@ -30,25 +56,123 @@ Economy.START = { price = 1, helper = false, menus = { "Tteokbokki" }, + carry = 1, + stage = 1, } Economy.MENUS = { - Tteokbokki = { name = "떡볶이", price = 10 }, - Gimbap = { name = "김밥", price = 20 }, - Sundae = { name = "순대", price = 35 }, -} + Tteokbokki = { name = "떡볶이", nameEn = "Tteokbokki", price = 10, icon = "🌶️" }, + Gimbap = { name = "김밥", nameEn = "Gimbap", price = 20, icon = "🍙" }, + Sundae = { name = "순대", nameEn = "Sundae", price = 35, icon = "🌭" }, + Eomuk = { name = "어묵", nameEn = "Fish Cake", price = 50, icon = "🍢" }, + Twigim = { name = "튀김", nameEn = "Twigim", price = 70, icon = "🍤" }, +} :: { [string]: Menu } +-- 메뉴 표시 순서 +Economy.MENU_ORDER = { "Tteokbokki", "Gimbap", "Sundae", "Eomuk", "Twigim" } + +-- 1~10: 첫 10분(1단계 포장마차). 11~20: 2단계 실내 분식집. Economy.PURCHASES = { - { id = "Table2", name = "테이블 2", cost = 10, effect = { seats = 2 } }, - { id = "UnlockGimbap", name = "김밥 해금", cost = 40, effect = { menu = "Gimbap" } }, - { id = "Sign1", name = "간판 Lv1", cost = 70, effect = { spawn = 5 } }, - { id = "Stove1", name = "화구 Lv1", cost = 90, effect = { cook = 1.5 } }, - { id = "Table3", name = "테이블 3", cost = 120, effect = { seats = 3 } }, - { id = "UnlockSundae", name = "순대 해금", cost = 160, effect = { menu = "Sundae" } }, - { id = "Sauce1", name = "양념 비법 Lv1", cost = 240, effect = { price = 1.5 } }, - { id = "Helper", name = "알바생 고용", cost = 360, effect = { helper = true } }, - { id = "Table4", name = "테이블 4", cost = 480, effect = { seats = 4, spawn = 4 } }, - { id = "Expand", name = "실내 분식집 확장", cost = 600, effect = {} }, + { id = "Table2", name = "테이블 2", nameEn = "Table 2", cost = 10, effect = { seats = 2 } }, + { id = "UnlockGimbap", name = "김밥 해금", nameEn = "Unlock Gimbap", cost = 40, effect = { menu = "Gimbap" } }, + { id = "Sign1", name = "간판 Lv1", nameEn = "Sign Lv1", cost = 70, effect = { spawn = 5 } }, + { id = "Stove1", name = "화구 Lv1", nameEn = "Stove Lv1", cost = 90, effect = { cook = 1.5 } }, + { id = "Table3", name = "테이블 3", nameEn = "Table 3", cost = 120, effect = { seats = 3 } }, + { id = "UnlockSundae", name = "순대 해금", nameEn = "Unlock Sundae", cost = 160, effect = { menu = "Sundae" } }, + { id = "Sauce1", name = "양념 비법 Lv1", nameEn = "Secret Sauce Lv1", cost = 240, effect = { price = 1.5 } }, + { id = "Helper", name = "알바생 고용", nameEn = "Hire Helper", cost = 360, effect = { helper = true } }, + { id = "Table4", name = "테이블 4", nameEn = "Table 4", cost = 480, effect = { seats = 4, spawn = 4 } }, + { id = "Expand", name = "실내 분식집 확장", nameEn = "Indoor Shop", cost = 600, effect = { stage = 2 } }, + + { id = "Tray1", name = "쟁반", nameEn = "Tray", cost = 700, effect = { carry = 2 } }, + { id = "Table5", name = "테이블 5", nameEn = "Table 5", cost = 800, effect = { seats = 5 } }, + { + id = "UnlockEomuk", + name = "어묵 해금", + nameEn = "Unlock Fish Cake", + cost = 950, + effect = { menu = "Eomuk" }, + }, + { id = "Sign2", name = "간판 Lv2", nameEn = "Sign Lv2", cost = 1150, effect = { spawn = 3 } }, + { id = "Table6", name = "테이블 6", nameEn = "Table 6", cost = 1400, effect = { seats = 6 } }, + { id = "Stove2", name = "화구 Lv2", nameEn = "Stove Lv2", cost = 1700, effect = { cook = 1 } }, + { + id = "UnlockTwigim", + name = "튀김 해금", + nameEn = "Unlock Twigim", + cost = 2000, + effect = { menu = "Twigim" }, + }, + { id = "Sauce2", name = "양념 비법 Lv2", nameEn = "Secret Sauce Lv2", cost = 2500, effect = { price = 2 } }, + { id = "Tray2", name = "큰 쟁반", nameEn = "Big Tray", cost = 3000, effect = { carry = 3 } }, + { id = "Table8", name = "테이블 7·8", nameEn = "Tables 7-8", cost = 3600, effect = { seats = 8, spawn = 2.5 } }, } :: { Purchase } +Economy.MAX_SEATS = 8 + +-- 앞에서부터 `bought`개를 산 상태의 능력치 +function Economy.statsAt(bought: number): Stats + local s = Economy.START + local stats: Stats = { + seats = s.seats, + spawn = s.spawn, + cook = s.cook, + price = s.price, + helper = s.helper, + menus = table.clone(s.menus), + carry = s.carry, + stage = s.stage, + } + for i = 1, math.min(bought, #Economy.PURCHASES) do + local e = Economy.PURCHASES[i].effect + if e.seats then + stats.seats = e.seats + end + if e.spawn then + stats.spawn = e.spawn + end + if e.cook then + stats.cook = e.cook + end + if e.price then + stats.price = e.price + end + if e.helper then + stats.helper = true + end + if e.menu then + table.insert(stats.menus, e.menu) + end + if e.carry then + stats.carry = e.carry + end + if e.stage then + stats.stage = e.stage + end + end + return stats +end + +-- 한 접시 값(정수). moneyMult는 2배 수익 게임패스(1 또는 2) +function Economy.dishPrice(menu: string, stats: Stats, moneyMult: number): number + return math.floor(Economy.MENUS[menu].price * stats.price) * moneyMult +end + +-- 현재 능력치로 1분에 버는 돈(대략). 돈 부스트 팩 지급액 계산용 +function Economy.incomePerMinute(stats: Stats): number + local total = 0 + for _, m in stats.menus do + total += Economy.dishPrice(m, stats, 1) + end + local avg = total / #stats.menus + -- 손님 수는 간격과 자리 회전(식사+이동+조리) 중 느린 쪽으로 제한 + local perSeat = 60 / (Economy.EAT + Economy.WALK_IN + Economy.WALK + stats.cook) + local customers = math.min(60 / stats.spawn, perSeat * stats.seats) + return math.floor(customers * avg) +end + +function Economy.boostAmount(stats: Stats): number + return math.max(Economy.BOOST_MIN, Economy.incomePerMinute(stats) * Economy.BOOST_MINUTES) +end + return Economy diff --git a/bunsik-tycoon/src/shared/Locale.luau b/bunsik-tycoon/src/shared/Locale.luau new file mode 100644 index 0000000..a05a305 --- /dev/null +++ b/bunsik-tycoon/src/shared/Locale.luau @@ -0,0 +1,127 @@ +--!strict +-- 화면 글자(한국어·영어). 키가 없으면 키 이름을 그대로 보여 줘서 빠진 번역이 바로 보입니다. + +local Locale = {} + +local STRINGS: { [string]: { [string]: string } } = { + ko = { + title = "분식집 타이쿤", + money = "{money}원", + shop = "업그레이드", + buy = "사기", + bought = "완료", + locked = "잠김", + notEnough = "돈이 {need}원 더 필요해요", + maxed = "모든 업그레이드를 샀어요! 2호점은 다음 업데이트에서 열려요", + stage1 = "1단계 · 포장마차", + stage2 = "2단계 · 실내 분식집", + next = "다음", + close = "닫기", + language = "English", + cookAction = "{menu} 만들기", + cookWait = "손님 기다리는 중", + cookHandFull = "손이 꽉 찼어요", + stoveObject = "조리대", + tut1 = "손님이 왔어요! 빛나는 조리대로 가서 버튼을 꾹 누르세요", + tut2 = "다 만들었어요! 접시를 손님 자리로 가져가세요", + tut3 = "돈을 벌었어요! 아래 [사기] 버튼으로 테이블을 사세요", + tutDone = "잘했어요! 계속 손님을 받고 가게를 키워 보세요", + double = "2배 수익", + doubleOwned = "2배 수익 적용 중", + doubleDesc = "모든 판매 금액이 영원히 2배", + boost = "돈 부스트", + boostDesc = "지금 매출 10분치 {amount}원 즉시 받기", + boostGot = "돈 부스트 {amount}원을 받았어요!", + purchased = "{name} 구매 완료!", + expanded = "실내 분식집으로 확장했어요! 새 업그레이드가 열렸어요", + plotOwner = "{name}의 분식집", + plotEmpty = "빈 가게 자리", + helperNote = "알바생이 요리 중! 카운터에서 접시를 가져가세요", + saveFail = "저장된 데이터를 불러오지 못했어요. 다시 접속해 주세요", + visitor = "다른 친구의 가게예요", + devTitle = "개발자 테스트", + devMoney = "+1,000원", + devDouble = "2배 켜기/끄기", + devReset = "처음부터", + devResetDone = "진행을 처음으로 되돌렸어요", + }, + en = { + title = "Bunsik Tycoon", + money = "₩{money}", + shop = "Upgrades", + buy = "Buy", + bought = "Done", + locked = "Locked", + notEnough = "Need ₩{need} more", + maxed = "All upgrades bought! Shop #2 opens in the next update", + stage1 = "Stage 1 · Street Stall", + stage2 = "Stage 2 · Indoor Shop", + next = "Next", + close = "Close", + language = "한국어", + cookAction = "Cook {menu}", + cookWait = "Waiting for customers", + cookHandFull = "Hands are full", + stoveObject = "Stove", + tut1 = "A customer is here! Go to the glowing stove and hold the button", + tut2 = "Done! Bring the dish to the customer's seat", + tut3 = "You earned money! Tap [Buy] at the bottom to get a table", + tutDone = "Great job! Keep serving and grow your shop", + double = "Double Money", + doubleOwned = "Double Money active", + doubleDesc = "All sales are doubled forever", + boost = "Money Boost", + boostDesc = "Get 10 minutes of sales (₩{amount}) now", + boostGot = "Money Boost: +₩{amount}!", + purchased = "{name} bought!", + expanded = "Your shop moved indoors! New upgrades unlocked", + plotOwner = "{name}'s Bunsik Shop", + plotEmpty = "Empty lot", + helperNote = "Your helper is cooking! Grab dishes from the counter", + saveFail = "Couldn't load your save. Please rejoin", + visitor = "This is a friend's shop", + devTitle = "Dev test", + devMoney = "+₩1,000", + devDouble = "Toggle x2", + devReset = "Reset", + devResetDone = "Progress reset", + }, +} + +Locale.LANGS = { "ko", "en" } + +function Locale.pick(localeId: string): string + if string.sub(string.lower(localeId), 1, 2) == "ko" then + return "ko" + end + return "en" +end + +function Locale.t(lang: string, key: string, args: { [string]: any }?): string + local tbl = STRINGS[lang] or STRINGS.en + local s = tbl[key] or STRINGS.en[key] or key + if args then + s = string.gsub(s, "{(%w+)}", function(k) + local v = args[k] + return if v ~= nil then tostring(v) else "{" .. k .. "}" + end) + end + return s +end + +function Locale.keys(lang: string): { string } + local out = {} + for k in STRINGS[lang] do + table.insert(out, k) + end + return out +end + +-- 숫자에 천 단위 쉼표 +function Locale.number(n: number): string + local s = tostring(math.floor(n)) + local out = string.reverse((string.gsub(string.reverse(s), "(%d%d%d)", "%1,"))) + return (string.gsub(out, "^(-?),", "%1")) +end + +return Locale diff --git a/bunsik-tycoon/src/shared/Products.luau b/bunsik-tycoon/src/shared/Products.luau new file mode 100644 index 0000000..9d2c1f0 --- /dev/null +++ b/bunsik-tycoon/src/shared/Products.luau @@ -0,0 +1,7 @@ +--!strict +-- 게임패스·개발자 상품 ID. tools/cloud.py products 로 만들고 여기에 적습니다. 0이면 버튼을 숨깁니다. + +return { + DOUBLE_MONEY_PASS = 2026574937, + MONEY_BOOST_PRODUCT = 3717970589, +} diff --git a/bunsik-tycoon/src/shared/Shop.luau b/bunsik-tycoon/src/shared/Shop.luau new file mode 100644 index 0000000..a9321d9 --- /dev/null +++ b/bunsik-tycoon/src/shared/Shop.luau @@ -0,0 +1,236 @@ +--!strict +-- 가게 한 곳의 규칙(손님, 주문, 조리, 서빙, 돈, 구매)을 담은 순수 로직입니다. +-- 로블록스 API를 쓰지 않아서 lune 단위 테스트와 시뮬레이터에서 그대로 돌립니다. +-- 화면(NPC, 접시 모형, 효과)은 서버의 PlotController가 이벤트를 받아 그립니다. + +-- 로블록스에서는 script.Parent, lune(테스트)에서는 파일 경로로 불러옵니다. +local Economy: typeof(require(script.Parent.Economy)) = if script + then require(script.Parent.Economy) + else (require :: any)("./Economy") + +type Stats = typeof(Economy.statsAt(0)) +type Purchase = typeof(Economy.PURCHASES[1]) + +export type CustomerState = "walking" | "waiting" | "eating" + +export type Customer = { + id: number, + seat: number, + menu: string, + state: CustomerState, + untilT: number, -- walking/eating이 끝나는 시각 +} + +export type Event = + { kind: "spawn", id: number, seat: number, menu: string } + | { kind: "seated", id: number } + | { kind: "leave", id: number, seat: number } + | { kind: "counter", menu: string } + +export type Shop = { + money: number, + bought: number, + moneyMult: number, + stats: Stats, + customers: { [number]: Customer }, + seatTaken: { [number]: number }, + hand: { string }, + counter: { string }, + now: number, + nextSpawn: number, + nextHelper: number, + menuIndex: number, + lastId: number, + served: number, + earned: number, +} + +local Shop = {} + +function Shop.new(money: number, bought: number, now: number): Shop + return { + money = money, + bought = math.clamp(bought, 0, #Economy.PURCHASES), + moneyMult = 1, + stats = Economy.statsAt(bought), + customers = {}, + seatTaken = {}, + hand = {}, + counter = {}, + now = now, + nextSpawn = now, -- 접속하자마자 첫 손님 + nextHelper = now, + menuIndex = 0, + lastId = 0, + served = 0, + earned = 0, + } +end + +local function freeSeat(self: Shop): number? + for seat = 1, self.stats.seats do + if self.seatTaken[seat] == nil then + return seat + end + end + return nil +end + +-- 아직 접시가 정해지지 않은 주문(먼저 온 손님부터). 걷는 중인 손님도 주문은 이미 정해져 있습니다. +function Shop.openOrders(self: Shop): { Customer } + local covered: { [string]: number } = {} + for _, m in self.hand do + covered[m] = (covered[m] or 0) + 1 + end + for _, m in self.counter do + covered[m] = (covered[m] or 0) + 1 + end + local list = {} + for _, c in self.customers do + if c.state ~= "eating" then + table.insert(list, c) + end + end + table.sort(list, function(a, b) + return a.id < b.id + end) + local open = {} + for _, c in list do + local n = covered[c.menu] or 0 + if n > 0 then + covered[c.menu] = n - 1 + else + table.insert(open, c) + end + end + return open +end + +-- 지금 조리대에서 만들 메뉴(없으면 nil) +function Shop.nextCookMenu(self: Shop): string? + local open = Shop.openOrders(self) + return if open[1] then open[1].menu else nil +end + +function Shop.handFull(self: Shop): boolean + return #self.hand >= self.stats.carry +end + +-- 시간을 now까지 진행합니다. 일어난 일을 이벤트로 돌려줍니다. +function Shop.tick(self: Shop, now: number): { Event } + self.now = now + local events: { Event } = {} + + for id, c in self.customers do + if c.state == "walking" and now >= c.untilT then + c.state = "waiting" + table.insert(events, { kind = "seated", id = id } :: Event) + elseif c.state == "eating" and now >= c.untilT then + self.customers[id] = nil + self.seatTaken[c.seat] = nil + table.insert(events, { kind = "leave", id = id, seat = c.seat } :: Event) + end + end + + if now >= self.nextSpawn then + local seat = freeSeat(self) + if seat then + self.lastId += 1 + local menus = self.stats.menus + local menu = menus[(self.menuIndex % #menus) + 1] + self.menuIndex += 1 + local c: Customer = { + id = self.lastId, + seat = seat, + menu = menu, + state = "walking", + untilT = now + Economy.WALK_IN, + } + self.customers[c.id] = c + self.seatTaken[seat] = c.id + table.insert(events, { kind = "spawn", id = c.id, seat = seat, menu = menu } :: Event) + end + self.nextSpawn = now + self.stats.spawn + end + + if self.stats.helper and now >= self.nextHelper then + local menu = Shop.nextCookMenu(self) + if menu and #self.counter < Economy.COUNTER_MAX then + table.insert(self.counter, menu) + table.insert(events, { kind = "counter", menu = menu } :: Event) + self.nextHelper = now + self.stats.cook + end + end + + return events +end + +-- 플레이어가 조리대에서 다 만들었을 때. 만든 메뉴를 돌려줍니다. +function Shop.cook(self: Shop): string? + if Shop.handFull(self) then + return nil + end + local menu = Shop.nextCookMenu(self) + if menu then + table.insert(self.hand, menu) + end + return menu +end + +-- 알바생이 만들어 둔 접시를 손에 듭니다. 든 접시 수를 돌려줍니다. +function Shop.pickup(self: Shop): number + local n = 0 + while #self.counter > 0 and not Shop.handFull(self) do + table.insert(self.hand, table.remove(self.counter, 1) :: string) + n += 1 + end + return n +end + +-- 손에 든 접시를 손님에게 줍니다. 번 돈을 돌려줍니다(못 주면 nil). +function Shop.serve(self: Shop, id: number): number? + local c = self.customers[id] + if not c or c.state ~= "waiting" then + return nil + end + local idx = table.find(self.hand, c.menu) + if not idx then + return nil + end + table.remove(self.hand, idx) + c.state = "eating" + c.untilT = self.now + Economy.EAT + local earn = Economy.dishPrice(c.menu, self.stats, self.moneyMult) + self.money += earn + self.earned += earn + self.served += 1 + return earn +end + +function Shop.nextPurchase(self: Shop): Purchase? + return Economy.PURCHASES[self.bought + 1] +end + +-- 다음 업그레이드를 삽니다. 성공하면 산 항목을 돌려줍니다. +function Shop.buyNext(self: Shop): (Purchase?, string?) + local p = Shop.nextPurchase(self) + if not p then + return nil, "max" + end + if self.money < p.cost then + return nil, "money" + end + self.money -= p.cost + self.bought += 1 + self.stats = Economy.statsAt(self.bought) + if p.effect.spawn then + self.nextSpawn = math.min(self.nextSpawn, self.now + p.effect.spawn) + end + return p, nil +end + +function Shop.addMoney(self: Shop, amount: number) + self.money += amount +end + +return Shop diff --git a/bunsik-tycoon/src/shared/Sounds.luau b/bunsik-tycoon/src/shared/Sounds.luau new file mode 100644 index 0000000..355df9f --- /dev/null +++ b/bunsik-tycoon/src/shared/Sounds.luau @@ -0,0 +1,8 @@ +--!strict +-- 효과음 ID. ProSoundEffects는 로블록스가 라이선스한 공개 효과음이라 누구나 쓸 수 있습니다. + +return { + SIZZLE = "rbxassetid://9114542867", -- Fry Or Sizzle 1 (SFX), ProSoundEffects + COIN = "rbxasset://sounds/electronicpingshort.wav", -- 로블록스 기본 내장음 + BUY = "rbxasset://sounds/electronicpingshort.wav", +} diff --git a/bunsik-tycoon/tests/Economy.spec.luau b/bunsik-tycoon/tests/Economy.spec.luau index c573865..df03ed6 100644 --- a/bunsik-tycoon/tests/Economy.spec.luau +++ b/bunsik-tycoon/tests/Economy.spec.luau @@ -1,34 +1,65 @@ --- 로블록스 없이 서버에서 돌리는 단위 테스트: lune run tests/Economy.spec.luau +-- 경제 수치표 검사: lune run tests/Economy.spec.luau local Economy = require("../src/shared/Economy") +local T = require("./check") -local failures = 0 -local function check(cond: boolean, msg: string) - if not cond then - failures += 1 - print("FAIL " .. msg) - end -end - -check(#Economy.PURCHASES == 10, "구매 항목은 10개") +T.eq(#Economy.PURCHASES, 20, "구매 항목은 20개(1단계 10 + 2단계 10)") +T.eq(Economy.PURCHASES[10].id, "Expand", "10번째는 실내 확장") +T.eq(Economy.PURCHASES[10].effect.stage, 2, "확장하면 2단계") local seen = {} local prev = 0 for i, p in Economy.PURCHASES do - check(p.cost > prev, `#{i} {p.id} 비용이 앞 단계보다 커야 함`) + T.check(p.cost > prev, `#{i} {p.id} 비용이 앞 단계보다 커야 함`) prev = p.cost - check(seen[p.id] == nil, `#{i} {p.id} id 중복`) + T.check(seen[p.id] == nil, `#{i} {p.id} id 중복`) seen[p.id] = true + T.check(p.name ~= "" and p.nameEn ~= "", `#{i} 이름(한/영)`) if p.effect.menu then - check(Economy.MENUS[p.effect.menu] ~= nil, `#{i} 없는 메뉴 {p.effect.menu}`) + T.check(Economy.MENUS[p.effect.menu] ~= nil, `#{i} 없는 메뉴 {p.effect.menu}`) end end -check(Economy.PURCHASES[#Economy.PURCHASES].id == "Expand", "마지막 구매는 확장") -for _, m in Economy.START.menus do - check(Economy.MENUS[m] ~= nil, `시작 메뉴 {m} 없음`) +for _, key in Economy.MENU_ORDER do + T.check(Economy.MENUS[key] ~= nil, `메뉴 순서의 {key}`) end -if failures > 0 then - error(`{failures} test(s) failed`) -end -print("Economy.spec: all passed") +local s0 = Economy.statsAt(0) +T.eq(s0.seats, 1, "처음 테이블 1") +T.eq(s0.spawn, 6, "처음 손님 간격 6초") +T.eq(s0.cook, 2.5, "처음 조리 2.5초") +T.eq(#s0.menus, 1, "처음 메뉴 1개") +T.eq(s0.carry, 1, "처음 접시 1개") + +local s10 = Economy.statsAt(10) +T.eq(s10.seats, 4, "10개 산 뒤 테이블 4") +T.eq(s10.spawn, 4, "10개 산 뒤 손님 간격 4초") +T.eq(s10.helper, true, "10개 산 뒤 알바생") +T.eq(s10.stage, 2, "10개 산 뒤 2단계") +T.eq(#s10.menus, 3, "10개 산 뒤 메뉴 3개") + +local s20 = Economy.statsAt(20) +T.eq(s20.seats, Economy.MAX_SEATS, "전부 산 뒤 테이블 8") +T.eq(s20.carry, 3, "전부 산 뒤 접시 3개") +T.eq(#s20.menus, 5, "전부 산 뒤 메뉴 5개") +T.eq(Economy.statsAt(99).seats, 8, "범위를 넘어도 안전") + +-- statsAt은 START를 바꾸면 안 됨 +Economy.statsAt(20) +T.eq(#Economy.START.menus, 1, "START.menus 불변") + +T.eq(Economy.dishPrice("Tteokbokki", s0, 1), 10, "떡볶이 10") +T.eq(Economy.dishPrice("Sundae", Economy.statsAt(7), 1), 52, "순대 35 x 1.5 = 52(내림)") +T.eq(Economy.dishPrice("Tteokbokki", s0, 2), 20, "2배 수익") + +T.eq( + Economy.boostAmount(s0), + math.max(Economy.BOOST_MIN, Economy.incomePerMinute(s0) * 10), + "부스트 = 1분 매출 x 10분" +) +T.check( + Economy.incomePerMinute(s0) >= 30 and Economy.incomePerMinute(s0) <= 60, + "처음 1분 매출 30~60원(시뮬레이터와 비슷)" +) +T.check(Economy.boostAmount(s20) > Economy.boostAmount(s10), "후반일수록 부스트가 큼") + +T.done("Economy.spec") diff --git a/bunsik-tycoon/tests/Locale.spec.luau b/bunsik-tycoon/tests/Locale.spec.luau new file mode 100644 index 0000000..d6d5b4a --- /dev/null +++ b/bunsik-tycoon/tests/Locale.spec.luau @@ -0,0 +1,40 @@ +-- 번역 검사: 한/영 키가 같고, 코드에서 쓰는 키가 모두 있는지. lune run tests/Locale.spec.luau +local fs = require("@lune/fs") +local Locale = require("../src/shared/Locale") +local T = require("./check") + +local ko = Locale.keys("ko") +local en = Locale.keys("en") +table.sort(ko) +table.sort(en) +T.eq(#ko, #en, "한/영 키 개수") +for _, k in ko do + T.check(table.find(en, k) ~= nil, `영어에 {k} 있음`) +end + +local function scan(dir: string) + for _, name in fs.readDir(dir) do + local path = dir .. "/" .. name + if fs.isDir(path) then + scan(path) + elseif string.match(name, "%.luau$") then + local src = fs.readFile(path) + for _, pat in { 'Locale%.t%([^,]+,%s*"([%w]+)"', '[%s%(:]L%("([%w]+)"[,%)]', 'notify%("([%w]+)"' } do + for key in string.gmatch(src, pat) do + T.check(table.find(ko, key) ~= nil, `{path}: 키 {key}`) + end + end + end + end +end +scan("src") + +T.eq(Locale.pick("ko-kr"), "ko", "ko-kr -> ko") +T.eq(Locale.pick("en-us"), "en", "en-us -> en") +T.eq(Locale.pick("ja-jp"), "en", "그 외 -> en") +T.eq(Locale.t("ko", "money", { money = "1,000" }), "1,000원", "치환") +T.eq(Locale.number(1234567), "1,234,567", "쉼표") +T.eq(Locale.number(999), "999", "쉼표 없음") +T.eq(Locale.number(0), "0", "0") + +T.done("Locale.spec") diff --git a/bunsik-tycoon/tests/Receipts.spec.luau b/bunsik-tycoon/tests/Receipts.spec.luau new file mode 100644 index 0000000..7ed8c5b --- /dev/null +++ b/bunsik-tycoon/tests/Receipts.spec.luau @@ -0,0 +1,90 @@ +-- 결제 1회 = 지급 1회 검사(가짜 프로필): lune run tests/Receipts.spec.luau +local Receipts = require("../src/server/Receipts") +local T = require("./check") + +local function deepcopy(t) + local out = {} + for k, v in t do + out[k] = if type(v) == "table" then deepcopy(v) else v + end + return out +end + +local function fakeProfile(saveWorks: boolean) + local p = { + Data = { PurchaseIdCache = {}, Money = 0 }, + LastSavedData = { PurchaseIdCache = {} }, + active = true, + saves = 0, + } + function p:IsActive() + return self.active + end + function p:Save() + self.saves += 1 + if saveWorks then + self.LastSavedData = deepcopy(self.Data) + else + self.active = false -- 저장 실패 끝에 세션이 끝난 상황 + end + end + p.OnAfterSave = { Wait = function() end } + return p +end + +local p = fakeProfile(true) +local grants = 0 +local function grant() + grants += 1 + p.Data.Money += 100 + return true +end +T.eq(Receipts.process(p, "A", grant), "Granted", "첫 결제 지급") +T.eq(grants, 1, "지급 1회") +T.eq(p.Data.Money, 100, "돈 들어옴") +T.check(table.find(p.LastSavedData.PurchaseIdCache, "A") ~= nil, "저장된 데이터에 PurchaseId 기록") +T.eq(Receipts.process(p, "A", grant), "Granted", "같은 결제 재시도도 완료로 답함") +T.eq(grants, 1, "같은 결제는 다시 지급하지 않음") +T.eq(Receipts.process(p, "B", grant), "Granted", "다른 결제는 지급") +T.eq(grants, 2, "지급 2회") + +T.eq(Receipts.process(nil, "C", grant), "NotProcessedYet", "프로필 없으면 나중에") +T.eq(grants, 2, "프로필 없으면 지급 안 함") + +local q = fakeProfile(true) +T.eq( + Receipts.process(q, "X", function() + return false + end), + "NotProcessedYet", + "지급 실패면 나중에" +) +T.eq(#q.Data.PurchaseIdCache, 0, "실패한 결제는 기록 안 함") +T.eq( + Receipts.process(q, "Y", function() + error("boom") + end), + "NotProcessedYet", + "지급 중 오류면 나중에" +) + +local r = fakeProfile(false) +local rg = 0 +T.eq( + Receipts.process(r, "Z", function() + rg += 1 + return true + end), + "NotProcessedYet", + "저장 확인 못 하면 완료로 답하지 않음" +) + +local c = fakeProfile(true) +for i = 1, Receipts.CACHE_SIZE + 5 do + Receipts.process(c, "P" .. i, function() + return true + end) +end +T.eq(#c.Data.PurchaseIdCache, Receipts.CACHE_SIZE, "기록은 최근 100개까지") + +T.done("Receipts.spec") diff --git a/bunsik-tycoon/tests/Shop.spec.luau b/bunsik-tycoon/tests/Shop.spec.luau new file mode 100644 index 0000000..5c41d0e --- /dev/null +++ b/bunsik-tycoon/tests/Shop.spec.luau @@ -0,0 +1,112 @@ +-- 가게 로직 검사: lune run tests/Shop.spec.luau +local Economy = require("../src/shared/Economy") +local Shop = require("../src/shared/Shop") +local T = require("./check") + +-- 첫 손님은 바로 오고, 걸어서 자리에 앉습니다. +local s = Shop.new(0, 0, 100) +local ev = Shop.tick(s, 100) +T.eq(#ev, 1, "접속하자마자 손님 1명") +T.eq(ev[1].kind, "spawn", "spawn 이벤트") +T.eq(ev[1].menu, "Tteokbokki", "첫 주문은 떡볶이") +T.eq(Shop.nextCookMenu(s), "Tteokbokki", "걷는 중인 손님 주문도 미리 만들 수 있음") +T.eq(Shop.serve(s, 1), nil, "앉기 전에는 서빙 불가") + +-- 자리가 1개면 두 번째 손님은 못 들어옴 +local ev2 = Shop.tick(s, 106) +local spawned = 0 +for _, e in ev2 do + if e.kind == "spawn" then + spawned += 1 + end +end +T.eq(spawned, 0, "빈자리 없으면 손님이 지나감") +T.eq(s.customers[1].state, "waiting", "2.5초 뒤 자리에 앉음") + +-- 조리 -> 서빙 -> 돈 +T.eq(Shop.cook(s), "Tteokbokki", "조리하면 떡볶이") +T.eq(Shop.cook(s), nil, "손이 꽉 차면 더 못 만듦") +T.eq(Shop.nextCookMenu(s), nil, "열린 주문 없음") +local earn = Shop.serve(s, 1) +T.eq(earn, 10, "떡볶이 10원") +T.eq(s.money, 10, "돈 10") +T.eq(#s.hand, 0, "접시를 내려놓음") +T.eq(Shop.serve(s, 1), nil, "같은 손님에게 두 번 못 줌") +T.eq(s.customers[1].state, "eating", "먹는 중") + +-- 다 먹으면 나가고 자리가 빔 +local ev3 = Shop.tick(s, 106 + Economy.EAT + 0.1) +local left = false +for _, e in ev3 do + if e.kind == "leave" then + left = true + end +end +T.check(left, "다 먹으면 나감") +T.eq(s.customers[1], nil, "손님 목록에서 빠짐") + +-- 구매 +local p, err = Shop.buyNext(s) +T.eq(p and p.id, "Table2", "첫 구매는 테이블 2") +T.eq(err, nil, "구매 성공") +T.eq(s.money, 0, "돈 차감") +T.eq(s.stats.seats, 2, "테이블 2개") +local p2, err2 = Shop.buyNext(s) +T.eq(p2, nil, "돈이 모자라면 실패") +T.eq(err2, "money", "실패 이유 money") + +-- 2배 수익 +local d = Shop.new(0, 0, 0) +d.moneyMult = 2 +Shop.tick(d, 0) +Shop.tick(d, 3) +Shop.cook(d) +T.eq(Shop.serve(d, 1), 20, "2배 수익이면 20원") + +-- 메뉴는 해금된 것을 돌아가며 주문 +local m = Shop.new(0, 2, 0) -- 테이블2, 김밥 해금 +Shop.tick(m, 0) +Shop.tick(m, 6) +T.eq(m.customers[1].menu, "Tteokbokki", "첫 손님 떡볶이") +T.eq(m.customers[2].menu, "Gimbap", "두 번째 손님 김밥") + +-- 다른 메뉴 접시는 다른 손님에게 못 줌 +Shop.tick(m, 9) +T.eq(Shop.cook(m), "Tteokbokki", "먼저 온 손님 메뉴부터") +T.eq(Shop.serve(m, 2), nil, "김밥 손님에게 떡볶이 불가") +T.eq(Shop.serve(m, 1), 10, "떡볶이 손님에게 성공") + +-- 알바생: 카운터에 접시를 만들어 두고, 플레이어는 집어서 나름 +local h = Shop.new(0, 8, 0) +T.eq(h.stats.helper, true, "알바생 있음") +local evs = Shop.tick(h, 0) +local counter = 0 +for _, e in evs do + if e.kind == "counter" then + counter += 1 + end +end +T.eq(counter, 1, "알바생이 첫 주문을 바로 만듦") +T.eq(#h.counter, 1, "카운터에 접시 1") +T.eq(Shop.nextCookMenu(h), nil, "만들어 둔 접시가 주문을 덮음") +T.eq(Shop.pickup(h), 1, "접시를 집음") +T.eq(#h.counter, 0, "카운터 비움") +Shop.tick(h, 3) +T.check(Shop.serve(h, 1) ~= nil, "알바생 접시로 서빙") + +-- 쟁반: 여러 접시 +local t = Shop.new(0, 11, 0) +T.eq(t.stats.carry, 2, "쟁반이면 2개") +T.eq(t.stats.seats, 4, "11번째까지 테이블 4") + +-- 전부 산 뒤 +local full = Shop.new(1e9, #Economy.PURCHASES, 0) +local none, why = Shop.buyNext(full) +T.eq(none, nil, "더 살 것 없음") +T.eq(why, "max", "이유 max") + +-- 세이브 값이 이상해도 안전 +local weird = Shop.new(5, 999, 0) +T.eq(weird.bought, #Economy.PURCHASES, "산 개수는 최대값으로 자름") + +T.done("Shop.spec") diff --git a/bunsik-tycoon/tests/Sim.spec.luau b/bunsik-tycoon/tests/Sim.spec.luau new file mode 100644 index 0000000..f3973eb --- /dev/null +++ b/bunsik-tycoon/tests/Sim.spec.luau @@ -0,0 +1,31 @@ +-- 봇 플레이로 구매 시점 목표를 검사: lune run tests/Sim.spec.luau +local Sim = require("../tools/simlib") +local T = require("./check") + +local function at(log, id) + for _, e in log do + if e.id == id then + return e.t + end + end + return math.huge +end + +local base = Sim.run(1, 3600) +T.eq(#base, 20, "봇이 1시간 안에 20개 모두 삼") +T.check(at(base, "Table2") <= 10, "첫 구매 10초 안") +T.check(at(base, "Expand") >= 8 * 60 and at(base, "Expand") <= 12 * 60, "실내 확장 8~12분") +local prev = 0 +for i, e in base do + if i > 1 and i <= 10 then + T.check(e.t - prev <= 100, `1단계 #{i} 구매 간격 100초 이하`) + elseif i > 10 then + T.check(e.t - prev <= 180, `2단계 #{i} 구매 간격 180초 이하`) + end + prev = e.t +end + +local x2 = Sim.run(2, 3600) +T.check(at(x2, "Expand") < at(base, "Expand") * 0.65, "2배 수익이면 확장이 훨씬 빠름") + +T.done("Sim.spec") diff --git a/bunsik-tycoon/tests/check.luau b/bunsik-tycoon/tests/check.luau new file mode 100644 index 0000000..2d1bbdf --- /dev/null +++ b/bunsik-tycoon/tests/check.luau @@ -0,0 +1,25 @@ +-- 아주 작은 테스트 도우미: check(조건, 메시지) 후 done(이름) +local failures = 0 +local count = 0 +local M = {} + +function M.check(cond: any, msg: string) + count += 1 + if not cond then + failures += 1 + print("FAIL " .. msg) + end +end + +function M.eq(a: any, b: any, msg: string) + M.check(a == b, `{msg} (기대 {tostring(b)}, 실제 {tostring(a)})`) +end + +function M.done(name: string) + if failures > 0 then + error(`{name}: {failures}/{count} failed`) + end + print(`{name}: {count} checks passed`) +end + +return M diff --git a/bunsik-tycoon/tests/cloud/integration.luau b/bunsik-tycoon/tests/cloud/integration.luau new file mode 100644 index 0000000..68dfcfb --- /dev/null +++ b/bunsik-tycoon/tests/cloud/integration.luau @@ -0,0 +1,339 @@ +-- 로블록스 서버(Open Cloud Luau Execution)에서 돌리는 통합 테스트. +-- python3 tools/cloud.py run tests/cloud/integration.luau --version <저장 버전> +-- 이 환경에서는 플레이어가 없고 물리가 돌지 않으며 Script가 자동 실행되지 않으므로, +-- 모듈을 직접 불러 가짜 플레이어(Folder)와 가상 시계로 가게를 돌립니다. + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local ServerScriptService = game:GetService("ServerScriptService") +local StarterPlayer = game:GetService("StarterPlayer") + +local Server = ServerScriptService.Server +local failures = {} +local count = 0 +local function check(cond: any, msg: string) + count += 1 + if not cond then + table.insert(failures, msg) + print("FAIL " .. msg) + end +end +local function eq(a: any, b: any, msg: string) + check(a == b, `{msg} (기대 {tostring(b)}, 실제 {tostring(a)})`) +end +local function section(name: string) + print("== " .. name) +end + +local Economy = require(ReplicatedStorage.Shared.Economy) + +section("맵") +local World = require(Server.World) +local slots = World.build() +eq(#slots, 6, "부지 6칸") +for i, s in slots do + check(s.refs.stove and s.refs.stove:IsDescendantOf(workspace), `부지 {i} 조리대`) + for j, o in slots do + if i < j then + local d = (s.cf.Position - o.cf.Position).Magnitude + check(d >= 76, `부지 {i},{j} 겹치지 않음 (거리 {d})`) + end + end + -- 입구(+Z)가 길(z=0) 쪽을 봐야 함 + local front = s.cf:PointToWorldSpace(Vector3.new(0, 0, 40)) + check(math.abs(front.Z) < math.abs(s.cf.Position.Z), `부지 {i} 입구가 길 쪽`) +end +check(workspace.BunsikWorld:FindFirstChild("Spawn") ~= nil, "스폰 지점") +local partCount = 0 +for _, d in workspace.BunsikWorld:GetDescendants() do + if d:IsA("BasePart") then + partCount += 1 + check(not d:IsA("PartOperation"), "Union 없음(업로드 제한)") + end +end +print("맵 파트 수", partCount) +check(partCount < 6000, "맵 파트 6000개 미만") + +section("NPC") +local Npc = require(Server.Npc) +Npc.preload() +local npc = Npc.spawn(workspace, CFrame.new(0, 5, 0), Random.new(1)) +check(npc.model:FindFirstChild("HumanoidRootPart") ~= nil, "NPC 몸") +check(npc.tracks.walk ~= nil and npc.tracks.sit ~= nil and npc.tracks.idle ~= nil, "NPC 애니메이션 3종 로드") +npc.model:Destroy() + +section("가게 1: 튜토리얼 흐름") +local PlotController = require(Server.PlotController) +local Data = require(Server.Data) +local function newData() + local d = table.clone(Data.TEMPLATE) + d.PurchaseIdCache = {} + return d +end +local owner = Instance.new("Folder") +owner.Name = "FakePlayer" +owner.Parent = ServerScriptService +local notes = {} +local data = newData() +local c = PlotController.new(slots[1], owner, { + userId = 111, + displayName = "Tester", + data = data, + now = 0, + lang = "ko", + notify = function(k) + table.insert(notes, k) + end, +}) +eq(owner:GetAttribute("Tut"), 1, "튜토리얼 1단계") +eq(owner:GetAttribute("Money"), 0, "돈 0") +eq(slots[1].refs.nameLabel.Text, "Tester의 분식집", "이름판") +c:update(0) +local dyn = slots[1].refs.dynamic +local customers = 0 +for _, ch in dyn:GetChildren() do + if ch.Name == "Customer" then + customers += 1 + check(ch:FindFirstChild("Order", true) ~= nil, "손님 주문 말풍선") + end +end +eq(customers, 1, "첫 손님 NPC 1명") +eq(slots[1].refs.stove:GetAttribute("CookMenu"), "Tteokbokki", "조리대에 떡볶이 주문 표시") +eq(slots[1].refs.stove:GetAttribute("OwnerId"), 111, "조리대 주인") +check((owner:FindFirstChild("Guide") :: ObjectValue).Value ~= nil, "튜토리얼 화살표 목표(조리대)") +c:update(3) +eq(c.shop.customers[1].state, "waiting", "손님이 앉음") +eq(c:cook(), "Tteokbokki", "조리") +eq(owner:GetAttribute("Tut"), 2, "튜토리얼 2단계") +eq(owner:GetAttribute("Carry"), 1, "접시 1개 듦") +eq(slots[1].refs.stove:GetAttribute("CookMenu"), "", "더 만들 것 없음") +eq(c:serve(1), 10, "서빙 10원") +eq(owner:GetAttribute("Money"), 10, "돈 10") +eq(data.Money, 10, "세이브 데이터 돈 10") +eq(owner:GetAttribute("Tut"), 3, "튜토리얼 3단계") +check(dyn:FindFirstChild("Dish_Tteokbokki") ~= nil, "테이블에 접시") +local ok = c:buy() +check(ok, "테이블 2 구매") +check(slots[1].refs.upgrades:FindFirstChild("Table2") ~= nil, "테이블 2 모형") +eq(owner:GetAttribute("Tut"), 0, "튜토리얼 끝") +eq(data.TutorialDone, true, "튜토리얼 저장") +eq(data.Bought, 1, "세이브 데이터 구매 1") +check(table.find(notes, "tutDone") and table.find(notes, "purchased"), "알림") +c:update(3 + Economy.EAT + 0.5) +eq(dyn:FindFirstChild("Dish_Tteokbokki"), nil, "다 먹은 접시 치움") + +section("가게 1: 전부 구매") +c:addMoney(10_000_000) +for i = 2, #Economy.PURCHASES do + local okBuy, err = c:buy() + check(okBuy, `#{i} 구매 ({err})`) +end +eq(owner:GetAttribute("Bought"), #Economy.PURCHASES, "20개 구매") +eq(owner:GetAttribute("Stage"), 2, "2단계") +for _, id in { "Expand", "Sign1", "Sign2", "Stove1", "Stove2", "Sauce1", "Sauce2", "Tray1", "Tray2", "Table8" } do + check(slots[1].refs.upgrades:FindFirstChild(id) ~= nil, `업그레이드 모형 {id}`) +end +check(dyn:FindFirstChild("Helper") ~= nil, "알바생 NPC") +check(table.find(notes, "expanded") ~= nil, "확장 알림") +local okMax, errMax = c:buy() +check(not okMax and errMax == "max", "더 살 것 없음") +check(string.find(slots[1].refs.menuLabel.Text, "튀김") ~= nil, "메뉴판에 튀김") + +section("가게 1: 가상 5분 영업(봇)") +local t = 20 +local servedBefore = c.shop.served +local t0 = os.clock() +while t < 320 do + t += 0.1 + c:update(t) + c:pickup() + if not c.shop.stats.helper then + c:cook() + end + for id, cust in c.shop.customers do + if cust.state == "waiting" then + c:serve(id) + end + end +end +local elapsed = os.clock() - t0 +local served = c.shop.served - servedBefore +print(`5분 영업: 서빙 {served}회, 계산 시간 {math.floor(elapsed * 1000)}ms`) +check(served > 60, "5분 동안 60회 넘게 서빙") +-- 나가는 손님은 실제 시간으로 몇 초 뒤 지워지므로 잠깐 기다립니다. +task.wait(Economy.WALK_IN + 1.5) +local alive = 0 +for _, ch in dyn:GetChildren() do + if ch.Name == "Customer" then + alive += 1 + end +end +check(alive <= Economy.MAX_SEATS + 6, `손님 NPC가 쌓이지 않음 ({alive})`) + +section("가게 2: 캐릭터 가까이 가면 자동 서빙·집기") +local charModel = + Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15) +charModel.Name = "FakeCharacter" +charModel.Parent = workspace +local hrp = charModel:FindFirstChild("HumanoidRootPart") :: BasePart +hrp.Anchored = true +local owner2 = Instance.new("Folder") +owner2.Parent = ServerScriptService +local data2 = newData() +data2.Bought = 8 -- 알바생까지 산 상태 +data2.Money = 5 +local c2 = PlotController.new(slots[2], owner2, { + userId = 222, + displayName = "Tester2", + data = data2, + now = 0, + getCharacter = function() + return charModel + end, +}) +eq(owner2:GetAttribute("Money"), 5, "저장된 돈 불러옴") +eq(owner2:GetAttribute("Tut"), 1, "튜토리얼 안 끝났으면 1") +c2:update(0) +eq(#c2.shop.counter, 1, "알바생이 카운터에 접시") +hrp.CFrame = slots[2].refs.counter.CFrame + Vector3.new(0, 3, 4) +c2:update(0.2) +eq(#c2.shop.hand, 1, "카운터 근처에서 자동으로 집음") +local held = 0 +for _, ch in charModel:GetChildren() do + if string.sub(ch.Name, 1, 5) == "Dish_" then + held += 1 + end +end +eq(held, 1, "손에 접시 모형") +c2:update(3) +local seat = c2.shop.customers[1].seat +local PlotBuilder = require(Server.PlotBuilder) +hrp.CFrame = PlotBuilder.seatCFrame(slots[2].cf, seat) + Vector3.new(0, 2, 2) +local before = c2.shop.money +c2:update(3.2) +check(c2.shop.money > before, "손님 근처에서 자동 서빙") +-- 리스폰: 손에 든 접시 모형 다시 만들기 +c2:update(4) +c2:update(4.1) +c2:rebuildHand() +c2:destroy() +eq(#slots[2].refs.dynamic:GetChildren(), 0, "나가면 가게 비움") +eq(slots[2].refs.stove:GetAttribute("OwnerId"), nil, "조리대 주인 해제") +charModel:Destroy() + +section("결제(ProfileStore Mock + Receipts)") +local ProfileStore = require(ServerScriptService.Vendor.ProfileStore) +local Receipts = require(Server.Receipts) +local store = ProfileStore.New("CloudTest", Data.TEMPLATE) +local prof = store.Mock:StartSessionAsync("Player_1") +check(prof ~= nil, "Mock 세션") +local grants = 0 +local decision = Receipts.process(prof, "purchase-1", function() + grants += 1 + prof.Data.Money += 100 + return true +end) +eq(decision, "Granted", "첫 결제 지급") +local decision2 = Receipts.process(prof, "purchase-1", function() + grants += 1 + return true +end) +eq(decision2, "Granted", "재시도 완료 응답") +eq(grants, 1, "한 번만 지급") +eq(prof.Data.Money, 100, "Mock 돈") +prof:EndSession() + +section("실제 DataStore 세션") +local live = ProfileStore.New("CloudTest_v1", Data.TEMPLATE) +local lp = live:StartSessionAsync("Player_test", { + Cancel = function() + return false + end, +}) +check(lp ~= nil, "실제 저장소 세션 시작") +if lp then + lp.Data.Money += 1 + lp:Save() + lp:EndSession() +end + +section("Game.processReceipt(플레이어 없음)") +local Game = require(Server.Game) +eq( + Game.processReceipt({ PlayerId = 1, PurchaseId = "x", ProductId = 1 }), + Enum.ProductPurchaseDecision.NotProcessedYet, + "플레이어가 없으면 나중에" +) + +section("화면 UI(서버에서 생성)") +local Hud = require(StarterPlayer.StarterPlayerScripts.Client.Hud) +local state = Instance.new("Folder") +state:SetAttribute("Lang", "ko") +state:SetAttribute("Money", 25) +state:SetAttribute("Bought", 1) +state:SetAttribute("Tut", 3) +local sent = {} +local holder = Instance.new("Folder") +local hud = Hud.build(holder, state, function(kind, arg) + table.insert(sent, { kind, arg }) +end) +local root = hud.gui:FindFirstChild("Root") :: Frame +local moneyText = root:FindFirstChild("Money"):FindFirstChild("Text") :: TextLabel +eq(moneyText.Text, "💰 25원", "돈 표시") +local nextTitle = root:FindFirstChild("Next"):FindFirstChild("Title") :: TextLabel +eq(nextTitle.Text, "다음: 김밥 해금", "다음 업그레이드") +check((root:FindFirstChild("Hint") :: Frame).Visible, "튜토리얼 안내 보임") +state:SetAttribute("Lang", "en") +eq(moneyText.Text, "💰 ₩25", "영어 돈 표시") +eq(nextTitle.Text, "Next: Unlock Gimbap", "영어 다음 업그레이드") +state:SetAttribute("Bought", #Economy.PURCHASES) +check(not (root:FindFirstChild("Next"):FindFirstChild("Buy") :: TextButton).Visible, "다 사면 사기 버튼 숨김") +check(not (root:FindFirstChild("Dev") :: Frame).Visible, "개발자 버튼은 기본으로 숨김") +state:SetAttribute("Dev", true) +check((root:FindFirstChild("Dev") :: Frame).Visible, "게임 주인에게 개발자 버튼") +check((root:FindFirstChild("Double") :: TextButton).Visible, "2배 수익 버튼(상품 ID 설정됨)") +hud.notify("purchased", { name = "X" }) +hud.setScale(Hud.scaleFor(Vector2.new(844, 390))) +hud.destroy() + +section("조리 버튼(클라이언트 모듈)") +local Stove = require(StarterPlayer.StarterPlayerScripts.Client.Stove) +local stove = slots[3].refs.stove +local pstate = Instance.new("Folder") +pstate:SetAttribute("Lang", "ko") +local prompt = Stove.attach(stove, pstate, function() end) +check(not prompt.Enabled, "주문 없으면 버튼 꺼짐") +stove:SetAttribute("CookMenu", "Gimbap") +stove:SetAttribute("CookTime", 1.5) +check(prompt.Enabled, "주문 있으면 버튼 켜짐") +eq(prompt.ActionText, "🍙 김밥 만들기", "버튼 글자") +eq(prompt.HoldDuration, 1.5, "누르는 시간") +prompt:Destroy() + +section("Products") +local Products = require(ReplicatedStorage.Shared.Products) +local MarketplaceService = game:GetService("MarketplaceService") +if Products.DOUBLE_MONEY_PASS ~= 0 then + local info = MarketplaceService:GetProductInfoAsync(Products.DOUBLE_MONEY_PASS, Enum.InfoType.GamePass) + print("게임패스", info.Name, info.PriceInRobux, info.IsForSale) + check(info.IsForSale, "2배 수익 판매 중") +end +if Products.MONEY_BOOST_PRODUCT ~= 0 then + local info = MarketplaceService:GetProductInfoAsync(Products.MONEY_BOOST_PRODUCT, Enum.InfoType.Product) + print("개발자 상품", info.Name, info.PriceInRobux) + check(info.PriceInRobux ~= nil, "돈 부스트 가격") +end + +c:destroy() + +section("Game.start(실제 서버 시작 순서)") +local okStart, errStart = pcall(Game.start) +check(okStart, `Game.start 오류 없음 ({errStart})`) +task.wait(1) +eq(#workspace.BunsikWorld.Plots:GetChildren(), 6, "시작 후 부지 6칸") + +print(`통합 테스트: {count - #failures}/{count} 통과`) +if #failures > 0 then + error(`{#failures} failed: ` .. table.concat(failures, " | ")) +end +return { passed = count } diff --git a/bunsik-tycoon/tools/art.py b/bunsik-tycoon/tools/art.py new file mode 100644 index 0000000..e434cc9 --- /dev/null +++ b/bunsik-tycoon/tools/art.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""게임패스·개발자 상품 아이콘(512x512 PNG)을 그립니다. 외부 그림을 쓰지 않아 저작권 걱정이 없습니다. + + python3 tools/art.py # art/*.png 생성 +""" +import math +import os + +from PIL import Image, ImageDraw, ImageFilter, ImageFont + +OUT = os.path.join(os.path.dirname(__file__), "..", "art") +BOLD = "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" +S = 512 + + +def font(size): + return ImageFont.truetype(BOLD, size, index=1) # KR + + +def background(c1, c2): + img = Image.new("RGBA", (S, S)) + d = ImageDraw.Draw(img) + for y in range(S): + t = y / S + col = tuple(int(c1[i] * (1 - t) + c2[i] * t) for i in range(3)) + (255,) + d.line([(0, y), (S, y)], fill=col) + # 햇살 무늬 + rays = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + rd = ImageDraw.Draw(rays) + for i in range(16): + a0 = i * math.pi / 8 + a1 = a0 + math.pi / 16 + rd.polygon([(S / 2, S / 2), (S / 2 + 800 * math.cos(a0), S / 2 + 800 * math.sin(a0)), + (S / 2 + 800 * math.cos(a1), S / 2 + 800 * math.sin(a1))], fill=(255, 255, 255, 40)) + img.alpha_composite(rays) + mask = Image.new("L", (S, S), 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, S - 1, S - 1], radius=90, fill=255) + out = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + out.paste(img, (0, 0), mask) + return out + + +def coin(d, cx, cy, r): + d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(255, 200, 40), outline=(190, 120, 10), width=max(4, r // 8)) + d.ellipse([cx - r * 0.65, cy - r * 0.65, cx + r * 0.65, cy + r * 0.65], outline=(230, 160, 20), width=max(3, r // 12)) + f = font(int(r * 1.0)) + d.text((cx, cy - r * 0.05), "₩", font=f, fill=(190, 120, 10), anchor="mm") + + +def outlined(d, xy, text, f, fill, stroke, width): + d.text(xy, text, font=f, fill=fill, anchor="mm", stroke_width=width, stroke_fill=stroke) + + +def shadow(img): + sh = img.copy().filter(ImageFilter.GaussianBlur(6)) + return sh + + +def double_money(): + img = background((170, 90, 230), (90, 40, 170)) + d = ImageDraw.Draw(img) + for (x, y, r) in [(140, 330, 80), (370, 350, 70), (255, 395, 90)]: + coin(d, x, y, r) + outlined(d, (256, 190), "x2", font(250), (255, 230, 60), (90, 30, 120), 14) + return img + + +def money_boost(): + img = background((255, 190, 60), (240, 110, 30)) + d = ImageDraw.Draw(img) + for (x, y, r) in [(130, 380, 70), (385, 380, 70), (256, 410, 80)]: + coin(d, x, y, r) + bolt = [(290, 40), (150, 270), (245, 270), (205, 430), (360, 200), (265, 200), (320, 40)] + d.polygon(bolt, fill=(255, 250, 120), outline=(160, 70, 0)) + d.line(bolt + [bolt[0]], fill=(160, 70, 0), width=12, joint="curve") + return img + + +def main(): + os.makedirs(OUT, exist_ok=True) + for name, fn in [("double_money", double_money), ("money_boost", money_boost)]: + path = os.path.join(OUT, name + ".png") + fn().save(path) + print(path) + + +if __name__ == "__main__": + main() diff --git a/bunsik-tycoon/tools/check.sh b/bunsik-tycoon/tools/check.sh index 1bedbe8..672f9f5 100755 --- a/bunsik-tycoon/tools/check.sh +++ b/bunsik-tycoon/tools/check.sh @@ -1,11 +1,22 @@ #!/usr/bin/env bash -# 코드 스타일·린트·단위 테스트·빌드를 한 번에 돌립니다. 실패하면 0이 아닌 값으로 끝납니다. +# 코드 스타일·린트·타입 검사·단위 테스트·빌드를 한 번에 돌립니다. 실패하면 0이 아닌 값으로 끝납니다. set -euo pipefail cd "$(dirname "$0")/.." export PATH="$HOME/.rokit/bin:$PATH" -stylua --check src tests +stylua --check src tests tools selene src +mkdir -p .cache build +if [ ! -s .cache/globalTypes.d.luau ]; then + curl -sfL https://raw.githubusercontent.com/JohnnyMorganz/luau-lsp/main/scripts/globalTypes.d.luau -o .cache/globalTypes.d.luau +fi +rojo sourcemap default.project.json -o .cache/sourcemap.json +out=$(luau-lsp analyze --platform=roblox --sourcemap=.cache/sourcemap.json \ + --definitions=@roblox=.cache/globalTypes.d.luau --ignore="vendor/**" src 2>&1 | grep -v '^\[' || true) +if [ -n "$out" ]; then + echo "$out" + exit 1 +fi for t in tests/*.spec.luau; do lune run "$t"; done -mkdir -p build rojo build default.project.json -o build/BunsikTycoon.rbxl +echo "check: OK" diff --git a/bunsik-tycoon/tools/cloud.py b/bunsik-tycoon/tools/cloud.py new file mode 100644 index 0000000..b90a495 --- /dev/null +++ b/bunsik-tycoon/tools/cloud.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Open Cloud 도구: 게임 파일 업로드, 로블록스 서버에서 Luau 실행. + + python3 tools/cloud.py publish build/BunsikTycoon.rbxl [--published] + python3 tools/cloud.py run script.luau [--version N] # 기본: 가장 최근 저장 버전 + python3 tools/cloud.py products # 게임패스·개발자 상품 만들기(이미 있으면 건너뜀) + python3 tools/cloud.py place # 서버 인원 6명, 설명 설정 + +API 키는 ~/.config/ejclaw/secrets.json 의 roblox.opencloud/bunsik-tycoon 에서 읽습니다. +""" +import json +import os +import sys +import time +import urllib.error +import urllib.request + +UNIVERSE = 10770390863 +PLACE = 98118751156219 +SECRETS = os.path.expanduser("~/.config/ejclaw/secrets.json") + + +def api_key(): + with open(SECRETS) as f: + return json.load(f)["credentials"]["roblox.opencloud/bunsik-tycoon"]["token"] + + +def request(method, url, body=None, ctype="application/json", tries=5): + data = body + if body is not None and ctype == "application/json": + data = json.dumps(body).encode() + for attempt in range(tries): + req = urllib.request.Request(url, data=data, method=method) + req.add_header("x-api-key", api_key()) + if data is not None: + req.add_header("Content-Type", ctype) + try: + with urllib.request.urlopen(req, timeout=120) as r: + raw = r.read() + return json.loads(raw) if raw else {} + except urllib.error.HTTPError as e: + msg = e.read().decode(errors="replace") + if e.code in (429, 500, 502, 503, 504) and attempt < tries - 1: + time.sleep(5 * (attempt + 1)) + continue + raise SystemExit(f"HTTP {e.code} {method} {url}\n{msg}") + + +def publish(path, published=False): + vt = "Published" if published else "Saved" + with open(path, "rb") as f: + body = f.read() + url = f"https://apis.roblox.com/universes/v1/{UNIVERSE}/places/{PLACE}/versions?versionType={vt}" + res = request("POST", url, body, "application/octet-stream") + return res["versionNumber"] + + +def run(script, version=None, timeout_s=300): + base = f"https://apis.roblox.com/cloud/v2/universes/{UNIVERSE}/places/{PLACE}" + if version: + base += f"/versions/{version}" + task = request("POST", base + "/luau-execution-session-tasks", {"script": script, "timeout": f"{timeout_s}s"}) + path = task["path"] + while task.get("state") not in ("COMPLETE", "FAILED", "CANCELLED"): + time.sleep(3) + task = request("GET", f"https://apis.roblox.com/cloud/v2/{path}") + logs = request("GET", f"https://apis.roblox.com/cloud/v2/{path}/logs?maxPageSize=10000") + lines = [] + for page in logs.get("luauExecutionSessionTaskLogs", []): + lines.extend(page.get("messages", [])) + return task, lines + + +def multipart(fields, files): + boundary = "----bunsik" + str(int(time.time() * 1000)) + out = b"" + for k, v in fields.items(): + out += f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode() + for k, path in files.items(): + with open(path, "rb") as f: + data = f.read() + name = os.path.basename(path) + out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"; filename=\"{name}\"\r\n" + f"Content-Type: image/png\r\n\r\n").encode() + data + b"\r\n" + out += f"--{boundary}--\r\n".encode() + return out, f"multipart/form-data; boundary={boundary}" + + +ART = os.path.join(os.path.dirname(__file__), "..", "art") +PRODUCTS = [ + # (종류, 이름, 설명, 가격, 그림, Products.luau 키) + ("game-passes", "Double Money (2배 수익)", + "All sales are doubled forever! 모든 판매 금액이 영원히 2배!", 199, "double_money.png", "DOUBLE_MONEY_PASS"), + ("developer-products", "Money Boost (돈 부스트)", + "Get 10 minutes of your current sales right now. 지금 매출 10분치를 바로 받아요.", 25, "money_boost.png", + "MONEY_BOOST_PRODUCT"), +] + + +def products(): + found = {} + for kind, name, desc, price, image, key in PRODUCTS: + if kind == "game-passes": + base = f"https://apis.roblox.com/game-passes/v1/universes/{UNIVERSE}/game-passes" + listing = request("GET", base + "/creator?pageSize=100") + items = listing.get("gamePasses", []) + id_key = "gamePassId" + else: + base = f"https://apis.roblox.com/developer-products/v2/universes/{UNIVERSE}/developer-products" + listing = request("GET", base + "/creator?pageSize=100") + items = listing.get("developerProducts", []) + id_key = "productId" + existing = [i for i in items if i.get("name") == name] + if existing: + found[key] = existing[0][id_key] + print(f"{key}: 이미 있음 {found[key]}") + continue + body, ctype = multipart( + {"name": name, "description": desc, "price": str(price), "isForSale": "true", + "isRegionalPricingEnabled": "false"}, + {"imageFile": os.path.join(ART, image)}, + ) + res = request("POST", base, body, ctype) + found[key] = res[id_key] + print(f"{key}: 만듦 {found[key]}") + return found + + +def place(): + url = (f"https://apis.roblox.com/cloud/v2/universes/{UNIVERSE}/places/{PLACE}" + "?updateMask=serverSize,description") + body = { + "serverSize": 6, + "description": "떡볶이 포장마차에서 시작해 분식 제국을 키우는 타이쿤! " + "Grow your tiny tteokbokki street stall into a K-food empire!", + } + return request("PATCH", url, body) + + +def main(argv): + if argv[:1] == ["products"]: + print(json.dumps(products())) + return 0 + if argv[:1] == ["place"]: + print(json.dumps(place(), ensure_ascii=False)) + return 0 + if len(argv) >= 2 and argv[0] == "publish": + v = publish(argv[1], "--published" in argv) + print(f"version {v}") + return 0 + if len(argv) >= 2 and argv[0] == "run": + version = None + if "--version" in argv: + version = int(argv[argv.index("--version") + 1]) + with open(argv[1]) as f: + script = f.read() + task, lines = run(script, version) + for line in lines: + print(line) + print(f"state: {task['state']}") + if task["state"] == "COMPLETE": + print("output:", json.dumps(task.get("output", {}), ensure_ascii=False)) + return 0 + print("error:", json.dumps(task.get("error", {}), ensure_ascii=False)) + return 1 + print(__doc__) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/bunsik-tycoon/tools/economy_sim.py b/bunsik-tycoon/tools/economy_sim.py deleted file mode 100644 index ff43925..0000000 --- a/bunsik-tycoon/tools/economy_sim.py +++ /dev/null @@ -1,93 +0,0 @@ -"""분식집 타이쿤 첫 10분 경제 시뮬레이터. - -ECONOMY.md 표의 숫자를 바꾸면 이 파일의 표도 같이 바꾸고 다시 돌려서 -구매 시점이 목표 범위에 드는지 확인한다. - - python3 bunsik-tycoon/tools/economy_sim.py # 기본 - python3 bunsik-tycoon/tools/economy_sim.py --x2 # 2배 수익 게임패스 - -모델(1초 단위, 결정적): -- 손님은 SPAWN초마다 1명 오고, 빈자리가 없으면 돌아간다. -- 플레이어는 한 번에 한 접시: 조리(cook초) + 왕복(WALK초) 후 서빙. -- 접시가 도착하면 바로 계산되고, 손님은 EAT초 먹고 나간다. 자리는 그때 빈다. -- 알바생을 고용하면 조리는 알바생이 하고 플레이어는 나르기만 한다. -- 돈이 다음 구매 비용 이상이 되면 즉시 산다(가장 빠른 플레이어 기준). -""" -import sys - -WALK = 5 # 조리대 -> 테이블 -> 조리대 왕복(초) -EAT = 6 # 먹는 시간(초) - -MENUS = {"떡볶이": 10, "김밥": 20, "순대": 35} # 한 접시 기본 가격 - -# (이름, 비용, 효과) seats=테이블 수, spawn=손님 간격(초), cook=조리 시간(초), -# price=가격 배율, helper=알바생(조리 자동) -PURCHASES = [ - ("테이블 2", 10, {"seats": 2}), - ("김밥 해금", 40, {"menu": "김밥"}), - ("간판 Lv1", 70, {"spawn": 5}), - ("화구 Lv1", 90, {"cook": 1.5}), - ("테이블 3", 120, {"seats": 3}), - ("순대 해금", 160, {"menu": "순대"}), - ("양념 비법 Lv1", 240, {"price": 1.5}), - ("알바생 고용", 360, {"helper": True}), - ("테이블 4", 480, {"seats": 4, "spawn": 4}), - ("실내 분식집 확장", 600, {}), -] - - -def simulate(mult=1.0, limit=1200): - st = {"seats": 1, "spawn": 6, "cook": 2.5, "helper": False, "price": 1.0, - "menus": ["떡볶이"]} - money = 0.0 - t = 0 - next_spawn = 0 - waiting = [] # 주문하고 기다리는 손님 수(카운트) - eating = [] # 식사 끝나는 시각 목록 - busy_until = 0 # 들고 있는 접시가 손님에게 도착하는 시각 - carrying = None # 들고 있는 접시 가격 - menu_i = 0 - log = [] - nxt = 0 - while t < limit and nxt < len(PURCHASES): - # 식사 끝난 손님 퇴장(자리 반환) - eating = [e for e in eating if e > t] - # 손님 입장 - if t >= next_spawn: - if len(waiting) + len(eating) + (carrying is not None) < st["seats"]: - waiting.append(t) - next_spawn = t + st["spawn"] - # 배달 완료 -> 계산 - if carrying is not None and t >= busy_until: - money += carrying * st["price"] * mult - eating.append(t + EAT) - carrying = None - # 다음 접시 시작 - if carrying is None and waiting: - waiting.pop(0) - cook = 0 if st["helper"] else st["cook"] - busy_until = t + cook + WALK - carrying = MENUS[st["menus"][menu_i % len(st["menus"])]] - menu_i += 1 - # 구매 - name, cost, eff = PURCHASES[nxt] - if money >= cost: - money -= cost - if "menu" in eff: - st["menus"].append(eff["menu"]) - for k in ("seats", "spawn", "cook", "helper", "price"): - if k in eff: - st[k] = eff[k] - log.append((t, name, cost)) - nxt += 1 - t += 1 - return log - - -if __name__ == "__main__": - mult = 2.0 if "--x2" in sys.argv else 1.0 - prev = 0 - print(f"수익 배율 x{mult:g}") - for t, name, cost in simulate(mult): - print(f"{t//60:2d}:{t%60:02d} (+{t-prev:3d}s) {name:<12} {cost:>5}원") - prev = t diff --git a/bunsik-tycoon/tools/sim.luau b/bunsik-tycoon/tools/sim.luau new file mode 100644 index 0000000..5d80f8e --- /dev/null +++ b/bunsik-tycoon/tools/sim.luau @@ -0,0 +1,14 @@ +-- 경제 시뮬레이터 실행 +-- lune run tools/sim.luau # 기본 +-- lune run tools/sim.luau x2 # 2배 수익 게임패스 +local process = require("@lune/process") +local Sim = require("./simlib") + +local mult = if table.find(process.args, "x2") then 2 else 1 +print(`수익 배율 x{mult}`) +local prev = 0 +for i, e in Sim.run(mult, 3600) do + local s = math.floor(e.t + 0.5) + print(string.format("%2d %2d:%02d (+%3ds) %-16s %5d", i, s // 60, s % 60, s - prev, e.id, e.cost)) + prev = s +end diff --git a/bunsik-tycoon/tools/simlib.luau b/bunsik-tycoon/tools/simlib.luau new file mode 100644 index 0000000..98a2ee4 --- /dev/null +++ b/bunsik-tycoon/tools/simlib.luau @@ -0,0 +1,61 @@ +-- 경제 시뮬레이터 본체: 실제 게임 로직(src/shared/Shop)을 봇이 쉬지 않고 최적으로 플레이합니다. +-- 실행은 tools/sim.luau, 검사는 tests/Sim.spec.luau +-- 봇 가정: 조리대 <-> 테이블 편도 WALK/2초, 알바생이 있으면 직접 조리하지 않고 나르기만 합니다. +local Economy = require("../src/shared/Economy") +local Shop = require("../src/shared/Shop") + +local Sim = {} + +function Sim.run(mult: number, limit: number): { { t: number, id: string, name: string, cost: number } } + local shop = Shop.new(0, 0, 0) + shop.moneyMult = mult + local dt = 0.1 + local t = 0 + local at = "stove" + local busyUntil = 0 + local pending: string? = nil -- 끝나면 할 일: "cook" | "arrive_tables" | "arrive_stove" + local log = {} + while t < limit and Shop.nextPurchase(shop) do + Shop.tick(shop, t) + if t >= busyUntil then + if pending == "cook" then + Shop.cook(shop) + elseif pending == "arrive_tables" then + at = "tables" + elseif pending == "arrive_stove" then + at = "stove" + end + pending = nil + if at == "stove" then + Shop.pickup(shop) + local canCook = not shop.stats.helper and not Shop.handFull(shop) and Shop.nextCookMenu(shop) ~= nil + if canCook then + pending = "cook" + busyUntil = t + shop.stats.cook + elseif #shop.hand > 0 and (Shop.handFull(shop) or #shop.counter == 0) then + pending = "arrive_tables" + busyUntil = t + Economy.WALK / 2 + end + else + for id, c in shop.customers do + if c.state == "waiting" then + Shop.serve(shop, id) + end + end + if #shop.hand == 0 then + pending = "arrive_stove" + busyUntil = t + Economy.WALK / 2 + end + end + end + local p = Shop.nextPurchase(shop) + if p and shop.money >= p.cost then + Shop.buyNext(shop) + table.insert(log, { t = t, id = p.id, name = p.name, cost = p.cost }) + end + t += dt + end + return log +end + +return Sim diff --git a/bunsik-tycoon/vendor/ProfileStore.LICENSE.txt b/bunsik-tycoon/vendor/ProfileStore.LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/bunsik-tycoon/vendor/ProfileStore.LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/bunsik-tycoon/vendor/ProfileStore.luau b/bunsik-tycoon/vendor/ProfileStore.luau new file mode 100644 index 0000000..5b196af --- /dev/null +++ b/bunsik-tycoon/vendor/ProfileStore.luau @@ -0,0 +1,2243 @@ +--[[ +MAD STUDIO (by loleris) + +-[ProfileStore]--------------------------------------- + + Periodic DataStore saving solution with session locking + + WARNINGS FOR "Profile.Data" VALUES: + ! Do not create numeric tables with gaps - attempting to store such tables will result in an error. + ! Do not create mixed tables (some values indexed by number and others by a string key) + - only numerically indexed data will be stored. + ! Do not index tables by anything other than numbers and strings. + ! Do not reference Roblox Instances + ! Do not reference userdata (Vector3, Color3, CFrame...) - Serialize userdata before referencing + ! Do not reference functions + + Members: + + ProfileStore.IsClosing [bool] + -- Set to true after a game:BindToClose() trigger + + ProfileStore.IsCriticalState [bool] + -- Set to true when ProfileStore experiences too many consecutive errors + + ProfileStore.OnError [Signal] (message, store_name, profile_key) + -- Most ProfileStore errors will be caught and passed to this signal + + ProfileStore.OnOverwrite [Signal] (store_name, profile_key) + -- Triggered when a DataStore key was likely used to store data that wasn't + a ProfileStore profile or the ProfileStore structure was invalidly manually + altered for that DataStore key + + ProfileStore.OnCriticalToggle [Signal] (is_critical) + -- Triggered when ProfileStore experiences too many consecutive errors + + ProfileStore.DataStoreState [string] ("NotReady", "NoInternet", "NoAccess", "Access") + -- This value resembles ProfileStore's access to the DataStore; The value starts + as "NotReady" and will eventually change to one of the other 3 possible values. + + Functions: + + ProfileStore.New(store_name, template?) --> [ProfileStore] + store_name [string] -- DataStore name + template [table] or nil -- Profiles will default to given table (hard-copy) when no data was saved previously + + ProfileStore.SetConstant(name, value) + name [string] + value [number] + + Members [ProfileStore]: + + ProfileStore.Mock [ProfileStore] + -- Reflection of ProfileStore methods, but the methods will now query a mock + DataStore with no relation to the real DataStore + + ProfileStore.Name [string] + + Methods [ProfileStore]: + + ProfileStore:StartSessionAsync(profile_key, params?) --> [Profile] or nil + profile_key [string] -- DataStore key + params nil or [table]: -- Custom params; E.g. {Steal = true} + { + Steal = true, -- Pass this to disregard an existing session lock + Cancel = fn() -> (boolean), -- Pass this to create a request cancel condition. + -- If the cancel function returns true, ProfileStore will stop trying to + -- start the session and return nil + } + + ProfileStore:MessageAsync(profile_key, message) --> is_success [bool] + profile_key [string] -- DataStore key + message [table] -- Data to be messaged to the profile + + ProfileStore:GetAsync(profile_key, version?) --> [Profile] or nil + -- Reads a profile without starting a session - will not autosave + profile_key [string] -- DataStore key + version nil or [string] -- DataStore key version + + ProfileStore:VersionQuery(profile_key, sort_direction?, min_date?, max_date?) --> [VersionQuery] + profile_key [string] + sort_direction nil or [Enum.SortDirection] + min_date nil or [DateTime] + max_date nil or [DateTime] + + ProfileStore:RemoveAsync(profile_key) --> is_success [bool] + -- Completely removes profile data from the DataStore / mock DataStore with no way to recover it. + + Methods [VersionQuery]: + + VersionQuery:NextAsync() --> [Profile] or nil -- (Yields) + -- Returned profile is similar to profiles returned by ProfileStore:GetAsync() + + Members [Profile]: + + Profile.Data [table] + -- When the profile is active changes to this table are guaranteed to be saved + Profile.LastSavedData [table] (Read-only) + -- Last snapshot of "Profile.Data" that has been successfully saved to the DataStore; + Useful for proper developer product purchase receipt handling + + Profile.FirstSessionTime [number] (Read-only) + -- os.time() timestamp of the first profile session + + Profile.SessionLoadCount [number] (Read-only) -- Amount of times a session was started for this profile + + Profile.Session [table] (Read-only) {PlaceId = number, JobId = string} / nil + -- Set to a table if this profile is in use by a server; nil if released + + Profile.RobloxMetaData [table] -- Writable table that gets saved automatically and once the profile is released + Profile.UserIds [table] -- (Read-only) -- {user_id [number], ...} -- User ids associated with this profile + + Profile.KeyInfo [DataStoreKeyInfo] -- Changes before OnAfterSave signal + + Profile.OnSave [Signal] () + -- Triggered right before changes to Profile.Data are saved to the DataStore + + Profile.OnLastSave [Signal] (reason [string]: "Manual", "External", "Shutdown") + -- Triggered right before changes to Profile.Data are saved to the DataStore + for the last time; A reason is provided for the last save: + - "Manual" - Profile:EndSession() was called + - "Shutdown" - The server that has ownership of this profile is shutting down + - "External" - Another server has started a session for this profile + Note that this event will not trigger for when a profile session is ended by + another server trying to take ownership of the session - this is impossible to + do without compromising on ProfileStore's speed. + + Profile.OnSessionEnd [Signal] () + -- Triggered when the profile session is terminated on this server + + Profile.OnAfterSave [Signal] (last_saved_data) + -- Triggered after a successful save + last_saved_data [table] -- Profile.LastSavedData + + Profile.ProfileStore [ProfileStore] -- ProfileStore object this profile belongs to + Profile.Key [string] -- DataStore key + + Methods [Profile]: + + Profile:IsActive() --> [bool] -- If "true" is returned, changes to Profile.Data are guaranteed to save; + This guarantee is only valid until code yields (e.g. task.wait() is used). + + Profile:Reconcile() -- Fills in missing (nil) [string_key] = [value] pairs to the Profile.Data structure + from the "template" argument that was passed to "ProfileStore.New()" + + Profile:EndSession() -- Call after the server has finished working with this profile + e.g., after the player leaves (Profile object will become inactive) + + Profile:AddUserId(user_id) -- Associates user_id with profile (GDPR compliance) + user_id [number] + + Profile:RemoveUserId(user_id) -- Removes user_id association with profile (safe function) + user_id [number] + + Profile:MessageHandler(fn) -- Sets a message handler for this profile + fn [function] (message [table], processed [function]()) + -- The handler function receives a message table and a callback function; + The callback function is to be called when a message has been processed + - this will discard the message from the profile message cache; If the + callback function is not called, other message handlers will also be triggered + with unprocessed message data. + + Profile:Save() -- If the profile session is still active makes an UpdateAsync call + to the DataStore to immediately save profile data + + Profile:SetAsync() -- Forcefully saves changes to the profile; Only for profiles + loaded with ProfileStore:GetAsync() or ProfileStore:VersionQuery() + +--]] + +local AUTO_SAVE_PERIOD = 300 -- (Seconds) Time between when changes to a profile are saved to the DataStore +local LOAD_REPEAT_PERIOD = 10 -- (Seconds) Time between successive profile reads when handling a session conflict +local FIRST_LOAD_REPEAT = 5 -- (Seconds) Time between first and second profile read when handling a session conflict +local SESSION_STEAL = 40 -- (Seconds) Time until a session conflict is resolved with the waiting server stealing the session +local ASSUME_DEAD = 630 -- (Seconds) If a profile hasn't had updates for this long, quickly assume an active session belongs to a crashed server +local START_SESSION_TIMEOUT = 120 -- (Seconds) If a session can't be started for a profile for this long, stop repeating calls to the DataStore + +local CRITICAL_STATE_ERROR_COUNT = 5 -- Assume critical state if this many issues happen in a short amount of time +local CRITICAL_STATE_ERROR_EXPIRE = 120 -- (Seconds) Individual issue expiration +local CRITICAL_STATE_EXPIRE = 120 -- (Seconds) Critical state expiration + +local MAX_MESSAGE_QUEUE = 1000 -- Max messages saved in a profile that were sent using "ProfileStore:MessageAsync()" + +----- Dependencies ----- + +-- local Util = require(game.ReplicatedStorage.Shared.Util) +-- local Signal = Util.Signal + +local Signal do + + local FreeRunnerThread + + --[[ + Yield-safe coroutine reusing by stravant; + Sources: + https://devforum.roblox.com/t/lua-signal-class-comparison-optimal-goodsignal-class/1387063 + https://gist.github.com/stravant/b75a322e0919d60dde8a0316d1f09d2f + --]] + + local function AcquireRunnerThreadAndCallEventHandler(fn, ...) + local acquired_runner_thread = FreeRunnerThread + FreeRunnerThread = nil + fn(...) + -- The handler finished running, this runner thread is free again. + FreeRunnerThread = acquired_runner_thread + end + + local function RunEventHandlerInFreeThread(...) + AcquireRunnerThreadAndCallEventHandler(...) + while true do + AcquireRunnerThreadAndCallEventHandler(coroutine.yield()) + end + end + + local Connection = {} + Connection.__index = Connection + + local SignalClass = {} + SignalClass.__index = SignalClass + + function Connection:Disconnect() + + if self.is_connected == false then + return + end + + local signal = self.signal + self.is_connected = false + signal.listener_count -= 1 + + if signal.head == self then + signal.head = self.next + else + local prev = signal.head + while prev ~= nil and prev.next ~= self do + prev = prev.next + end + if prev ~= nil then + prev.next = self.next + end + end + + end + + function SignalClass.New() + + local self = { + head = nil, + listener_count = 0, + } + setmetatable(self, SignalClass) + + return self + + end + + function SignalClass:Connect(listener: (...any) -> ()) + + if type(listener) ~= "function" then + error(`[{script.Name}]: \"listener\" must be a function; Received {typeof(listener)}`) + end + + local connection = { + listener = listener, + signal = self, + next = self.head, + is_connected = true, + } + setmetatable(connection, Connection) + + self.head = connection + self.listener_count += 1 + + return connection + + end + + function SignalClass:GetListenerCount(): number + return self.listener_count + end + + function SignalClass:Fire(...) + local item = self.head + while item ~= nil do + if item.is_connected == true then + if not FreeRunnerThread then + FreeRunnerThread = coroutine.create(RunEventHandlerInFreeThread) + end + task.spawn(FreeRunnerThread, item.listener, ...) + end + item = item.next + end + end + + function SignalClass:Wait() + local co = coroutine.running() + local connection + connection = self:Connect(function(...) + connection:Disconnect() + task.spawn(co, ...) + end) + return coroutine.yield() + end + + Signal = table.freeze({ + New = SignalClass.New, + }) + +end + +----- Private ----- + +local ActiveSessionCheck = {} -- {[session_token] = profile, ...} +local AutoSaveList = {} -- {profile, ...} -- Loaded profile table which will be circularly auto-saved +local IssueQueue = {} -- {issue_time, ...} + +local DataStoreService = game:GetService("DataStoreService") +local MessagingService = game:GetService("MessagingService") +local HttpService = game:GetService("HttpService") +local RunService = game:GetService("RunService") + +local PlaceId = game.PlaceId +local JobId = game.JobId + +local AutoSaveIndex = 1 -- Next profile to auto save +local LastAutoSave = os.clock() + +local LoadIndex = 0 + +local ActiveProfileLoadJobs = 0 -- Number of active threads that are loading in profiles +local ActiveProfileSaveJobs = 0 -- Number of active threads that are saving profiles + +local CriticalStateStart = 0 -- os.clock() + +local IsStudio = RunService:IsStudio() +local DataStoreState: "NotReady" | "NoInternet" | "NoAccess" | "Access" = "NotReady" + +local MockStore = {} +local UserMockStore = {} +local MockFlag = false + +local OnError = Signal.New() -- (message, store_name, profile_key) +local OnOverwrite = Signal.New() -- (store_name, profile_key) + +local UpdateQueue = { -- For stability sake, we won't do UpdateAsync calls for the same key until all previous calls finish + --[[ + [session_token] = { + coroutine, ... + }, + ... + --]] +} + +local function WaitInUpdateQueue(session_token) --> next_in_queue() + + local is_first = false + + if UpdateQueue[session_token] == nil then + is_first = true + UpdateQueue[session_token] = {} + end + + local queue = UpdateQueue[session_token] + + if is_first == false then + table.insert(queue, coroutine.running()) + coroutine.yield() + end + + return function() + local next_co = table.remove(queue, 1) + if next_co ~= nil then + coroutine.resume(next_co) + else + UpdateQueue[session_token] = nil + end + end + +end + +local function SessionToken(store_name, profile_key, is_mock) + + local session_token = "L_" -- Live + + if is_mock == true then + session_token = "U_" -- User mock + elseif DataStoreState ~= "Access" then + session_token = "M_" -- Mock, cause no DataStore access + end + + session_token ..= store_name .. "\0" .. profile_key + + return session_token + +end + +local function DeepCopyTable(t) + local copy = {} + for key, value in pairs(t) do + if type(value) == "table" then + copy[key] = DeepCopyTable(value) + else + copy[key] = value + end + end + return copy +end + +local function ReconcileTable(target, template) + for k, v in pairs(template) do + if type(k) == "string" then -- Only string keys will be reconciled + if target[k] == nil then + if type(v) == "table" then + target[k] = DeepCopyTable(v) + else + target[k] = v + end + elseif type(target[k]) == "table" and type(v) == "table" then + ReconcileTable(target[k], v) + end + end + end +end + +local function RegisterError(error_message, store_name, profile_key) -- Called when a DataStore API call errors + warn(`[{script.Name}]: DataStore API error (STORE:{store_name}; KEY:{profile_key}) - {tostring(error_message)}`) + table.insert(IssueQueue, os.clock()) -- Adding issue time to queue + OnError:Fire(tostring(error_message), store_name, profile_key) +end + +local function RegisterOverwrite(store_name, profile_key) -- Called when a corrupted profile is loaded + warn(`[{script.Name}]: Invalid profile was overwritten (STORE:{store_name}; KEY:{profile_key})`) + OnOverwrite:Fire(store_name, profile_key) +end + +local function NewMockDataStoreKeyInfo(params) + + local version_id_string = tostring(params.VersionId or 0) + local meta_data = params.MetaData or {} + local user_ids = params.UserIds or {} + + return { + CreatedTime = params.CreatedTime, + UpdatedTime = params.UpdatedTime, + Version = string.rep("0", 16) .. "." + .. string.rep("0", 10 - string.len(version_id_string)) .. version_id_string + .. "." .. string.rep("0", 16) .. "." .. "01", + + GetMetadata = function() + return DeepCopyTable(meta_data) + end, + + GetUserIds = function() + return DeepCopyTable(user_ids) + end, + } + +end + +local function MockUpdateAsync(mock_data_store, profile_store_name, key, transform_function, is_get_call) --> loaded_data, key_info + + local profile_store = mock_data_store[profile_store_name] + + if profile_store == nil then + profile_store = {} + mock_data_store[profile_store_name] = profile_store + end + + local epoch_time = math.floor(os.time() * 1000) + local mock_entry = profile_store[key] + local mock_entry_was_nil = false + + if mock_entry == nil then + mock_entry_was_nil = true + if is_get_call ~= true then + mock_entry = { + Data = nil, + CreatedTime = epoch_time, + UpdatedTime = epoch_time, + VersionId = 0, + UserIds = {}, + MetaData = {}, + } + profile_store[key] = mock_entry + end + end + + local mock_key_info = mock_entry_was_nil == false and NewMockDataStoreKeyInfo(mock_entry) or nil + + local transform, user_ids, roblox_meta_data = transform_function(mock_entry and mock_entry.Data, mock_key_info) + + if transform == nil then + return nil + else + if mock_entry ~= nil and is_get_call ~= true then + mock_entry.Data = DeepCopyTable(transform) + mock_entry.UserIds = DeepCopyTable(user_ids or {}) + mock_entry.MetaData = DeepCopyTable(roblox_meta_data or {}) + mock_entry.VersionId += 1 + mock_entry.UpdatedTime = epoch_time + end + + return DeepCopyTable(transform), mock_entry ~= nil and NewMockDataStoreKeyInfo(mock_entry) or nil + end + +end + +local function UpdateAsync(profile_store, profile_key, transform_params, is_user_mock, is_get_call, version) --> loaded_data, key_info + --transform_params = { + -- ExistingProfileHandle = function(latest_data), + -- MissingProfileHandle = function(latest_data), + -- EditProfile = function(latest_data), + --} + + local loaded_data, key_info + + local next_in_queue = WaitInUpdateQueue(SessionToken(profile_store.Name, profile_key, is_user_mock)) + + local success = true + + local success, error_message = pcall(function() + local transform_function = function(latest_data) + + local missing_profile = false + local overwritten = false + local global_updates = {0, {}} + + if latest_data == nil then + + missing_profile = true + + elseif type(latest_data) ~= "table" then + + missing_profile = true + overwritten = true + + else + + if type(latest_data.Data) == "table" and type(latest_data.MetaData) == "table" and type(latest_data.GlobalUpdates) == "table" then + + -- Regular profile structure detected: + + latest_data.WasOverwritten = false -- Must be set to false if set previously + global_updates = latest_data.GlobalUpdates + + if transform_params.ExistingProfileHandle ~= nil then + transform_params.ExistingProfileHandle(latest_data) + end + + elseif latest_data.Data == nil and latest_data.MetaData == nil and type(latest_data.GlobalUpdates) == "table" then + + -- Regular structure not detected, but GlobalUpdate data exists: + + latest_data.WasOverwritten = false -- Must be set to false if set previously + global_updates = latest_data.GlobalUpdates or global_updates + missing_profile = true + + else + + missing_profile = true + overwritten = true + + end + + end + + -- Profile was not created or corrupted and no GlobalUpdate data exists: + if missing_profile == true then + latest_data = { + -- Data = nil, + -- MetaData = nil, + GlobalUpdates = global_updates, + } + if transform_params.MissingProfileHandle ~= nil then + transform_params.MissingProfileHandle(latest_data) + end + end + + -- Editing profile: + if transform_params.EditProfile ~= nil then + transform_params.EditProfile(latest_data) + end + + -- Invalid data handling (Silently override with empty profile) + if overwritten == true then + latest_data.WasOverwritten = true -- Temporary tag that will be removed on first save + end + + return latest_data, latest_data.UserIds, latest_data.RobloxMetaData + end + + if is_user_mock == true then -- Used when the profile is accessed through ProfileStore.Mock + + loaded_data, key_info = MockUpdateAsync(UserMockStore, profile_store.Name, profile_key, transform_function, is_get_call) + task.wait() -- Simulate API call yield + + elseif DataStoreState ~= "Access" then -- Used when API access is disabled + + loaded_data, key_info = MockUpdateAsync(MockStore, profile_store.Name, profile_key, transform_function, is_get_call) + task.wait() -- Simulate API call yield + + else + + if is_get_call == true then + + if version ~= nil then + + local success, error_message = pcall(function() + loaded_data, key_info = profile_store.data_store:GetVersionAsync(profile_key, version) + end) + + if success == false and type(error_message) == "string" and string.find(error_message, "not valid") ~= nil then + warn(`[{script.Name}]: Passed version argument is not valid; Traceback:\n` .. debug.traceback()) + end + + else + + loaded_data, key_info = profile_store.data_store:GetAsync(profile_key) + + end + + loaded_data = transform_function(loaded_data) + + else + + loaded_data, key_info = profile_store.data_store:UpdateAsync(profile_key, transform_function) + + end + + end + + end) + + next_in_queue() + + if success == true and type(loaded_data) == "table" then + -- Invalid data handling: + if loaded_data.WasOverwritten == true and is_get_call ~= true then + RegisterOverwrite( + profile_store.Name, + profile_key + ) + end + -- Return loaded_data: + return loaded_data, key_info + else + -- Error handling: + RegisterError( + error_message or "Undefined error", + profile_store.Name, + profile_key + ) + -- Return nothing: + return nil + end + +end + +local function IsThisSession(session_tag) + return session_tag[1] == PlaceId and session_tag[2] == JobId +end + +local function ReadMockFlag(): boolean + local is_mock = MockFlag + MockFlag = false + return is_mock +end + +local function WaitForStoreReady(profile_store) + while profile_store.is_ready == false do + task.wait() + end +end + +local function AddProfileToAutoSave(profile) + + ActiveSessionCheck[profile.session_token] = profile + + -- Add at AutoSaveIndex and move AutoSaveIndex right: + + table.insert(AutoSaveList, AutoSaveIndex, profile) + + if #AutoSaveList > 1 then + AutoSaveIndex = AutoSaveIndex + 1 + elseif #AutoSaveList == 1 then + -- First profile created - make sure it doesn't get immediately auto saved: + LastAutoSave = os.clock() + end + +end + +local function RemoveProfileFromAutoSave(profile) + + ActiveSessionCheck[profile.session_token] = nil + + local auto_save_index = table.find(AutoSaveList, profile) + + if auto_save_index ~= nil then + table.remove(AutoSaveList, auto_save_index) + if auto_save_index < AutoSaveIndex then + AutoSaveIndex = AutoSaveIndex - 1 -- Table contents were moved left before AutoSaveIndex so move AutoSaveIndex left as well + end + if AutoSaveList[AutoSaveIndex] == nil then -- AutoSaveIndex was at the end of the AutoSaveList - reset to 1 + AutoSaveIndex = 1 + end + end + +end + +local function SaveProfileAsync(profile, is_ending_session, is_overwriting, last_save_reason) + + if type(profile.Data) ~= "table" then + error(`[{script.Name}]: Developer code likely set "Profile.Data" to a non-table value! (STORE:{profile.ProfileStore.Name}; KEY:{profile.Key})`) + end + + profile.OnSave:Fire() + if is_ending_session == true then + profile.OnLastSave:Fire(last_save_reason or "Manual") + end + + if is_ending_session == true and is_overwriting ~= true then + if profile.roblox_message_subscription ~= nil then + profile.roblox_message_subscription:Disconnect() + end + RemoveProfileFromAutoSave(profile) + profile.OnSessionEnd:Fire() + end + + ActiveProfileSaveJobs = ActiveProfileSaveJobs + 1 + + -- Compare "SessionLoadCount" when writing to profile to prevent a rare case of repeat last save when the profile is loaded on the same server again + + local repeat_save_flag = true -- Released Profile save calls have to repeat until they succeed + local exp_backoff = 1 + + while repeat_save_flag == true do + + if is_ending_session ~= true then + repeat_save_flag = false + end + + local loaded_data, key_info = UpdateAsync( + profile.ProfileStore, + profile.Key, + { + ExistingProfileHandle = nil, + MissingProfileHandle = nil, + EditProfile = function(latest_data) + + -- Check if this session still owns the profile: + + local session_owns_profile = false + + if is_overwriting ~= true then + + local active_session = latest_data.MetaData.ActiveSession + local session_load_count = latest_data.MetaData.SessionLoadCount + + if type(active_session) == "table" then + session_owns_profile = IsThisSession(active_session) and session_load_count == profile.load_index + end + + else + session_owns_profile = true + end + + -- We may only edit the profile if this server has ownership of the profile: + + if session_owns_profile == true then + + -- Clear processed updates (messages): + + local locked_updates = profile.locked_global_updates -- [index] = true, ... + local active_updates = latest_data.GlobalUpdates[2] + -- ProfileService module format: {{update_id, version_id, update_locked, update_data}, ...} + -- ProfileStore module format: {{update_id, update_data}, ...} + + if next(locked_updates) ~= nil then + local i = 1 + while i <= #active_updates do + local update = active_updates[i] + if locked_updates[update[1]] == true then + table.remove(active_updates, i) + else + i += 1 + end + end + end + + -- Save profile data: + + latest_data.Data = profile.Data + latest_data.RobloxMetaData = profile.RobloxMetaData + latest_data.UserIds = profile.UserIds + + if is_overwriting ~= true then + + latest_data.MetaData.LastUpdate = os.time() + + if is_ending_session == true then + latest_data.MetaData.ActiveSession = nil + end + + else + + latest_data.MetaData.ActiveSession = nil + latest_data.MetaData.ForceLoadSession = nil + + end + + end + + end, + }, + profile.is_mock + ) + + if loaded_data ~= nil and key_info ~= nil then + + if is_overwriting == true then + break + end + + repeat_save_flag = false + + local active_session = loaded_data.MetaData.ActiveSession + local session_load_count = loaded_data.MetaData.SessionLoadCount + local session_owns_profile = false + + if type(active_session) == "table" then + session_owns_profile = IsThisSession(active_session) and session_load_count == profile.load_index + end + + local force_load_session = loaded_data.MetaData.ForceLoadSession + local force_load_pending = false + if type(force_load_session) == "table" then + force_load_pending = not IsThisSession(force_load_session) + end + + local is_active = profile:IsActive() + + -- If another server is trying to start a session for this profile - end the session: + + if force_load_pending == true and session_owns_profile == true then + if is_active == true then + SaveProfileAsync(profile, true, false, "External") + end + break + end + + -- Clearing processed update list / Detecting new updates: + + local locked_updates = profile.locked_global_updates -- [index] = true, ... + local received_updates = profile.received_global_updates -- [index] = true, ... + local active_updates = loaded_data.GlobalUpdates[2] + + local new_updates = {} -- {}, ... + local still_pending = {} -- [index] = true, ... + + for _, update in ipairs(active_updates) do + if locked_updates[update[1]] == true then + still_pending[update[1]] = true + elseif received_updates[update[1]] ~= true then + received_updates[update[1]] = true + table.insert(new_updates, update) + end + end + + for index in pairs(locked_updates) do + if still_pending[index] ~= true then + locked_updates[index] = nil + end + end + + -- Updating profile values: + + profile.KeyInfo = key_info + profile.LastSavedData = loaded_data.Data + profile.global_updates = loaded_data.GlobalUpdates and loaded_data.GlobalUpdates[2] or {} + + if session_owns_profile == true then + if is_active == true and is_ending_session ~= true then + + -- Processing new global updates (messages): + + for _, update in ipairs(new_updates) do + + local index = update[1] + local update_data = update[#update] -- Backwards compatibility with ProfileService + + for _, handler in ipairs(profile.message_handlers) do + + local is_processed = false + local processed_callback = function() + is_processed = true + locked_updates[index] = true + end + + local send_update_data = DeepCopyTable(update_data) + + task.spawn(handler, send_update_data, processed_callback) + + if is_processed == true then + break + end + + end + + end + + end + else + + if profile.roblox_message_subscription ~= nil then + profile.roblox_message_subscription:Disconnect() + end + + if is_active == true then + RemoveProfileFromAutoSave(profile) + profile.OnSessionEnd:Fire() + end + + end + + profile.OnAfterSave:Fire(profile.LastSavedData) + + elseif repeat_save_flag == true then + + -- DataStore call likely resulted in an error; Repeat the DataStore call shortly + task.wait(exp_backoff) + exp_backoff = math.min(if last_save_reason == "Shutdown" then 8 else 20, exp_backoff * 2) + + end + + end + + ActiveProfileSaveJobs = ActiveProfileSaveJobs - 1 + +end + +----- Public ----- + +--[[ + Saved profile structure: + + { + Data = {}, + + MetaData = { + ProfileCreateTime = 0, + SessionLoadCount = 0, + ActiveSession = {place_id, game_job_id, unique_session_id} / nil, + ForceLoadSession = {place_id, game_job_id} / nil, + LastUpdate = 0, -- os.time() + MetaTags = {}, -- Backwards compatibility with ProfileService + }, + + RobloxMetaData = {}, + UserIds = {}, + + GlobalUpdates = { + update_index, + { + {update_index, data}, ... + }, + }, + } + +--]] + +export type JSONAcceptable = { JSONAcceptable } | { [string]: JSONAcceptable } | number | string | boolean | buffer + +export type Profile = { + Data: T & JSONAcceptable, + LastSavedData: T & JSONAcceptable, + FirstSessionTime: number, + SessionLoadCount: number, + Session: {PlaceId: number, JobId: string}?, + RobloxMetaData: JSONAcceptable, + UserIds: {number}, + KeyInfo: DataStoreKeyInfo, + OnSave: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})}, + OnLastSave: {Connect: (self: any, listener: (reason: "Manual" | "External" | "Shutdown") -> ()) -> ({Disconnect: (self: any) -> ()})}, + OnSessionEnd: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})}, + OnAfterSave: {Connect: (self: any, listener: (last_saved_data: T & JSONAcceptable) -> ()) -> ({Disconnect: (self: any) -> ()})}, + ProfileStore: JSONAcceptable, + Key: string, + + IsActive: (self: any) -> (boolean), + Reconcile: (self: any) -> (), + EndSession: (self: any) -> (), + AddUserId: (self: any, user_id: number) -> (), + RemoveUserId: (self: any, user_id: number) -> (), + MessageHandler: (self: any, fn: (message: JSONAcceptable, processed: () -> ()) -> ()) -> (), + Save: (self: any) -> (), + SetAsync: (self: any) -> (), +} + +export type VersionQuery = { + NextAsync: (self: any) -> (Profile?), +} + +type ProfileStoreStandard = { + Name: string, + StartSessionAsync: (self: any, profile_key: string, params: {Steal: boolean?}) -> (Profile?), + MessageAsync: (self: any, profile_key: string, message: JSONAcceptable) -> (boolean), + GetAsync: (self: any, profile_key: string, version: string?) -> (Profile?), + VersionQuery: (self: any, profile_key: string, sort_direction: Enum.SortDirection?, min_date: DateTime | number | nil, max_date: DateTime | number | nil) -> (VersionQuery), + RemoveAsync: (self: any, profile_key: string) -> (boolean), +} + +export type ProfileStore = { + Mock: ProfileStoreStandard, +} & ProfileStoreStandard + +type ConstantName = "AUTO_SAVE_PERIOD" | "LOAD_REPEAT_PERIOD" | "FIRST_LOAD_REPEAT" | "SESSION_STEAL" +| "ASSUME_DEAD" | "START_SESSION_TIMEOUT" | "CRITICAL_STATE_ERROR_COUNT" | "CRITICAL_STATE_ERROR_EXPIRE" +| "CRITICAL_STATE_EXPIRE" | "MAX_MESSAGE_QUEUE" + +export type ProfileStoreModule = { + IsClosing: boolean, + IsCriticalState: boolean, + OnError: {Connect: (self: any, listener: (message: string, store_name: string, profile_key: string) -> ()) -> ({Disconnect: (self: any) -> ()})}, + OnOverwrite: {Connect: (self: any, listener: (store_name: string, profile_key: string) -> ()) -> ({Disconnect: (self: any) -> ()})}, + OnCriticalToggle: {Connect: (self: any, listener: (is_critical: boolean) -> ()) -> ({Disconnect: (self: any) -> ()})}, + DataStoreState: "NotReady" | "NoInternet" | "NoAccess" | "Access", + New: (store_name: string, template: (T & JSONAcceptable)?) -> (ProfileStore), + SetConstant: (name: ConstantName, value: number) -> () +} + +local Profile = {} +Profile.__index = Profile + +function Profile.New(raw_data, key_info, profile_store, key, is_mock, session_token) + + local data = raw_data.Data or {} + local session = raw_data.MetaData and raw_data.MetaData.ActiveSession or nil + + local global_updates = raw_data.GlobalUpdates and raw_data.GlobalUpdates[2] or {} + local received_global_updates = {} + + for _, update in ipairs(global_updates) do + received_global_updates[update[1]] = true + end + + local self = { + + Data = data, + LastSavedData = DeepCopyTable(data), + + FirstSessionTime = raw_data.MetaData and raw_data.MetaData.ProfileCreateTime or 0, + SessionLoadCount = raw_data.MetaData and raw_data.MetaData.SessionLoadCount or 0, + Session = session and {PlaceId = session[1], JobId = session[2]}, + + RobloxMetaData = raw_data.RobloxMetaData or {}, + UserIds = raw_data.UserIds or {}, + KeyInfo = key_info, + + OnAfterSave = Signal.New(), + OnSave = Signal.New(), + OnLastSave = Signal.New(), + OnSessionEnd = Signal.New(), + + ProfileStore = profile_store, + Key = key, + + load_timestamp = os.clock(), + is_mock = is_mock, + session_token = session_token or "", + load_index = raw_data.MetaData and raw_data.MetaData.SessionLoadCount or 0, + locked_global_updates = {}, + received_global_updates = received_global_updates, + message_handlers = {}, + global_updates = global_updates, + + } + setmetatable(self, Profile) + + return self + +end + +function Profile:IsActive() + return ActiveSessionCheck[self.session_token] == self +end + +function Profile:Reconcile() + ReconcileTable(self.Data, self.ProfileStore.template) +end + +function Profile:EndSession() + if self:IsActive() == true then + task.spawn(SaveProfileAsync, self, true, nil, "Manual") -- Call save function in a new thread with release_from_session = true + end +end + +function Profile:AddUserId(user_id) -- Associates user_id with profile (GDPR compliance) + + if type(user_id) ~= "number" or user_id % 1 ~= 0 then + warn(`[{script.Name}]: Invalid UserId argument for :AddUserId() ({tostring(user_id)}); Traceback:\n` .. debug.traceback()) + return + end + + if user_id < 0 and self.is_mock ~= true and DataStoreState == "Access" then + return -- Avoid giving real Roblox APIs negative UserId's + end + + if table.find(self.UserIds, user_id) == nil then + table.insert(self.UserIds, user_id) + end + +end + +function Profile:RemoveUserId(user_id) -- Removes user_id association with profile (safe function) + + if type(user_id) ~= "number" or user_id % 1 ~= 0 then + warn(`[{script.Name}]: Invalid UserId argument for :RemoveUserId() ({tostring(user_id)}); Traceback:\n` .. debug.traceback()) + return + end + + local index = table.find(self.UserIds, user_id) + + if index ~= nil then + table.remove(self.UserIds, index) + end + +end + +function Profile:SetAsync() -- Saves the profile to the DataStore and removes the session lock + + if self.view_mode ~= true then + error(`[{script.Name}]: :SetAsync() can only be used in view mode`) + end + + SaveProfileAsync(self, nil, true) + +end + +function Profile:MessageHandler(fn) + + if type(fn) ~= "function" then + error(`[{script.Name}]: fn argument is not a function`) + end + + if self.view_mode ~= true and self:IsActive() ~= true then + return -- Don't process messages if the profile session was ended + end + + local locked_updates = self.locked_global_updates + table.insert(self.message_handlers, fn) + + for _, update in ipairs(self.global_updates) do + + local index = update[1] + local update_data = update[#update] -- Backwards compatibility with ProfileService + + if locked_updates[index] ~= true then + + local processed_callback = function() + locked_updates[index] = true + end + + local send_update_data = DeepCopyTable(update_data) + + task.spawn(fn, send_update_data, processed_callback) + + end + + end + +end + +function Profile:Save() + + if self.view_mode == true then + error(`[{script.Name}]: Can't save profile in view mode; Should you be calling :SetAsync() instead?`) + end + + if self:IsActive() == false then + warn(`[{script.Name}]: Attempted saving an inactive profile (STORE:{self.ProfileStore.Name}; KEY:{self.Key});` + .. ` Traceback:\n` .. debug.traceback()) + return + end + + -- Move the profile right behind the auto save index to delay the next auto save for it: + RemoveProfileFromAutoSave(self) + AddProfileToAutoSave(self) + + -- Perform save in new thread: + task.spawn(SaveProfileAsync, self) + +end + +local ProfileStore: ProfileStoreModule = { + + IsClosing = false, + IsCriticalState = false, + OnError = OnError, -- (message, store_name, profile_key) + OnOverwrite = OnOverwrite, -- (store_name, profile_key) + OnCriticalToggle = Signal.New(), -- (is_critical) + DataStoreState = "NotReady", -- ("NotReady", "NoInternet", "NoAccess", "Access") + +} +ProfileStore.__index = ProfileStore + +function ProfileStore.SetConstant(name, value) + + if type(value) ~= "number" then + error(`[{script.Name}]: Invalid value type`) + end + + if name == "AUTO_SAVE_PERIOD" then + AUTO_SAVE_PERIOD = value + elseif name == "LOAD_REPEAT_PERIOD" then + LOAD_REPEAT_PERIOD = value + elseif name == "FIRST_LOAD_REPEAT" then + FIRST_LOAD_REPEAT = value + elseif name == "SESSION_STEAL" then + SESSION_STEAL = value + elseif name == "ASSUME_DEAD" then + ASSUME_DEAD = value + elseif name == "START_SESSION_TIMEOUT" then + START_SESSION_TIMEOUT = value + elseif name == "CRITICAL_STATE_ERROR_COUNT" then + CRITICAL_STATE_ERROR_COUNT = value + elseif name == "CRITICAL_STATE_ERROR_EXPIRE" then + CRITICAL_STATE_ERROR_EXPIRE = value + elseif name == "CRITICAL_STATE_EXPIRE" then + CRITICAL_STATE_EXPIRE = value + elseif name == "MAX_MESSAGE_QUEUE" then + MAX_MESSAGE_QUEUE = value + else + error(`[{script.Name}]: Invalid constant name was provided`) + end + +end + +function ProfileStore.Test() + return { + ActiveSessionCheck = ActiveSessionCheck, + AutoSaveList = AutoSaveList, + ActiveProfileLoadJobs = ActiveProfileLoadJobs, + ActiveProfileSaveJobs = ActiveProfileSaveJobs, + MockStore = MockStore, + UserMockStore = UserMockStore, + UpdateQueue = UpdateQueue, + } +end + +function ProfileStore.New(store_name, template) + + template = template or {} + + if type(store_name) ~= "string" then + error(`[{script.Name}]: Invalid or missing "store_name"`) + elseif string.len(store_name) == 0 then + error(`[{script.Name}]: store_name cannot be an empty string`) + elseif string.len(store_name) > 50 then + error(`[{script.Name}]: store_name is too long`) + end + + if type(template) ~= "table" then + error(`[{script.Name}]: Invalid template argument`) + end + + local self + self = { + + Mock = { + + Name = store_name, + + StartSessionAsync = function(_, profile_key) + MockFlag = true + return self:StartSessionAsync(profile_key) + end, + MessageAsync = function(_, profile_key, message) + MockFlag = true + return self:MessageAsync(profile_key, message) + end, + GetAsync = function(_, profile_key, version) + MockFlag = true + return self:GetAsync(profile_key, version) + end, + VersionQuery = function(_, profile_key, sort_direction, min_date, max_date) + MockFlag = true + return self:VersionQuery(profile_key, sort_direction, min_date, max_date) + end, + RemoveAsync = function(_, profile_key) + MockFlag = true + return self:RemoveAsync(profile_key) + end + }, + + Name = store_name, + + template = template, + data_store = nil, + load_jobs = {}, + mock_load_jobs = {}, + is_ready = true, + + } + setmetatable(self, ProfileStore) + + local options = Instance.new("DataStoreOptions") + options:SetExperimentalFeatures({v2 = true}) + + if DataStoreState == "NotReady" then + + -- The module is not sure whether DataStores are accessible yet: + + self.is_ready = false + + task.spawn(function() + + repeat task.wait() until DataStoreState ~= "NotReady" + + if DataStoreState == "Access" then + self.data_store = DataStoreService:GetDataStore(store_name, nil, options) + end + + self.is_ready = true + + end) + + elseif DataStoreState == "Access" then + + self.data_store = DataStoreService:GetDataStore(store_name, nil, options) + + end + + return self + +end + +local function RobloxMessageSubscription(profile, unique_session_id) + + local last_roblox_message = 0 + + local roblox_message_subscription = MessagingService:SubscribeAsync("PS_" .. unique_session_id, function(message) + if type(message.Data) == "table" and message.Data.LoadCount == profile.SessionLoadCount then + -- High reaction rate, based on numPlayers × 10 DataStore budget as of writing + if os.clock() - last_roblox_message > 6 then + last_roblox_message = os.clock() + if profile:IsActive() == true then + if message.Data.EndSession == true then + SaveProfileAsync(profile, true, false, "External") + else + profile:Save() + end + end + end + end + end) + + if profile:IsActive() == true then + profile.roblox_message_subscription = roblox_message_subscription + else + roblox_message_subscription:Disconnect() + end + +end + +function ProfileStore:StartSessionAsync(profile_key, params) + + local is_mock = ReadMockFlag() + + if type(profile_key) ~= "string" then + error(`[{script.Name}]: profile_key must be a string`) + elseif string.len(profile_key) == 0 then + error(`[{script.Name}]: Invalid profile_key`) + elseif string.len(profile_key) > 50 then + error(`[{script.Name}]: profile_key is too long`) + end + + if params ~= nil and type(params) ~= "table" then + error(`[{script.Name}]: Invalid params`) + end + + params = params or {} + + if ProfileStore.IsClosing == true then + return nil + end + + WaitForStoreReady(self) + + local session_token = SessionToken(self.Name, profile_key, is_mock) + + if ActiveSessionCheck[session_token] ~= nil then + error(`[{script.Name}]: Profile (STORE:{self.Name}; KEY:{profile_key}) is already loaded in this session`) + end + + ActiveProfileLoadJobs = ActiveProfileLoadJobs + 1 + + local is_user_cancel = false + + local function cancel_condition() + if is_user_cancel == false then + if params.Cancel ~= nil then + is_user_cancel = params.Cancel() == true + end + return is_user_cancel + end + return true + end + + local user_steal = params.Steal == true + + local force_load_steps = 0 -- Session conflict handling values + local request_force_load = true + local steal_session = false + + local start = os.clock() + local exp_backoff = 1 + + while ProfileStore.IsClosing == false and cancel_condition() == false do + + -- Load profile: + + -- SPECIAL CASE - If StartSessionAsync is called for the same key again before another StartSessionAsync finishes, + -- grab the DataStore return for the new call. The early call will return nil. This is supposed to retain + -- expected and efficient behavior in cases where a player would quickly rejoin the same server. + + LoadIndex += 1 + local load_id = LoadIndex + local profile_load_jobs = is_mock == true and self.mock_load_jobs or self.load_jobs + local profile_load_job = profile_load_jobs[profile_key] -- {load_id, {loaded_data, key_info} or nil} + + local loaded_data, key_info + local unique_session_id = HttpService:GenerateGUID(false) + + if profile_load_job ~= nil then + + profile_load_job[1] = load_id -- Steal load job + while profile_load_job[2] == nil do -- Wait for job to finish + task.wait() + end + if profile_load_job[1] == load_id then -- Load job hasn't been double-stolen + loaded_data, key_info = table.unpack(profile_load_job[2]) + profile_load_jobs[profile_key] = nil + else + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil + end + + else + + profile_load_job = {load_id, nil} + profile_load_jobs[profile_key] = profile_load_job + + profile_load_job[2] = table.pack(UpdateAsync( + self, + profile_key, + { + ExistingProfileHandle = function(latest_data) + + if ProfileStore.IsClosing == true or cancel_condition() == true then + return + end + + local active_session = latest_data.MetaData.ActiveSession + local force_load_session = latest_data.MetaData.ForceLoadSession + + if active_session == nil then + latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id} + latest_data.MetaData.ForceLoadSession = nil + elseif type(active_session) == "table" then + if IsThisSession(active_session) == false then + local last_update = latest_data.MetaData.LastUpdate + if last_update ~= nil then + if os.time() - last_update > ASSUME_DEAD then + latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id} + latest_data.MetaData.ForceLoadSession = nil + return + end + end + if steal_session == true or user_steal == true then + local force_load_interrupted = if force_load_session ~= nil then not IsThisSession(force_load_session) else true + if force_load_interrupted == false or user_steal == true then + latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id} + latest_data.MetaData.ForceLoadSession = nil + end + elseif request_force_load == true then + latest_data.MetaData.ForceLoadSession = {PlaceId, JobId} + end + else + latest_data.MetaData.ForceLoadSession = nil + end + end + + end, + MissingProfileHandle = function(latest_data) + + local is_cancel = ProfileStore.IsClosing == true or cancel_condition() == true + + latest_data.Data = DeepCopyTable(self.template) + latest_data.MetaData = { + ProfileCreateTime = os.time(), + SessionLoadCount = 0, + ActiveSession = if is_cancel == false then {PlaceId, JobId, unique_session_id} else nil, + ForceLoadSession = nil, + MetaTags = {}, -- Backwards compatibility with ProfileService + } + + end, + EditProfile = function(latest_data) + + if ProfileStore.IsClosing == true or cancel_condition() == true then + return + end + + local active_session = latest_data.MetaData.ActiveSession + if active_session ~= nil and IsThisSession(active_session) == true then + latest_data.MetaData.SessionLoadCount = latest_data.MetaData.SessionLoadCount + 1 + latest_data.MetaData.LastUpdate = os.time() + end + + end, + }, + is_mock + )) + if profile_load_job[1] == load_id then -- Load job hasn't been stolen + loaded_data, key_info = table.unpack(profile_load_job[2]) + profile_load_jobs[profile_key] = nil + else + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil -- Load job stolen + end + end + + -- Handle load_data: + + if loaded_data ~= nil and key_info ~= nil then + local active_session = loaded_data.MetaData.ActiveSession + if type(active_session) == "table" then + + if IsThisSession(active_session) == true then + + -- Profile is now taken by this session: + + local profile = Profile.New(loaded_data, key_info, self, profile_key, is_mock, session_token) + AddProfileToAutoSave(profile) + + if is_mock ~= true and DataStoreState == "Access" then + + -- Use MessagingService to quickly detect session conflicts and resolve them quickly: + task.spawn(RobloxMessageSubscription, profile, unique_session_id) -- Blocking prevention + + end + + if ProfileStore.IsClosing == true or cancel_condition() == true then + -- The server has initiated a shutdown by the time this profile was loaded + SaveProfileAsync(profile, true) -- Release profile and yield until the DataStore call is finished + profile = nil -- Don't return the profile object + end + + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return profile + + else + + if ProfileStore.IsClosing == true or cancel_condition() == true then + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil + end + + -- Profile is taken by some other session: + + local force_load_session = loaded_data.MetaData.ForceLoadSession + local force_load_interrupted = if force_load_session ~= nil then not IsThisSession(force_load_session) else true + + if force_load_interrupted == false then + + if request_force_load == false then + force_load_steps = force_load_steps + 1 + if force_load_steps >= math.ceil(SESSION_STEAL / LOAD_REPEAT_PERIOD) then + steal_session = true + end + end + + -- Request the remote server to end its session: + if type(active_session[3]) == "string" then + local session_load_count = loaded_data.MetaData.SessionLoadCount or 0 + task.spawn(MessagingService.PublishAsync, MessagingService, "PS_" .. active_session[3], {LoadCount = session_load_count, EndSession = true}) + end + + -- Attempt to load the profile again after a delay + local wait_until = os.clock() + if request_force_load == true then FIRST_LOAD_REPEAT else LOAD_REPEAT_PERIOD + repeat task.wait() until os.clock() >= wait_until or ProfileStore.IsClosing == true + + else + -- Another session tried to load this profile: + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil + end + + request_force_load = false -- Only request a force load once + + end + + else + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil -- In this scenario it is likely that this server started shutting down + end + else + + -- A DataStore call has likely ended in an error: + + local default_timeout = false + + if params.Cancel == nil then + default_timeout = os.clock() - start >= START_SESSION_TIMEOUT + end + + if default_timeout == true or ProfileStore.IsClosing == true or cancel_condition() == true then + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil + end + + task.wait(exp_backoff) -- Repeat the call shortly + exp_backoff = math.min(20, exp_backoff * 2) + + end + + end + + ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1 + return nil -- Game started shutting down or the request was cancelled - don't return the profile + +end + +function ProfileStore:MessageAsync(profile_key, message) + + local is_mock = ReadMockFlag() + + if type(profile_key) ~= "string" then + error(`[{script.Name}]: profile_key must be a string`) + elseif string.len(profile_key) == 0 then + error(`[{script.Name}]: Invalid profile_key`) + elseif string.len(profile_key) > 50 then + error(`[{script.Name}]: profile_key is too long`) + end + + if type(message) ~= "table" then + error(`[{script.Name}]: message must be a table`) + end + + if ProfileStore.IsClosing == true then + return false + end + + WaitForStoreReady(self) + + local exp_backoff = 1 + + while ProfileStore.IsClosing == false do + + -- Updating profile: + + local loaded_data = UpdateAsync( + self, + profile_key, + { + ExistingProfileHandle = nil, + MissingProfileHandle = nil, + EditProfile = function(latest_data) + + local global_updates = latest_data.GlobalUpdates + local update_list = global_updates[2] + --{ + -- update_index, + -- { + -- {update_index, data}, ... + -- }, + --}, + + global_updates[1] += 1 + table.insert(update_list, {global_updates[1], message}) + + -- Clearing queue if above limit: + + while #update_list > MAX_MESSAGE_QUEUE do + table.remove(update_list, 1) + end + + end, + }, + is_mock + ) + + if loaded_data ~= nil then + + local session_token = SessionToken(self.Name, profile_key, is_mock) + + local profile = ActiveSessionCheck[session_token] + + if profile ~= nil then + + -- The message was sent to a profile that is active in this server: + profile:Save() + + else + + local meta_data = loaded_data.MetaData or {} + local active_session = meta_data.ActiveSession + local session_load_count = meta_data.SessionLoadCount or 0 + + if type(active_session) == "table" and type(active_session[3]) == "string" then + -- Request the remote server to auto-save sooner and receive the message: + task.spawn(MessagingService.PublishAsync, MessagingService, "PS_" .. active_session[3], {LoadCount = session_load_count}) + end + + end + + return true + + else + + task.wait(exp_backoff) -- A DataStore call has likely ended in an error - repeat the call shortly + exp_backoff = math.min(20, exp_backoff * 2) + + end + + end + + return false + +end + +function ProfileStore:GetAsync(profile_key, version) + + local is_mock = ReadMockFlag() + + if type(profile_key) ~= "string" then + error(`[{script.Name}]: profile_key must be a string`) + elseif string.len(profile_key) == 0 then + error(`[{script.Name}]: Invalid profile_key`) + elseif string.len(profile_key) > 50 then + error(`[{script.Name}]: profile_key is too long`) + end + + if ProfileStore.IsClosing == true then + return nil + end + + WaitForStoreReady(self) + + if version ~= nil and (is_mock or DataStoreState ~= "Access") then + return nil -- No version support in mock mode + end + + local exp_backoff = 1 + + while ProfileStore.IsClosing == false do + + -- Load profile: + + local loaded_data, key_info = UpdateAsync( + self, + profile_key, + { + ExistingProfileHandle = nil, + MissingProfileHandle = function(latest_data) + + latest_data.Data = DeepCopyTable(self.template) + latest_data.MetaData = { + ProfileCreateTime = os.time(), + SessionLoadCount = 0, + ActiveSession = nil, + ForceLoadSession = nil, + MetaTags = {}, -- Backwards compatibility with ProfileService + } + + end, + EditProfile = nil, + }, + is_mock, + true, -- Use :GetAsync() + version -- DataStore key version + ) + + -- Handle load_data: + + if loaded_data ~= nil then + + if key_info == nil then + return nil -- Load was successful, but the key was empty - return no profile object + end + + local profile = Profile.New(loaded_data, key_info, self, profile_key, is_mock) + profile.view_mode = true + + return profile + + else + + task.wait(exp_backoff) -- A DataStore call has likely ended in an error - repeat the call shortly + exp_backoff = math.min(20, exp_backoff * 2) + + end + + end + + return nil -- Game started shutting down - don't return the profile + +end + +function ProfileStore:RemoveAsync(profile_key) + + local is_mock = ReadMockFlag() + + if type(profile_key) ~= "string" or string.len(profile_key) == 0 then + error(`[{script.Name}]: Invalid profile_key`) + end + + if ProfileStore.IsClosing == true then + return false + end + + WaitForStoreReady(self) + + local wipe_status = false + + local next_in_queue = WaitInUpdateQueue(SessionToken(self.Name, profile_key, is_mock)) + + if is_mock == true then -- Used when the profile is accessed through ProfileStore.Mock + + local mock_data_store = UserMockStore[self.Name] + + if mock_data_store ~= nil then + mock_data_store[profile_key] = nil + if next(mock_data_store) == nil then + UserMockStore[self.Name] = nil + end + end + + wipe_status = true + task.wait() -- Simulate API call yield + + elseif DataStoreState ~= "Access" then -- Used when API access is disabled + + local mock_data_store = MockStore[self.Name] + + if mock_data_store ~= nil then + mock_data_store[profile_key] = nil + if next(mock_data_store) == nil then + MockStore[self.Name] = nil + end + end + + wipe_status = true + task.wait() -- Simulate API call yield + + else -- Live DataStore + + wipe_status = pcall(function() + self.data_store:RemoveAsync(profile_key) + end) + + end + + next_in_queue() + + return wipe_status + +end + +local ProfileVersionQuery = {} +ProfileVersionQuery.__index = ProfileVersionQuery + +function ProfileVersionQuery.New(profile_store, profile_key, sort_direction, min_date, max_date, is_mock) + + local self = { + profile_store = profile_store, + profile_key = profile_key, + sort_direction = sort_direction, + min_date = min_date, + max_date = max_date, + + query_pages = nil, + query_index = 0, + query_failure = false, + + is_query_yielded = false, + query_queue = {}, + + is_mock = is_mock, + } + setmetatable(self, ProfileVersionQuery) + + return self + +end + +function MoveVersionQueryQueue(self) -- Hidden ProfileVersionQuery method + while #self.query_queue > 0 do + + local queue_entry = table.remove(self.query_queue, 1) + + task.spawn(queue_entry) + + if self.is_query_yielded == true then + break + end + + end +end + +local VersionQueryNextAsyncStackingFlag = false +local WarnAboutVersionQueryOnce = false + +function ProfileVersionQuery:NextAsync() + + local is_stacking = VersionQueryNextAsyncStackingFlag == true + VersionQueryNextAsyncStackingFlag = false + + WaitForStoreReady(self.profile_store) + + if ProfileStore.IsClosing == true then + return nil -- Silently fail :NextAsync() requests + end + + if self.is_mock == true or DataStoreState ~= "Access" then + if IsStudio == true and WarnAboutVersionQueryOnce == false then + WarnAboutVersionQueryOnce = true + warn(`[{script.Name}]: :VersionQuery() is not supported in mock mode!`) + end + return nil -- Silently fail :NextAsync() requests + end + + local profile + local is_finished = false + + local function query_job() + + if self.query_failure == true then + is_finished = true + return + end + + -- First "next" call loads version pages: + + if self.query_pages == nil then + + self.is_query_yielded = true + + task.spawn(function() + VersionQueryNextAsyncStackingFlag = true + profile = self:NextAsync() + is_finished = true + end) + + local list_success, error_message = pcall(function() + self.query_pages = self.profile_store.data_store:ListVersionsAsync( + self.profile_key, + self.sort_direction, + self.min_date, + self.max_date + ) + self.query_index = 0 + end) + + if list_success == false or self.query_pages == nil then + warn(`[{script.Name}]: Version query fail - {tostring(error_message)}`) + self.query_failure = true + end + + self.is_query_yielded = false + + MoveVersionQueryQueue(self) + + return + + end + + local current_page = self.query_pages:GetCurrentPage() + local next_item = current_page[self.query_index + 1] + + -- No more entries: + + if self.query_pages.IsFinished == true and next_item == nil then + is_finished = true + return + end + + -- Load next page when this page is over: + + if next_item == nil then + + self.is_query_yielded = true + task.spawn(function() + VersionQueryNextAsyncStackingFlag = true + profile = self:NextAsync() + is_finished = true + end) + + local success, error_message = pcall(function() + self.query_pages:AdvanceToNextPageAsync() + self.query_index = 0 + end) + + if success == false or #self.query_pages:GetCurrentPage() == 0 then + self.query_failure = true + end + + self.is_query_yielded = false + MoveVersionQueryQueue(self) + + return + + end + + -- Next page item: + + self.query_index += 1 + profile = self.profile_store:GetAsync(self.profile_key, next_item.Version) + is_finished = true + + end + + if self.is_query_yielded == false then + query_job() + else + if is_stacking == true then + table.insert(self.query_queue, 1, query_job) + else + table.insert(self.query_queue, query_job) + end + end + + while is_finished == false do + task.wait() + end + + return profile + +end + +function ProfileStore:VersionQuery(profile_key, sort_direction, min_date, max_date) + + local is_mock = ReadMockFlag() + + if type(profile_key) ~= "string" or string.len(profile_key) == 0 then + error(`[{script.Name}]: Invalid profile_key`) + end + + -- Type check: + + if sort_direction ~= nil and (typeof(sort_direction) ~= "EnumItem" + or sort_direction.EnumType ~= Enum.SortDirection) then + error(`[{script.Name}]: Invalid sort_direction ({tostring(sort_direction)})`) + end + + if min_date ~= nil and typeof(min_date) ~= "DateTime" and typeof(min_date) ~= "number" then + error(`[{script.Name}]: Invalid min_date ({tostring(min_date)})`) + end + + if max_date ~= nil and typeof(max_date) ~= "DateTime" and typeof(max_date) ~= "number" then + error(`[{script.Name}]: Invalid max_date ({tostring(max_date)})`) + end + + min_date = typeof(min_date) == "DateTime" and min_date.UnixTimestampMillis or min_date + max_date = typeof(max_date) == "DateTime" and max_date.UnixTimestampMillis or max_date + + return ProfileVersionQuery.New(self, profile_key, sort_direction, min_date, max_date, is_mock) + +end + +-- DataStore API access check: + +if IsStudio == true then + + task.spawn(function() + + local new_state = "NoAccess" + + local status, message = pcall(function() + -- This will error if current instance has no Studio API access: + DataStoreService:GetDataStore("____PS"):SetAsync("____PS", os.time()) + end) + + local no_internet_access = status == false and string.find(message, "ConnectFail", 1, true) ~= nil + + if no_internet_access == true then + warn(`[{script.Name}]: No internet access - check your network connection`) + end + + if status == false and + (string.find(message, "403", 1, true) ~= nil or -- Cannot write to DataStore from studio if API access is not enabled + string.find(message, "must publish", 1, true) ~= nil or -- Game must be published to access live keys + no_internet_access == true) then -- No internet access + + new_state = if no_internet_access == true then "NoInternet" else "NoAccess" + print(`[{script.Name}]: Roblox API services unavailable - data will not be saved`) + else + new_state = "Access" + print(`[{script.Name}]: Roblox API services available - data will be saved`) + end + + DataStoreState = new_state + ProfileStore.DataStoreState = new_state + + end) + +else + + DataStoreState = "Access" + ProfileStore.DataStoreState = "Access" + +end + +-- Update loop: + +RunService.Heartbeat:Connect(function() + + -- Auto saving: + + local auto_save_list_length = #AutoSaveList + if auto_save_list_length > 0 then + local auto_save_index_speed = AUTO_SAVE_PERIOD / auto_save_list_length + local os_clock = os.clock() + while os_clock - LastAutoSave > auto_save_index_speed do + LastAutoSave = LastAutoSave + auto_save_index_speed + local profile = AutoSaveList[AutoSaveIndex] + if os_clock - profile.load_timestamp < AUTO_SAVE_PERIOD / 2 then + -- This profile is freshly loaded - auto saving immediately is not necessary: + profile = nil + for _ = 1, auto_save_list_length - 1 do + -- Move auto save index to the right: + AutoSaveIndex = AutoSaveIndex + 1 + if AutoSaveIndex > auto_save_list_length then + AutoSaveIndex = 1 + end + profile = AutoSaveList[AutoSaveIndex] + if os_clock - profile.load_timestamp >= AUTO_SAVE_PERIOD / 2 then + break + else + profile = nil + end + end + end + -- Move auto save index to the right: + AutoSaveIndex = AutoSaveIndex + 1 + if AutoSaveIndex > auto_save_list_length then + AutoSaveIndex = 1 + end + -- Perform save call: + if profile ~= nil then + task.spawn(SaveProfileAsync, profile) -- Auto save profile in new thread + end + end + end + + -- Critical state handling: + + if ProfileStore.IsCriticalState == false then + if #IssueQueue >= CRITICAL_STATE_ERROR_COUNT then + ProfileStore.IsCriticalState = true + ProfileStore.OnCriticalToggle:Fire(true) + CriticalStateStart = os.clock() + warn(`[{script.Name}]: Entered critical state`) + end + else + if #IssueQueue >= CRITICAL_STATE_ERROR_COUNT then + CriticalStateStart = os.clock() + elseif os.clock() - CriticalStateStart > CRITICAL_STATE_EXPIRE then + ProfileStore.IsCriticalState = false + ProfileStore.OnCriticalToggle:Fire(false) + warn(`[{script.Name}]: Critical state ended`) + end + end + + -- Issue queue: + + while true do + local issue_time = IssueQueue[1] + if issue_time == nil then + break + elseif os.clock() - issue_time > CRITICAL_STATE_ERROR_EXPIRE then + table.remove(IssueQueue, 1) + else + break + end + end + +end) + +-- Release all loaded profiles when the server is shutting down: + +task.spawn(function() + + while DataStoreState == "NotReady" do + task.wait() + end + + if DataStoreState ~= "Access" then + + game:BindToClose(function() + ProfileStore.IsClosing = true + task.wait() -- Mock shutdown delay + end) + + return -- Don't wait for profiles to properly save in mock mode so studio could end the simulation faster + + end + + game:BindToClose(function() + + ProfileStore.IsClosing = true + + -- Release all active profiles: + -- (Clone AutoSaveList to a new table because AutoSaveList changes when profiles are released) + + local on_close_save_job_count = 0 + local active_profiles = {} + for index, profile in ipairs(AutoSaveList) do + active_profiles[index] = profile + end + + -- Release the profiles; Releasing profiles can trigger listeners that release other profiles, so check active state: + for _, profile in ipairs(active_profiles) do + if profile:IsActive() == true then + on_close_save_job_count = on_close_save_job_count + 1 + task.spawn(function() -- Save profile on new thread + SaveProfileAsync(profile, true, nil, "Shutdown") + on_close_save_job_count = on_close_save_job_count - 1 + end) + end + end + + -- Yield until all active profile jobs are finished: + while on_close_save_job_count > 0 or ActiveProfileLoadJobs > 0 or ActiveProfileSaveJobs > 0 do + task.wait() + end + + return -- We're done! + + end) + +end) + +return ProfileStore \ No newline at end of file diff --git a/rokit.toml b/rokit.toml index 2aa3742..1276308 100644 --- a/rokit.toml +++ b/rokit.toml @@ -6,3 +6,4 @@ rojo = "rojo-rbx/rojo@7.7.1" selene = "Kampfkarren/selene@0.32.0" stylua = "JohnnyMorganz/StyLua@2.6.0" lune = "lune-org/lune@0.11.0" +luau-lsp = "JohnnyMorganz/luau-lsp@1.70.1"