feat(bunsik): MVP 전체 구현 — 맵, 요리·서빙, 손님 NPC, 업그레이드 20개, 세이브, 결제, 한/영 UI

- 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 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 01:34:06 +09:00
parent 060974e277
commit 802ba10e1a
45 changed files with 6997 additions and 202 deletions

View File

@@ -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()

View File

@@ -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"

View File

@@ -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:]))

View File

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

View File

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

View File

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