wip(bunsik): 경제 개편 공용 로직 — 업그레이드 갈래, 의자·테이블 배치와 길 찾기(Floor), 알바생 역할·시급, 손님 러시·홍보·쫓아내기 로직, 서버↔클라이언트 약속(NETWORK.md)

서버·클라이언트는 다음 커밋에서 새 구조로 옮깁니다(이 커밋만으로는 빌드 검사가 통과하지 않음).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 01:19:40 +09:00
parent 8d29656aa3
commit 52668f219a
12 changed files with 2180 additions and 346 deletions

82
bunsik-tycoon/NETWORK.md Normal file
View File

@@ -0,0 +1,82 @@
# 서버 ↔ 클라이언트 약속 (2026-10-14 개편)
서버는 상태를 **속성(Attribute)** 으로 내보내고, 클라이언트는 `Remotes.Action:FireServer(kind, arg)` 로 요청합니다.
알림은 `Remotes.Notify:FireClient(player, key, args)` 이고, 글자는 클라이언트가 `Locale.t(lang, key, args)` 로 씁니다.
경제·배치 규칙은 공용 모듈(`src/shared/Economy.luau`, `Shop.luau`, `Floor.luau`)이 원본입니다. 클라이언트는 같은 모듈로 값·미리보기를 계산하고, 서버가 다시 검사합니다.
## 플레이어 속성 (Player)
| 속성 | 형 | 뜻 |
|---|---|---|
| Ready | bool | 세이브 로드 끝 |
| Plot | number | 내 부지 번호 |
| Money, Earned | number | 돈, 지금까지 번 돈 |
| Levels | string | 갈래 레벨 `"Stage=1,Menu=2,Price=0,Speed=1,Stove=0,Tray=0,Staff=1"` (Economy.TRACK_ORDER 순서). `Shared.Codec.decodeMap` 로 읽음 |
| Stage | number | 건물 단계 1 포장마차, 2 실내, 3 2층 |
| Seats, Tables | number | 놓은 의자 수(= 손님 자리 수), 테이블 수 |
| Layout | string | 배치 JSON(`Floor.Layout` 모양). `HttpService:JSONDecode` 후 `Floor.clean` |
| Staff | string | 고용한 알바 수 `"Cook=1,Server=0,Promoter=0"` |
| Strike | bool | 시급이 모자라 알바생이 쉬는 중 |
| Wage | number | 1분마다 주는 시급 합계 |
| RushUntil | number | 손님 러시가 끝나는 서버 시각(`workspace:GetServerTimeNow()` 기준, 0이면 없음) |
| PromoteAt | number | 다음 홍보를 할 수 있는 서버 시각(광고 없이) |
| PromoteAdAt | number | 광고를 보고 홍보할 수 있는 서버 시각 |
| KickCredits | number | 남은 "손님 쫓아내기" 횟수(유료로 산 것) |
| ShopName | string | 내가 정한 가게 이름 원문("" = 기본 이름). 다른 사람에게 보이는 이름은 부지 속성 ShopName(필터 거친 글) |
| Rainbow | bool | 무지개 이름 켜기 설정 |
| RainbowOwned | bool | 무지개 이름 게임패스 보유 |
| Design | string | 건물 디자인 id(Economy.DESIGNS) |
| DesignsOwned | string | 유료 디자인 보유 목록 `"Candy,Hanok"` |
| Double | bool | 2배 수익 |
| Boost | number | 돈 부스트 팩 지급액 |
| Tut | number | 튜토리얼 단계(0 끝, 1 조리대로, 2 서빙, 3 사기) |
| Carry, Hand | number, string | 든 접시 수, 든 메뉴 `"Gimbap,Sundae"` |
| Orders | string | 메뉴별 열린 주문 `"Tteokbokki=2,Gimbap=1"` |
| Lang, LangSetting, MouseLook, Sfx, Dev | | 설정(예전과 같음) |
## 부지 모델 속성 (workspace.BunsikWorld.Plots.PlotN, 모두에게 보임)
| 속성 | 뜻 |
|---|---|
| OwnerId, OwnerName | 플레이어 가게 주인 |
| Npc | 이웃 가게(NPC) 번호 |
| Level | 가게 레벨(Economy.shopLevel) |
| Stage | 건물 단계 |
| Menus | 파는 메뉴 `"Tteokbokki,Gimbap"` (메뉴판) |
| PriceMult | 판매 금액 배율(메뉴판 값) |
| ShopName | 필터를 거친 가게 이름("" = 기본 이름 "{name}의 분식집") |
| Rainbow | 무지개 이름(게임패스 + 켜짐) |
| Design | 건물 디자인 |
| ShieldUntil | 손님 쫓아내기 보호가 끝나는 서버 시각 |
## 요청 (Action kind, arg)
| kind | arg | 서버가 하는 일 |
|---|---|---|
| `cookStart`, `cook` | 메뉴 | 요리 창(예전과 같음) |
| `upgrade` | 갈래 id | 다음 단계 구매 |
| `buySeat` | 테이블 번호 또는 nil | 의자 1개(빈 쪽에 자동 배치) |
| `buyTable` | nil | 테이블 + 의자 1개(빈 곳 자동 배치) |
| `buyDecor` | 소품 id | 소품 1개(빈 곳 자동 배치) |
| `buyOffer` | `"Seat"`/`"Table"`/갈래 id | 화면 아래 추천 막대의 [사기] |
| `move` | `{kind="stove"/"table"/"decor", i, x, z, f, r}` | 옮기기(Floor.move로 검사). 의자는 `{kind="chair", i, x=쪽(1~4), z=테이블 번호(0=그대로)}` |
| `hire`, `fire` | 역할 id | 알바 고용·해고 |
| `rename` | 문자열(최대 20자) | 이름 바꾸기(TextService 필터) |
| `rainbow` | bool | 무지개 이름 켜기/끄기. 없으면 게임패스 결제 창 |
| `design` | 디자인 id | 디자인 바꾸기(실내 분식집부터). 유료인데 없으면 결제 창 |
| `promote` | `{ad=bool}` | 홍보. ad=true면 보상형 광고(서버가 AdService로 띄움), 아니면 대기 시간 확인 후 바로 |
| `kick` | 부지 번호 | 손님 쫓아내기. 횟수가 있으면 바로 쓰고, 없으면 결제 창(결제되면 그 부지에 씀) |
| `rush` | nil | 손님 러시 결제 창 |
| `visit`, `lang`, `mouseLook`, `sfx`, `pass`, `boost`, `dev_*` | | 예전과 같음 |
## 알림 키 (Notify)
예전 키(`purchased` 등)에 더해:
- `upgraded {track, level}` 갈래 업그레이드, `newMenu {menu}`, `expanded`(실내), `floor2`(2층)
- `seatAdded`, `tableAdded`, `decorAdded {kind}`, `noSpace`(놓을 곳 없음), `seatMax`, `tableMax`, `needStage`
- `placeFail {why}`: why = bounds | overlap | reserved | floor | blocked | chair
- `hired {role}`, `fired {role}`, `staffLocked`, `staffMax`, `strike`(시급 부족), `strikeOver`
- `renamed`, `nameRejected`(필터 실패·빈 이름), `designSet {design}`, `designLocked`(실내 분식집부터)
- `promoted {n}`, `promoteNone`(데려올 손님 없음), `promoteFull`(빈자리 없음), `promoteWait {sec}`, `adUnavailable`
- `kicked {n, shop}`(내가 쫓아냄), `kickedBy {name}`(내 가게 손님이 쫓겨남), `shielded`(보호 중), `kickOwn`(내 가게는 안 됨)
- `rushOn {min}`, `notEnough {need}`

View File

@@ -0,0 +1,38 @@
--!strict
-- 속성(Attribute)에 표·목록을 글자로 담는 작은 도구. 속성은 표를 담을 수 없어서 씁니다.
-- encodeMap({Cook=1, Server=0}, {"Cook","Server"}) -> "Cook=1,Server=0"
-- decodeMap("Cook=1,Server=0") -> {Cook=1, Server=0}
local Codec = {}
function Codec.encodeMap(map: { [string]: number }, order: { string }): string
local parts = {}
for _, k in order do
table.insert(parts, `{k}={map[k] or 0}`)
end
return table.concat(parts, ",")
end
function Codec.decodeMap(s: any): { [string]: number }
local out = {}
if typeof(s) ~= "string" then
return out
end
for k, v in string.gmatch(s, "([%w_]+)=([%-%d%.]+)") do
out[k] = tonumber(v) or 0
end
return out
end
function Codec.decodeList(s: any): { string }
local out = {}
if typeof(s) ~= "string" then
return out
end
for item in string.gmatch(s, "[^,]+") do
table.insert(out, item)
end
return out
end
return Codec

View File

@@ -1,22 +1,43 @@
--!strict --!strict
-- 분식집 경제 수치. ECONOMY.md 표와 같은 숫자여야 합니다. -- 분식집 경제 수치. ECONOMY.md 표와 같은 숫자여야 합니다.
-- 숫자를 바꾸면 `lune run tools/sim.luau` 로 구매 시점을 다시 확인합니다. -- 숫자를 바꾸면 `lune run tools/sim.luau` 로 구매 시점을 다시 확인합니다.
--
-- 2026-10-14: 한 줄로 쭉 사던 업그레이드 20개를 갈래(트랙)별로 나눴습니다.
-- 갈래: 건물(포장마차 → 실내 → 2층), 메뉴 해금, 판매 금액, 손님 오는 속도, 화구, 쟁반, 알바생 기능
-- 자리(테이블·의자)는 꾸미기에서 사고 원하는 곳에 놓습니다. 손님이 앉는 자리 수 = 놓은 의자 수입니다.
-- 알바생은 알바생 기능을 산 뒤 역할(요리·서빙·홍보)별로 돈 주고 고용하고, 1분마다 시급을 줍니다.
export type Effect = { export type Level = {
seats: number?, -- 테이블 수 cost: number,
spawn: number?, -- 손님 간격(초) stage: number, -- 이 단계(건물) 이상이어야 살 수 있음
cook: number?, -- 조리 시간(초) value: any, -- 갈래마다 뜻이 다름(메뉴 이름, 배율, 초, 접시 수, 단계)
price: number?, -- 가격 배율
helper: boolean?, -- 알바생(조리 자동)
menu: string?, -- 해금할 메뉴
carry: number?, -- 한 번에 드는 접시 수
stage: number?, -- 가게 단계(2 = 실내 분식집)
} }
export type Purchase = { export type Track = {
id: string, id: string,
cost: number, levels: { Level },
effect: Effect, }
export type Levels = { [string]: number }
export type Staff = { [string]: number } -- 역할별 고용 수(Cook, Server, Promoter)
export type Stats = {
stage: number,
menus: { string },
price: number,
spawn: number, -- 손님 간격(초). 홍보 알바·손님 러시 반영 전 값
cook: number,
carry: number,
staffUnlocked: boolean,
seats: number,
}
export type Role = {
id: string,
hire: number, -- 고용비(한 번)
wage: number, -- 시급(1분마다, 판매 금액 배율을 곱함)
max: number,
} }
export type Menu = { export type Menu = {
@@ -24,40 +45,35 @@ export type Menu = {
icon: string, icon: string,
} }
export type Stats = {
seats: number,
spawn: number,
cook: number,
price: number,
helper: boolean,
menus: { string },
carry: number,
stage: number,
}
local Economy = {} local Economy = {}
Economy.WALK = 5 -- 조리대 -> 테이블 -> 조리대 왕복(초, 시뮬레이터 가정) Economy.WALK = 5 -- 조리대 -> 테이블 -> 조리대 왕복(초, 시뮬레이터 가정)
Economy.EAT = 6 -- 식사 시간(초) Economy.EAT = 6 -- 식사 시간(초)
Economy.WALK_IN = 2.5 -- 손님이 입구에서 자리까지 걷는 시간(초) Economy.WALK_IN = 2.5 -- 손님이 입구에서 자리까지 걷는 기본 시간(초). 실제 길 길이에 맞춰 자리마다 바뀝니다
Economy.COUNTER_MAX = 3 -- 알바생이 미리 만들어 두는 접시 최대 수 Economy.COUNTER_MAX = 3 -- 요리 알바가 미리 만들어 두는 접시 최대 수(요리 알바 1명당)
Economy.BOOST_MINUTES = 10 -- 돈 부스트 팩: 현재 1분 매출 x 10분 Economy.BOOST_MINUTES = 10 -- 돈 부스트 팩: 현재 1분 매출 x 10분
Economy.BOOST_MIN = 100 -- 돈 부스트 팩 최소 지급액 Economy.BOOST_MIN = 100 -- 돈 부스트 팩 최소 지급액
Economy.GUEST_MULT = 2 -- 다른 플레이어가 손님으로 오면 주인은 접시 값의 2배를 받습니다 Economy.GUEST_MULT = 2 -- 다른 플레이어가 손님으로 오면 주인은 접시 값의 2배를 받습니다
Economy.GUEST_WAIT = 60 -- 손님으로 온 플레이어가 음식을 기다리는 최대 시간(초) Economy.GUEST_WAIT = 60 -- 손님으로 온 플레이어가 음식을 기다리는 최대 시간(초)
Economy.GUEST_BONUS_COOLDOWN = 60 -- 손님으로 먹었을 때 시식 보너스는 1분에 한 번 Economy.GUEST_BONUS_COOLDOWN = 60 -- 손님으로 먹었을 때 시식 보너스는 1분에 한 번
Economy.START = { Economy.WAGE_PERIOD = 60 -- 시급은 1분마다 줍니다(게임 속 1시간 = 1분)
money = 0, Economy.STRIKE_RETRY = 5 -- 시급이 모자라 쉬는 알바생은 5초마다 다시 확인
seats = 1, Economy.SERVER_TRIP = 3 -- 서빙 알바가 카운터에서 손님 자리까지 가는 기본 시간(초, 자리마다 바뀜)
spawn = 6, Economy.PROMOTER_MULT = 0.75 -- 홍보 알바가 있으면 손님 간격 x0.75
cook = 2.5,
price = 1, Economy.RUSH_SECONDS = 600 -- 손님 러시(유료): 10분 동안
helper = false, Economy.RUSH_MULT = 0.5 -- 손님 간격 절반
menus = { "Tteokbokki" }, Economy.PROMOTE_MAX = 3 -- 홍보 한 번에 옆 가게에서 데려오는 손님 수(빈자리만큼)
carry = 1, Economy.PROMOTE_COOLDOWN = 180 -- 광고 없이 하는 홍보 대기 시간(초)
stage = 1, Economy.PROMOTE_AD_COOLDOWN = 45 -- 광고를 보고 하는 홍보 대기 시간(초)
} Economy.KICK_SHIELD = 180 -- 손님을 쫓겨난 가게는 3분 동안 다시 쫓겨나지 않음
Economy.TRANSFER_WALK = 7 -- 옆 가게에서 우리 가게 자리까지 걸어오는 시간(초)
Economy.START_MONEY = 0
Economy.START_SPAWN = 10 -- 처음 손님 간격(예전 6초에서 느리게)
Economy.START_COOK = 2.5
Economy.START_MENUS = { "Tteokbokki" }
Economy.MENUS = { Economy.MENUS = {
Tteokbokki = { price = 15, icon = "🌶️" }, Tteokbokki = { price = 15, icon = "🌶️" },
@@ -70,89 +86,270 @@ Economy.MENUS = {
-- 메뉴 표시 순서 -- 메뉴 표시 순서
Economy.MENU_ORDER = { "Tteokbokki", "Gimbap", "Sundae", "Eomuk", "Twigim" } Economy.MENU_ORDER = { "Tteokbokki", "Gimbap", "Sundae", "Eomuk", "Twigim" }
-- 1~10: 첫 10분(1단계 포장마차). 11~20: 2단계 실내 분식집. -- 업그레이드 갈래. 각 갈래는 앞 단계부터 차례로 삽니다.
Economy.PURCHASES = { Economy.TRACKS = {
{ id = "Table2", cost = 10, effect = { seats = 2 } },
{ id = "UnlockGimbap", cost = 40, effect = { menu = "Gimbap" } },
{ id = "Sign1", cost = 70, effect = { spawn = 5 } },
{ id = "Stove1", cost = 90, effect = { cook = 1.5 } },
{ id = "Table3", cost = 120, effect = { seats = 3 } },
{ id = "UnlockSundae", cost = 160, effect = { menu = "Sundae" } },
{ id = "Sauce1", cost = 240, effect = { price = 1.5 } },
{ id = "Helper", cost = 360, effect = { helper = true } },
{ id = "Table4", cost = 480, effect = { seats = 4, spawn = 4 } },
{ id = "Expand", cost = 600, effect = { stage = 2 } },
{ id = "Tray1", cost = 700, effect = { carry = 2 } },
{ id = "Table5", cost = 800, effect = { seats = 5 } },
{ {
id = "UnlockEomuk", id = "Stage", -- 건물: 1 포장마차 → 2 실내 분식집 → 3 2층
cost = 950, levels = {
effect = { menu = "Eomuk" }, { cost = 450, stage = 1, value = 2 },
{ cost = 5000, stage = 2, value = 3 },
},
}, },
{ id = "Sign2", cost = 1150, effect = { spawn = 3 } },
{ id = "Table6", cost = 1400, effect = { seats = 6 } },
{ id = "Stove2", cost = 1700, effect = { cook = 1 } },
{ {
id = "UnlockTwigim", id = "Menu", -- 새 메뉴 해금
cost = 2000, levels = {
effect = { menu = "Twigim" }, { cost = 40, stage = 1, value = "Gimbap" },
{ cost = 160, stage = 1, value = "Sundae" },
{ cost = 950, stage = 2, value = "Eomuk" },
{ cost = 2000, stage = 2, value = "Twigim" },
},
}, },
{ id = "Sauce2", cost = 2500, effect = { price = 2 } }, {
{ id = "Tray2", cost = 3000, effect = { carry = 3 } }, id = "Price", -- 판매 금액(양념 비법): 모든 메뉴 값 배율
{ id = "Table8", cost = 3600, effect = { seats = 8, spawn = 2.5 } }, levels = {
} :: { Purchase } { cost = 120, stage = 1, value = 1.25 },
{ cost = 260, stage = 1, value = 1.5 },
{ cost = 1100, stage = 2, value = 1.75 },
{ cost = 2400, stage = 2, value = 2 },
{ cost = 7000, stage = 3, value = 2.5 },
{ cost = 12000, stage = 3, value = 3 },
},
},
{
id = "Speed", -- 손님 오는 속도(간판·전단지): 손님 간격(초)
levels = {
{ cost = 60, stage = 1, value = 8.5 },
{ cost = 150, stage = 1, value = 7 },
{ cost = 320, stage = 1, value = 6 },
{ cost = 1000, stage = 2, value = 5 },
{ cost = 2000, stage = 2, value = 4.2 },
{ cost = 6500, stage = 3, value = 3.5 },
{ cost = 11000, stage = 3, value = 3 },
},
},
{
id = "Stove", -- 화구: 요리 창에서 누르는 양(조리 수준)
levels = {
{ cost = 90, stage = 1, value = 1.8 },
{ cost = 800, stage = 2, value = 1.4 },
{ cost = 1800, stage = 2, value = 1 },
},
},
{
id = "Tray", -- 쟁반: 한 번에 드는 접시 수
levels = {
{ cost = 700, stage = 2, value = 2 },
{ cost = 2600, stage = 2, value = 3 },
},
},
{
id = "Staff", -- 알바생 기능 해금(이걸 사야 알바생을 고용할 수 있음)
levels = {
{ cost = 250, stage = 1, value = true },
},
},
} :: { Track }
Economy.MAX_SEATS = 8 Economy.TRACK_ORDER = {} :: { string }
local trackById: { [string]: Track } = {}
for _, t in Economy.TRACKS do
table.insert(Economy.TRACK_ORDER, t.id)
trackById[t.id] = t
end
-- 앞에서부터 `bought`개를 산 상태의 능력치 function Economy.track(id: string): Track?
function Economy.statsAt(bought: number): Stats return trackById[id]
local s = Economy.START end
-- 알바생 역할. 시급은 판매 금액 배율만큼 오릅니다(가게가 클수록 시급도 높음).
Economy.ROLES = {
{ id = "Cook", hire = 200, wage = 12, max = 2 }, -- 요리: 카운터에 접시를 만들어 둠
{ id = "Server", hire = 500, wage = 15, max = 2 }, -- 서빙: 카운터 접시를 손님 자리로 날라 줌
{ id = "Promoter", hire = 400, wage = 10, max = 1 }, -- 홍보: 입구에서 전단지, 손님 간격 x0.75
} :: { Role }
local roleById: { [string]: Role } = {}
for _, r in Economy.ROLES do
roleById[r.id] = r
end
function Economy.role(id: string): Role?
return roleById[id]
end
-- 자리(손님 의자). 테이블 하나에 의자 4개까지. 건물 단계별로 놓을 수 있는 수가 다릅니다.
Economy.CHAIRS_PER_TABLE = 4
Economy.SEAT_CAP = { 6, 14, 24 } -- 단계별 최대 의자 수
Economy.TABLE_CAP = { 3, 6, 12 } -- 단계별 최대 테이블 수
-- s번째 자리(의자)를 사는 값. 처음 자리는 공짜(처음부터 테이블 1 + 의자 1).
function Economy.seatCost(s: number): number
if s <= 1 then
return 0
end
local raw = 10 * (s - 1) ^ 2.1
return math.floor(raw / 5 + 0.5) * 5
end
-- 테이블(의자 1개 포함)은 자리 값에 테이블 값을 더합니다.
function Economy.tableCost(tables: number, seats: number): number
return Economy.seatCost(seats + 1) + 15 * tables * tables
end
-- 꾸미기 소품(손님 수와 상관없는 장식). 크기는 Floor.FOOTPRINT
Economy.DECOR = {
{ id = "Plant", cost = 50 },
{ id = "Rug", cost = 80 },
{ id = "Balloons", cost = 120 },
{ id = "Lamp", cost = 150 },
{ id = "Teddy", cost = 250 },
{ id = "Fridge", cost = 400 },
} :: { { id: string, cost: number } }
Economy.DECOR_MAX = 20
function Economy.decor(id: string): { id: string, cost: number }?
for _, d in Economy.DECOR do
if d.id == id then
return d
end
end
return nil
end
-- 가게 건물 디자인(실내 분식집 이상에서 바꿀 수 있음). pass가 있으면 게임패스(Products 키)로 삽니다.
Economy.DESIGNS = {
{ id = "Basic" },
{ id = "Mint" },
{ id = "Brick" },
{ id = "Candy", pass = "CANDY_DESIGN_PASS" },
{ id = "Hanok", pass = "HANOK_DESIGN_PASS" },
} :: { { id: string, pass: string? } }
function Economy.design(id: string): { id: string, pass: string? }?
for _, d in Economy.DESIGNS do
if d.id == id then
return d
end
end
return nil
end
Economy.NAME_MAX = 20 -- 가게 이름 최대 글자 수
function Economy.level(levels: Levels, id: string): number
return levels[id] or 0
end
function Economy.emptyLevels(): Levels
local out = {}
for _, id in Economy.TRACK_ORDER do
out[id] = 0
end
return out
end
-- 저장된 값을 정리합니다(없는 갈래, 범위 밖 숫자).
function Economy.cleanLevels(raw: any): Levels
local out = Economy.emptyLevels()
if typeof(raw) == "table" then
for _, t in Economy.TRACKS do
local v = raw[t.id]
if typeof(v) == "number" then
out[t.id] = math.clamp(math.floor(v), 0, #t.levels)
end
end
end
return out
end
-- 갈래 레벨과 자리 수로 능력치를 계산합니다.
function Economy.stats(levels: Levels, seats: number): Stats
local stats: Stats = { local stats: Stats = {
seats = s.seats, stage = 1,
spawn = s.spawn, menus = table.clone(Economy.START_MENUS),
cook = s.cook, price = 1,
price = s.price, spawn = Economy.START_SPAWN,
helper = s.helper, cook = Economy.START_COOK,
menus = table.clone(s.menus), carry = 1,
carry = s.carry, staffUnlocked = false,
stage = s.stage, seats = math.max(1, seats),
} }
for i = 1, math.min(bought, #Economy.PURCHASES) do for _, t in Economy.TRACKS do
local e = Economy.PURCHASES[i].effect local n = math.min(levels[t.id] or 0, #t.levels)
if e.seats then for i = 1, n do
stats.seats = e.seats local v = t.levels[i].value
end if t.id == "Stage" then
if e.spawn then stats.stage = v
stats.spawn = e.spawn elseif t.id == "Menu" then
end table.insert(stats.menus, v)
if e.cook then elseif t.id == "Price" then
stats.cook = e.cook stats.price = v
end elseif t.id == "Speed" then
if e.price then stats.spawn = v
stats.price = e.price elseif t.id == "Stove" then
end stats.cook = v
if e.helper then elseif t.id == "Tray" then
stats.helper = true stats.carry = v
end elseif t.id == "Staff" then
if e.menu then stats.staffUnlocked = true
table.insert(stats.menus, e.menu) end
end
if e.carry then
stats.carry = e.carry
end
if e.stage then
stats.stage = e.stage
end end
end end
return stats return stats
end end
-- 갈래의 다음 단계(없으면 nil)
function Economy.nextLevel(levels: Levels, id: string): Level?
local t = trackById[id]
if not t then
return nil
end
return t.levels[(levels[id] or 0) + 1]
end
function Economy.seatCap(stage: number): number
return Economy.SEAT_CAP[math.clamp(stage, 1, #Economy.SEAT_CAP)]
end
function Economy.tableCap(stage: number): number
return Economy.TABLE_CAP[math.clamp(stage, 1, #Economy.TABLE_CAP)]
end
-- 한 접시 값(정수). moneyMult는 2배 수익 게임패스(1 또는 2) -- 한 접시 값(정수). moneyMult는 2배 수익 게임패스(1 또는 2)
function Economy.dishPrice(menu: string, stats: Stats, moneyMult: number): number function Economy.dishPrice(menu: string, stats: Stats, moneyMult: number): number
return math.floor(Economy.MENUS[menu].price * stats.price) * moneyMult return math.floor(Economy.MENUS[menu].price * stats.price) * moneyMult
end end
-- 역할별 시급(1분마다)
function Economy.wage(roleId: string, stats: Stats): number
local r = roleById[roleId]
if not r then
return 0
end
return math.floor(r.wage * stats.price + 0.5)
end
function Economy.totalWage(staff: Staff, stats: Stats): number
local total = 0
for _, r in Economy.ROLES do
total += (staff[r.id] or 0) * Economy.wage(r.id, stats)
end
return total
end
-- 손님 간격(초): 홍보 알바, 손님 러시 반영
function Economy.spawnInterval(stats: Stats, promoters: number, rush: boolean): number
local s = stats.spawn
if promoters > 0 then
s *= Economy.PROMOTER_MULT
end
if rush then
s *= Economy.RUSH_MULT
end
return s
end
-- 현재 능력치로 1분에 버는 돈(대략). 돈 부스트 팩 지급액 계산용 -- 현재 능력치로 1분에 버는 돈(대략). 돈 부스트 팩 지급액 계산용
function Economy.incomePerMinute(stats: Stats): number function Economy.incomePerMinute(stats: Stats): number
local total = 0 local total = 0
@@ -170,4 +367,132 @@ function Economy.boostAmount(stats: Stats): number
return math.max(Economy.BOOST_MIN, Economy.incomePerMinute(stats) * Economy.BOOST_MINUTES) return math.max(Economy.BOOST_MIN, Economy.incomePerMinute(stats) * Economy.BOOST_MINUTES)
end end
-- 이름판에 붙는 가게 레벨: 산 업그레이드 단계 수 + 늘린 자리 수
function Economy.shopLevel(levels: Levels, seats: number): number
local n = math.max(0, seats - 1)
for _, id in Economy.TRACK_ORDER do
n += levels[id] or 0
end
return n
end
export type Offer = {
kind: string, -- "track" | "seat" | "table"
id: string, -- 갈래 id 또는 "Seat"/"Table"
cost: number,
}
-- 지금 살 수 있는 다음 단계들(건물 단계 조건을 채운 것). 화면 아래 "다음 업그레이드" 추천과 봇이 씁니다.
-- tables: 놓은 테이블 수, seats: 놓은 의자 수
function Economy.offers(levels: Levels, tables: number, seats: number): { Offer }
local stats = Economy.stats(levels, seats)
local out: { Offer } = {}
for _, id in Economy.TRACK_ORDER do
local nl = Economy.nextLevel(levels, id)
if nl and nl.stage <= stats.stage then
table.insert(out, { kind = "track", id = id, cost = nl.cost })
end
end
if seats < Economy.seatCap(stats.stage) then
if seats < tables * Economy.CHAIRS_PER_TABLE then
table.insert(out, { kind = "seat", id = "Seat", cost = Economy.seatCost(seats + 1) })
end
if tables < Economy.tableCap(stats.stage) then
table.insert(out, { kind = "table", id = "Table", cost = Economy.tableCost(tables, seats) })
end
end
table.sort(out, function(a, b)
if a.cost ~= b.cost then
return a.cost < b.cost
end
return a.id < b.id
end)
return out
end
-- 예전 세이브(한 줄 업그레이드 Bought개)를 갈래 레벨로 옮깁니다.
-- 돌려주는 값: 레벨, 자리 수, 테이블 수, 요리 알바 수
function Economy.migrate(bought: number): (Levels, number, number, number)
local OLD = {
"Table2",
"UnlockGimbap",
"Sign1",
"Stove1",
"Table3",
"UnlockSundae",
"Sauce1",
"Helper",
"Table4",
"Expand",
"Tray1",
"Table5",
"UnlockEomuk",
"Sign2",
"Table6",
"Stove2",
"UnlockTwigim",
"Sauce2",
"Tray2",
"Table8",
}
local levels = Economy.emptyLevels()
local seats = 1
local cooks = 0
local function up(id: string, n: number)
levels[id] = math.max(levels[id], n)
end
for i = 1, math.clamp(bought, 0, #OLD) do
local id = OLD[i]
if id == "Table2" then
seats = 2
elseif id == "Table3" then
seats = 3
elseif id == "Table4" then
seats = 4
up("Speed", 3)
elseif id == "Table5" then
seats = 5
elseif id == "Table6" then
seats = 6
elseif id == "Table8" then
seats = 8
up("Speed", 5)
elseif id == "UnlockGimbap" then
up("Menu", 1)
elseif id == "UnlockSundae" then
up("Menu", 2)
elseif id == "UnlockEomuk" then
up("Menu", 3)
elseif id == "UnlockTwigim" then
up("Menu", 4)
elseif id == "Sign1" then
up("Speed", 2)
elseif id == "Sign2" then
up("Speed", 4)
elseif id == "Stove1" then
up("Stove", 1)
elseif id == "Stove2" then
up("Stove", 3)
elseif id == "Sauce1" then
up("Price", 2)
elseif id == "Sauce2" then
up("Price", 4)
elseif id == "Helper" then
up("Staff", 1)
cooks = 1
elseif id == "Expand" then
up("Stage", 1)
elseif id == "Tray1" then
up("Tray", 1)
elseif id == "Tray2" then
up("Tray", 2)
end
end
-- 예전 테이블은 1인석이었으므로 자리 수만큼 테이블을 둡니다(단계별 최대 수 안에서).
local stage = Economy.stats(levels, seats).stage
local tables = math.min(seats, Economy.tableCap(stage))
seats = math.min(seats, tables * Economy.CHAIRS_PER_TABLE)
return levels, seats, tables, cooks
end
return Economy return Economy

View File

@@ -0,0 +1,831 @@
--!strict
-- 가게 안 배치(테이블·의자·조리대·소품)와 손님 길 찾기. 로블록스 API 없이 lune에서도 돌아갑니다.
-- 좌표는 부지 기준 상대 좌표(stud)입니다. 부지 원점은 바닥 가운데, +Z가 길(입구) 쪽.
-- 배치할 수 있는 곳은 건물 안쪽과 같은 넓이(포장마차 단계에서도 같음), 2층은 2층 건물(3단계)부터.
--
-- 저장 모양(Layout):
-- stove = { x, z, r } 조리대(포장마차 수레 + 카운터). r은 90도 단위 회전(0~3), 앞(+Z)으로 손님을 봄
-- tables = { { x, z, f } } f = 층(1 또는 2)
-- chairs = { { t, s } } t = 테이블 번호, s = 테이블의 어느 쪽(1 앞 +Z, 2 오른쪽 +X, 3 뒤 -Z, 4 왼쪽 -X)
-- decor = { { k, x, z, f, r } } k = 소품 종류(Economy.DECOR)
-- 의자는 테이블에 붙어 있어서 테이블을 옮기면 같이 옮겨집니다. 손님 자리 번호 = chairs 순서.
export type Pos = { x: number, z: number, f: number }
export type Stove = { x: number, z: number, r: number }
export type Table = { x: number, z: number, f: number }
export type Chair = { t: number, s: number }
export type Decor = { k: string, x: number, z: number, f: number, r: number }
export type Layout = {
stove: Stove,
tables: { Table },
chairs: { Chair },
decor: { Decor },
}
export type Rect = { x0: number, z0: number, x1: number, z1: number, f: number }
local Floor = {}
-- 배치할 수 있는 넓이(건물 안쪽 벽에서 1 stud 띄움)
Floor.X0 = -33
Floor.X1 = 33
Floor.Z0 = -37
Floor.Z1 = 19
Floor.FLOOR2_Y = 15 -- 2층 바닥 높이(1층 바닥 기준)
Floor.CELL = 1
Floor.DOOR = { x = 0, z = 19.5, f = 1 } -- 손님이 들어오는 문 안쪽
Floor.ENTRANCE = { x = 0, z = 32, f = 1 } -- 부지 입구(길 쪽)
-- 2층 계단: 왼쪽 벽을 따라 앞(아래)에서 뒤(위)로 올라갑니다.
Floor.STAIR_X = -30.5
Floor.STAIR_BOTTOM = { x = -30.5, z = 9, f = 1 }
Floor.STAIR_TOP = { x = -30.5, z = -23, f = 2 }
Floor.STAIR_HALF_W = 2.5
Floor.TABLE_SIZE = 5
Floor.CHAIR_SIZE = 2
Floor.CHAIR_OFFSET = 3.5 -- 테이블 가운데에서 의자 가운데까지
-- 소품 크기(가로 x, 세로 z, 회전 0 기준). walk = 밟고 지나갈 수 있음(러그)
Floor.FOOTPRINT = {
Stove = { w = 22, d = 10.5, walk = false },
Plant = { w = 2, d = 2, walk = false },
Rug = { w = 8, d = 6, walk = true },
Balloons = { w = 2, d = 2, walk = false },
Lamp = { w = 2, d = 2, walk = false },
Teddy = { w = 3, d = 3, walk = false },
Fridge = { w = 4, d = 2, walk = false },
} :: { [string]: { w: number, d: number, walk: boolean } }
-- 조리대 안의 위치(조리대 기준, 회전 0). 플레이어는 앞(+Z)에 서서 요리합니다.
Floor.STOVE_COOK = { x = -3, z = 0 } -- 화구
Floor.STOVE_COUNTER = { x = 5.5, z = 0 } -- 카운터(알바생 접시)
Floor.STOVE_FRONT = { x = 0, z = 4.5 } -- 플레이어가 서는 곳
Floor.STOVE_BACK = { x = -3, z = -4 } -- 요리 알바가 서는 곳
local SIDES = {
{ x = 0, z = 1 },
{ x = 1, z = 0 },
{ x = 0, z = -1 },
{ x = -1, z = 0 },
}
Floor.SIDES = SIDES
function Floor.default(): Layout
return {
stove = { x = 0, z = -26, r = 0 },
tables = { { x = -9, z = -10, f = 1 } },
chairs = { { t = 1, s = 1 } },
decor = {},
}
end
-- 회전(0~3, 90도 단위)한 상대 좌표. r=1이면 +Z가 +X 쪽을 봅니다.
function Floor.rotate(x: number, z: number, r: number): (number, number)
r = r % 4
if r == 0 then
return x, z
elseif r == 1 then
return z, -x
elseif r == 2 then
return -x, -z
end
return -z, x
end
-- 조리대 기준 상대 위치를 부지 좌표로
function Floor.stovePoint(stove: Stove, p: { x: number, z: number }): (number, number)
local dx, dz = Floor.rotate(p.x, p.z, stove.r)
return stove.x + dx, stove.z + dz
end
function Floor.chairPos(layout: Layout, i: number): Pos?
local c = layout.chairs[i]
local t = c and layout.tables[c.t]
if not t then
return nil
end
local d = SIDES[c.s]
if not d then
return nil
end
return { x = t.x + d.x * Floor.CHAIR_OFFSET, z = t.z + d.z * Floor.CHAIR_OFFSET, f = t.f }
end
local function rectAt(x: number, z: number, w: number, d: number, r: number, f: number): Rect
if r % 2 == 1 then
w, d = d, w
end
return { x0 = x - w / 2, z0 = z - d / 2, x1 = x + w / 2, z1 = z + d / 2, f = f }
end
local function overlap(a: Rect, b: Rect): boolean
return a.f == b.f and a.x0 < b.x1 - 1e-6 and b.x0 < a.x1 - 1e-6 and a.z0 < b.z1 - 1e-6 and b.z0 < a.z1 - 1e-6
end
-- 아무것도 놓을 수 없는 곳: 문 앞, 계단(2층 건물일 때)
function Floor.reserved(stage: number): { Rect }
local out: { Rect } = {
{ x0 = -5, z0 = 14, x1 = 5, z1 = 20, f = 1 },
}
if stage >= 3 then
local w = Floor.STAIR_HALF_W + 0.5
-- 1층: 계단과 아래 계단참, 2층: 계단 구멍과 위 계단참
table.insert(out, { x0 = Floor.STAIR_X - w, z0 = -24, x1 = Floor.STAIR_X + w, z1 = 13, f = 1 })
table.insert(out, { x0 = Floor.STAIR_X - w, z0 = -27, x1 = Floor.STAIR_X + w, z1 = 13, f = 2 })
end
return out
end
export type Piece = { kind: string, index: number, rect: Rect, walk: boolean }
-- 배치된 모든 물건의 바닥 차지 영역
function Floor.pieces(layout: Layout): { Piece }
local out: { Piece } = {}
local s = layout.stove
local fp = Floor.FOOTPRINT.Stove
-- 조리대 영역: 수레와 뒤쪽(알바생·진열대) + 천막 앞 기둥 2개. 플레이어가 서는 앞쪽(천막 아래)은 비워 둡니다.
local cx, cz = Floor.stovePoint(s, { x = 0, z = -2.75 })
table.insert(out, { kind = "stove", index = 1, rect = rectAt(cx, cz, fp.w, fp.d, s.r, 1), walk = false })
for _, px in { -10, 10 } do
local qx, qz = Floor.stovePoint(s, { x = px, z = 6 })
table.insert(out, { kind = "stove", index = 1, rect = rectAt(qx, qz, 1, 1, 0, 1), walk = false })
end
for i, t in layout.tables do
table.insert(out, {
kind = "table",
index = i,
rect = rectAt(t.x, t.z, Floor.TABLE_SIZE, Floor.TABLE_SIZE, 0, t.f),
walk = false,
})
end
for i in layout.chairs do
local p = Floor.chairPos(layout, i)
if p then
table.insert(out, {
kind = "chair",
index = i,
rect = rectAt(p.x, p.z, Floor.CHAIR_SIZE, Floor.CHAIR_SIZE, 0, p.f),
walk = false,
})
end
end
for i, d in layout.decor do
local f = Floor.FOOTPRINT[d.k]
if f then
table.insert(out, { kind = "decor", index = i, rect = rectAt(d.x, d.z, f.w, f.d, d.r, d.f), walk = f.walk })
end
end
return out
end
-- 격자(1 stud 칸). 막힌 칸 = true
type Grid = { [number]: boolean }
local NX = math.floor((Floor.X1 - Floor.X0) / Floor.CELL + 0.5) + 2 -- 벽 쪽 1칸씩 여유
local NZ = math.floor((Floor.Z1 - Floor.Z0) / Floor.CELL + 0.5) + 2
local GX0 = Floor.X0 - Floor.CELL
local GZ0 = Floor.Z0 - Floor.CELL
local function cellOf(x: number, z: number): (number, number)
return math.floor((x - GX0) / Floor.CELL), math.floor((z - GZ0) / Floor.CELL)
end
local function cellCenter(i: number, j: number): (number, number)
return GX0 + (i + 0.5) * Floor.CELL, GZ0 + (j + 0.5) * Floor.CELL
end
local function key(i: number, j: number): number
return j * NX + i
end
local function inGrid(i: number, j: number): boolean
return i >= 0 and j >= 0 and i < NX and j < NZ
end
local function blockRect(g: Grid, r: Rect, pad: number)
local i0, j0 = cellOf(r.x0 - pad + 1e-6, r.z0 - pad + 1e-6)
local i1, j1 = cellOf(r.x1 + pad - 1e-6, r.z1 + pad - 1e-6)
for i = i0, i1 do
for j = j0, j1 do
if inGrid(i, j) then
g[key(i, j)] = true
end
end
end
end
-- 층별 막힌 칸. 계단 구멍(2층)도 막습니다. 계단 자체(1층)는 걸어서 지나갈 수 없게 막습니다.
local function buildGrid(layout: Layout, stage: number, f: number): Grid
local g: Grid = {}
for _, p in Floor.pieces(layout) do
if p.rect.f == f and not p.walk then
blockRect(g, p.rect, 0)
end
end
if stage >= 3 then
local w = Floor.STAIR_HALF_W
if f == 1 then
blockRect(g, { x0 = Floor.STAIR_X - w, z0 = -24, x1 = Floor.STAIR_X + w, z1 = 8, f = 1 }, 0)
else
blockRect(g, { x0 = Floor.STAIR_X - w, z0 = -22, x1 = Floor.STAIR_X + w, z1 = 13, f = 2 }, 0)
end
end
return g
end
-- start 칸에서 걸어서 닿는 칸들(4방향)
local function flood(g: Grid, si: number, sj: number): { [number]: boolean }
local seen: { [number]: boolean } = {}
if not inGrid(si, sj) or g[key(si, sj)] then
return seen
end
local qi, qj = { si }, { sj }
seen[key(si, sj)] = true
local h = 1
while h <= #qi do
local i, j = qi[h], qj[h]
h += 1
for _, d in SIDES do
local ni, nj = i + d.x, j + d.z
local k = key(ni, nj)
if inGrid(ni, nj) and not g[k] and not seen[k] then
seen[k] = true
table.insert(qi, ni)
table.insert(qj, nj)
end
end
end
return seen
end
-- 사각형 바로 둘레 칸 중 닿는 칸이 있는지
local function touches(seen: { [number]: boolean }, r: Rect): boolean
local i0, j0 = cellOf(r.x0 - 0.5, r.z0 - 0.5)
local i1, j1 = cellOf(r.x1 + 0.5 - 1e-6, r.z1 + 0.5 - 1e-6)
for i = i0, i1 do
for j = j0, j1 do
if seen[key(i, j)] then
return true
end
end
end
return false
end
local function inBounds(r: Rect): boolean
return r.x0 >= Floor.X0 - 1e-6 and r.x1 <= Floor.X1 + 1e-6 and r.z0 >= Floor.Z0 - 1e-6 and r.z1 <= Floor.Z1 + 1e-6
end
-- 배치 전체를 검사합니다. 문제가 없으면 nil, 있으면 이유를 돌려줍니다.
-- "bounds"(밖), "overlap"(겹침), "reserved"(문·계단), "floor"(2층 없음), "blocked"(길이 막힘), "chair"(잘못된 의자)
function Floor.validate(layout: Layout, stage: number): string?
local pieces = Floor.pieces(layout)
if #pieces ~= 3 + #layout.tables + #layout.chairs + #layout.decor then
return "chair"
end
local reserved = Floor.reserved(stage)
for _, p in pieces do
if p.rect.f ~= 1 and (p.rect.f ~= 2 or stage < 3) then
return "floor"
end
if not inBounds(p.rect) then
return "bounds"
end
for _, r in reserved do
if overlap(p.rect, r) then
return "reserved"
end
end
end
if layout.stove.r % 1 ~= 0 then
return "bounds"
end
-- 같은 테이블의 같은 쪽에 의자 둘 금지
local used: { [string]: boolean } = {}
for _, c in layout.chairs do
local k = `{c.t}:{c.s}`
if used[k] then
return "chair"
end
used[k] = true
end
for a = 1, #pieces do
local pa = pieces[a]
if not pa.walk then
for b = a + 1, #pieces do
local pb = pieces[b]
if not pb.walk then
-- 의자는 자기 테이블과 붙어 있어도 됩니다(실제로 겹치지 않음).
if overlap(pa.rect, pb.rect) then
return "overlap"
end
end
end
end
end
-- 길: 문에서 조리대 앞과 1층 의자, 2층은 계단 위에서 2층 의자까지 닿아야 합니다.
local g1 = buildGrid(layout, stage, 1)
local di, dj = cellOf(Floor.DOOR.x, Floor.DOOR.z - 0.6)
local seen1 = flood(g1, di, dj)
local fx, fz = Floor.stovePoint(layout.stove, Floor.STOVE_FRONT)
local si, sj = cellOf(fx, fz)
if not seen1[key(si, sj)] then
return "blocked"
end
local seen2: { [number]: boolean }? = nil
if stage >= 3 then
local bi, bj = cellOf(Floor.STAIR_BOTTOM.x, Floor.STAIR_BOTTOM.z + 1.5)
if not seen1[key(bi, bj)] then
return "blocked"
end
local g2 = buildGrid(layout, stage, 2)
local ti, tj = cellOf(Floor.STAIR_TOP.x, Floor.STAIR_TOP.z - 1.5)
seen2 = flood(g2, ti, tj)
end
for _, p in pieces do
if p.kind == "chair" then
local seen = if p.rect.f == 1 then seen1 else seen2
if not seen or not touches(seen, p.rect) then
return "blocked"
end
end
end
return nil
end
function Floor.clone(layout: Layout): Layout
local out: Layout = {
stove = table.clone(layout.stove),
tables = {},
chairs = {},
decor = {},
}
for i, t in layout.tables do
out.tables[i] = table.clone(t)
end
for i, c in layout.chairs do
out.chairs[i] = table.clone(c)
end
for i, d in layout.decor do
out.decor[i] = table.clone(d)
end
return out
end
local function num(v: any, default: number): number
return if typeof(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then v else default
end
-- 저장된 값을 안전한 모양으로 고칩니다(빠진 값·이상한 값). 검사(validate)는 따로 합니다.
function Floor.clean(raw: any): Layout
local layout = Floor.default()
if typeof(raw) ~= "table" then
return layout
end
if typeof(raw.stove) == "table" then
layout.stove = {
x = num(raw.stove.x, 0),
z = num(raw.stove.z, -26),
r = math.floor(num(raw.stove.r, 0)) % 4,
}
end
if typeof(raw.tables) == "table" then
layout.tables = {}
for _, t in raw.tables do
if typeof(t) == "table" then
table.insert(layout.tables, { x = num(t.x, 0), z = num(t.z, 0), f = if t.f == 2 then 2 else 1 })
end
end
end
if typeof(raw.chairs) == "table" then
layout.chairs = {}
for _, c in raw.chairs do
if typeof(c) == "table" then
local t = math.floor(num(c.t, 0))
local s = math.floor(num(c.s, 0))
if layout.tables[t] and SIDES[s] then
table.insert(layout.chairs, { t = t, s = s })
end
end
end
end
if typeof(raw.decor) == "table" then
layout.decor = {}
for _, d in raw.decor do
if typeof(d) == "table" and typeof(d.k) == "string" and Floor.FOOTPRINT[d.k] and d.k ~= "Stove" then
table.insert(layout.decor, {
k = d.k,
x = num(d.x, 0),
z = num(d.z, 0),
f = if d.f == 2 then 2 else 1,
r = math.floor(num(d.r, 0)) % 4,
})
end
end
end
if #layout.tables == 0 then
layout.tables = { { x = -9, z = -10, f = 1 } }
end
if #layout.chairs == 0 then
layout.chairs = { { t = 1, s = 1 } }
end
return layout
end
-- 새 물건을 놓을 빈 곳 후보(문 가까운 앞쪽부터, 가운데 통로를 비워 두는 순서)
local function candidates(f: number): { { x: number, z: number, f: number } }
local out = {}
local preferred = {
{ -9, -10 },
{ 9, -10 },
{ -9, 4 },
{ 9, 4 },
{ -23, -10 },
{ 23, -10 },
{ -23, 4 },
{ 23, 4 },
{ -9, -20 },
{ 9, -20 },
{ -23, -22 },
{ 23, -22 },
{ -23, -32 },
{ 23, -32 },
}
for _, p in preferred do
table.insert(out, { x = p[1], z = p[2], f = f })
end
for z = Floor.Z1 - 3, Floor.Z0 + 3, -2 do
for _, sx in { 1, -1 } do
for x = 7, Floor.X1 - 2, 2 do
table.insert(out, { x = x * sx, z = z, f = f })
end
end
end
return out
end
-- 새 테이블(+의자 1개)을 놓을 곳을 찾아 layout에 넣습니다. 놓으면 테이블 번호를 돌려줍니다.
function Floor.addTable(layout: Layout, stage: number): number?
local floors = if stage >= 3 then { 1, 2 } else { 1 }
for _, f in floors do
for _, c in candidates(f) do
local test = Floor.clone(layout)
table.insert(test.tables, { x = c.x, z = c.z, f = c.f })
local ti = #test.tables
for _, s in { 1, 3, 2, 4 } do
test.chairs[#layout.chairs + 1] = { t = ti, s = s }
if Floor.validate(test, stage) == nil then
layout.tables = test.tables
layout.chairs = test.chairs
return ti
end
end
end
end
return nil
end
-- 의자 1개를 빈 쪽에 붙입니다(table을 주면 그 테이블 먼저). 놓은 의자 번호를 돌려줍니다.
function Floor.addChair(layout: Layout, stage: number, prefer: number?): number?
local order = {}
if prefer and layout.tables[prefer] then
table.insert(order, prefer)
end
for i in layout.tables do
if i ~= prefer then
table.insert(order, i)
end
end
for _, ti in order do
for _, s in { 1, 3, 2, 4 } do
local test = Floor.clone(layout)
table.insert(test.chairs, { t = ti, s = s })
if Floor.validate(test, stage) == nil then
layout.chairs = test.chairs
return #layout.chairs
end
end
end
return nil
end
function Floor.addDecor(layout: Layout, stage: number, kind: string): number?
if not Floor.FOOTPRINT[kind] or kind == "Stove" then
return nil
end
local floors = if stage >= 3 then { 1, 2 } else { 1 }
for _, f in floors do
-- 소품은 벽 쪽부터 찾습니다.
local list = {}
for z = Floor.Z0 + 2, Floor.Z1 - 2, 2 do
table.insert(list, { x = Floor.X0 + 2, z = z })
table.insert(list, { x = Floor.X1 - 2, z = z })
end
for x = Floor.X0 + 4, Floor.X1 - 4, 2 do
table.insert(list, { x = x, z = Floor.Z0 + 2 })
end
for _, c in candidates(f) do
table.insert(list, { x = c.x, z = c.z })
end
for _, c in list do
local test = Floor.clone(layout)
table.insert(test.decor, { k = kind, x = c.x, z = c.z, f = f, r = 0 })
if Floor.validate(test, stage) == nil then
layout.decor = test.decor
return #layout.decor
end
end
end
return nil
end
-- 물건 하나를 옮긴 새 배치를 만들어 검사합니다. 문제없으면 (새 배치, nil), 아니면 (nil, 이유)
-- kind: "stove" | "table" | "decor" | "chair"(chair는 s만 바꿈: x 자리에 쪽 번호)
export type Move = { kind: string, i: number, x: number, z: number, f: number?, r: number? }
function Floor.move(layout: Layout, stage: number, m: Move): (Layout?, string?)
local test = Floor.clone(layout)
local x = math.floor(m.x * 2 + 0.5) / 2 -- 0.5 stud 단위
local z = math.floor(m.z * 2 + 0.5) / 2
local f = if m.f == 2 then 2 else 1
local r = math.floor(m.r or 0) % 4
if m.kind == "stove" then
test.stove = { x = x, z = z, r = r }
elseif m.kind == "table" then
local t = test.tables[m.i]
if not t then
return nil, "none"
end
test.tables[m.i] = { x = x, z = z, f = f }
elseif m.kind == "decor" then
local d = test.decor[m.i]
if not d then
return nil, "none"
end
test.decor[m.i] = { k = d.k, x = x, z = z, f = f, r = r }
elseif m.kind == "chair" then
local c = test.chairs[m.i]
local s = math.floor(m.x)
if not c or not SIDES[s] then
return nil, "none"
end
-- 다른 테이블로 옮길 수도 있음(z 자리에 테이블 번호, 0이면 그대로)
local t = math.floor(m.z)
if t ~= 0 then
if not test.tables[t] then
return nil, "none"
end
c.t = t
end
c.s = s
else
return nil, "none"
end
local why = Floor.validate(test, stage)
if why then
return nil, why
end
return test, nil
end
-- 2층 건물로 올릴 때처럼 배치가 더 이상 맞지 않으면, 문제 있는 물건을 빈 곳으로 옮깁니다.
function Floor.repair(layout: Layout, stage: number): Layout
if Floor.validate(layout, stage) == nil then
return layout
end
local fixed = Floor.clone(layout)
-- 조리대가 문제면 기본 자리로
local reserved = Floor.reserved(stage)
local function bad(rect: Rect): boolean
if not inBounds(rect) or (rect.f == 2 and stage < 3) then
return true
end
for _, r in reserved do
if overlap(rect, r) then
return true
end
end
return false
end
local pieces = Floor.pieces(fixed)
if bad(pieces[1].rect) then
fixed.stove = Floor.default().stove
end
-- 문제 있는 테이블(또는 그 의자)·소품을 빼고 다시 놓습니다.
local movedTables: { number } = {}
local tableBad: { [number]: boolean } = {}
for _, p in pieces do
if (p.kind == "table" or p.kind == "chair") and bad(p.rect) then
local ti = if p.kind == "table" then p.index else fixed.chairs[p.index].t
tableBad[ti] = true
end
end
for i in fixed.tables do
if tableBad[i] then
table.insert(movedTables, i)
end
end
for _, ti in movedTables do
-- 그 테이블을 아무도 안 쓰는 먼 곳에 잠깐 두고, 빈 곳을 찾아 옮깁니다.
local chairsOf = {}
for ci, c in fixed.chairs do
if c.t == ti then
table.insert(chairsOf, ci)
end
end
local placed = false
local floors = if stage >= 3 then { 2, 1 } else { 1 }
for _, f in floors do
if placed then
break
end
for _, c in candidates(f) do
local test = Floor.clone(fixed)
test.tables[ti] = { x = c.x, z = c.z, f = f }
local ok = true
for _, ci in chairsOf do
local found = false
for _, s in { 1, 3, 2, 4 } do
test.chairs[ci] = { t = ti, s = s }
-- 의자끼리 같은 쪽이면 안 되므로 다른 의자와 비교
local dup = false
for _, cj in chairsOf do
if cj < ci and test.chairs[cj].s == s then
dup = true
end
end
if not dup then
found = true
break
end
end
ok = ok and found
end
if ok and Floor.validate(test, stage) == nil then
fixed = test
placed = true
break
end
end
end
end
-- 소품은 맞지 않으면 다시 놓고, 놓을 곳이 없으면 뺍니다.
local decor = fixed.decor
fixed.decor = {}
for _, d in decor do
local test = Floor.clone(fixed)
table.insert(test.decor, d)
if Floor.validate(test, stage) == nil then
fixed.decor = test.decor
else
Floor.addDecor(fixed, stage, d.k)
end
end
return fixed
end
-- 손님 길: 부지 입구 -> 문 -> (계단) -> 의자. 꺾이는 점들만 돌려줍니다.
local function gridPath(g: Grid, ax: number, az: number, bx: number, bz: number): { { x: number, z: number } }?
local si, sj = cellOf(ax, az)
local ti, tj = cellOf(bx, bz)
if not inGrid(si, sj) or not inGrid(ti, tj) then
return nil
end
local startK = key(si, sj)
local goalK = key(ti, tj)
local prev: { [number]: number } = { [startK] = -1 }
local qi, qj = { si }, { sj }
local h = 1
local found = startK == goalK
while h <= #qi and not found do
local i, j = qi[h], qj[h]
h += 1
for _, d in SIDES do
local ni, nj = i + d.x, j + d.z
local k = key(ni, nj)
if inGrid(ni, nj) and prev[k] == nil and (not g[k] or k == goalK) then
prev[k] = key(i, j)
if k == goalK then
found = true
break
end
table.insert(qi, ni)
table.insert(qj, nj)
end
end
end
if not found then
return nil
end
local cells = {}
local k = goalK
while k ~= -1 do
table.insert(cells, 1, k)
k = prev[k]
end
-- 칸 경로를 직선으로 이어도 막힌 칸을 지나지 않는 점만 남깁니다.
local function clear(k1: number, k2: number): boolean
local i1, j1 = k1 % NX, k1 // NX
local i2, j2 = k2 % NX, k2 // NX
local steps = math.max(math.abs(i2 - i1), math.abs(j2 - j1)) * 3
for s = 1, steps - 1 do
local t = s / steps
local ci = math.floor(i1 + 0.5 + (i2 - i1) * t)
local cj = math.floor(j1 + 0.5 + (j2 - j1) * t)
local kk = key(ci, cj)
if g[kk] and kk ~= goalK and kk ~= startK then
return false
end
end
return true
end
local out = {}
local anchor = 1
table.insert(out, cells[1])
local i = 2
while i <= #cells do
if i == #cells or not clear(cells[anchor], cells[i + 1]) then
table.insert(out, cells[i])
anchor = i
end
i += 1
end
local pts = {}
for idx, kk in out do
local cx, cz = cellCenter(kk % NX, kk // NX)
if idx == 1 then
cx, cz = ax, az
elseif idx == #out then
cx, cz = bx, bz
end
table.insert(pts, { x = cx, z = cz })
end
return pts
end
-- 입구에서 의자까지 손님이 걷는 점들(층 포함). 못 찾으면 직선으로라도 이어 줍니다.
function Floor.pathToChair(layout: Layout, stage: number, chair: number): { Pos }
local target = Floor.chairPos(layout, chair)
local out: { Pos } = { Floor.ENTRANCE, { x = 0, z = 22, f = 1 }, { x = Floor.DOOR.x, z = Floor.DOOR.z, f = 1 } }
if not target then
return out
end
local g1 = buildGrid(layout, stage, 1)
local function append(g: Grid, f: number, ax: number, az: number, bx: number, bz: number)
local pts = gridPath(g, ax, az, bx, bz)
if not pts then
table.insert(out, { x = bx, z = bz, f = f })
return
end
for i = 2, #pts do
table.insert(out, { x = pts[i].x, z = pts[i].z, f = f })
end
end
-- 의자 바로 앞(테이블 반대쪽, 없으면 옆) 빈칸까지 걸어간 뒤 의자에 앉습니다.
local function approach(g: Grid): (number, number)
local c = layout.chairs[chair]
local back = SIDES[c.s]
local dirs = { back, { x = back.z, z = back.x }, { x = -back.z, z = -back.x } }
local dist = Floor.CHAIR_SIZE / 2 + 0.6
for _, d in dirs do
local ax, az = target.x + d.x * dist, target.z + d.z * dist
local i, j = cellOf(ax, az)
if inGrid(i, j) and not g[key(i, j)] then
return ax, az
end
end
return target.x + back.x * dist, target.z + back.z * dist
end
local doorIn = Floor.DOOR.z - 0.6
table.insert(out, { x = Floor.DOOR.x, z = doorIn, f = 1 })
if target.f == 1 then
local ax, az = approach(g1)
append(g1, 1, Floor.DOOR.x, doorIn, ax, az)
else
local b = Floor.STAIR_BOTTOM
local t = Floor.STAIR_TOP
append(g1, 1, Floor.DOOR.x, doorIn, b.x, b.z + 1.5)
table.insert(out, { x = b.x, z = b.z, f = 1 })
table.insert(out, { x = t.x, z = t.z, f = 2 })
local g2 = buildGrid(layout, stage, 2)
local ax, az = approach(g2)
append(g2, 2, t.x, t.z - 1.5, ax, az)
end
table.insert(out, target)
return out
end
-- 길 길이(stud). 층 사이는 계단 길이로 셉니다.
function Floor.pathLength(path: { Pos }): number
local total = 0
for i = 2, #path do
local a, b = path[i - 1], path[i]
local dy = (b.f - a.f) * Floor.FLOOR2_Y
total += math.sqrt((b.x - a.x) ^ 2 + (b.z - a.z) ^ 2 + dy * dy)
end
return total
end
return Floor

View File

@@ -1,15 +1,16 @@
--!strict --!strict
-- 가게 한 곳의 규칙(손님, 주문, 조리, 서빙, 돈, 구매)을 담은 순수 로직입니다. -- 가게 한 곳의 규칙(손님, 주문, 조리, 서빙, 돈, 업그레이드, 알바생, 시급)을 담은 순수 로직입니다.
-- 로블록스 API를 쓰지 않아서 lune 단위 테스트와 시뮬레이터에서 그대로 돌립니다. -- 로블록스 API를 쓰지 않아서 lune 단위 테스트와 시뮬레이터에서 그대로 돌립니다.
-- 화면(NPC, 접시 모형, 효과)은 서버의 PlotController가 이벤트를 받아 그립니다. -- 화면(NPC, 접시 모형, 효과)은 서버의 PlotController가 이벤트를 받아 그립니다.
-- 테이블·의자 위치는 모릅니다. 자리 수(seats)와 자리별 걷는 시간(seatWalk)만 압니다.
-- 로블록스에서는 script.Parent, lune(테스트)에서는 파일 경로로 불러옵니다. -- 로블록스에서는 script.Parent, lune(테스트)에서는 파일 경로로 불러옵니다.
local Economy: typeof(require(script.Parent.Economy)) = if script local Economy: typeof(require(script.Parent.Economy)) = if script
then require(script.Parent.Economy) then require(script.Parent.Economy)
else (require :: any)("./Economy") else (require :: any)("./Economy")
type Stats = typeof(Economy.statsAt(0)) type Stats = Economy.Stats
type Purchase = typeof(Economy.PURCHASES[1]) type Levels = Economy.Levels
export type CustomerState = "walking" | "waiting" | "eating" export type CustomerState = "walking" | "waiting" | "eating"
@@ -20,47 +21,89 @@ export type Customer = {
state: CustomerState, state: CustomerState,
untilT: number, -- walking/eating이 끝나는 시각. 플레이어 손님은 기다리다 일어나는 시각 untilT: number, -- walking/eating이 끝나는 시각. 플레이어 손님은 기다리다 일어나는 시각
guest: number?, -- 다른 플레이어가 손님으로 왔으면 그 UserId guest: number?, -- 다른 플레이어가 손님으로 왔으면 그 UserId
transfer: boolean?, -- 옆 가게에서 데려온 손님
}
-- 서빙 알바가 나르는 중인 접시
export type Trip = {
staff: number, -- 서빙 알바 번호(1부터)
id: number, -- 손님 id
menu: string,
doneT: number,
} }
export type Event = export type Event =
{ kind: "spawn", id: number, seat: number, menu: string } { kind: "spawn", id: number, seat: number, menu: string, transfer: boolean? }
| { kind: "seated", id: number } | { kind: "seated", id: number }
| { kind: "leave", id: number, seat: number, guest: number?, served: boolean } | { kind: "leave", id: number, seat: number, guest: number?, served: boolean }
| { kind: "counter", menu: string } | { kind: "counter", menu: string, staff: number }
| { kind: "deliver", id: number, menu: string, staff: number, index: number }
| { kind: "delivered", id: number, staff: number, earn: number }
| { kind: "returned", menu: string, staff: number }
| { kind: "wage", amount: number }
| { kind: "strike", on: boolean }
export type Shop = { export type Shop = {
money: number, money: number,
bought: number, levels: Levels,
moneyMult: number,
stats: Stats, stats: Stats,
moneyMult: number,
customers: { [number]: Customer }, customers: { [number]: Customer },
seatTaken: { [number]: number }, seatTaken: { [number]: number },
seatWalk: { [number]: number }, -- 자리별 입구 -> 자리 걷는 시간
hand: { string }, hand: { string },
counter: { string }, counter: { string },
trips: { [number]: Trip }, -- 서빙 알바 번호 -> 나르는 중
staff: Economy.Staff,
strike: boolean, -- 시급이 모자라 알바생이 쉬는 중
wageDue: number, -- 다음 시급 주는 시각
cookNext: { [number]: number }, -- 요리 알바 번호 -> 다음에 만들 수 있는 시각
rushLeft: number, -- 손님 러시 남은 초
now: number, now: number,
nextSpawn: number, nextSpawn: number,
nextHelper: number,
menuIndex: number, menuIndex: number,
lastId: number, lastId: number,
served: number, served: number,
earned: number, earned: number,
} }
export type Options = {
money: number,
levels: Levels?,
seats: number?,
staff: Economy.Staff?,
now: number,
rushLeft: number?,
}
local Shop = {} local Shop = {}
function Shop.new(money: number, bought: number, now: number): Shop function Shop.new(opts: Options): Shop
local levels = Economy.cleanLevels(opts.levels)
local seats = math.max(1, opts.seats or 1)
local staff: Economy.Staff = {}
for _, r in Economy.ROLES do
local n = if opts.staff then opts.staff[r.id] else nil
staff[r.id] = if typeof(n) == "number" then math.clamp(math.floor(n), 0, r.max) else 0
end
return { return {
money = money, money = opts.money,
bought = math.clamp(bought, 0, #Economy.PURCHASES), levels = levels,
stats = Economy.stats(levels, seats),
moneyMult = 1, moneyMult = 1,
stats = Economy.statsAt(bought),
customers = {}, customers = {},
seatTaken = {}, seatTaken = {},
seatWalk = {},
hand = {}, hand = {},
counter = {}, counter = {},
now = now, trips = {},
nextSpawn = now, -- 접속하자마자 첫 손님 staff = staff,
nextHelper = now, strike = false,
wageDue = opts.now + Economy.WAGE_PERIOD,
cookNext = {},
rushLeft = math.max(0, opts.rushLeft or 0),
now = opts.now,
nextSpawn = opts.now, -- 접속하자마자 첫 손님
menuIndex = 0, menuIndex = 0,
lastId = 0, lastId = 0,
served = 0, served = 0,
@@ -68,7 +111,14 @@ function Shop.new(money: number, bought: number, now: number): Shop
} }
end end
local function freeSeat(self: Shop): number? local function staffWorking(self: Shop, role: string): number
if self.strike or not self.stats.staffUnlocked then
return 0
end
return self.staff[role] or 0
end
function Shop.freeSeat(self: Shop): number?
for seat = 1, self.stats.seats do for seat = 1, self.stats.seats do
if self.seatTaken[seat] == nil then if self.seatTaken[seat] == nil then
return seat return seat
@@ -77,8 +127,48 @@ local function freeSeat(self: Shop): number?
return nil return nil
end end
-- 다음 손님이 주문할 메뉴(해금된 메뉴를 돌아가며) function Shop.freeSeatCount(self: Shop): number
local n = 0
for seat = 1, self.stats.seats do
if self.seatTaken[seat] == nil then
n += 1
end
end
return n
end
-- 손에 든 접시·카운터·나르는 중인 접시 중 기다리는 손님이 없는 메뉴(주인 없는 접시).
-- 손님이 옆 가게로 가 버려서 남은 접시입니다. 다음 손님이 이 메뉴를 주문하게 해서 접시가 버려지지 않게 합니다.
local function orphanMenu(self: Shop): string?
local have: { [string]: number } = {}
for _, m in self.hand do
have[m] = (have[m] or 0) + 1
end
for _, m in self.counter do
have[m] = (have[m] or 0) + 1
end
for _, t in self.trips do
have[t.menu] = (have[t.menu] or 0) + 1
end
for _, c in self.customers do
if c.state ~= "eating" and have[c.menu] then
have[c.menu] -= 1
end
end
for _, m in Economy.MENU_ORDER do
if (have[m] or 0) > 0 and table.find(self.stats.menus, m) then
return m
end
end
return nil
end
-- 다음 손님이 주문할 메뉴(주인 없는 접시가 있으면 그 메뉴, 아니면 해금된 메뉴를 돌아가며)
local function nextOrder(self: Shop): string local function nextOrder(self: Shop): string
local orphan = orphanMenu(self)
if orphan then
return orphan
end
local menus = self.stats.menus local menus = self.stats.menus
local menu = menus[(self.menuIndex % #menus) + 1] local menu = menus[(self.menuIndex % #menus) + 1]
self.menuIndex += 1 self.menuIndex += 1
@@ -94,9 +184,13 @@ function Shop.openOrders(self: Shop): { Customer }
for _, m in self.counter do for _, m in self.counter do
covered[m] = (covered[m] or 0) + 1 covered[m] = (covered[m] or 0) + 1
end end
local tripFor: { [number]: boolean } = {}
for _, t in self.trips do
tripFor[t.id] = true
end
local list = {} local list = {}
for _, c in self.customers do for _, c in self.customers do
if c.state ~= "eating" then if c.state ~= "eating" and not tripFor[c.id] then
table.insert(list, c) table.insert(list, c)
end end
end end
@@ -134,10 +228,71 @@ function Shop.handFull(self: Shop): boolean
return #self.hand >= self.stats.carry return #self.hand >= self.stats.carry
end end
function Shop.spawnInterval(self: Shop): number
return Economy.spawnInterval(self.stats, staffWorking(self, "Promoter"), self.rushLeft > 0)
end
local function addCustomer(self: Shop, seat: number, menu: string, walk: number, transfer: boolean?): Customer
self.lastId += 1
local c: Customer = {
id = self.lastId,
seat = seat,
menu = menu,
state = "walking",
untilT = self.now + walk,
transfer = transfer,
}
self.customers[c.id] = c
self.seatTaken[seat] = c.id
return c
end
-- 손님 자리까지 서빙 알바가 가는 시간
local function tripTime(self: Shop, seat: number): number
local walk = self.seatWalk[seat] or Economy.WALK_IN
return math.max(1.5, Economy.SERVER_TRIP * walk / Economy.WALK_IN)
end
local function payWages(self: Shop, now: number, events: { Event })
if now < self.wageDue then
return
end
local total = Economy.totalWage(self.staff, self.stats)
if total <= 0 or not self.stats.staffUnlocked then
self.wageDue = now + Economy.WAGE_PERIOD
if self.strike then
self.strike = false
table.insert(events, { kind = "strike", on = false } :: Event)
end
return
end
if self.money >= total then
self.money -= total
self.wageDue = now + Economy.WAGE_PERIOD
table.insert(events, { kind = "wage", amount = total } :: Event)
if self.strike then
self.strike = false
table.insert(events, { kind = "strike", on = false } :: Event)
end
else
self.wageDue = now + Economy.STRIKE_RETRY
if not self.strike then
self.strike = true
table.insert(events, { kind = "strike", on = true } :: Event)
end
end
end
-- 시간을 now까지 진행합니다. 일어난 일을 이벤트로 돌려줍니다. -- 시간을 now까지 진행합니다. 일어난 일을 이벤트로 돌려줍니다.
function Shop.tick(self: Shop, now: number): { Event } function Shop.tick(self: Shop, now: number): { Event }
local dt = math.max(0, now - self.now)
self.now = now self.now = now
local events: { Event } = {} local events: { Event } = {}
if self.rushLeft > 0 then
self.rushLeft = math.max(0, self.rushLeft - dt)
end
payWages(self, now, events)
for id, c in self.customers do for id, c in self.customers do
if c.state == "walking" and now >= c.untilT then if c.state == "walking" and now >= c.untilT then
@@ -155,36 +310,88 @@ function Shop.tick(self: Shop, now: number): { Event }
end end
if now >= self.nextSpawn then if now >= self.nextSpawn then
local seat = freeSeat(self) local seat = Shop.freeSeat(self)
if seat then if seat then
self.lastId += 1
local menu = nextOrder(self) local menu = nextOrder(self)
local c: Customer = { local c = addCustomer(self, seat, menu, self.seatWalk[seat] or Economy.WALK_IN)
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) table.insert(events, { kind = "spawn", id = c.id, seat = seat, menu = menu } :: Event)
end end
self.nextSpawn = now + self.stats.spawn self.nextSpawn = now + Shop.spawnInterval(self)
end end
if self.stats.helper and now >= self.nextHelper then -- 요리 알바: 한 명마다 조리 수준(초)에 한 접시씩 카운터에 만들어 둡니다.
local menu = Shop.nextCookMenu(self) local cooks = staffWorking(self, "Cook")
if menu and #self.counter < Economy.COUNTER_MAX then for i = 1, cooks do
table.insert(self.counter, menu) if now >= (self.cookNext[i] or 0) and #self.counter < Economy.COUNTER_MAX * cooks then
table.insert(events, { kind = "counter", menu = menu } :: Event) local menu = Shop.nextCookMenu(self)
self.nextHelper = now + self.stats.cook if menu then
table.insert(self.counter, menu)
table.insert(events, { kind = "counter", menu = menu, staff = i } :: Event)
self.cookNext[i] = now + self.stats.cook
end
end
end
-- 서빙 알바: 다 나른 접시는 손님에게 놓고, 빈 손이면 카운터 접시를 기다리는 손님에게 가져갑니다.
for i, t in self.trips do
if now >= t.doneT then
self.trips[i] = nil
local c = self.customers[t.id]
if c and c.state == "waiting" then
c.state = "eating"
c.untilT = now + Economy.EAT
local earn = Shop.pay(self, c)
table.insert(events, { kind = "delivered", id = c.id, staff = i, earn = earn } :: Event)
else
table.insert(self.counter, t.menu)
table.insert(events, { kind = "returned", menu = t.menu, staff = i } :: Event)
end
end
end
local servers = staffWorking(self, "Server")
for i = 1, servers do
if not self.trips[i] and #self.counter > 0 then
local busy: { [number]: boolean } = {}
for _, t in self.trips do
busy[t.id] = true
end
local best: Customer? = nil
local bestIdx = 0
for _, c in self.customers do
if c.state == "waiting" and not busy[c.id] and (not best or c.id < best.id) then
local idx = table.find(self.counter, c.menu)
if idx then
best = c
bestIdx = idx
end
end
end
if best then
table.remove(self.counter, bestIdx)
self.trips[i] = { staff = i, id = best.id, menu = best.menu, doneT = now + tripTime(self, best.seat) }
table.insert(
events,
{ kind = "deliver", id = best.id, menu = best.menu, staff = i, index = bestIdx } :: Event
)
end
end end
end end
return events return events
end end
-- 손님 한 명 값(접시 값, 플레이어 손님이면 2배)을 받습니다.
function Shop.pay(self: Shop, c: Customer): number
local earn = Economy.dishPrice(c.menu, self.stats, self.moneyMult)
if c.guest then
earn *= Economy.GUEST_MULT
end
self.money += earn
self.earned += earn
self.served += 1
return earn
end
-- 플레이어가 요리 화면에서 다 만들었을 때. 만든 메뉴를 돌려줍니다. -- 플레이어가 요리 화면에서 다 만들었을 때. 만든 메뉴를 돌려줍니다.
-- menu를 주면 그 메뉴를 기다리는 주문이 있을 때만 만들고, 없으면 먼저 온 손님 메뉴를 만듭니다. -- menu를 주면 그 메뉴를 기다리는 주문이 있을 때만 만들고, 없으면 먼저 온 손님 메뉴를 만듭니다.
function Shop.cook(self: Shop, menu: string?): string? function Shop.cook(self: Shop, menu: string?): string?
@@ -204,7 +411,7 @@ function Shop.cook(self: Shop, menu: string?): string?
return menu return menu
end end
-- 알바생이 만들어 둔 접시를 손에 듭니다. 든 접시 수를 돌려줍니다. -- 요리 알바가 만들어 둔 접시를 손에 듭니다. 든 접시 수를 돌려줍니다.
function Shop.pickup(self: Shop): number function Shop.pickup(self: Shop): number
local n = 0 local n = 0
while #self.counter > 0 and not Shop.handFull(self) do while #self.counter > 0 and not Shop.handFull(self) do
@@ -220,6 +427,11 @@ function Shop.serve(self: Shop, id: number): number?
if not c or c.state ~= "waiting" then if not c or c.state ~= "waiting" then
return nil return nil
end end
for _, t in self.trips do
if t.id == id then
return nil -- 서빙 알바가 가져가는 중
end
end
local idx = table.find(self.hand, c.menu) local idx = table.find(self.hand, c.menu)
if not idx then if not idx then
return nil return nil
@@ -227,41 +439,143 @@ function Shop.serve(self: Shop, id: number): number?
table.remove(self.hand, idx) table.remove(self.hand, idx)
c.state = "eating" c.state = "eating"
c.untilT = self.now + Economy.EAT c.untilT = self.now + Economy.EAT
local earn = Economy.dishPrice(c.menu, self.stats, self.moneyMult) return Shop.pay(self, c)
if c.guest then end
earn *= Economy.GUEST_MULT
-- 돈을 씁니다. 모자라면 false
function Shop.spend(self: Shop, cost: number): boolean
if cost < 0 or self.money < cost then
return false
end end
self.money += earn self.money -= cost
self.earned += earn return true
self.served += 1
return earn
end end
function Shop.nextPurchase(self: Shop): Purchase? local function refreshStats(self: Shop)
return Economy.PURCHASES[self.bought + 1] local before = self.stats
self.stats = Economy.stats(self.levels, before.seats)
if self.stats.spawn < before.spawn then
self.nextSpawn = math.min(self.nextSpawn, self.now + Shop.spawnInterval(self))
end
end end
-- 다음 업그레이드를 삽니다. 성공하면 산 항목을 돌려줍니다. -- 업그레이드 갈래의 다음 단계를 삽니다. 성공하면 산 단계(Level)를 돌려줍니다.
function Shop.buyNext(self: Shop): (Purchase?, string?) -- 실패 이유: "max"(다 삼), "stage"(건물 단계 부족), "money"
local p = Shop.nextPurchase(self) function Shop.buyLevel(self: Shop, trackId: string): (Economy.Level?, string?)
if not p then local nl = Economy.nextLevel(self.levels, trackId)
if not nl then
return nil, "max" return nil, "max"
end end
if self.money < p.cost then if nl.stage > self.stats.stage then
return nil, "stage"
end
if not Shop.spend(self, nl.cost) then
return nil, "money" return nil, "money"
end end
self.money -= p.cost self.levels[trackId] += 1
self.bought += 1 refreshStats(self)
self.stats = Economy.statsAt(self.bought) if trackId == "Menu" then
if p.effect.spawn then
self.nextSpawn = math.min(self.nextSpawn, self.now + p.effect.spawn)
end
if p.effect.menu then
-- 새 메뉴를 사면 다음 손님이 바로 그 메뉴를 주문해서, 산 효과가 곧바로 보이게 합니다. -- 새 메뉴를 사면 다음 손님이 바로 그 메뉴를 주문해서, 산 효과가 곧바로 보이게 합니다.
self.menuIndex = #self.stats.menus - 1 self.menuIndex = #self.stats.menus - 1
self.nextSpawn = math.min(self.nextSpawn, self.now + 1) self.nextSpawn = math.min(self.nextSpawn, self.now + 1)
end end
return p, nil return nl, nil
end
-- 자리 수가 바뀌었을 때(의자를 사거나 놓음)
function Shop.setSeats(self: Shop, seats: number)
self.stats = Economy.stats(self.levels, seats)
self.stats.seats = math.max(1, seats)
-- 새 자리가 생기면 손님이 곧 옵니다.
self.nextSpawn = math.min(self.nextSpawn, self.now + 1)
end
-- 알바생 고용·해고. 고용은 고용비를 냅니다. 실패 이유: "locked", "max", "money", "none"
function Shop.hire(self: Shop, roleId: string): (boolean, string?)
local r = Economy.role(roleId)
if not r then
return false, "none"
end
if not self.stats.staffUnlocked then
return false, "locked"
end
if (self.staff[roleId] or 0) >= r.max then
return false, "max"
end
if not Shop.spend(self, r.hire) then
return false, "money"
end
self.staff[roleId] = (self.staff[roleId] or 0) + 1
if self.wageDue < self.now then
self.wageDue = self.now + Economy.WAGE_PERIOD
end
if roleId == "Promoter" then
self.nextSpawn = math.min(self.nextSpawn, self.now + Shop.spawnInterval(self))
end
return true, nil
end
function Shop.fire(self: Shop, roleId: string): boolean
local n = self.staff[roleId] or 0
if n <= 0 then
return false
end
self.staff[roleId] = n - 1
if roleId == "Server" and self.trips[n] then
-- 나르던 접시는 카운터로 돌려놓습니다.
table.insert(self.counter, self.trips[n].menu)
self.trips[n] = nil
end
self.cookNext[n] = nil
return true
end
-- 손님 러시(유료): 남은 시간을 늘립니다.
function Shop.addRush(self: Shop, seconds: number)
self.rushLeft += seconds
self.nextSpawn = math.min(self.nextSpawn, self.now + Shop.spawnInterval(self))
end
-- 옆 가게에서 손님을 데려갈 때: 아직 음식을 못 받은(먹는 중이 아닌) NPC 손님을 최대 n명 빼서 돌려줍니다.
-- 그 손님 자리로 가던 서빙 알바 접시는 카운터로 돌아갑니다.
function Shop.takeCustomers(self: Shop, n: number): { Customer }
local list = {}
for _, c in self.customers do
if c.state ~= "eating" and not c.guest then
table.insert(list, c)
end
end
-- 늦게 온 손님부터(오래 기다린 손님은 곧 음식을 받으니까)
table.sort(list, function(a, b)
return a.id > b.id
end)
local out = {}
for i = 1, math.min(n, #list) do
local c = list[i]
self.customers[c.id] = nil
self.seatTaken[c.seat] = nil
for s, t in self.trips do
if t.id == c.id then
table.insert(self.counter, t.menu)
self.trips[s] = nil
end
end
table.insert(out, c)
end
return out
end
-- 옆 가게에서 온 손님을 빈자리에 앉힙니다(walk초 걸어옴). 자리가 없으면 nil
function Shop.addTransfer(self: Shop, menu: string, walk: number): Customer?
local seat = Shop.freeSeat(self)
if not seat then
return nil
end
-- 우리 가게에 없는 메뉴를 원하던 손님은 우리 메뉴로 바꿔 주문합니다.
if not table.find(self.stats.menus, menu) then
menu = nextOrder(self)
end
return addCustomer(self, seat, menu, walk, true)
end end
-- 다른 플레이어가 손님으로 와서 빈자리에 앉습니다(걷지 않고 바로 주문). 자리가 없거나 이미 앉아 있으면 nil. -- 다른 플레이어가 손님으로 와서 빈자리에 앉습니다(걷지 않고 바로 주문). 자리가 없거나 이미 앉아 있으면 nil.
@@ -271,21 +585,14 @@ function Shop.addGuest(self: Shop, userId: number): Customer?
return nil return nil
end end
end end
local seat = freeSeat(self) local seat = Shop.freeSeat(self)
if not seat then if not seat then
return nil return nil
end end
self.lastId += 1 local c = addCustomer(self, seat, nextOrder(self), 0)
local c: Customer = { c.state = "waiting"
id = self.lastId, c.untilT = self.now + Economy.GUEST_WAIT
seat = seat, c.guest = userId
menu = nextOrder(self),
state = "waiting",
untilT = self.now + Economy.GUEST_WAIT,
guest = userId,
}
self.customers[c.id] = c
self.seatTaken[seat] = c.id
return c return c
end end

View File

@@ -0,0 +1,13 @@
-- lune run tests/Codec.spec.luau
local Codec = require("../src/shared/Codec")
local T = require("./check")
local s = Codec.encodeMap({ Cook = 1, Server = 2 }, { "Cook", "Server", "Promoter" })
T.eq(s, "Cook=1,Server=2,Promoter=0", "encode")
local m = Codec.decodeMap(s)
T.eq(m.Server, 2, "decode")
T.eq(m.Promoter, 0, "decode 0")
T.eq(next(Codec.decodeMap(nil)), nil, "nil")
T.eq(Codec.decodeMap("Price=1.5").Price, 1.5, "소수")
T.eq(#Codec.decodeList("A,B,,C"), 3, "list")
T.eq(#Codec.decodeList(""), 0, "빈 list")
T.done("Codec.spec")

View File

@@ -2,63 +2,101 @@
local Economy = require("../src/shared/Economy") local Economy = require("../src/shared/Economy")
local T = require("./check") local T = require("./check")
T.eq(#Economy.PURCHASES, 20, "구매 항목은 20개(1단계 10 + 2단계 10)") -- 갈래마다 단계 값이 오르고 필요한 건물 단계가 내려가지 않음
T.eq(Economy.PURCHASES[10].id, "Expand", "10번째는 실내 확장") for _, t in Economy.TRACKS do
T.eq(Economy.PURCHASES[10].effect.stage, 2, "확장하면 2단계") local prevCost, prevStage = 0, 1
for i, l in t.levels do
local seen = {} T.check(l.cost > prevCost, `{t.id}{i} 비용이 앞 단계보다 커야 함`)
local prev = 0 T.check(l.stage >= prevStage, `{t.id}{i} 필요 단계가 줄지 않음`)
for i, p in Economy.PURCHASES do prevCost, prevStage = l.cost, l.stage
T.check(p.cost > prev, `#{i} {p.id} 비용이 앞 단계보다 커야 함`) if t.id == "Menu" then
prev = p.cost T.check(Economy.MENUS[l.value] ~= nil, `없는 메뉴 {l.value}`)
T.check(seen[p.id] == nil, `#{i} {p.id} id 중복`) end
seen[p.id] = true
if p.effect.menu then
T.check(Economy.MENUS[p.effect.menu] ~= nil, `#{i} 없는 메뉴 {p.effect.menu}`)
end end
end end
for _, key in Economy.MENU_ORDER do for _, key in Economy.MENU_ORDER do
T.check(Economy.MENUS[key] ~= nil, `메뉴 순서의 {key}`) T.check(Economy.MENUS[key] ~= nil, `메뉴 순서의 {key}`)
end end
local s0 = Economy.statsAt(0) local lv0 = Economy.emptyLevels()
T.eq(s0.seats, 1, "처음 테이블 1") local s0 = Economy.stats(lv0, 1)
T.eq(s0.spawn, 6, "처음 손님 간격 6초") T.eq(s0.seats, 1, "처음 자리 1")
T.eq(s0.cook, 2.5, "처음 조리 2.5초") T.eq(s0.spawn, 10, "처음 손님 간격 10초(예전 6초보다 느림)")
T.eq(s0.cook, 2.5, "처음 조리 2.5")
T.eq(#s0.menus, 1, "처음 메뉴 1개") T.eq(#s0.menus, 1, "처음 메뉴 1개")
T.eq(s0.carry, 1, "처음 접시 1개") T.eq(s0.carry, 1, "처음 접시 1개")
T.eq(s0.stage, 1, "처음 포장마차")
T.eq(s0.staffUnlocked, false, "처음엔 알바생 잠김")
local s10 = Economy.statsAt(10) local all = Economy.emptyLevels()
T.eq(s10.seats, 4, "10개 산 뒤 테이블 4") for _, t in Economy.TRACKS do
T.eq(s10.spawn, 4, "10개 산 뒤 손님 간격 4초") all[t.id] = #t.levels
T.eq(s10.helper, true, "10개 산 뒤 알바생") end
T.eq(s10.stage, 2, "10개 산 뒤 2단계") local sAll = Economy.stats(all, 24)
T.eq(#s10.menus, 3, "10개 산 뒤 메뉴 3개") T.eq(sAll.stage, 3, "다 사면 2층")
T.eq(#sAll.menus, 5, "메뉴 5개")
T.eq(sAll.carry, 3, "접시 3개")
T.eq(sAll.staffUnlocked, true, "알바생 열림")
T.eq(Economy.stats(Economy.cleanLevels({ Menu = 99, Bad = 3 }), 1).menus[5], "Twigim", "범위를 넘어도 안전")
T.eq(Economy.cleanLevels({ Menu = 99 }).Menu, 4, "레벨은 최대값으로 자름")
local s20 = Economy.statsAt(20) -- stats는 START_MENUS를 바꾸면 안 됨
T.eq(s20.seats, Economy.MAX_SEATS, "전부 산 뒤 테이블 8") Economy.stats(all, 1)
T.eq(s20.carry, 3, "전부 산 뒤 접시 3개") T.eq(#Economy.START_MENUS, 1, "START_MENUS 불변")
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), 15, "떡볶이 15") T.eq(Economy.dishPrice("Tteokbokki", s0, 1), 15, "떡볶이 15")
T.eq(Economy.dishPrice("Gimbap", Economy.statsAt(7), 1), 37, "김밥 25 x 1.5 = 37(내림)") local p2 = Economy.stats(Economy.cleanLevels({ Price = 2 }), 1)
T.eq(Economy.dishPrice("Gimbap", p2, 1), 37, "김밥 25 x 1.5 = 37(내림)")
T.eq(Economy.dishPrice("Tteokbokki", s0, 2), 30, "2배 수익") T.eq(Economy.dishPrice("Tteokbokki", s0, 2), 30, "2배 수익")
T.eq( -- 자리 값
Economy.boostAmount(s0), T.eq(Economy.seatCost(1), 0, "첫 자리 공짜")
math.max(Economy.BOOST_MIN, Economy.incomePerMinute(s0) * 10), T.eq(Economy.seatCost(2), 10, "두 번째 자리 10원(첫 구매 10초 안)")
"부스트 = 1분 매출 x 10분" local prev = 0
) for s = 2, 24 do
T.check( T.check(Economy.seatCost(s) > prev, `자리 {s} 값이 오름`)
Economy.incomePerMinute(s0) >= 30 and Economy.incomePerMinute(s0) <= 60, prev = Economy.seatCost(s)
"처음 1분 매출 30~60원(시뮬레이터와 비슷)" end
) T.check(Economy.tableCost(1, 1) > Economy.seatCost(2), "테이블은 의자보다 비쌈")
T.check(Economy.boostAmount(s20) > Economy.boostAmount(s10), "후반일수록 부스트가 큼")
-- 살 수 있는 것: 건물 단계 조건
local offers = Economy.offers(lv0, 1, 1)
local ids = {}
for _, o in offers do
ids[o.id] = true
end
T.check(ids.Menu and ids.Price and ids.Speed and ids.Stage and ids.Staff, "처음 살 수 있는 갈래")
T.check(not ids.Tray, "쟁반은 실내 분식집부터")
T.check(ids.Seat and ids.Table, "의자·테이블")
T.check(offers[1].cost <= offers[#offers].cost, "싼 순서")
local capped = Economy.offers(lv0, 3, 6)
for _, o in capped do
T.check(o.kind ~= "seat" and o.kind ~= "table", "1단계 자리 최대(6)면 자리 못 삼")
end
-- 시급
T.eq(Economy.wage("Cook", s0), 12, "요리 알바 시급 12")
T.eq(Economy.wage("Cook", p2), 18, "판매 금액 1.5배면 시급도 1.5배")
T.eq(Economy.totalWage({ Cook = 2, Server = 1 }, s0), 39, "시급 합")
T.eq(Economy.spawnInterval(s0, 1, false), 7.5, "홍보 알바 x0.75")
T.eq(Economy.spawnInterval(s0, 0, true), 5, "손님 러시 x0.5")
-- 예전 세이브 옮기기
local lv8, seats8, tables8, cooks8 = Economy.migrate(8)
T.eq(lv8.Menu, 2, "예전 8개: 메뉴 2")
T.eq(lv8.Price, 2, "양념 Lv1 = 판매 금액 1.5배")
T.eq(lv8.Staff, 1, "알바생 기능")
T.eq(cooks8, 1, "요리 알바 1명")
T.eq(seats8, 3, "자리 3")
T.eq(tables8, 3, "테이블 3")
local lv20, seats20, tables20 = Economy.migrate(20)
T.eq(lv20.Stage, 1, "예전 20개: 실내 분식집")
T.eq(seats20, 8, "자리 8")
T.eq(tables20, 6, "테이블은 2단계 최대 6")
T.eq(Economy.migrate(0).Menu, 0, "예전 0개")
T.check(Economy.incomePerMinute(s0) >= 20 and Economy.incomePerMinute(s0) <= 60, "처음 1분 매출 20~60원")
T.check(Economy.boostAmount(Economy.stats(all, 24)) > Economy.boostAmount(s0), "후반일수록 부스트가 큼")
T.eq(Economy.shopLevel(lv0, 1), 0, "처음 가게 레벨 0")
T.done("Economy.spec") T.done("Economy.spec")

View File

@@ -0,0 +1,118 @@
-- 배치·길 찾기 검사: lune run tests/Floor.spec.luau
local Floor = require("../src/shared/Floor")
local T = require("./check")
local base = Floor.default()
T.eq(Floor.validate(base, 1), nil, "기본 배치는 문제없음")
T.eq(#base.chairs, 1, "처음 의자 1개")
local p1 = Floor.chairPos(base, 1)
T.eq(p1 and p1.x, -9, "첫 의자 x")
T.eq(p1 and p1.z, -6.5, "첫 의자는 테이블 앞(+Z) 3.5")
-- 밖, 겹침, 문 앞
T.eq(select(2, Floor.move(base, 1, { kind = "table", i = 1, x = 40, z = 0 })), "bounds", "부지 밖")
T.eq(select(2, Floor.move(base, 1, { kind = "table", i = 1, x = 0, z = 16 })), "reserved", "문 앞에는 못 놓음")
T.eq(select(2, Floor.move(base, 1, { kind = "table", i = 1, x = 0, z = -24 })), "overlap", "조리대와 겹침")
T.eq(select(2, Floor.move(base, 1, { kind = "table", i = 1, x = 0, z = 0, f = 2 })), "floor", "2층은 3단계부터")
local moved, why = Floor.move(base, 1, { kind = "table", i = 1, x = 20, z = 5 })
T.eq(why, nil, "빈 곳으로 옮기기")
T.eq(moved and Floor.chairPos(moved, 1).x, 20, "의자도 같이 옮겨짐")
T.eq(base.tables[1].x, -9, "원래 배치는 그대로(복사본)")
-- 의자 쪽 바꾸기, 같은 쪽 두 개 금지
local two = Floor.clone(base)
T.check(Floor.addChair(two, 1, 1) ~= nil, "의자 추가")
T.eq(#two.chairs, 2, "의자 2")
T.check(two.chairs[2].s ~= two.chairs[1].s, "다른 쪽에 붙음")
T.eq(select(2, Floor.move(two, 1, { kind = "chair", i = 2, x = 1, z = 0 })), "chair", "같은 쪽 금지")
-- 테이블 자동 배치: 단계별 최대까지 놓을 수 있어야 함
local full = Floor.clone(base)
for _ = 2, 6 do
T.check(Floor.addTable(full, 2) ~= nil, "테이블 자동 배치")
end
T.eq(#full.tables, 6, "테이블 6")
T.eq(Floor.validate(full, 2), nil, "자동 배치 결과가 검사 통과")
for _ = 1, 8 do
T.check(Floor.addChair(full, 2) ~= nil, "의자 자동 배치")
end
T.eq(#full.chairs, 14, "의자 14(2단계 최대)")
T.eq(Floor.validate(full, 2), nil, "의자 14개 배치 통과")
-- 길: 입구에서 의자까지
for i = 1, #full.chairs do
local path = Floor.pathToChair(full, 2, i)
local last = path[#path]
local cp = Floor.chairPos(full, i)
T.check(last.x == cp.x and last.z == cp.z, `의자 {i}까지 길 끝`)
T.check(Floor.pathLength(path) < 120, `의자 {i} 길 길이 적당`)
end
-- 길을 막으면 거절: 조리대 앞을 테이블로 막기
local block = Floor.clone(base)
block.tables = { { x = -5, z = -21, f = 1 }, { x = 5, z = -21, f = 1 }, { x = 0, z = -17, f = 1 } }
block.chairs = { { t = 1, s = 1 }, { t = 2, s = 1 }, { t = 3, s = 1 } }
T.eq(Floor.validate(block, 1), "blocked", "조리대 앞을 테이블로 둘러싸면 거절")
block.tables[3] = { x = 0, z = -10, f = 1 }
T.eq(Floor.validate(block, 1), nil, "한쪽을 열면 통과")
-- 2층(3단계): 계단 자리 정리 후 2층에도 배치
local stair = Floor.clone(base)
stair.tables[1] = { x = -28, z = -2, f = 1 }
T.eq(Floor.validate(stair, 2), nil, "2단계에서는 계단 자리에 놓아도 됨")
T.check(Floor.validate(stair, 3) ~= nil, "3단계에서는 계단 자리와 겹침")
local fixed = Floor.repair(stair, 3)
T.eq(Floor.validate(fixed, 3), nil, "repair 후 통과")
local up = Floor.clone(fixed)
for _ = 1, 10 do
Floor.addTable(up, 3)
end
local on2 = 0
for _, t in up.tables do
if t.f == 2 then
on2 += 1
end
end
T.check(on2 > 0, "3단계에서는 2층에도 테이블이 놓임")
T.eq(Floor.validate(up, 3), nil, "2층 배치 통과")
for i, t in up.tables do
if t.f == 2 then
for ci, c in up.chairs do
if c.t == i then
local path = Floor.pathToChair(up, 3, ci)
local sawStair = false
for _, pt in path do
if pt.f == 2 then
sawStair = true
end
end
T.check(sawStair, "2층 의자 길은 계단을 지남")
end
end
end
end
-- 조리대 회전·이동
local s2, sw = Floor.move(base, 1, { kind = "stove", i = 1, x = 20, z = -28, r = 2 })
T.eq(sw, nil, "조리대를 옮기고 돌리기")
T.eq(s2 and s2.stove.r, 2, "회전 저장")
local fx, fz = Floor.stovePoint({ x = 0, z = 0, r = 1 }, { x = 0, z = 4.5 })
T.eq(fx, 4.5, "r=1이면 앞이 +X")
T.eq(fz, 0, "r=1 z")
-- 소품
local d = Floor.clone(base)
T.check(Floor.addDecor(d, 1, "Plant") ~= nil, "화분 놓기")
T.check(Floor.addDecor(d, 1, "Rug") ~= nil, "러그 놓기")
T.eq(Floor.addDecor(d, 1, "Stove"), nil, "조리대는 소품 아님")
T.eq(Floor.validate(d, 1), nil, "소품 배치 통과")
-- 저장값 정리
local cleaned =
Floor.clean({ stove = { x = "a" }, tables = { { x = 1, z = 2, f = 9 } }, chairs = { { t = 5, s = 1 } } })
T.eq(cleaned.stove.x, 0, "이상한 값은 기본값")
T.eq(cleaned.tables[1].f, 1, "층은 1 또는 2")
T.eq(#cleaned.chairs, 1, "없는 테이블 의자는 빼고 기본 의자")
T.eq(#Floor.clean(nil).tables, 1, "nil이면 기본 배치")
T.done("Floor.spec")

View File

@@ -3,8 +3,18 @@ local Economy = require("../src/shared/Economy")
local Shop = require("../src/shared/Shop") local Shop = require("../src/shared/Shop")
local T = require("./check") local T = require("./check")
local function kinds(evs, kind)
local out = {}
for _, e in evs do
if e.kind == kind then
table.insert(out, e)
end
end
return out
end
-- 첫 손님은 바로 오고, 걸어서 자리에 앉습니다. -- 첫 손님은 바로 오고, 걸어서 자리에 앉습니다.
local s = Shop.new(0, 0, 100) local s = Shop.new({ money = 0, now = 100 })
local ev = Shop.tick(s, 100) local ev = Shop.tick(s, 100)
T.eq(#ev, 1, "접속하자마자 손님 1명") T.eq(#ev, 1, "접속하자마자 손님 1명")
T.eq(ev[1].kind, "spawn", "spawn 이벤트") T.eq(ev[1].kind, "spawn", "spawn 이벤트")
@@ -13,131 +23,169 @@ T.eq(Shop.nextCookMenu(s), "Tteokbokki", "걷는 중인 손님 주문도 미리
T.eq(Shop.serve(s, 1), nil, "앉기 전에는 서빙 불가") T.eq(Shop.serve(s, 1), nil, "앉기 전에는 서빙 불가")
-- 자리가 1개면 두 번째 손님은 못 들어옴 -- 자리가 1개면 두 번째 손님은 못 들어옴
local ev2 = Shop.tick(s, 106) T.eq(#kinds(Shop.tick(s, 110), "spawn"), 0, "빈자리 없으면 손님이 지나감")
local spawned = 0 T.eq(s.customers[1].state, "waiting", "자리에 앉음")
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), "Tteokbokki", "조리하면 떡볶이")
T.eq(Shop.cook(s), nil, "손이 꽉 차면 더 못 만듦") T.eq(Shop.cook(s), nil, "손이 꽉 차면 더 못 만듦")
T.eq(Shop.nextCookMenu(s), nil, "열린 주문 없음") T.eq(Shop.serve(s, 1), 15, "떡볶이 15원")
local earn = Shop.serve(s, 1)
T.eq(earn, 15, "떡볶이 15원")
T.eq(s.money, 15, "돈 15") T.eq(s.money, 15, "돈 15")
T.eq(#s.hand, 0, "접시를 내려놓음") T.eq(#s.hand, 0, "접시를 내려놓음")
T.eq(Shop.serve(s, 1), nil, "같은 손님에게 두 번 못 줌") T.eq(Shop.serve(s, 1), nil, "같은 손님에게 두 번 못 줌")
T.eq(s.customers[1].state, "eating", "먹는 중") T.check(#kinds(Shop.tick(s, 110 + Economy.EAT + 0.1), "leave") == 1, "다 먹으면 나감")
-- 다 먹으면 나가고 자리가 빔
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, "손님 목록에서 빠짐") T.eq(s.customers[1], nil, "손님 목록에서 빠짐")
-- 구매 -- 갈래 업그레이드
local p, err = Shop.buyNext(s) local b = Shop.new({ money = 100, now = 0 })
T.eq(p and p.id, "Table2", "첫 구매는 테이블 2") local lv, err = Shop.buyLevel(b, "Menu")
T.eq(lv and lv.value, "Gimbap", "메뉴 갈래 첫 단계 = 김밥")
T.eq(err, nil, "구매 성공") T.eq(err, nil, "구매 성공")
T.eq(s.money, 5, "돈 차감(15 - 10)") T.eq(b.money, 60, "돈 차감")
T.eq(s.stats.seats, 2, "테이블 2개") T.eq(#b.stats.menus, 2, "메뉴 2개")
local p2, err2 = Shop.buyNext(s) T.eq(select(2, Shop.buyLevel(b, "Tray")), "stage", "쟁반은 실내 분식집부터")
T.eq(p2, nil, "돈이 모자라면 실패") T.eq(select(2, Shop.buyLevel(b, "Stage")), "money", "돈 모자람")
T.eq(err2, "money", "실패 이유 money") b.money = 1e6
for _ = 1, 3 do
Shop.buyLevel(b, "Menu")
end
T.eq(#b.stats.menus, 3, "건물 단계가 낮으면 어묵은 못 삼")
T.check(Shop.buyLevel(b, "Stage") ~= nil, "실내 확장")
T.eq(b.stats.stage, 2, "2단계")
Shop.buyLevel(b, "Menu")
Shop.buyLevel(b, "Menu")
T.eq(#b.stats.menus, 5, "2단계면 메뉴 5개까지")
T.eq(select(2, Shop.buyLevel(b, "Menu")), "max", "다 삼")
T.eq(select(2, Shop.buyLevel(b, "Nope")), "max", "없는 갈래")
-- 손님 오는 속도
local sp = Shop.new({ money = 60, now = 0 })
Shop.tick(sp, 0)
Shop.buyLevel(sp, "Speed")
T.eq(sp.stats.spawn, 8.5, "간격 8.5초")
T.check(sp.nextSpawn <= 8.5, "산 직후 다음 손님 시각이 당겨짐")
-- 자리
local seats = Shop.new({ money = 0, now = 0, seats = 2 })
Shop.tick(seats, 0)
T.eq(#kinds(Shop.tick(seats, 10), "spawn"), 1, "자리 2개면 두 번째 손님")
Shop.setSeats(seats, 3)
T.eq(seats.stats.seats, 3, "자리 3")
T.check(seats.nextSpawn <= 11, "자리가 생기면 곧 손님")
-- 2배 수익 -- 2배 수익
local d = Shop.new(0, 0, 0) local d = Shop.new({ money = 0, now = 0 })
d.moneyMult = 2 d.moneyMult = 2
Shop.tick(d, 0) Shop.tick(d, 0)
Shop.tick(d, 3) Shop.tick(d, 3)
Shop.cook(d) Shop.cook(d)
T.eq(Shop.serve(d, 1), 30, "2배 수익이면 30원") T.eq(Shop.serve(d, 1), 30, "2배 수익이면 30원")
-- 메뉴는 해금된 것을 돌아가며 주문
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), 15, "떡볶이 손님에게 성공")
-- 요리 화면에서 메뉴 고르기: 주문이 있는 메뉴만 만들 수 있음 -- 요리 화면에서 메뉴 고르기: 주문이 있는 메뉴만 만들 수 있음
local pick = Shop.new(0, 2, 0) local pick = Shop.new({ money = 0, now = 0, seats = 2, levels = { Menu = 1 } })
Shop.tick(pick, 0) Shop.tick(pick, 0)
Shop.tick(pick, 6) Shop.tick(pick, 10)
local counts = Shop.openCounts(pick) local counts = Shop.openCounts(pick)
T.eq(counts.Tteokbokki, 1, "떡볶이 주문 1") T.eq(counts.Tteokbokki, 1, "떡볶이 주문 1")
T.eq(counts.Gimbap, 1, "김밥 주문 1") T.eq(counts.Gimbap, 1, "김밥 주문 1")
T.eq(Shop.cook(pick, "Sundae"), nil, "주문 없는 메뉴는 못 만듦") T.eq(Shop.cook(pick, "Sundae"), nil, "주문 없는 메뉴는 못 만듦")
T.eq(Shop.cook(pick, "Gimbap"), "Gimbap", "나중에 온 손님 메뉴를 골라 만들 수 있음") T.eq(Shop.cook(pick, "Gimbap"), "Gimbap", "나중에 온 손님 메뉴를 골라 만들 수 있음")
T.eq(Shop.openCounts(pick).Gimbap, nil, "만든 김밥만큼 주문이 채워짐") T.eq(Shop.openCounts(pick).Gimbap, nil, "만든 김밥만큼 주문이 채워짐")
T.eq(Shop.openCounts(pick).Tteokbokki, 1, "떡볶이 주문은 그대로")
T.eq(Shop.cook(pick, "Tteokbokki"), nil, "손이 꽉 차면 못 만듦") T.eq(Shop.cook(pick, "Tteokbokki"), nil, "손이 꽉 차면 못 만듦")
-- 알바생: 카운터에 접시를 만들어 두고, 플레이어는 집어서 나름 -- 알바생: 잠김 → 열고 고용 → 요리 알바가 카운터에 접시
local h = Shop.new(0, 8, 0) local h = Shop.new({ money = 1000, now = 0 })
T.eq(h.stats.helper, true, "알바생 있음") T.eq(select(2, Shop.hire(h, "Cook")), "locked", "알바생 기능 전에는 고용 불가")
Shop.buyLevel(h, "Staff")
local before = h.money
T.eq(Shop.hire(h, "Cook"), true, "요리 알바 고용")
T.eq(h.money, before - 200, "고용비")
Shop.hire(h, "Cook")
T.eq(select(2, Shop.hire(h, "Cook")), "max", "요리 알바는 2명까지")
T.eq(select(2, Shop.hire(h, "Boss")), "none", "없는 역할")
local evs = Shop.tick(h, 0) local evs = Shop.tick(h, 0)
local counter = 0 T.eq(#kinds(evs, "counter"), 1, "요리 알바가 첫 주문을 바로 만듦(주문 1개)")
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.nextCookMenu(h), nil, "만들어 둔 접시가 주문을 덮음")
T.eq(Shop.pickup(h), 1, "접시를 집음") T.eq(Shop.pickup(h), 1, "접시를 집음")
T.eq(#h.counter, 0, "카운터 비움")
Shop.tick(h, 3) Shop.tick(h, 3)
T.check(Shop.serve(h, 1) ~= nil, "알바생 접시로 서빙") T.check(Shop.serve(h, 1) ~= nil, "알바 접시로 서빙")
-- 쟁반: 여러 접시 -- 시급: 1분마다, 모자라면 쉼
local t = Shop.new(0, 11, 0) local wage = Shop.new({ money = 0, now = 0, levels = { Staff = 1 }, staff = { Cook = 1 } })
T.eq(t.stats.carry, 2, "쟁반이면 2개") T.eq(#kinds(Shop.tick(wage, 1), "counter"), 1, "고용 직후 일함")
T.eq(t.stats.seats, 4, "11번째까지 테이블 4") local strike = kinds(Shop.tick(wage, Economy.WAGE_PERIOD + 0.1), "strike")
T.eq(strike[1] and strike[1].on, true, "시급이 모자라면 쉼")
T.eq(wage.money, 0, "빚은 지지 않음")
Shop.tick(wage, Economy.WAGE_PERIOD + 20)
T.eq(#wage.counter, 1, "쉬는 동안 안 만듦(처음 1개만)")
wage.money = 100
local paid = Shop.tick(wage, Economy.WAGE_PERIOD + 30)
T.eq(kinds(paid, "wage")[1] and kinds(paid, "wage")[1].amount, 12, "돈이 생기면 시급 12")
T.eq(kinds(paid, "strike")[1] and kinds(paid, "strike")[1].on, false, "다시 일함")
T.eq(wage.money, 88, "시급 차감")
T.eq(Shop.fire(wage, "Cook"), true, "해고")
T.eq(Shop.fire(wage, "Cook"), false, "더 없음")
-- 전부 산 뒤 -- 서빙 알바: 카운터 접시를 손님에게
local full = Shop.new(1e9, #Economy.PURCHASES, 0) local sv = Shop.new({ money = 0, now = 0, levels = { Staff = 1 }, staff = { Cook = 1, Server = 1 } })
local none, why = Shop.buyNext(full) local e0 = Shop.tick(sv, 0) -- 손님 + 요리 알바 접시
T.eq(none, nil, "더 살 것 없음") T.eq(#kinds(e0, "counter"), 1, "카운터 접시")
T.eq(why, "max", "이유 max") T.eq(#kinds(Shop.tick(sv, 1), "deliver"), 0, "손님이 앉기 전에는 안 나름")
local e2 = Shop.tick(sv, Economy.WALK_IN + 0.1)
T.eq(#kinds(e2, "deliver"), 1, "앉으면 서빙 알바가 가져감")
T.eq(#sv.counter, 0, "카운터에서 빠짐")
T.eq(Shop.serve(sv, 1), nil, "알바가 가져가는 손님은 플레이어가 못 줌")
local e3 = Shop.tick(sv, Economy.WALK_IN + 0.1 + Economy.SERVER_TRIP + 0.1)
local delivered = kinds(e3, "delivered")
T.eq(delivered[1] and delivered[1].earn, 15, "서빙 알바가 놓으면 돈")
T.eq(sv.customers[1].state, "eating", "먹는 중")
-- 세이브 값이 이상해도 안전 -- 홍보 알바·손님 러시
local weird = Shop.new(5, 999, 0) local pr = Shop.new({ money = 0, now = 0, levels = { Staff = 1 }, staff = { Promoter = 1 } })
T.eq(weird.bought, #Economy.PURCHASES, "산 개수는 최대값으로 자름") T.eq(Shop.spawnInterval(pr), 7.5, "홍보 알바 간격 x0.75")
Shop.addRush(pr, 30)
T.eq(Shop.spawnInterval(pr), 3.75, "러시 x0.5")
Shop.tick(pr, 31)
T.eq(pr.rushLeft, 0, "러시 끝")
-- 옆 가게로 손님 데려가기: 먹는 중이 아닌 NPC 손님만, 늦게 온 손님부터
local victim = Shop.new({ money = 0, now = 0, seats = 3, levels = { Menu = 1 } })
Shop.tick(victim, 0)
Shop.tick(victim, 10)
Shop.tick(victim, 20)
Shop.cook(victim) -- 1번 손님 떡볶이를 들고 있음
local taken = Shop.takeCustomers(victim, 5)
T.eq(#taken, 3, "3명 모두 데려감(아직 못 먹음)")
T.eq(taken[1].id, 3, "늦게 온 손님부터")
T.eq(next(victim.customers), nil, "손님 없음")
-- 남은 떡볶이 접시: 다음 손님이 떡볶이를 주문
victim.menuIndex = 1 -- 원래라면 다음은 김밥
local nextEv = kinds(Shop.tick(victim, 30), "spawn")
T.eq(nextEv[1] and nextEv[1].menu, "Tteokbokki", "주인 없는 접시 메뉴를 다음 손님이 주문")
local thief = Shop.new({ money = 0, now = 0, seats = 2 })
local tc = Shop.addTransfer(thief, "Twigim", 7)
T.eq(tc and tc.menu, "Tteokbokki", "우리 가게에 없는 메뉴면 우리 메뉴로")
T.eq(tc and tc.transfer, true, "옆 가게 손님 표시")
T.check(Shop.addTransfer(thief, "Tteokbokki", 7) ~= nil, "두 번째 자리")
T.eq(Shop.addTransfer(thief, "Tteokbokki", 7), nil, "자리 없으면 못 옴")
T.eq(Shop.freeSeatCount(thief), 0, "빈자리 0")
-- 새 메뉴를 사면 다음 손님이 1초 안에 와서 그 메뉴를 주문 -- 새 메뉴를 사면 다음 손님이 1초 안에 와서 그 메뉴를 주문
local nm = Shop.new(40, 1, 0) -- 테이블 2개, 다음 구매는 김밥 해금 local nm = Shop.new({ money = 40, now = 0, seats = 2 })
Shop.tick(nm, 0) -- 첫 손님(떡볶이) Shop.tick(nm, 0)
local bp = Shop.buyNext(nm) Shop.buyLevel(nm, "Menu")
T.eq(bp and bp.id, "UnlockGimbap", "김밥 해금 구매") local newOrder = kinds(Shop.tick(nm, 1), "spawn")
local nmEv = Shop.tick(nm, 1) T.eq(newOrder[1] and newOrder[1].menu, "Gimbap", "사자마자 다음 손님이 김밥 주문")
local newOrder = nil
for _, e in nmEv do -- 세이브 값이 이상해도 안전
if e.kind == "spawn" then local weird = Shop.new({ money = 5, now = 0, levels = { Menu = 99 } :: any, staff = { Cook = 99, Server = -3 } })
newOrder = e.menu T.eq(#weird.stats.menus, 5, "레벨은 최대값으로 자름")
end T.eq(weird.staff.Cook, 2, "알바 수는 최대값으로 자름")
end T.eq(weird.staff.Server, 0, "음수는 0")
T.eq(newOrder, "Gimbap", "사자마자 다음 손님이 김밥 주문")
-- 플레이어 손님: 빈자리에 바로 앉고, 2배 값을 내고, 다 먹으면 나감 -- 플레이어 손님: 빈자리에 바로 앉고, 2배 값을 내고, 다 먹으면 나감
local g = Shop.new(0, 1, 0) -- 테이블 2개 local g = Shop.new({ money = 0, now = 0, seats = 2 })
Shop.tick(g, 0) -- NPC 손님 1명(1번 자리) Shop.tick(g, 0) -- NPC 손님 1명(1번 자리)
local guest = Shop.addGuest(g, 777) local guest = Shop.addGuest(g, 777)
T.check(guest ~= nil, "플레이어 손님 앉음") T.check(guest ~= nil, "플레이어 손님 앉음")
@@ -145,44 +193,32 @@ T.eq(guest and guest.seat, 2, "빈 2번 자리")
T.eq(guest and guest.state, "waiting", "걷지 않고 바로 주문") T.eq(guest and guest.state, "waiting", "걷지 않고 바로 주문")
T.eq(Shop.addGuest(g, 777), nil, "같은 플레이어는 한 번만") T.eq(Shop.addGuest(g, 777), nil, "같은 플레이어는 한 번만")
T.eq(Shop.addGuest(g, 888), nil, "빈자리가 없으면 못 앉음") T.eq(Shop.addGuest(g, 888), nil, "빈자리가 없으면 못 앉음")
local spawnedWhileFull = false T.eq(#kinds(Shop.tick(g, 10.5), "spawn"), 0, "플레이어 손님 자리에는 NPC가 안 옴")
for _, e in Shop.tick(g, 6.5) do Shop.cook(g)
if e.kind == "spawn" then
spawnedWhileFull = true
end
end
T.check(not spawnedWhileFull, "플레이어 손님 자리에는 NPC가 안 옴")
Shop.cook(g) -- 1번 손님 떡볶이
T.eq(Shop.serve(g, 1), 15, "NPC 손님은 1배") T.eq(Shop.serve(g, 1), 15, "NPC 손님은 1배")
local gid = (guest :: any).id local gid = (guest :: any).id
T.eq(Shop.nextCookMenu(g), (guest :: any).menu, "플레이어 손님 주문도 조리대에 뜸") T.eq(Shop.nextCookMenu(g), (guest :: any).menu, "플레이어 손님 주문도 조리대에 뜸")
Shop.cook(g) Shop.cook(g)
T.eq(Shop.serve(g, gid), 30, "플레이어 손님은 2배") T.eq(Shop.serve(g, gid), 30, "플레이어 손님은 2배")
local guestLeave = nil local guestLeave = nil
for _, e in Shop.tick(g, 6.5 + Economy.EAT + 0.1) do for _, e in Shop.tick(g, 10.5 + Economy.EAT + 0.1) do
if e.kind == "leave" and e.guest then if e.kind == "leave" and e.guest then
guestLeave = e guestLeave = e
end end
end end
T.check(guestLeave ~= nil, "다 먹으면 플레이어 손님도 나감") T.eq(guestLeave and guestLeave.guest, 777, "다 먹으면 플레이어 손님도 나감")
T.eq(guestLeave and guestLeave.guest, 777, "나간 손님 UserId")
T.eq(guestLeave and guestLeave.served, true, "먹고 나감") T.eq(guestLeave and guestLeave.served, true, "먹고 나감")
T.eq(#Shop.takeCustomers(g, 5), 0, "플레이어 손님·먹는 손님은 못 데려감")
-- 음식을 너무 오래 못 받으면 일어남 -- 음식을 너무 오래 못 받으면 일어남
local w = Shop.new(0, 0, 0) local w = Shop.new({ money = 0, now = 0 })
local wg = Shop.addGuest(w, 5) local wg = Shop.addGuest(w, 5)
T.check(wg ~= nil, "자리 1개에 플레이어 손님") T.check(wg ~= nil, "자리 1개에 플레이어 손님")
local hungry = nil local hungry = kinds(Shop.tick(w, Economy.GUEST_WAIT + 0.1), "leave")[1]
for _, e in Shop.tick(w, Economy.GUEST_WAIT + 0.1) do
if e.kind == "leave" then
hungry = e
end
end
T.eq(hungry and hungry.served, false, "못 먹고 나감") T.eq(hungry and hungry.served, false, "못 먹고 나감")
T.check(w.seatTaken[1] ~= (wg :: any).id, "자리 비움(바로 NPC 손님이 앉을 수 있음)")
-- 먼저 일어나면 자리만 비움 -- 먼저 일어나면 자리만 비움
local r = Shop.new(0, 0, 0) local r = Shop.new({ money = 0, now = 0 })
local rg = Shop.addGuest(r, 9) :: any local rg = Shop.addGuest(r, 9) :: any
T.eq(Shop.removeGuest(r, rg.id) and true, true, "일어남") T.eq(Shop.removeGuest(r, rg.id) and true, true, "일어남")
T.eq(r.seatTaken[1], nil, "자리 비움") T.eq(r.seatTaken[1], nil, "자리 비움")

View File

@@ -11,21 +11,23 @@ local function at(log, id)
return math.huge return math.huge
end end
local base = Sim.run(1, 3600) local base = Sim.run(1, 7200)
T.eq(#base, 20, "봇이 1시간 안에 20개 모두 삼") T.check(#base >= 30, "봇이 2시간 안에 30번 넘게 삼(업그레이드가 잘게 나뉨)")
T.check(at(base, "Table2") <= 10, "첫 구매 10초 안") T.check(base[1].t <= 10, "첫 구매 10초 안")
T.check(at(base, "Expand") >= 8 * 60 and at(base, "Expand") <= 12 * 60, "실내 확장 8~12분") T.check(at(base, "Stage1") >= 8 * 60 and at(base, "Stage1") <= 16 * 60, "실내 확장 8~16분")
T.check(at(base, "Stage2") >= 40 * 60 and at(base, "Stage2") <= 70 * 60, "2층 40~70분")
T.check(at(base, "Staff1") < at(base, "Stage1"), "알바생 기능은 확장 전에 열림")
local prev = 0 local prev = 0
for i, e in base do for i, e in base do
if i > 1 and i <= 10 then if i > 1 and e.t < at(base, "Stage1") then
T.check(e.t - prev <= 100, `1단계 #{i} 구매 간격 100초 이하`) T.check(e.t - prev <= 100, `1단계 #{i} {e.id} 구매 간격 100초 이하`)
elseif i > 10 then elseif i > 1 then
T.check(e.t - prev <= 180, `2단계 #{i} 구매 간격 180초 이하`) T.check(e.t - prev <= 240, `#{i} {e.id} 구매 간격 4분 이하`)
end end
prev = e.t prev = e.t
end end
local x2 = Sim.run(2, 3600) local x2 = Sim.run(2, 7200)
T.check(at(x2, "Expand") < at(base, "Expand") * 0.65, "2배 수익이면 확장이 훨씬 빠름") T.check(at(x2, "Stage1") < at(base, "Stage1") * 0.65, "2배 수익이면 확장이 훨씬 빠름")
T.done("Sim.spec") T.done("Sim.spec")

View File

@@ -7,8 +7,8 @@ local Sim = require("./simlib")
local mult = if table.find(process.args, "x2") then 2 else 1 local mult = if table.find(process.args, "x2") then 2 else 1
print(`수익 배율 x{mult}`) print(`수익 배율 x{mult}`)
local prev = 0 local prev = 0
for i, e in Sim.run(mult, 3600) do for i, e in Sim.run(mult, 7200) do
local s = math.floor(e.t + 0.5) 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)) print(string.format("%2d %2d:%02d (+%3ds) %-12s %6d", i, s // 60, s % 60, s - prev, e.id, e.cost))
prev = s prev = s
end end

View File

@@ -1,23 +1,50 @@
-- 경제 시뮬레이터 본체: 실제 게임 로직(src/shared/Shop)을 봇이 쉬지 않고 최적으로 플레이합니다. -- 경제 시뮬레이터 본체: 실제 게임 로직(src/shared/Shop)을 봇이 쉬지 않고 플레이합니다.
-- 실행은 tools/sim.luau, 검사는 tests/Sim.spec.luau -- 실행은 tools/sim.luau, 검사는 tests/Sim.spec.luau
-- 봇 가정: 조리대 <-> 테이블 편도 WALK/2초, 알바생이 있으면 직접 조리하지 않고 나르기만 합니다. -- 봇 가정: 조리대 <-> 테이블 편도 WALK/2초, 요리 알바가 있으면 직접 조리하지 않고 나르기만 합니다.
-- 조리 시간은 요리 화면을 쉬지 않고 했을 때의 시간(Recipes.expectedTime: 메뉴 고르기 + 단계 + 완성 연출)입니다. -- 조리 시간은 요리 화면을 쉬지 않고 했을 때의 시간(Recipes.expectedTime: 메뉴 고르기 + 단계 + 완성 연출)입니다.
-- 사는 순서: 지금 살 수 있는 것(업그레이드 갈래 다음 단계, 의자, 테이블, 알바생 고용) 중 가장 싼 것부터.
local Economy = require("../src/shared/Economy") local Economy = require("../src/shared/Economy")
local Recipes = require("../src/shared/Recipes") local Recipes = require("../src/shared/Recipes")
local Shop = require("../src/shared/Shop") local Shop = require("../src/shared/Shop")
local Sim = {} local Sim = {}
function Sim.run(mult: number, limit: number): { { t: number, id: string, cost: number } } export type Entry = { t: number, id: string, cost: number, kind: string }
local shop = Shop.new(0, 0, 0)
-- 봇이 다음에 살 것(가장 싼 것)
local function nextBuy(shop, tables: number): { kind: string, id: string, cost: number }?
local offers = Economy.offers(shop.levels, tables, shop.stats.seats)
local list = {}
for _, o in offers do
table.insert(list, { kind = o.kind, id = o.id, cost = o.cost })
end
if shop.stats.staffUnlocked then
for _, r in Economy.ROLES do
-- 서빙·홍보 알바는 실내 분식집부터 고용(봇 가정)
local want = if r.id == "Cook" then 1 elseif shop.stats.stage >= 2 then r.max else 0
if (shop.staff[r.id] or 0) < want then
table.insert(list, { kind = "hire", id = r.id, cost = r.hire })
end
end
end
table.sort(list, function(a, b)
return a.cost < b.cost
end)
return list[1]
end
function Sim.run(mult: number, limit: number, untilStage: number?): { Entry }
local shop = Shop.new({ money = 0, now = 0 })
shop.moneyMult = mult shop.moneyMult = mult
local tables = 1
local dt = 0.1 local dt = 0.1
local t = 0 local t = 0
local at = "stove" local at = "stove"
local busyUntil = 0 local busyUntil = 0
local pending: string? = nil -- 끝나면 할 일: "cook" | "arrive_tables" | "arrive_stove" local pending: string? = nil -- 끝나면 할 일: "cook" | "arrive_tables" | "arrive_stove"
local log = {} local log: { Entry } = {}
while t < limit and Shop.nextPurchase(shop) do local goal = untilStage or 3
while t < limit do
Shop.tick(shop, t) Shop.tick(shop, t)
if t >= busyUntil then if t >= busyUntil then
if pending == "cook" then if pending == "cook" then
@@ -30,7 +57,8 @@ function Sim.run(mult: number, limit: number): { { t: number, id: string, cost:
pending = nil pending = nil
if at == "stove" then if at == "stove" then
Shop.pickup(shop) Shop.pickup(shop)
local canCook = not shop.stats.helper and not Shop.handFull(shop) and Shop.nextCookMenu(shop) ~= nil local cooks = shop.staff.Cook or 0
local canCook = cooks == 0 and not Shop.handFull(shop) and Shop.nextCookMenu(shop) ~= nil
if canCook then if canCook then
pending = "cook" pending = "cook"
local menu = Shop.nextCookMenu(shop) :: string local menu = Shop.nextCookMenu(shop) :: string
@@ -51,10 +79,26 @@ function Sim.run(mult: number, limit: number): { { t: number, id: string, cost:
end end
end end
end end
local p = Shop.nextPurchase(shop) local b = nextBuy(shop, tables)
if p and shop.money >= p.cost then -- 시급 낼 돈은 남겨 둡니다.
Shop.buyNext(shop) local reserve = Economy.totalWage(shop.staff, shop.stats)
table.insert(log, { t = t, id = p.id, cost = p.cost }) if b and shop.money >= b.cost + reserve then
if b.kind == "track" then
Shop.buyLevel(shop, b.id)
elseif b.kind == "hire" then
Shop.hire(shop, b.id)
else
Shop.spend(shop, b.cost)
if b.kind == "table" then
tables += 1
end
Shop.setSeats(shop, shop.stats.seats + 1)
end
local label = if b.kind == "track" then `{b.id}{shop.levels[b.id]}` else b.id
table.insert(log, { t = t, id = label, cost = b.cost, kind = b.kind })
if shop.stats.stage >= goal and b.id == "Stage" then
break
end
end end
t += dt t += dt
end end