commit 8cebfc9db5ac466249322e390baafd50c4603060 Author: daniel wang Date: Wed Oct 28 15:58:33 2026 +0800 初始匯入:選舉小鎮(backend、web、art 合成一個 repo) - backend:規則(選戰卡牌、選民模型)、Fastify 伺服器、校準工具、Python 資料管線 - web:React + Vite 前端 - art:卡牌插圖的生圖腳本與原圖(原圖用 Git LFS) - 架構總覽在 backend/docs/README.md Co-Authored-By: Claude Opus 5.5 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6271b37 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# 生圖原圖(每張約 1.4 MB,整批重生時會換掉)放 Git LFS;code.30cm.net 的 Gitea 已開 LFS。 +# 要先安裝 git-lfs 並執行過 git lfs install,再 git add,否則會被當成一般檔案收進去。 +art/generated/*.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..55c01bf --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# 整個專案共用;backend/ 與 web/ 另有自己的 .gitignore(只管各自的資料夾) + +# 系統與編輯器 +.DS_Store +._* +Thumbs.db +*.log + +# 生圖工具的暫存工作資料夾(art/gen-card-grokcli.sh 產生) +art/grok-work/ diff --git a/archive/classic-files.txt b/archive/classic-files.txt new file mode 100644 index 0000000..be775e7 --- /dev/null +++ b/archive/classic-files.txt @@ -0,0 +1,22 @@ +web/src/game/Feed.tsx +web/src/game/GameScreen.tsx +web/src/game/StartScreen.tsx +web/src/game/audio/speech.ts +web/src/game/hq +web/src/game/hud/TopBar.tsx +web/src/game/hud/WeekBanner.tsx +web/src/game/news/BreakingNews.tsx +web/src/game/news/NewsRoom.tsx +web/src/game/news/advice.ts +web/src/game/news/newsroom.css +web/src/game/night +web/src/game/paper +web/src/game/plan +web/src/game/playback +web/src/game/start/CandidateStats.tsx +web/src/game/start/LineupBuilder.tsx +web/src/game/start/RunningMatePicker.tsx +web/src/game/start/TaiwanPicker.tsx +web/src/game/art/scenes/title.tsx +web/test/tactics.test.ts +web/test/cards.test.ts diff --git a/archive/classic-mode-2026-10-26.tar.gz b/archive/classic-mode-2026-10-26.tar.gz new file mode 100644 index 0000000..5a8d0ec Binary files /dev/null and b/archive/classic-mode-2026-10-26.tar.gz differ diff --git a/archive/classic-mode-extra-2026-10-26.tar.gz b/archive/classic-mode-extra-2026-10-26.tar.gz new file mode 100644 index 0000000..5407adc Binary files /dev/null and b/archive/classic-mode-extra-2026-10-26.tar.gz differ diff --git a/archive/classic-mode-extra2-2026-10-26.tar.gz b/archive/classic-mode-extra2-2026-10-26.tar.gz new file mode 100644 index 0000000..bd1a80f Binary files /dev/null and b/archive/classic-mode-extra2-2026-10-26.tar.gz differ diff --git a/art/cards.tsv b/art/cards.tsv new file mode 100644 index 0000000..a9bdd92 --- /dev/null +++ b/art/cards.tsv @@ -0,0 +1,87 @@ +street_canvass a candidate team walking down a busy Taiwanese street lined with arcade shophouses (騎樓), scooters parked, shopkeepers waving, campaign volunteers in matching vests handing out flyers +market_visit a lively Taiwanese traditional wet market, vegetable and fruit stalls under striped awnings, a small campaign group shaking hands with stall owners and elderly shoppers +temple_visit a Taiwanese temple courtyard with ornate swallowtail roof and dragons, incense burner with smoke, worshippers holding incense, a small campaign group bowing +factory_visit an industrial park in Taiwan at shift change, factory buildings with sawtooth roofs, workers in uniforms and safety helmets at the gate, a campaign group greeting them +sound_truck a small campaign sound truck with loudspeakers on its roof driving through a rural Taiwanese town with rice paddies and a betel nut stand, villagers looking on +rally a huge night-time campaign rally in a Taiwanese city plaza, big illuminated stage with spotlights, a sea of supporters waving blank colored flags and glow sticks +open_office a newly opened campaign office in a Taiwanese street-front shop, big blank banners, flower baskets lined up outside, volunteers setting up tables +recruit_machine a neighborhood chief (village head) in a small Taiwanese community office, tea set on the table, local elders chatting with a campaign aide +hire_staff a busy campaign war room with desks, laptops, whiteboards with blank sticky notes and a map of Taiwan, staff members discussing strategy +recruit_volunteers young volunteers in matching vests gathering at a campaign headquarters, sign-up table, stacks of leaflets and boxes, cheerful atmosphere +print_flyers a Taiwanese print shop with offset presses, stacks of colorful blank campaign leaflets and posters coming off the press, workers bundling them +tv_ad a television studio shooting a campaign commercial, cameras, lighting rigs, a director's monitor, a crew filming a small anonymous actor family on a set +online_ad an anonymous person on a crowded Taipei MRT train scrolling a smartphone with blank colorful video thumbnails glowing, other commuters on phones +talk_show a Taiwanese political TV talk show studio, panel desk with four anonymous pundits, bright studio lights, cameras and a live audience-less set with blank screens +announce_policy a press conference podium in a hotel ballroom, rows of reporters with cameras and microphones raised, blank backdrop panel +fundraiser_dinner a Taiwanese banquet hall fundraising dinner with round tables and red tablecloths, many guests toasting, a small stage at the front +small_donations a cozy home desk at night with a laptop showing a blank progress bar and coins, a piggy bank, many tiny glowing notification bubbles floating +self_fund a campaign treasurer's desk with a bank passbook, stacks of banknotes, a calculator and a worried anonymous person counting money +expose_press a dramatic press conference where an anonymous spokesperson holds up a thick folder of documents, flashbulbs going off, reporters crowding +rebuttal_press a calm press conference with an anonymous spokesperson standing beside a blank chart board, reporters listening, a clock on the wall +investigate a private investigator in a parked car at night with a long-lens camera watching a building, rain on the windshield, noir mood but cozy miniature style +internal_poll a phone survey call center with rows of operators wearing headsets, monitors showing blank bar charts, late evening +vote_buying a shady back alley at night where an anonymous figure secretly hands over a red envelope, shadows, a lamp post, tense mood, no faces visible +troll_army a dim room full of computer monitors and smartphones on racks, anonymous figures typing, many identical blank chat bubbles floating upward +rest a quiet morning in a small Taiwanese apartment, a tired campaigner napping on a sofa, a cup of tea, sunlight through the window, a cat +eve_rally the final eve-of-election mega rally, a gigantic crowd filling a boulevard at night, fireworks overhead, stage with giant blank screens, confetti +kneel on a rally stage in the rain, a small anonymous candidate figure kneeling and bowing to the crowd, supporters holding umbrellas, emotional atmosphere +eve_phone_bank a campaign phone bank late at night, volunteers making calls with lists, clock showing late hour, cups of instant noodles on the desks +eve_online_ad a night city skyline with dozens of floating smartphone screens showing blank campaign video thumbnails, energetic neon glow +eve_vote_buying a village at night before election day, an anonymous figure on a scooter dropping envelopes at doorsteps, dogs barking, lights in windows +scene-typhoon a Taiwanese coastal city during a typhoon, palm trees bending, rain sheets, flooded street with scooters, emergency crew in raincoats +scene-debate a televised election debate stage with three empty podiums, dramatic lighting, studio audience seats, big blank screens +scene-election-night election night inside a campaign headquarters, crowd watching a giant screen with blank rising bar charts, confetti and tense faces from behind +scene-ballot a Taiwanese polling station in a school classroom, voting booths, ballot boxes, voters lining up, election officials at tables +scene-registration candidates registering at the Central Election Commission office, anonymous figures with document folders, staff behind counters, cameras +scene-scandal a newspaper stand with stacks of newspapers and magazines with blank dramatic headlines blocks, people gathering to read, morning light +night_market a bustling Taiwanese night market at night, food stalls with steam and lanterns, crowds of young people and office workers, a small campaign group greeting visitors +door_to_door a quiet residential lane of Taiwanese apartment buildings with iron gates and potted plants, a campaign volunteer ringing a doorbell, an elderly resident opening the door +pilgrimage a long temple pilgrimage procession on a rural road, palanquin carriers, flags, drums, firecracker smoke, pilgrims walking in a line +church_visit a small church and a Buddhist temple side by side in a Taiwanese town, a campaign group respectfully greeting worshippers at the entrance +weddings_funerals a lively Taiwanese outdoor wedding banquet under a red tent at night, round tables, a small anonymous figure toasting guests table by table +banquet a Taiwanese outdoor roadside banquet (bando) with many round tables under a big red-and-white tent, chefs cooking in large woks, elderly guests eating +concert an outdoor evening campaign concert, a band on a lit stage, young crowd with glow sticks, festive lights +flags_billboards a Taiwanese street intersection lined with rows of plain colorful campaign flags and big blank billboards, scooters passing by +phone_banking volunteers making phone calls in a campaign office in the evening, call lists on desks, headsets, warm lamp light +homecoming a busy Taiwanese train station and bus terminal crowded with people carrying luggage going home, chartered buses waiting outside +radio_ad a cozy radio studio with an anonymous host at a microphone, on-air light glowing, and an elderly couple listening to a radio at home in an inset +short_video a young campaign staffer filming a short video on a smartphone gimbal in a colorful street, ring light, playful energy +line_groups a grandmother and grandfather on a sofa looking at smartphones with many blank chat bubbles and sticker icons floating around +influencer_live a podcast and livestream studio with microphones, a ring light, a camera, two anonymous hosts chatting, neon sign without text +press_conference a policy press conference in a hotel meeting room, podium with flowers, reporters with cameras and microphones, blank backdrop +interview a calm newspaper interview in a cafe, a journalist with a notebook and recorder sitting across from an anonymous figure, warm light +forum a government-hosted candidate forum in a school auditorium, three podiums on stage, sparse audience, TV cameras broadcasting +visit_associations a clan association hall with ancestral tablets and red decorations, elders in a meeting room, a campaign group bowing and shaking hands +endorsement a respected elderly scholar and local notables standing on a small stage giving thumbs up, a modest crowd applauding, plain banners +party_elder a big rally stage where a senior party figure (anonymous, seen from behind) raises the hand of a candidate, crowd cheering, plain flags +gifts gift boxes with fruit baskets, tea tins and liquor bottles being delivered to a traditional house courtyard, tense subtle mood +councilor_allies several anonymous local politicians in campaign sashes (blank) walking together through a market street waving to people +big_donor a modern office tower lobby, an anonymous campaign team meeting a businessman in a glass meeting room overlooking the city +party_fund a political party headquarters building with a treasury counter, an envelope and documents being handed over at a desk +white_paper a stack of thick policy documents and charts on a large table, a team working late with highlighters and laptops +lawsuit a Taiwanese courthouse entrance with stone steps, lawyers carrying folders, reporters waiting with cameras +report_prosecutor a prosecutors office building at dusk, an anonymous person handing a sealed envelope of evidence at the reception counter +protest_government a peaceful protest in front of a government building, people holding blank placards and a petition, police lined calmly +protest_hq a noisy crowd with blank placards gathered in front of a rival campaign headquarters storefront, reporters filming +crisis_pr an anonymous spokesperson bowing deeply in apology at a press conference, camera flashes, serious mood +fact_check a fact-checking room with screens showing blank charts and magnifying glass icons, staff marking items as checked +promise_bribe a secret late-night meeting in a back room of a small restaurant, two anonymous figures shaking hands over a table, shadows +smear a dark room where anonymous figures send many messages from phones, red warning icons and blank messages flying out +impersonate late at night, an elderly person woken up by a ringing phone in a dark bedroom, annoyed expression, clock showing midnight +frame_vote_buying a nighttime alley where an anonymous figure hands out envelopes while another hides and secretly photographs it, noir mood +staged_attack a chaotic moment on a rally street with spilled paint on the ground, security guards and crowd reacting, dramatic but not violent +buyout two anonymous figures meeting in a parked car at night, a briefcase of money on the seat between them, city lights outside +slush_fund a white-gloved hand passing a bag of cash under a table in a dim karaoke room, secretive mood +fake_poll a messy desk with printed fake charts and a phone screen showing a blank rising bar chart, a mischievous mood +chicken_oath a traditional Taiwanese temple square where an anonymous figure in a sash swears an oath before the temple, holding a rooster, crowd watching, dramatic +invite_oath two empty chairs and a rooster cage in front of a temple, reporters waiting, a sign-less table set for an oath ceremony +live_pledge an anonymous candidate signing a pledge document while being livestreamed on a smartphone on a tripod, chat bubbles floating +workout an early morning riverside park in Taiwan, an anonymous campaigner jogging with staff, joggers and morning exercisers around +study a cozy study at night with piles of books, policy reports and a desk lamp, an anonymous figure reading intently +debate_training a mock debate rehearsal in a campaign office, staff playing opponents at podiums, a coach with a stopwatch +media_training a media training session with a coach, a camera and a monitor replaying a clip, an anonymous trainee practicing answers +fire_staff an empty office desk with a cardboard box of belongings, an anonymous staffer walking out the door, somber light +street_interview a Taiwanese street corner with arcade shophouses, a small camera crew filming a friendly interview with a passer-by holding a bubble tea, a microphone held out, scooters in background +grassroots_walk a lone campaigner walking along a quiet Taiwanese rural road past rice paddies and a small temple, wearing a plain sash and carrying a rolled cloth banner, afternoon light +facebook_live a small cluttered Taiwanese campaign office at night, a smartphone on a tripod with ring light streaming live, floating heart and comment bubbles shown as abstract shapes, cup of tea on the desk +volunteer_calls a cozy Taiwanese apartment living room in the evening, two older volunteers sitting at a table with mobile phones and a handwritten contact notebook, making friendly calls diff --git a/art/fonts/gensen-rounded-OFL.txt b/art/fonts/gensen-rounded-OFL.txt new file mode 100644 index 0000000..1dfc687 --- /dev/null +++ b/art/fonts/gensen-rounded-OFL.txt @@ -0,0 +1,96 @@ +Copyright 2014-2019 Adobe (http://www.adobe.com/), with Reserved Font +Name 'Source'. Source is a trademark of Adobe in the United States +and/or other countries. + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/art/fonts/gensen-rounded2-tw-heavy.woff2 b/art/fonts/gensen-rounded2-tw-heavy.woff2 new file mode 100644 index 0000000..412e6b1 Binary files /dev/null and b/art/fonts/gensen-rounded2-tw-heavy.woff2 differ diff --git a/art/gen-card-grok.sh b/art/gen-card-grok.sh new file mode 100755 index 0000000..93f6dd9 --- /dev/null +++ b/art/gen-card-grok.sh @@ -0,0 +1,49 @@ +#!/bin/zsh +# 用 xAI(grok-imagine-image-2.0)產生一張卡牌插圖:gen-card-grok.sh <題材> +# 金鑰從環境變數 XAI_API_KEY 讀;沒有的話讀 ~/.config/tongsuan/xai.env(XAI_API_KEY=...)。不會印出金鑰。 +# 原圖存 art/generated/.png,網頁用的縮圖存 web/public/cards/.webp(和 gen-card.sh 一樣) +set -u +id="$1"; subject="$2" +here="${0:A:h}" +out="$here/generated/$id.png" +web="$here/../web/public/cards/$id.webp" +if [[ -z "${XAI_API_KEY:-}" && -r "$HOME/.config/tongsuan/xai.env" ]]; then + source "$HOME/.config/tongsuan/xai.env" +fi +if [[ -z "${XAI_API_KEY:-}" ]]; then + echo "FAIL $id(沒有 XAI_API_KEY)" + exit 1 +fi +style="Style: tabletop board-game card illustration, miniature diorama look with tilt-shift depth of field, soft isometric three-quarter top-down view, warm gouache texture, clean readable shapes, cohesive warm palette with a few saturated accents. Setting: present-day Taiwan. Absolutely no text, no letters, no numbers, no logos, no party symbols or party colors on flags (flags and banners are plain), no real or recognizable people; all figures are small, anonymous and stylized. Square image." +if [[ ! -s "$out" ]]; then + body=$(python3 -c 'import json,sys; print(json.dumps({"model": "grok-imagine-image-2.0", "prompt": sys.argv[1], "n": 1, "response_format": "b64_json"}))' "Subject: $subject. $style") + resp=$(curl -sS --max-time 180 https://api.x.ai/v1/images/generations \ + -H "Content-Type: application/json" -H "Authorization: Bearer $XAI_API_KEY" -d "$body") + # 回傳可能是 base64 或網址;兩種都接受(回應先存檔,避免和程式碼搶標準輸入) + print -r -- "$resp" > "$here/generated/$id.json" + python3 - "$out" "$here/generated/$id.json" 2>"$here/generated/$id.log" <<'PY' +import base64, json, sys, urllib.request +out = sys.argv[1] +raw = open(sys.argv[2], encoding="utf-8").read() +try: + d = json.loads(raw) +except json.JSONDecodeError: + sys.exit(f"不是 JSON:{raw[:200]}") +if "error" in d or not d.get("data"): + sys.exit(f"API 錯誤:{json.dumps(d, ensure_ascii=False)[:300]}") +item = d["data"][0] +if item.get("b64_json"): + data = base64.b64decode(item["b64_json"]) +else: + data = urllib.request.urlopen(item["url"], timeout=120).read() +open(out, "wb").write(data) +PY + rm -f "$here/generated/$id.json" +fi +if [[ -s "$out" ]]; then + # 原圖可能是 JPEG:先轉 PNG 存檔,網頁用 webp + file "$out" | grep -q PNG || { ffmpeg -loglevel error -y -i "$out" "$out.tmp.png" && mv "$out.tmp.png" "$out"; } + cwebp -quiet -q 80 -resize 640 640 "$out" -o "$web" && echo "ok $id" +else + echo "FAIL $id($(tail -1 "$here/generated/$id.log" 2>/dev/null))" +fi diff --git a/art/gen-card-grokcli.sh b/art/gen-card-grokcli.sh new file mode 100755 index 0000000..e70af62 --- /dev/null +++ b/art/gen-card-grokcli.sh @@ -0,0 +1,27 @@ +#!/bin/zsh +# 用本機 Grok Build(grok CLI 的 image_gen)產生一張卡牌插圖:gen-card-grokcli.sh <題材> +# 只開放生圖工具(--allow imagine),不讓它執行指令;圖存在 grok 自己的 session 資料夾,這裡再轉檔。 +# 原圖存 art/generated/.png,網頁用的縮圖存 web/public/cards/.webp(和 gen-card.sh 一樣) +set -u +id="$1"; subject="$2" +here="${0:A:h}" +out="$here/generated/$id.png" +web="$here/../web/public/cards/$id.webp" +work="$here/grok-work/$id" +style="Style: tabletop board-game card illustration, miniature diorama look with tilt-shift depth of field, soft isometric three-quarter top-down view, warm gouache texture, clean readable shapes, cohesive warm palette with a few saturated accents. Setting: present-day Taiwan. Absolutely no text, no letters, no numbers, no logos, no party symbols or party colors on flags (flags and banners are plain), no real or recognizable people; all figures are small, anonymous and stylized. Square image." +if [[ ! -s "$out" ]]; then + mkdir -p "$work" + marker="$work/.start" + : > "$marker" + grok -p "Use your image generation tool to create exactly ONE image. Subject: $subject. $style Do not run any shell commands and do not edit files; just generate the image and reply with the word done." \ + --cwd "$work" --allow imagine --max-turns 4 > "$here/generated/$id.log" 2>&1 + img=$(find "$HOME/.grok/sessions" -path "*grok-work%2F$id*" -newer "$marker" -type f \( -name "*.jpg" -o -name "*.png" -o -name "*.webp" \) 2>/dev/null | head -1) + if [[ -n "$img" ]]; then + ffmpeg -loglevel error -y -i "$img" "$out" + fi +fi +if [[ -s "$out" ]]; then + cwebp -quiet -q 80 -resize 640 640 "$out" -o "$web" && echo "ok $id" +else + echo "FAIL $id" +fi diff --git a/art/gen-card.sh b/art/gen-card.sh new file mode 100755 index 0000000..ebe407e --- /dev/null +++ b/art/gen-card.sh @@ -0,0 +1,19 @@ +#!/bin/zsh +# 用本機 codex 的生圖工具產生一張卡牌插圖:gen-card.sh <題材> +# 原圖存 art/generated/.png,網頁用的縮圖存 web/public/cards/.webp +set -u +id="$1"; subject="$2" +here="${0:A:h}" +out="$here/generated/$id.png" +web="$here/../web/public/cards/$id.webp" +style="Style: tabletop board-game card illustration, miniature diorama look with tilt-shift depth of field, soft isometric three-quarter top-down view, warm gouache texture, clean readable shapes, cohesive warm palette with a few saturated accents. Setting: present-day Taiwan. Absolutely no text, no letters, no numbers, no logos, no party symbols or party colors on flags (flags and banners are plain), no real or recognizable people; all figures are small, anonymous and stylized. Square 1024x1024." +if [[ ! -s "$out" ]]; then + codex exec --skip-git-repo-check --sandbox workspace-write -C "$here/generated" \ + "Use your image generation tool to create ONE image and save it as $id.png in the current directory (overwrite if it exists). Subject: $subject. $style After saving, print the absolute path of the file and nothing else." \ + > "$here/generated/$id.log" 2>&1 +fi +if [[ -s "$out" ]]; then + cwebp -quiet -q 80 -resize 640 640 "$out" -o "$web" && echo "ok $id" +else + echo "FAIL $id" +fi diff --git a/art/generated/announce_policy.png b/art/generated/announce_policy.png new file mode 100644 index 0000000..c8d3118 --- /dev/null +++ b/art/generated/announce_policy.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85d254ef36f0c45cfefa52c2f434d7efcc3abe436546f8a1546c61d2baf51142 +size 1492653 diff --git a/art/generated/banquet.png b/art/generated/banquet.png new file mode 100644 index 0000000..45c3c7f --- /dev/null +++ b/art/generated/banquet.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d166cbf2e1397d10b533f3cc205c4992140da6d290faf0e7f5b21550b7e2a6be +size 1845765 diff --git a/art/generated/big_donor.png b/art/generated/big_donor.png new file mode 100644 index 0000000..f0a01c2 --- /dev/null +++ b/art/generated/big_donor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e717cd93d0d1e71c1b676fab0033003cf7e601e22a13d9a4ba9b09b966d00cb6 +size 1132420 diff --git a/art/generated/buyout.png b/art/generated/buyout.png new file mode 100644 index 0000000..c01208a --- /dev/null +++ b/art/generated/buyout.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0daaffc9c6cd829d0bea7e0f7bc58979d85c0eccb2c5ad17facab42319ab6a71 +size 1059713 diff --git a/art/generated/chicken_oath.png b/art/generated/chicken_oath.png new file mode 100644 index 0000000..6a969bc --- /dev/null +++ b/art/generated/chicken_oath.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55dadab44ff9458fc423e10ddd203211a674279453e81dd9249eb87d3153b3c1 +size 1342285 diff --git a/art/generated/church_visit.png b/art/generated/church_visit.png new file mode 100644 index 0000000..1be14cd --- /dev/null +++ b/art/generated/church_visit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5eab06b9ffe0e8a703d34aec26919100b07e0eb7cde7e135430cbcbcddec051 +size 1813324 diff --git a/art/generated/concert.png b/art/generated/concert.png new file mode 100644 index 0000000..a77634d --- /dev/null +++ b/art/generated/concert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65eb3d8b6061dbc76faecb1916dda1c9d73c1f9e2484828d146c05cb0963757c +size 1771020 diff --git a/art/generated/councilor_allies.png b/art/generated/councilor_allies.png new file mode 100644 index 0000000..3ce0f36 --- /dev/null +++ b/art/generated/councilor_allies.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b022e6dd9644aa79bd1ddc6f7c3033d76c6e2d21ce467a41eb20293ca2b2bdd +size 1322840 diff --git a/art/generated/crisis_pr.png b/art/generated/crisis_pr.png new file mode 100644 index 0000000..ae66dbc --- /dev/null +++ b/art/generated/crisis_pr.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4573d55ef891b07fefef12a5139b2b959bc00a54bb823292924ee486f7791e5f +size 851943 diff --git a/art/generated/debate_training.png b/art/generated/debate_training.png new file mode 100644 index 0000000..fb10e45 --- /dev/null +++ b/art/generated/debate_training.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82eb338f8f2228b8805cd5b0f317111754b931d5f1e187f48814d028492e8f22 +size 1191442 diff --git a/art/generated/door_to_door.png b/art/generated/door_to_door.png new file mode 100644 index 0000000..f716511 --- /dev/null +++ b/art/generated/door_to_door.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e796fa57e38896332667b49dc92f86d3f7c89a8171dc5bc7295527ec3ba319e +size 1681599 diff --git a/art/generated/endorsement.png b/art/generated/endorsement.png new file mode 100644 index 0000000..5ba5833 --- /dev/null +++ b/art/generated/endorsement.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51cc7b9a03016385039f012a87e9afa8e353e9a6d30c4a075b9545604cb40342 +size 1418014 diff --git a/art/generated/eve_online_ad.png b/art/generated/eve_online_ad.png new file mode 100644 index 0000000..65c576e --- /dev/null +++ b/art/generated/eve_online_ad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d3d935d9bdf9ac424d8f93ef429ad630c3a8d08699c039397fb3fee281ed6e9 +size 1913662 diff --git a/art/generated/eve_phone_bank.png b/art/generated/eve_phone_bank.png new file mode 100644 index 0000000..1e166c3 --- /dev/null +++ b/art/generated/eve_phone_bank.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4a7322cc8ec097b02531809912ea960d25b40a6c65435c3fc4ec7c4c86db95f +size 1608752 diff --git a/art/generated/eve_rally.png b/art/generated/eve_rally.png new file mode 100644 index 0000000..69df69a --- /dev/null +++ b/art/generated/eve_rally.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcd8000ccd83b5cd575126a6a2336e0877b0d7407db510e4b5aac2e66b3d2643 +size 1988937 diff --git a/art/generated/eve_vote_buying.png b/art/generated/eve_vote_buying.png new file mode 100644 index 0000000..5470bc4 --- /dev/null +++ b/art/generated/eve_vote_buying.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab95ccbf8b09f3e3fe27a65b1bda5307e667a03e4deb1fe92c3513f579c55caa +size 1619408 diff --git a/art/generated/expose_press.png b/art/generated/expose_press.png new file mode 100644 index 0000000..d0a99ed --- /dev/null +++ b/art/generated/expose_press.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eedb945633a0c61fe365768b0c88ba096ff7a589045a7d624f138d8a164e347 +size 1518355 diff --git a/art/generated/facebook_live.png b/art/generated/facebook_live.png new file mode 100644 index 0000000..8664df7 --- /dev/null +++ b/art/generated/facebook_live.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2762f5facf7c61cbd18053ed719a405267b1daa80171424552eadfa7f6d8f373 +size 990368 diff --git a/art/generated/fact_check.png b/art/generated/fact_check.png new file mode 100644 index 0000000..c50a8c8 --- /dev/null +++ b/art/generated/fact_check.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfd0b8bd97e6ac204322a29b07b40a6fb1e9f0211e55cdb78eac1b9df5479848 +size 1126543 diff --git a/art/generated/factory_visit.png b/art/generated/factory_visit.png new file mode 100644 index 0000000..3fb405d --- /dev/null +++ b/art/generated/factory_visit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90103f83092d83e32b3770694a275264b875c6a94d400ccfddd64c1130f4f9cd +size 1732200 diff --git a/art/generated/fake_poll.png b/art/generated/fake_poll.png new file mode 100644 index 0000000..02a2f67 --- /dev/null +++ b/art/generated/fake_poll.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0677d2d7dc058b4bb4a1866df12c6a16980b22b1bc421b8da1994aaabcc874ba +size 967842 diff --git a/art/generated/fire_staff.png b/art/generated/fire_staff.png new file mode 100644 index 0000000..13cfc07 --- /dev/null +++ b/art/generated/fire_staff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e50ccc57d52d26547eed2e4cb2b0536dbc8bdaa124203fa516c30c38ed77066c +size 1016124 diff --git a/art/generated/flags_billboards.png b/art/generated/flags_billboards.png new file mode 100644 index 0000000..9ae46e3 --- /dev/null +++ b/art/generated/flags_billboards.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:453cbec531d48af906b8997d8c133ddc3b4219d5eb924e963649b268354bb49a +size 1669400 diff --git a/art/generated/forum.png b/art/generated/forum.png new file mode 100644 index 0000000..0ea7757 --- /dev/null +++ b/art/generated/forum.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74c07636615d6da59d1028db5078522f3896bdb06bfe76a97440040a22bf6073 +size 1051145 diff --git a/art/generated/frame_vote_buying.png b/art/generated/frame_vote_buying.png new file mode 100644 index 0000000..dfa3e77 --- /dev/null +++ b/art/generated/frame_vote_buying.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56938707ad889e5f5944bcc396f158a80f583448e8b8cf409090f2f438a61e20 +size 983988 diff --git a/art/generated/fundraiser_dinner.png b/art/generated/fundraiser_dinner.png new file mode 100644 index 0000000..45a9e98 --- /dev/null +++ b/art/generated/fundraiser_dinner.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:937d2d0238a59acdf9f8ba08e956eedee354c72b1f5722f06c09c027ddc75509 +size 1806270 diff --git a/art/generated/gifts.png b/art/generated/gifts.png new file mode 100644 index 0000000..11ad594 --- /dev/null +++ b/art/generated/gifts.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4cc513afa39fbf5c937cd52d0608e409190b32d21bc5a5ff98de59accc855b64 +size 1219911 diff --git a/art/generated/grassroots_walk.png b/art/generated/grassroots_walk.png new file mode 100644 index 0000000..d23b1e1 --- /dev/null +++ b/art/generated/grassroots_walk.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fe5aa97103b0cd02e58aabaf4bc1ea1179e0788bd3dfd16c9e37df43e764c34 +size 1347978 diff --git a/art/generated/hire_staff.png b/art/generated/hire_staff.png new file mode 100644 index 0000000..fdadb8d --- /dev/null +++ b/art/generated/hire_staff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4796f676614187be827e1ded9f6e886e1874b568725e7107a3dd758ce5383a06 +size 1639852 diff --git a/art/generated/homecoming.png b/art/generated/homecoming.png new file mode 100644 index 0000000..2b5ceda --- /dev/null +++ b/art/generated/homecoming.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bef9a8878c650b0d9fd7fa9a3fdb249e17a821f148f9dd50774ee7333fb1131d +size 2003413 diff --git a/art/generated/impersonate.png b/art/generated/impersonate.png new file mode 100644 index 0000000..365aa02 --- /dev/null +++ b/art/generated/impersonate.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9061f662ad71bacb12a8ba45f1705eae7909680e6efc16bd3614624888c5ec63 +size 960619 diff --git a/art/generated/influencer_live.png b/art/generated/influencer_live.png new file mode 100644 index 0000000..543c3fd --- /dev/null +++ b/art/generated/influencer_live.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f6f80f0beefa25cd394bd65fd142daed91d9e930dffddca8a745b9f85d1664e +size 955818 diff --git a/art/generated/internal_poll.png b/art/generated/internal_poll.png new file mode 100644 index 0000000..7c85634 --- /dev/null +++ b/art/generated/internal_poll.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed743413f7148fe7b732902f2bc7dab1419a1d48d747966f03c2a600d40c2ff4 +size 1559557 diff --git a/art/generated/interview.png b/art/generated/interview.png new file mode 100644 index 0000000..2e73494 --- /dev/null +++ b/art/generated/interview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1093490fcadbc43aca07400899e08baaa07b365221fd78c7166c06850f8b84fc +size 956267 diff --git a/art/generated/investigate.png b/art/generated/investigate.png new file mode 100644 index 0000000..03eca22 --- /dev/null +++ b/art/generated/investigate.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2e4149e2e0f433780aebf5e3877e8738502bfe9d157c2540f7eed43451bd558 +size 1767138 diff --git a/art/generated/invite_oath.png b/art/generated/invite_oath.png new file mode 100644 index 0000000..eafc370 --- /dev/null +++ b/art/generated/invite_oath.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbd328dbda24ccc3b5ca29149118a2182fdfaefc25a4123817ee46541a5e1021 +size 1118897 diff --git a/art/generated/kneel.png b/art/generated/kneel.png new file mode 100644 index 0000000..f790628 --- /dev/null +++ b/art/generated/kneel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d491163041319ded9e3792ecd36731a3b4f507901bca3d031839483c9cbf50b5 +size 1700810 diff --git a/art/generated/lawsuit.png b/art/generated/lawsuit.png new file mode 100644 index 0000000..c7dc3c4 --- /dev/null +++ b/art/generated/lawsuit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5d2568f90855c7752c6dc75bc9293e8c837b98a2cbbcbe0ffaed862531514b2 +size 856273 diff --git a/art/generated/line_groups.png b/art/generated/line_groups.png new file mode 100644 index 0000000..5ccf97b --- /dev/null +++ b/art/generated/line_groups.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f84653b22cb049cadd50cc875b75b8c53fa19c01c1494b77d406b4f01a076a4e +size 916787 diff --git a/art/generated/live_pledge.png b/art/generated/live_pledge.png new file mode 100644 index 0000000..42d33a8 --- /dev/null +++ b/art/generated/live_pledge.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d490e1c3d1fd0e6b2ce80eacccb08cf7e80ba537687a49ea4458e6ba119ff87f +size 1022081 diff --git a/art/generated/market_visit.png b/art/generated/market_visit.png new file mode 100644 index 0000000..023f90d --- /dev/null +++ b/art/generated/market_visit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4823d60bb3edb88ddb9ddf7aa6b629b28a550ea3a42e52984166919a11e9f988 +size 1726192 diff --git a/art/generated/media_training.png b/art/generated/media_training.png new file mode 100644 index 0000000..bc9b076 --- /dev/null +++ b/art/generated/media_training.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:206c4bbd3d5c3e5224c53b450b39f2f8eb13783c15c5fe0b4ed05e1f21aad030 +size 1042697 diff --git a/art/generated/night_market.png b/art/generated/night_market.png new file mode 100644 index 0000000..14d2402 --- /dev/null +++ b/art/generated/night_market.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf7ca805479a6efa91e8ad7c0a3a9ff13aa0d293a2ff43e1d9899ccb953cea90 +size 1856117 diff --git a/art/generated/online_ad.png b/art/generated/online_ad.png new file mode 100644 index 0000000..d82b613 --- /dev/null +++ b/art/generated/online_ad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3294db49892d0dacd3ac56077ab616c55c49837a433cd0c42616560ac4bd85fb +size 1519497 diff --git a/art/generated/open_office.png b/art/generated/open_office.png new file mode 100644 index 0000000..abe3b24 --- /dev/null +++ b/art/generated/open_office.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:430c31f017530566699005d788aeea5d87acff13cb35c0e1a5058f2ed2206b1a +size 1724144 diff --git a/art/generated/party_elder.png b/art/generated/party_elder.png new file mode 100644 index 0000000..45413f7 --- /dev/null +++ b/art/generated/party_elder.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45ffe3139a0d26b6ebd92da62ba7b49f73f63dac531edff2d9d5ac4549b0155c +size 1098060 diff --git a/art/generated/party_fund.png b/art/generated/party_fund.png new file mode 100644 index 0000000..e7b2d2b --- /dev/null +++ b/art/generated/party_fund.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4edb942893db91cbfcc0ac9e4f7b733459d5fd8eabfd0765d8e4e7e8738f0992 +size 1111589 diff --git a/art/generated/phone_banking.png b/art/generated/phone_banking.png new file mode 100644 index 0000000..57181e5 --- /dev/null +++ b/art/generated/phone_banking.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea9b96b5281ee636f705e4ada19404c292aceec77423fd2626a26e6197f1bf69 +size 1655760 diff --git a/art/generated/pilgrimage.png b/art/generated/pilgrimage.png new file mode 100644 index 0000000..b534043 --- /dev/null +++ b/art/generated/pilgrimage.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db4d92b4cc5696cea7080e4240340c1f1c83cf657846324f0e788293dd832c08 +size 1932923 diff --git a/art/generated/press_conference.png b/art/generated/press_conference.png new file mode 100644 index 0000000..7f7efe0 --- /dev/null +++ b/art/generated/press_conference.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f86c703dae3234a6283a8d412c6a67ff4e4a37cbe7c680f2d5d4bebe8b31e267 +size 1008000 diff --git a/art/generated/print_flyers.png b/art/generated/print_flyers.png new file mode 100644 index 0000000..6dd3d38 --- /dev/null +++ b/art/generated/print_flyers.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f9d67d83fe93554e217ce7fe124ffeace290430c45163e4e6cc76b8683737a9 +size 1745643 diff --git a/art/generated/promise_bribe.png b/art/generated/promise_bribe.png new file mode 100644 index 0000000..3ccecc0 --- /dev/null +++ b/art/generated/promise_bribe.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb91e007a4afc1db66c33905d4ae4b3c854ddb929dbdb99397c8cb2fef83a3b6 +size 897793 diff --git a/art/generated/protest_government.png b/art/generated/protest_government.png new file mode 100644 index 0000000..dad60ee --- /dev/null +++ b/art/generated/protest_government.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19327fa7109e76e973b9b8e8c01f92d71d387235fbcdadd16e1843ecc49bcf16 +size 1024657 diff --git a/art/generated/protest_hq.png b/art/generated/protest_hq.png new file mode 100644 index 0000000..954c029 --- /dev/null +++ b/art/generated/protest_hq.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbd6319ce20257daff71938b6393d3d40dc8f1a37aa8e8fba765b975d20aa451 +size 1172341 diff --git a/art/generated/radio_ad.png b/art/generated/radio_ad.png new file mode 100644 index 0000000..bf402fa --- /dev/null +++ b/art/generated/radio_ad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a691d2f9488b95f398bb9a8395afa566303da3ef61da2c51ebf57ffdf57fe153 +size 1649795 diff --git a/art/generated/rally.png b/art/generated/rally.png new file mode 100644 index 0000000..172c34f --- /dev/null +++ b/art/generated/rally.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9457026da099cf0035893d1f2b1a87692e819d0c8d6f6a6af85b1fc36e9109f4 +size 1985013 diff --git a/art/generated/rebuttal_press.png b/art/generated/rebuttal_press.png new file mode 100644 index 0000000..b4f754f --- /dev/null +++ b/art/generated/rebuttal_press.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86b554f8b54c4b72c6464e43401f685abf427fd374493754129afb37f4ec0c1c +size 1461460 diff --git a/art/generated/recruit_machine.png b/art/generated/recruit_machine.png new file mode 100644 index 0000000..ba72e7d --- /dev/null +++ b/art/generated/recruit_machine.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd33e3920c34134792d98b406215d8c65576d35b1f0b8c959d3599f14e285b65 +size 1671072 diff --git a/art/generated/recruit_volunteers.png b/art/generated/recruit_volunteers.png new file mode 100644 index 0000000..4b42848 --- /dev/null +++ b/art/generated/recruit_volunteers.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f86805d2f5a7d765b7969e8c6390d42a81d78f2dc96a59d7d2ab50be68b6192 +size 1666655 diff --git a/art/generated/report_prosecutor.png b/art/generated/report_prosecutor.png new file mode 100644 index 0000000..49ed8c4 --- /dev/null +++ b/art/generated/report_prosecutor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:730922013c41aa1dfc296680a3f7b213ab2b5baf53abb93b843f628f2d399efe +size 951332 diff --git a/art/generated/rest.png b/art/generated/rest.png new file mode 100644 index 0000000..97d3e8a --- /dev/null +++ b/art/generated/rest.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6e843e9dc893392fe8cf5f4a0f185e3d8ecb006bf32dd4f64df802a402edca9 +size 1751724 diff --git a/art/generated/scene-ballot.png b/art/generated/scene-ballot.png new file mode 100644 index 0000000..d39d0d8 --- /dev/null +++ b/art/generated/scene-ballot.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef9b10c9011470c248f3f2179eca7604d6fada83944add7bd2315fe1f5a58bec +size 1562618 diff --git a/art/generated/scene-debate.png b/art/generated/scene-debate.png new file mode 100644 index 0000000..0469289 --- /dev/null +++ b/art/generated/scene-debate.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c1f9e53c77f8d9a591a050e00c410653c90cb09d7066a25b7ae229867518015 +size 1686370 diff --git a/art/generated/scene-election-night.png b/art/generated/scene-election-night.png new file mode 100644 index 0000000..68bab5e --- /dev/null +++ b/art/generated/scene-election-night.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:495df059699ac978966687d09c8a7ba1245eceb2b4dc365863e19df7148818d6 +size 1587996 diff --git a/art/generated/scene-procession.png b/art/generated/scene-procession.png new file mode 100644 index 0000000..12ee588 --- /dev/null +++ b/art/generated/scene-procession.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:038219c4768510795202a3ab0eef0111889299683753ad895dcfac9cb8c678d6 +size 1889873 diff --git a/art/generated/scene-registration.png b/art/generated/scene-registration.png new file mode 100644 index 0000000..c3f6515 --- /dev/null +++ b/art/generated/scene-registration.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:036742d823dfe543b8471a30c2a17c7631872061f3bfe6983defec1936cf30d2 +size 1596339 diff --git a/art/generated/scene-scandal.png b/art/generated/scene-scandal.png new file mode 100644 index 0000000..a200da2 --- /dev/null +++ b/art/generated/scene-scandal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:799fa113ae3fdd6c1c1bb7d6f318c10f6a4645ee01fa51cae40c15293526a0b6 +size 1820089 diff --git a/art/generated/scene-typhoon.png b/art/generated/scene-typhoon.png new file mode 100644 index 0000000..520838f --- /dev/null +++ b/art/generated/scene-typhoon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9beabcbfb12fcd75dd80445338af3c94fe4e367005df1eea6590ffcd567fa953 +size 1898785 diff --git a/art/generated/self_fund.png b/art/generated/self_fund.png new file mode 100644 index 0000000..aa5ef18 --- /dev/null +++ b/art/generated/self_fund.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f56dc7d9abf7c88d563570a36faaf7fe650b2be550aeec2bd0726b2b67e661e +size 1547535 diff --git a/art/generated/short_video.png b/art/generated/short_video.png new file mode 100644 index 0000000..c72fda4 --- /dev/null +++ b/art/generated/short_video.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc229b0a1df598f415e384418a0e4429d832ca79d54596f812c2bf2f557b507f +size 1781274 diff --git a/art/generated/slush_fund.png b/art/generated/slush_fund.png new file mode 100644 index 0000000..1bf36c5 --- /dev/null +++ b/art/generated/slush_fund.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea5ce483431e8452bc7036a8ae6f2ec8e90f81263a9febaa21e5e6cddda4337e +size 901884 diff --git a/art/generated/small_donations.png b/art/generated/small_donations.png new file mode 100644 index 0000000..0085d3d --- /dev/null +++ b/art/generated/small_donations.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4215d2e3da6faa1c994f17806ba4428c83aa57ce081936f8810b0c1a42474244 +size 1525032 diff --git a/art/generated/smear.png b/art/generated/smear.png new file mode 100644 index 0000000..8aab631 --- /dev/null +++ b/art/generated/smear.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e4c0607749e3319a336eefb6367e67b58791193036d55ac7ae2eee65b5eac67 +size 1028312 diff --git a/art/generated/sound_truck.png b/art/generated/sound_truck.png new file mode 100644 index 0000000..33aec11 --- /dev/null +++ b/art/generated/sound_truck.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a72c5ef3dc975e65df287a21083141f5d096b4ab8c5180e86769797d12e580c4 +size 1792540 diff --git a/art/generated/staged_attack.png b/art/generated/staged_attack.png new file mode 100644 index 0000000..292a5dc --- /dev/null +++ b/art/generated/staged_attack.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:278ece75f9ece8fc7090fbab5936cb877b088b8d8a1fde8bac88f92248b36c6b +size 1326043 diff --git a/art/generated/street_canvass.png b/art/generated/street_canvass.png new file mode 100644 index 0000000..95ba357 --- /dev/null +++ b/art/generated/street_canvass.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afc9c17c810cc3229370fc9c34186381434d51233eb83ac97babd75adc15cec8 +size 1736469 diff --git a/art/generated/street_interview.png b/art/generated/street_interview.png new file mode 100644 index 0000000..af3af8a --- /dev/null +++ b/art/generated/street_interview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea52d8422aeae3a3322e6d00db4e15469be3e164284b36e783f7e1ba60cc0202 +size 1121526 diff --git a/art/generated/study.png b/art/generated/study.png new file mode 100644 index 0000000..a462ba2 --- /dev/null +++ b/art/generated/study.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69208998677b45a2b2e062f5847cdced68bbbe5ad12342ae016d080062f8ccd4 +size 1033717 diff --git a/art/generated/talk_show.png b/art/generated/talk_show.png new file mode 100644 index 0000000..0616f0c --- /dev/null +++ b/art/generated/talk_show.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f78ed7524ea9e962d3488777455e5fde9460d86c7515295fae624bc50ca47354 +size 1555058 diff --git a/art/generated/temple_visit.png b/art/generated/temple_visit.png new file mode 100644 index 0000000..fe6780e --- /dev/null +++ b/art/generated/temple_visit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9938bad5537f25917c368f6993ef5438a998b4ed0de59286fed11cffb12e85e +size 1976234 diff --git a/art/generated/troll_army.png b/art/generated/troll_army.png new file mode 100644 index 0000000..90b7962 --- /dev/null +++ b/art/generated/troll_army.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d48bc1aa90ae84a0df555a1422bb79e5672343c91dc682319ddb7fc5b829b63e +size 1703273 diff --git a/art/generated/tv_ad.png b/art/generated/tv_ad.png new file mode 100644 index 0000000..c478b50 --- /dev/null +++ b/art/generated/tv_ad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b2e9d9aedb6dae8375ea32734e22fa6a1b33121f35aa0a3ce59b891d68d96ec +size 1735156 diff --git a/art/generated/visit_associations.png b/art/generated/visit_associations.png new file mode 100644 index 0000000..4df0bcf --- /dev/null +++ b/art/generated/visit_associations.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:217bbc3b829c9d1bdbacbe1e07ff3695d49443a66cdd2a8e9ba85aefcb9b6132 +size 976968 diff --git a/art/generated/volunteer_calls.png b/art/generated/volunteer_calls.png new file mode 100644 index 0000000..3c5d6ab --- /dev/null +++ b/art/generated/volunteer_calls.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84f3cfbd76be2192e6dfd016f7cedf9fea39123b42cff2c5ca833e3e158a8ecb +size 967648 diff --git a/art/generated/vote_buying.png b/art/generated/vote_buying.png new file mode 100644 index 0000000..a29b374 --- /dev/null +++ b/art/generated/vote_buying.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c22ca8752c8f6ae9a12a49517a4a71f7696f0bc6766319dadf5be7dcf67417e +size 1613475 diff --git a/art/generated/weddings_funerals.png b/art/generated/weddings_funerals.png new file mode 100644 index 0000000..467e3df --- /dev/null +++ b/art/generated/weddings_funerals.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ee89a6543a13faeecdc70c4f5a00c5e0ab79e70a6ce0427d2757c90cfd70d38 +size 1759820 diff --git a/art/generated/white_paper.png b/art/generated/white_paper.png new file mode 100644 index 0000000..cedf142 --- /dev/null +++ b/art/generated/white_paper.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6398c6272996be84963372a5ecf23bb1536d5313a1343b5d3218eb9b602ae1c +size 1127680 diff --git a/art/generated/workout.png b/art/generated/workout.png new file mode 100644 index 0000000..3d68361 --- /dev/null +++ b/art/generated/workout.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9730f7eaa16b7ca49488d4ddff13e050ab726fbcd92d984b8e4de68873d78a9 +size 1228885 diff --git a/art/regen-grok.sh b/art/regen-grok.sh new file mode 100755 index 0000000..6860992 --- /dev/null +++ b/art/regen-grok.sh @@ -0,0 +1,6 @@ +#!/bin/zsh +# 用 grok 補生所有還沒有的卡牌插圖(一次兩張) +here="${0:A:h}" +while IFS=$'\t' read -r id subject; do + [[ -s "$here/generated/$id.png" ]] || printf '%s\0%s\0' "$id" "$subject" +done < "$here/cards.tsv" | xargs -0 -n 2 -P 2 "$here/gen-card-grok.sh" diff --git a/art/regen-grokcli.sh b/art/regen-grokcli.sh new file mode 100755 index 0000000..9cd406c --- /dev/null +++ b/art/regen-grokcli.sh @@ -0,0 +1,6 @@ +#!/bin/zsh +# 用本機 grok 補生所有還沒有的卡牌插圖(一次兩張) +here="${0:A:h}" +while IFS=$'\t' read -r id subject; do + [[ -s "$here/generated/$id.png" ]] || printf '%s\0%s\0' "$id" "$subject" +done < "$here/cards.tsv" | xargs -0 -n 2 -P 2 "$here/gen-card-grokcli.sh" diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..6de7571 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,34 @@ +node_modules/ +.DS_Store +._* +*.log +*.tsbuildinfo + +# 資料:原始下載與產出都可以由管線重建 +data/raw/ +data/build/ +data/cache/ + +# 選戰卡牌每一局的存檔(伺服器執行時寫入) +data/runs/ + +# 產出:pnpm schema 產生的 JSON Schema、apps/sim 的報告 +packages/protocol/schema/ +apps/sim/out/ + +# Python +.venv/ +__pycache__/ +*.pyc +*.egg-info/ +build/ +dist/ +.pytest_cache/ +.ruff_cache/ +.coverage +htmlcov/ + +# 祕密 +.env +.env.* +!.env.example diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..1de8225 --- /dev/null +++ b/backend/README.md @@ -0,0 +1,150 @@ +# 選舉小鎮 — 後端 + +遊戲規則、資料管線、人物資料庫與 AI 評分。前端在另一個程式庫(`../web`),只透過 `packages/protocol` 的協定和後端溝通。設計文件在 [`docs/`](docs/README.md)。 + +## 目錄 + +``` +packages/protocol/ 前後端契約(Zod)→ 產生 JSON Schema(schema/);頭像部件目錄 +packages/rogue/ 選戰卡牌的規則(主要玩法):純函式,狀態可序列化 +packages/engine/ 選民模型,加上舊的十週選戰引擎(只給 apps/sim 校準用) +packages/content/ 十週引擎的行動、事件、議題,與手工劇本(資料) +packages/scenarios/ 劇本目錄:手工劇本+管線產生的全台劇本,套上校準值 +packages/pack-loader/ 從磁碟讀取並驗證資料包(伺服器與模擬工具共用) +apps/server/ 遊戲 API 伺服器(Fastify) +apps/sim/ 校準、回測與平衡報告 +data/pipeline/ Python 資料管線(election_data 套件) +data/raw/ 下載的原始資料(不進版控,可重建) +data/build/ 產出的資料包、劇本、參選人資料(不進版控,可重建) +data/runs/ 選戰卡牌每一局的存檔 +docs/ 文件;docs/README.md 是整體架構 +``` + +## 需求 + +- Node.js 22 以上、pnpm 10 +- Python 3.12 以上 + +## 第一次設定 + +```bash +pnpm install +pnpm schema # 由 Zod 產生 JSON Schema,Python 管線驗證輸出時會用到 + +cd data/pipeline +python3 -m venv .venv +.venv/bin/pip install -e ".[dev]" +``` + +## 產生資料包 + +```bash +cd data/pipeline +.venv/bin/election-data pack --county 68000 # 桃園市 +.venv/bin/election-data pack --county 00000 # 全國 +``` + +輸出在 `data/build/packs/<縣市代碼>/`:`manifest.json`、`villages.json`、`towns.json`、`cells.json`、`history.json`、`topology.json`、`sources.json`,以及給人看的 `report.md`(欄位完整度、補值旗標、與中選會總數的核對)。 + +第一次執行會下載約 150 MB 的原始資料到 `data/raw/`(有快取,之後不再下載)。 + +歷史回測用的資料包要排除當次與之後的選舉,避免「先看答案」: + +```bash +.venv/bin/election-data pack --county 68000 --before 2022-11-26 # → packs/68000-before-2022-11-26 +``` + +一次做多個縣市用逗號分隔,`all` 是 22 個縣市。2018、2020 年劇本的資料包要加 `--older`,政黨傾向才有 2016、2018 年的選舉可用(不加時只用 2020 年以後的選舉,現有資料包不受影響): + +```bash +.venv/bin/election-data pack --county all,00000 --before 2020-01-11 --older # 2020 總統、立委 +.venv/bin/election-data pack --county all --before 2018-11-24 --older # 2018 縣市長 +``` + +## 劇本資料(全台的真實候選人與各里得票) + +```bash +.venv/bin/election-data local --year 2022 # 縣市長 → data/build/scenarios/2022-local/<縣市>.json(也可以 2018) +.venv/bin/election-data races --year 2024 # 總統、區域立委 → data/build/scenarios/2024-president/、2024-legislator/(也可以 2020) +``` + +候選人層級的得票都和中選會有效票核對(0 差);競選經費上限依法定公式計算,2018、2022 縣市長與 2020 總統已和中選會公告核對一致。 +立委選區只含選區內的里;選舉後才分出來的新里依相鄰的里歸到選區。 + +劇本產生後要校準(AI 對打讓全區得票接近真實結果,各區、各里當驗證): + +```bash +node apps/sim/src/calibrate-local.ts --set 2024-legislator [--only 63000-01] # → data/build/scenarios//calibration.json +``` + +## 玩遊戲 + +```bash +pnpm --filter @election2026/server start # API:http://127.0.0.1:8787 +cd ../web && pnpm dev # 網頁:http://localhost:5173(/api 轉給上面的伺服器) +``` + +伺服器啟動時不讀資料包,第一局開始時才讀(約 1 秒)。選戰卡牌每一局放在記憶體(最多 200 局),同時寫成 `data/runs/.json`(環境變數 `ROGUE_SAVE_DIR` 可改),伺服器重開也能繼續。 + +## 政治獻金(劇本的錢) + +```bash +cd data/pipeline +.venv/bin/election-data donations --election 111年直轄市市長選舉 --area 桃園市 # → data/build/finance/ +``` + +## 回測與平衡報告 + +```bash +pnpm --filter @election2026/sim backtest -- --seeds 12 --rounds 12 +``` + +用 AI 對打校準全國風向與投票率倍率,再拿各區、各里結果和真實開票比較,也比對 AI 陣營募到、花掉的錢和真實政治獻金。報告輸出到 `apps/sim/out/`。 + +```bash +pnpm --filter @election2026/sim balance -- --seeds 30 # 每位候選人 × 五種打法 +node apps/sim/src/even.ts # 校準「勢均力敵」劇本的風向 +pnpm --filter @election2026/sim rogue-balance # 選戰卡牌的平衡(模擬玩家) +``` + +`apps/sim/src/` 另外有 `career-balance.ts`、`party-balance.ts`、`ultimate-balance.ts`、`village-balance.ts`,直接用 `node` 執行。 + +## 歷屆參選人、政黨、頭像部件 + +```bash +cd data/pipeline +.venv/bin/election-data records # 歷屆參選人與資歷分數 → data/build/people/records.json、data/build/council/<年>.json +.venv/bin/election-data parties # 歷屆政黨清單 → data/build/parties/parties.json、packages/protocol/src/parties.ts +.venv/bin/python -m election_data.genders # 候選人性別(給頭像)→ data/build/people/genders.json +cd ../.. +pnpm avatar:build # 頭像部件 SVG → packages/protocol/src/avatar/*.generated.ts +``` + +## 人物資料庫與 AI 評分 + +> 目前遊戲不讀 `people.json` 和評分結果;歷屆參選人頁用的是上面 `records` 產生的客觀資歷分數。 + +```bash +cd data/pipeline +.venv/bin/python -m election_data.people # 產生 data/build/people/people.json +.venv/bin/python -m election_data.scoring --dry-run # 不呼叫 API:預覽證據包、估計費用 +.venv/bin/python -m election_data.scoring --limit 5 # 先評 5 人試跑 +.venv/bin/python -m election_data.scoring # 全部 +``` + +- 人物資料第一次執行約 8 分鐘(Wikidata 查詢服務有流量限制),之後讀快取約 1 秒。可以設定環境變數 `ELECTION_DATA_CONTACT`(專案網址),放進給 Wikidata 的 User-Agent。人工維護的資料在 `data/pipeline/config/people/`。 +- AI 評分使用 Claude API,憑證由 SDK 自行讀取:設定環境變數 `ANTHROPIC_API_KEY`,或安裝 `ant` 指令列工具後執行 `ant auth login`。 +- 評分會產生費用。請先用 `--dry-run` 看估計,再決定範圍。 +- 評分規則:[`docs/rubric-v1.md`](docs/rubric-v1.md)。輸出 `people_scored.json`、`scoring_report.md`(一致性、政黨偏差檢查)、`review_sample.csv`(人工抽查清單)。 + +## 測試 + +```bash +pnpm test # 協定、引擎、內容、伺服器測試;用到資料包的測試在資料包不存在時略過 +pnpm typecheck +cd data/pipeline && .venv/bin/pytest && .venv/bin/ruff check src tests +``` + +## 資料授權 + +政府開放資料多採「政府資料開放授權條款第 1 版」,每個資料包的 `sources.json` 列出所有來源、版本、擷取日期與授權。 diff --git a/backend/apps/server/package.json b/backend/apps/server/package.json new file mode 100644 index 0000000..f302302 --- /dev/null +++ b/backend/apps/server/package.json @@ -0,0 +1,23 @@ +{ + "name": "@election2026/server", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "遊戲 API 伺服器:比賽狀態只存在後端,前端只拿到玩家視角(docs/11)", + "scripts": { + "start": "node src/main.ts", + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "@election2026/content": "workspace:*", + "@election2026/engine": "workspace:*", + "@election2026/pack-loader": "workspace:*", + "@election2026/protocol": "workspace:*", + "@election2026/rogue": "workspace:*", + "@election2026/scenarios": "workspace:*", + "@fastify/rate-limit": "^11.2.1", + "fastify": "^5.12.7", + "zod": "^4.6.7" + } +} diff --git a/backend/apps/server/src/app.ts b/backend/apps/server/src/app.ts new file mode 100644 index 0000000..ae4b8af --- /dev/null +++ b/backend/apps/server/src/app.ts @@ -0,0 +1,201 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import rateLimit from "@fastify/rate-limit"; +import { CONTENT, candidateStats, personName, withCustomCandidate } from "@election2026/content"; +import { loadScenarioRegistry, type ScenarioRegistry } from "@election2026/scenarios"; +import { DEFAULT_PARAMS, buildPackData, type PackData, type PackFiles, type Scenario } from "@election2026/engine"; +import { DEFAULT_PACKS_ROOT, loadGenders, loadPackFiles, loadSlogans } from "@election2026/pack-loader"; +import { cleanAvatar, type ApiError, type ScenarioSummary } from "@election2026/protocol"; +import Fastify, { type FastifyInstance, type FastifyReply } from "fastify"; +import type { z } from "zod"; +import type { CouncilDistrict } from "@election2026/rogue/local"; +import type { TopologyLike } from "@election2026/rogue/setup"; +import { registerRogue } from "./rogue-routes.ts"; +import { registerPeople } from "./people-routes.ts"; + +export interface AppOptions { + packsRoot?: string; + /** 記憶體裡最多放幾局選戰卡牌(存檔另外寫成檔案) */ + maxRuns?: number; + /** 每個 IP 每分鐘的請求上限 */ + rateLimit?: number; + logger?: boolean; + /** 測試用:指定劇本目錄 */ + registry?: ScenarioRegistry; + /** 選戰卡牌的存檔目錄;沒給就只放記憶體 */ + rogueSaveDir?: string | null; + /** 議員選區檔;沒給就用 data/build/council/2022.json */ + councilFile?: string; +} + +const DEFAULT_COUNCIL_FILE = fileURLToPath(new URL("../../../data/build/council/2022.json", import.meta.url)); + +const PACK_NAME = /^[\w-]+$/; + +/** 補上候選人的性別(給 Q 版頭像);劇本本身沒有的從中選會資料查 */ +function withGenders(s: Scenario, genders: Readonly>): Scenario { + return { ...s, candidates: s.candidates.map((c) => ({ ...c, gender: c.gender ?? genders[personName(c.name)] ?? null })) }; +} + +type Slogans = Readonly>; + +/** 補上當年查證過的競選標語(姓名+選舉年份);客串的人在原本劇本就補過,帶著自己那一年的標語 */ +function withSlogans(s: Scenario, slogans: Slogans): Scenario { + const year = s.electionDate.slice(0, 4); + return { + ...s, + candidates: s.candidates.map((c) => { + if (c.slogan !== undefined) return c; + const hit = slogans[`${c.name}|${year}`]; + return { ...c, slogan: hit?.slogan ?? null, sloganSource: hit?.source ?? null }; + }), + }; +} + +function summary(raw: Scenario, genders: Readonly>, slogans: Slogans): ScenarioSummary { + const s = withSlogans(raw, slogans); + return { + id: s.id, + name: s.name, + description: s.description, + packId: s.packId, + weeks: s.weeks, + region: { + countyCode: s.region.countyCode, + countyName: s.region.countyName, + office: s.region.office, + kind: s.region.kind ?? "mayor", + area: s.region.area ?? s.region.countyName, + regionLevel: s.region.regionLevel ?? "town", + scope: s.region.scope ?? "", + }, + hypothetical: s.hypothetical ?? false, + electionDate: s.electionDate, + spendingCap: s.spendingCap, + candidates: s.candidates.map((c) => ({ + id: c.id, + name: c.name, + party: c.party, + slot: c.slot, + number: c.number, + description: c.description, + startingMoney: c.startingMoney, + staff: c.staff, + realFinance: c.realFinance, + runningMate: c.runningMate ?? null, + gender: c.gender ?? genders[c.name] ?? null, + slogan: c.slogan ?? null, + sloganSource: c.sloganSource ?? null, + stats: candidateStats(s, c), + })), + notes: [...s.notes], + sources: s.sources.map((x) => ({ ...x })), + }; +} + +function fail(reply: FastifyReply, status: number, error: string, details?: string[]): FastifyReply { + const body: ApiError = details ? { error, details } : { error }; + return reply.code(status).send(body); +} + +function parse(schema: T, body: unknown): { ok: true; data: z.infer } | { ok: false; details: string[] } { + const result = schema.safeParse(body); + if (result.success) return { ok: true, data: result.data }; + return { ok: false, details: result.error.issues.slice(0, 10).map((i) => `${i.path.join(".") || "(根)"}:${i.message}`) }; +} + +export async function buildApp(options: AppOptions = {}): Promise { + const packsRoot = options.packsRoot ?? DEFAULT_PACKS_ROOT; + const app = Fastify({ logger: options.logger ?? false, bodyLimit: 64 * 1024 }); + await app.register(rateLimit, { max: options.rateLimit ?? 300, timeWindow: "1 minute" }); + + const registry: ScenarioRegistry = options.registry ?? (await loadScenarioRegistry()); + const genders = await loadGenders(); + const slogans = await loadSlogans(); + /** 真實候選人的名字:自創角色不能用(docs/14 不冒用真人) */ + const realNames = new Set(registry.all.flatMap((s) => s.candidates.map((c) => c.name))); + // 資料包檔案依名稱快取;同一份檔案可以建出不同的遊戲資料(總統用縣市當區、立委只取選區內的里) + const files = new Map>(); + const packs = new Map>(); + const pack = (scenario: Scenario): Promise => { + const key = `${scenario.packId}|${scenario.region.regionLevel ?? "town"}|${scenario.villages ? scenario.id.replace(/-even$|\+.*$/g, "") : ""}`; + let p = packs.get(key); + if (!p) { + let f = files.get(scenario.packId); + if (!f) { + if (!PACK_NAME.test(scenario.packId)) throw new Error(`資料包名稱不合法:${scenario.packId}`); + f = loadPackFiles(join(packsRoot, scenario.packId)); + f.catch(() => files.delete(scenario.packId)); + files.set(scenario.packId, f); + } + p = f.then((x) => buildPackData(x, { regionLevel: scenario.region.regionLevel, villages: scenario.villages ? new Set(scenario.villages) : undefined })); + p.catch(() => packs.delete(key)); + packs.set(key, p); + } + return p; + }; + + app.get("/api/health", async () => ({ ok: true })); + + app.get("/api/scenarios", async () => registry.all.map((s) => summary(s, genders, slogans))); + + const topologies = new Map>(); + let council: Promise | null = null; + const people = registerPeople(app, { fail, parse }); + registerRogue(app, { + realAbilities: people.abilitiesFor, + council: () => + (council ??= readFile(options.councilFile ?? DEFAULT_COUNCIL_FILE, "utf-8") + .then((text) => (JSON.parse(text) as { districts: CouncilDistrict[] }).districts) + .catch((e: unknown) => { + app.log.warn(e, "讀不到議員選區資料(data/build/council/2022.json),政治生涯的議員關不能玩"); + return []; + })), + topology: (packId) => { + let t = topologies.get(packId); + if (!t) { + t = PACK_NAME.test(packId) + ? readFile(join(packsRoot, packId, "topology.json"), "utf-8") + .then((text) => JSON.parse(text) as TopologyLike) + .catch(() => null) + : Promise.resolve(null); + topologies.set(packId, t); + } + return t; + }, + saveDir: options.rogueSaveDir ?? null, + customWorld: async (scenarioId, custom) => { + const found = registry.find(scenarioId); + if (!found) return null; + // 頭像照部件目錄清洗:前端和伺服器上線時間差一點點,看不懂的部件代號換成預設值、記一筆,不擋開局(docs/24) + const cleaned = cleanAvatar(custom.avatar); + if (cleaned.notes.length) app.log.info({ notes: cleaned.notes }, "自創角色的頭像有看不懂的部件,已換成預設"); + const scenario = withGenders(withCustomCandidate(withSlogans(found, slogans), { ...custom, avatar: cleaned.spec }, realNames), genders); + return { scenario, pack: await pack(scenario), content: CONTENT, params: DEFAULT_PARAMS }; + }, + world: async (scenarioId) => { + const found = registry.find(scenarioId); + if (!found) return null; + const scenario = withGenders(withSlogans(found, slogans), genders); + return { scenario, pack: await pack(scenario), content: CONTENT, params: DEFAULT_PARAMS }; + }, + fail, + parse, + maxRuns: options.maxRuns ?? 200, + }); + + /** 地圖:資料包的 TopoJSON(前端只需要形狀,不需要選民模型) */ + app.get<{ Params: { packId: string } }>("/api/packs/:packId/topology", async (request, reply) => { + const { packId } = request.params; + if (!PACK_NAME.test(packId) || !registry.all.some((s) => s.packId === packId)) return fail(reply, 404, "找不到這個資料包"); + try { + const text = await readFile(join(packsRoot, packId, "topology.json"), "utf-8"); + return reply.type("application/json").header("cache-control", "public, max-age=86400").send(text); + } catch { + return fail(reply, 404, "這個資料包沒有地圖"); + } + }); + + return app; +} diff --git a/backend/apps/server/src/main.ts b/backend/apps/server/src/main.ts new file mode 100644 index 0000000..c0aa362 --- /dev/null +++ b/backend/apps/server/src/main.ts @@ -0,0 +1,10 @@ +import { fileURLToPath } from "node:url"; +import { buildApp } from "./app.ts"; + +const port = Number(process.env.PORT ?? 8787); +const host = process.env.HOST ?? "127.0.0.1"; +/** 選戰卡牌的存檔(每一局一個 JSON 檔),伺服器重開也能繼續玩 */ +const rogueSaveDir = process.env.ROGUE_SAVE_DIR ?? fileURLToPath(new URL("../../../data/runs/", import.meta.url)); + +const app = await buildApp({ logger: true, rogueSaveDir }); +await app.listen({ port, host }); diff --git a/backend/apps/server/src/people-routes.ts b/backend/apps/server/src/people-routes.ts new file mode 100644 index 0000000..f8f15e5 --- /dev/null +++ b/backend/apps/server/src/people-routes.ts @@ -0,0 +1,210 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { + PEOPLE_PAGE_SIZE, + type CareerAbilities, + PeopleListQuery, + RecordsFile, + type ElectionRun, + type PeopleListResponse, + type PersonRecord, + type PersonRecordResponse, +} from "@election2026/protocol"; +import type { FastifyInstance, FastifyReply } from "fastify"; +import type { z } from "zod"; + +/** election-data records 的輸出(歷屆參選人資料庫:縣市長、議員、總統副總統、立委) */ +export const DEFAULT_RECORDS_FILE = fileURLToPath(new URL("../../../data/build/people/records.json", import.meta.url)); + +const NOTE = "分數是依公開選舉紀錄計算的遊戲數值,不代表對個人的評價"; +const PERSON_ID = /^r-[0-9a-f]{10}$/; + +interface PeopleContext { + fail: (reply: FastifyReply, status: number, error: string, details?: string[]) => FastifyReply; + parse: (schema: T, body: unknown) => { ok: true; data: z.infer } | { ok: false; details: string[] }; + /** records.json 的路徑;沒給就用 data/build/people/records.json */ + file?: string; +} + +interface Indexed { + data: RecordsFile; + byId: Map; + /** 搜尋用的姓名(去空白、間隔號,小寫),和 data.people 同順序 */ + keys: string[]; + years: number[]; +} + +const emptyRecords = (): RecordsFile => ({ + protocolVersion: "1.0.0", + generatedAt: "1970-01-01", + note: NOTE, + sources: [], + scoreDefs: [], + elections: [], + people: [], +}); + +/** 姓名搜尋鍵:全形轉半形、去空白與間隔號、拼音轉小寫 */ +export const searchKey = (s: string): string => + s + .normalize("NFKC") + .replace(/[\s‧・·•..]/g, "") + .toLowerCase(); + +function index(data: RecordsFile): Indexed { + return { + data, + byId: new Map(data.people.map((p) => [p.id, p])), + keys: data.people.map((p) => searchKey(p.name)), + years: [...new Set(data.elections.map((e) => e.year))].sort((a, b) => b - a), + }; +} + +/** 讀 records.json:檔案不在或格式不對就當成空的資料庫(記一筆警告),伺服器照常運作 */ +export async function loadRecords(file: string, warn: (msg: string) => void = () => {}): Promise { + let raw: unknown; + try { + raw = JSON.parse(await readFile(file, "utf-8")); + } catch (e) { + warn(`政治人物資料庫讀不到,先用空的:${file}(${(e as Error).message})`); + return emptyRecords(); + } + const parsed = RecordsFile.safeParse(raw); + if (!parsed.success) { + const first = parsed.error.issues[0]; + warn(`政治人物資料庫格式不對,先用空的:${first ? `${first.path.join(".")}:${first.message}` : file}`); + return emptyRecords(); + } + return parsed.data; +} + +/** 玩真實候選人時的開局能力:依公開選舉紀錄換算(只看這場選舉之前的紀錄),附依據 */ +export interface RecordAbilities { + abilities: CareerAbilities; + basis: string; +} + +/** 全國性的劇本(總統選舉)用這個縣市代碼 */ +const NATIONWIDE = "00000"; + +/** + * 認人:同名、比對信心不是低、而且有在這個縣市參選過(總統選舉不限縣市)。 + * 同名的還有好幾位時,有「這場選舉本身」紀錄的那一位優先(同一天投票、同一個縣市;總統選舉看總統副總統紀錄)。 + * 這場選舉本身的紀錄只拿來認人,不算進能力。 + */ +function findPerson(people: readonly PersonRecord[], name: string, countyCode: string, date: string): PersonRecord | null { + const key = searchKey(name); + const nationwide = countyCode === NATIONWIDE; + const named = people.filter((p) => searchKey(p.name) === key && p.confidence !== "low" && (nationwide || p.runs.some((r) => r.countyCode === countyCode))); + if (named.length === 1) return named[0]!; + const same = named.filter((p) => p.runs.some((r) => r.date === date && (nationwide ? r.office === "president" : r.countyCode === countyCode))); + return same.length === 1 ? same[0]! : null; +} + +/** + * 依那場選舉之前的公開紀錄換算開局能力(0–2 級,溫和加成): + * 媒體看單次最高得票(知名度)、組織看當選次數、口才看從政年數。財務、清廉沒有客觀依據,一律 0(不做評價)。 + * 總統副總統、立委的紀錄也照同一套門檻換算,不另外加碼: + * - 總統選舉的全國票數只會讓媒體停在 2 級(30 萬票以上就是 2 級,和大縣市的縣市長一樣);副總統用同一組的票。 + * - 不分區立委沒有個人得票,不算進媒體;當選和其他選舉一樣算一次當選。 + * 認人的規則見 findPerson;比對信心低、或認不出是哪一位就不給(寧可不給也不要給錯人)。 + */ +export function recordAbilities(people: readonly PersonRecord[], name: string, countyCode: string, before: string): RecordAbilities | null { + const person = findPerson(people, name, countyCode, before); + if (!person) return null; + const runs = person.runs.filter((r) => r.date < before); + if (runs.length === 0) return null; + const maxVotes = Math.max(0, ...runs.map((r) => r.votes ?? 0)); + const wins = runs.filter((r) => r.elected); + const firstWin = wins[0]?.year ?? null; + const years = firstWin === null ? 0 : runs[runs.length - 1]!.year - firstWin; + const abilities: CareerAbilities = { + media: maxVotes >= 300_000 ? 2 : maxVotes >= 30_000 ? 1 : 0, + organization: wins.length >= 3 ? 2 : wins.length >= 1 ? 1 : 0, + eloquence: years >= 12 ? 2 : years >= 4 ? 1 : 0, + finance: 0, + integrity: 0, + }; + const basis = `參選 ${runs.length} 次、當選 ${wins.length} 次、單次最高 ${maxVotes.toLocaleString("en-US")} 票${firstWin ? `、${firstWin} 年第一次當選` : ""}(中選會歷屆選舉紀錄,${before.slice(0, 4)} 年以前)`; + return { abilities, basis }; +} + +/** 「2022 臺北市第3選區 直轄市議員(平地原住民)」「2024 全國 副總統」「2024 全國 不分區立法委員」 */ +export const runLabel = (r: ElectionRun): string => + `${r.year} ${r.county}${r.district ?? ""} ${r.election}${r.indigenous ? `(${r.indigenous})` : ""}`; + +/** + * 政治人物資料庫(歷屆縣市長、議員、總統副總統、立委): + * GET /api/people?county=&office=mayor|councilor|president|legislator&year=&q=&page= 每頁 50 人; + * 縣市、選舉種類、年份要同一次參選都符合(例如「2022 年臺北市議員」)。 + * president 含副總統候選人;legislator 含區域、原住民、不分區立委。總統副總統、原住民與不分區立委是全國性的, + * 沒有縣市,選了縣市就不會出現(例如「臺北市+立委」只列臺北市的區域立委)。 + * GET /api/people/:id 個人的歷次參選與資歷分數(附算法與出處)。 + * records.json 在註冊時讀一次,之後都用記憶體裡的。 + */ +export function registerPeople(app: FastifyInstance, ctx: PeopleContext): { abilitiesFor: (name: string, countyCode: string, before: string) => Promise } { + const ready: Promise = loadRecords(ctx.file ?? DEFAULT_RECORDS_FILE, (msg) => app.log.warn(msg)).then(index); + + app.get("/api/people", async (request, reply) => { + const query = ctx.parse(PeopleListQuery, request.query); + if (!query.ok) return ctx.fail(reply, 400, "查詢條件不對", query.details); + const { county, office, year, q, page } = query.data; + const db = await ready; + const needle = q ? searchKey(q) : ""; + const matchRun = (r: ElectionRun): boolean => + (!county || r.countyCode === county) && (!office || r.office === office) && (!year || r.year === year); + const filtered = db.data.people.filter( + (p, i) => (!needle || db.keys[i]!.includes(needle)) && (!county && !office && !year ? true : p.runs.some(matchRun)), + ); + const start = (page - 1) * PEOPLE_PAGE_SIZE; + const body: PeopleListResponse = { + total: filtered.length, + page, + pageSize: PEOPLE_PAGE_SIZE, + people: filtered.slice(start, start + PEOPLE_PAGE_SIZE).map((p) => { + const latest = p.runs[p.runs.length - 1]!; + return { + id: p.id, + name: p.name, + party: latest.party, + runs: p.stats.runs, + wins: p.stats.wins, + firstYear: p.stats.firstYear, + lastYear: p.stats.lastYear, + latest: runLabel(latest), + confidence: p.confidence, + }; + }), + years: db.years, + note: NOTE, + }; + return body; + }); + + app.get<{ Params: { id: string } }>("/api/people/:id", async (request, reply) => { + const { id } = request.params; + const db = await ready; + const person = PERSON_ID.test(id) ? db.byId.get(id) : undefined; + if (!person) return ctx.fail(reply, 404, "找不到這個人"); + const defs = new Map(db.data.scoreDefs.map((d) => [d.key, d])); + const body: PersonRecordResponse = { + person: { + ...person, + scores: person.scores.map((s) => { + const d = defs.get(s.key); + return { ...s, label: d?.label ?? s.key, formula: d?.formula ?? "", source: d?.source ?? "" }; + }), + }, + sources: db.data.sources, + note: NOTE, + }; + return body; + }); + + return { + abilitiesFor: async (name, countyCode, before) => { + const db = await ready; + return recordAbilities(db.data.people, name, countyCode, before); + }, + }; +} diff --git a/backend/apps/server/src/rogue-routes.ts b/backend/apps/server/src/rogue-routes.ts new file mode 100644 index 0000000..c00b55f --- /dev/null +++ b/backend/apps/server/src/rogue-routes.ts @@ -0,0 +1,245 @@ +import { randomInt, randomUUID } from "node:crypto"; +import { CUSTOM_ID, CustomCandidateError } from "@election2026/content"; +import type { World } from "@election2026/engine"; +import { CreateRogueRequest, RogueChooseRequest, RoguePlayRequest, RogueUltimateRequest, type CareerAbilities, type CustomCandidate, type RogueView, originAbilities, partyKind } from "@election2026/protocol"; +import { + ADVISOR_BY_ID, + CAREER_STAGES, + CARD_BY_ID, + TUTORIAL_DECK, + TUTORIAL_WEEKS, + catalog, + choose, + createRun, + endWeek, + playCard, + toView, + tutorialSetup, + ultimate, + type RogueSetup, + type RunState, +} from "@election2026/rogue"; +import { COUNCIL_WEEKS, LocalRaceError, VILLAGE_WEEKS, councilSetup, districtOfVillage, districtWithNewVillages, villageList, villageSetup, type CouncilDistrict } from "@election2026/rogue/local"; +import { buildSetup, type TopologyLike } from "@election2026/rogue/setup"; +import type { FastifyInstance, FastifyReply } from "fastify"; +import type { z } from "zod"; +import { RunStore } from "./run-store.ts"; + +interface RogueContext { + /** 依劇本 id 建好遊戲世界(含標語、性別);找不到劇本是 null */ + world: (scenarioId: string) => Promise; + /** 政治生涯:把自創角色放進劇本(名字和真實候選人一樣時丟 CustomCandidateError) */ + customWorld: (scenarioId: string, custom: CustomCandidate) => Promise; + /** 玩真實候選人:依公開選舉紀錄換算開局能力(before 是這場選舉的日期,只看之前的紀錄);查不到是 null */ + realAbilities?: (name: string, countyCode: string, before: string) => Promise<{ abilities: CareerAbilities; basis: string } | null>; + /** 2022 年議員選區(data/build/council/2022.json);讀不到是空陣列 */ + council: () => Promise; + /** 資料包的地圖拓撲(算相鄰的區);讀不到是 null */ + topology: (packId: string) => Promise; + fail: (reply: FastifyReply, status: number, error: string, details?: string[]) => FastifyReply; + parse: (schema: T, body: unknown) => { ok: true; data: z.infer } | { ok: false; details: string[] }; + maxRuns: number; + /** 存檔目錄;null 是只放記憶體(測試用) */ + saveDir: string | null; +} + +const RUN_ID = /^[0-9a-f-]{36}$/; + +/** 每日一戰:同一天同一個種子 */ +const dailySeed = (date: string): number => { + let h = 2166136261; + for (const ch of `tongsuan-${date}`) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); + return (h >>> 0) % 2 ** 31; +}; + +/** + * 選戰卡牌(新玩法,docs/21、22)的 API:規則在伺服器跑,前端每出一張牌就拿到新的畫面狀態。 + * POST /api/rogue/runs 開局;/tutorial 新手教學;/play 出牌;/end-week 結束這週;/choose 劇情、下一站的選擇。 + * 每一局存成 JSON 檔(有版本號),伺服器重開也能繼續玩。 + */ +export function registerRogue(app: FastifyInstance, ctx: RogueContext): void { + const runs = new RunStore(ctx.maxRuns, ctx.saveDir, (e) => app.log.error(e, "選戰卡牌存檔失敗")); + // 開局的底盤要跑一次選民模型,同一個劇本、同一位候選人重複使用 + const setups = new Map>(); + + const load = async (id: string): Promise => { + const s = RUN_ID.test(id) ? await runs.get(id) : undefined; + // 舊存檔沒有選區名稱:從劇本補上(自創角色的劇本 id 是「原劇本+custom」) + if (s && !s.setup.area && !s.options.tutorial) { + const world = await ctx.world(s.setup.scenarioId.replace(/\+.*$/, "")); + s.setup.area = world?.scenario.region.area ?? s.setup.countyName; + } + return s; + }; + const save = (s: RunState): RogueView => { + runs.set(s); + return toView(s); + }; + + app.get("/api/rogue/catalog", async () => catalog()); + + /** 政治生涯照真實底盤時,開局最多落後幾個百分點 */ + const CAREER_MAX_GAP = 0.1; + + app.post("/api/rogue/runs", async (request, reply) => { + const parsed = ctx.parse(CreateRogueRequest, request.body); + if (!parsed.ok) return ctx.fail(reply, 400, "請求格式不正確", parsed.details); + const { scenarioId, seed, ascension, even, daily, custom, career, carry, abilities, perks, policies, local } = parsed.data; + const candidateId = custom ? CUSTOM_ID : parsed.data.candidateId; + const runSeed = seed ?? (daily ? dailySeed(daily) : randomInt(2 ** 31)); + let setup: Promise | undefined; + if (local) { + // 地方選舉(里長、議員)只在政治生涯用自創角色打;scenarioId 是那個縣市的縣市長劇本(拿選民模型) + if (!custom) return ctx.fail(reply, 400, "里長、議員選舉要用自創角色"); + let world: World | null; + try { + world = await ctx.customWorld(scenarioId, custom); + } catch (e) { + if (e instanceof CustomCandidateError) return ctx.fail(reply, 400, e.message); + throw e; + } + // 早期手做的劇本(例如 taoyuan-2022-mayor)沒寫 kind,和劇本清單一樣當作縣市長 + if (!world || (world.scenario.region.kind ?? "mayor") !== "mayor") return ctx.fail(reply, 404, `找不到縣市長劇本 ${scenarioId}`); + try { + if (local.kind === "village") setup = Promise.resolve(villageSetup(world, candidateId, local.village, runSeed)); + else { + const districts = await ctx.council(); + const district = districtOfVillage(districts, local.village); + if (!district) return ctx.fail(reply, 400, "找不到這個里所在的議員選區"); + setup = Promise.resolve(councilSetup(world, candidateId, districtWithNewVillages(district, districts, world.pack.villages.map((v) => v.code)), runSeed, await ctx.topology(world.scenario.packId)).setup); + } + } catch (e) { + if (e instanceof LocalRaceError) return ctx.fail(reply, 400, e.message); + throw e; + } + } else if (custom) { + // 自創角色每個人都不一樣,不快取 + let world: World | null; + try { + world = await ctx.customWorld(scenarioId, custom); + } catch (e) { + if (e instanceof CustomCandidateError) return ctx.fail(reply, 400, e.message); + throw e; + } + if (!world) return ctx.fail(reply, 404, `找不到劇本 ${scenarioId}`); + // 政治生涯照真實底盤,但最多落後 10 個百分點(靠大絕招還有機會翻盤,18 第 57 項) + setup = Promise.resolve(buildSetup(world, candidateId, { even, maxGap: career ? CAREER_MAX_GAP : undefined, topology: await ctx.topology(world.scenario.packId) })); + } else { + const key = `${scenarioId}|${candidateId}|${even ? "even" : ""}`; + setup = setups.get(key); + if (!setup) { + const world = await ctx.world(scenarioId); + if (!world) return ctx.fail(reply, 404, `找不到劇本 ${scenarioId}`); + if (!world.scenario.candidates.some((c) => c.id === candidateId)) return ctx.fail(reply, 400, `劇本中沒有候選人 ${candidateId}`); + const topology = await ctx.topology(world.scenario.packId); + setup = Promise.resolve(buildSetup(world, candidateId, { even, topology })); + setup.catch(() => setups.delete(key)); + setups.set(key, setup); + } + } + // 帶過來的牌只能是一般的牌(不能帶狀態牌),幕僚要存在 + const bad = carry && (carry.advisors.some((a) => !ADVISOR_BY_ID.has(a)) || carry.cards.some((c) => (CARD_BY_ID.get(c.id)?.rarity ?? "status") === "status")); + if (bad) return ctx.fail(reply, 400, "帶過來的幕僚或牌不正確"); + // 玩真實候選人(不是每日一戰):依那場選舉之前的公開紀錄給一點開局能力 + let record: { abilities: CareerAbilities; basis: string } | null = null; + if (!custom && !local && !daily && !abilities && ctx.realAbilities) { + const world = await ctx.world(scenarioId); + const you = (await setup).you; + if (world) record = await ctx.realAbilities(you.name, world.scenario.region.countyCode, world.scenario.electionDate); + } + const state = createRun(await setup, randomUUID(), runSeed, { + weeks: local ? (local.kind === "village" ? VILLAGE_WEEKS : COUNCIL_WEEKS) : undefined, + ascension, + daily: daily ?? null, + even, + career: career ? { stage: career.stage, total: CAREER_STAGES } : null, + carry: carry ? { advisors: carry.advisors, cards: carry.cards.map((c) => ({ id: c.id, up: c.up })), money: carry.money, momentum: carry.momentum } : undefined, + // 每日一戰大家條件一樣:不帶政策島、能力、政策(建築 id 和等級由 createRun 再檢查一次) + // 自創角色沒帶能力(自由選戰):依捏人物點數、出身、黨的資源算起始能力(18 第 53 項) + abilities: daily ? null : (abilities ?? record?.abilities ?? (custom ? originAbilities(custom) : null)), + abilitiesBasis: record?.basis ?? null, + // 自創角色的出身與政黨:專屬起始牌、黨的資源(每日一戰大家條件一樣,不套用) + origin: custom && !daily ? { background: custom.background, party: custom.party, kind: partyKind(custom.party) } : null, + perks: daily ? [] : perks, + policies: daily ? [] : policies, + }); + return reply.code(201).send({ runId: state.runId, view: save(state) }); + }); + + app.post("/api/rogue/tutorial", async (_request, reply) => { + const state = createRun(tutorialSetup(), randomUUID(), 20261026, { tutorial: true, weeks: TUTORIAL_WEEKS, deck: TUTORIAL_DECK }); + return reply.code(201).send({ runId: state.runId, view: save(state) }); + }); + + /** 政治生涯里長關:縣市長劇本那個縣市的區和里(自己挑要選哪一里) */ + app.get<{ Params: { scenarioId: string } }>("/api/rogue/villages/:scenarioId", async (request, reply) => { + const world = await ctx.world(request.params.scenarioId); + if (!world || (world.scenario.region.kind ?? "mayor") !== "mayor") return ctx.fail(reply, 404, `找不到縣市長劇本 ${request.params.scenarioId}`); + return reply.header("cache-control", "public, max-age=3600").send(villageList(world)); + }); + + /** 選區範圍:立委選區只畫選區內的村里;縣市長、總統是 null(整份資料包) */ + app.get<{ Params: { id: string } }>("/api/rogue/runs/:id/area", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + if (s.options.tutorial || !s.setup.packId) return { villages: null, groups: null }; + // 議員選區:村里分群(或整區) + if (s.setup.scenarioId.startsWith("council:")) { + const districts = await ctx.council(); + const district = districts.find((d) => `council:${d.id}` === s.setup.scenarioId); + if (!district) return { villages: null, groups: s.setup.groups ?? null }; + // 2022 年以後新成立的里也畫進來(村里名單是 2022 年的) + const topology = await ctx.topology(s.setup.packId); + const codes = (topology?.objects.villages?.geometries ?? []).map((g) => String(g.properties?.code ?? "")); + return { villages: [...districtWithNewVillages(district, districts, codes).villages], groups: s.setup.groups ?? null }; + } + // 自創角色的劇本 id 是「原劇本+custom」,選區和原劇本一樣 + const world = await ctx.world(s.setup.scenarioId.replace(/\+.*$/, "")); + return { villages: world?.scenario.villages ? [...world.scenario.villages] : null, groups: null }; + }); + + app.get<{ Params: { id: string } }>("/api/rogue/runs/:id", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + return toView(s); + }); + + app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/play", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + const parsed = ctx.parse(RoguePlayRequest, request.body); + if (!parsed.ok) return ctx.fail(reply, 400, "請求格式不正確", parsed.details); + const r = playCard(s, parsed.data.uid, parsed.data.target); + if ("error" in r) return ctx.fail(reply, 400, r.error); + return { ...save(r.state), notes: r.notes }; + }); + + /** 大絕招(18 第 57 項):前端玩完小遊戲,把分數送來 */ + app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/ultimate", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + const parsed = ctx.parse(RogueUltimateRequest, request.body); + if (!parsed.ok) return ctx.fail(reply, 400, "請求格式不正確", parsed.details); + const r = ultimate(s, parsed.data.kind, parsed.data.score, parsed.data.towns); + if ("error" in r) return ctx.fail(reply, 409, r.error); + return save(r); + }); + + app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/end-week", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + const r = endWeek(s); + if ("error" in r) return ctx.fail(reply, 409, r.error); + return save(r); + }); + + app.post<{ Params: { id: string } }>("/api/rogue/runs/:id/choose", async (request, reply) => { + const s = await load(request.params.id); + if (!s) return ctx.fail(reply, 404, "找不到這一局(可能已過期或是舊版的存檔)"); + const parsed = ctx.parse(RogueChooseRequest, request.body); + if (!parsed.ok) return ctx.fail(reply, 400, "請求格式不正確", parsed.details); + const r = choose(s, parsed.data.pick, parsed.data.target, parsed.data.option); + if ("error" in r) return ctx.fail(reply, 409, r.error); + return save(r); + }); +} diff --git a/backend/apps/server/src/run-store.ts b/backend/apps/server/src/run-store.ts new file mode 100644 index 0000000..7e505ee --- /dev/null +++ b/backend/apps/server/src/run-store.ts @@ -0,0 +1,78 @@ +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { SAVE_VERSION, migrateRun, type RunState } from "@election2026/rogue"; +import { LruStore } from "./store.ts"; + +/** + * 選戰卡牌的存檔:記憶體放最近玩的幾局,每次變動另外寫成 JSON 檔(先寫暫存檔再改名,寫到一半當機也不會壞檔)。 + * 讀檔時檢查版本號;舊版的存檔不讀(規則改過,接著玩會出錯)。 + */ +export class RunStore { + private readonly memory: LruStore; + /** 同一局的寫檔依序進行,避免舊的狀態蓋掉新的 */ + private readonly writing = new Map>(); + private readonly dir: string | null; + private readonly onError: (e: unknown) => void; + + constructor(capacity: number, dir: string | null, onError: (e: unknown) => void) { + this.memory = new LruStore(capacity); + this.dir = dir; + this.onError = onError; + } + + private file(id: string): string { + return join(this.dir!, `${id}.json`); + } + + /** 同一局同時有好幾個請求從檔案讀:共用同一次讀檔,避免各自以舊狀態為基礎互相覆蓋 */ + private readonly loading = new Map>(); + + async get(id: string): Promise { + const hit = this.memory.get(id); + if (hit || !this.dir) return hit; + const pending = this.loading.get(id); + if (pending) return pending; + const load = (async () => { + await this.writing.get(id); + try { + const s = migrateRun(JSON.parse(await readFile(this.file(id), "utf-8")) as RunState); + if (s.version !== SAVE_VERSION || s.runId !== id) return undefined; + // 讀檔的時候如果已經有新的狀態寫進記憶體,以記憶體的為準 + const now = this.memory.get(id); + if (now) return now; + this.memory.set(id, s); + return s; + } catch { + return undefined; + } + })().finally(() => this.loading.delete(id)); + this.loading.set(id, load); + return load; + } + + set(s: RunState): void { + this.memory.set(s.runId, s); + if (!this.dir) return; + const dir = this.dir; + const file = this.file(s.runId); + const body = JSON.stringify(s); + const prev = this.writing.get(s.runId) ?? Promise.resolve(); + const next = prev + .then(async () => { + await mkdir(dir, { recursive: true }); + const tmp = `${file}.tmp`; + await writeFile(tmp, body); + await rename(tmp, file); + }) + .catch(this.onError) + .finally(() => { + if (this.writing.get(s.runId) === next) this.writing.delete(s.runId); + }); + this.writing.set(s.runId, next); + } + + /** 等所有寫檔完成(測試用) */ + async flush(): Promise { + await Promise.all(this.writing.values()); + } +} diff --git a/backend/apps/server/src/store.ts b/backend/apps/server/src/store.ts new file mode 100644 index 0000000..2c19929 --- /dev/null +++ b/backend/apps/server/src/store.ts @@ -0,0 +1,31 @@ +/** 選戰卡牌的一局:狀態很小(約 20 KB),一樣放記憶體、超過上限淘汰最久沒動的 */ +export class LruStore { + private readonly items = new Map(); + private readonly capacity: number; + + constructor(capacity: number) { + this.capacity = capacity; + } + + get(id: string): T | undefined { + const item = this.items.get(id); + if (item === undefined) return undefined; + this.items.delete(id); + this.items.set(id, item); + return item; + } + + set(id: string, item: T): void { + this.items.delete(id); + this.items.set(id, item); + while (this.items.size > this.capacity) { + const oldest = this.items.keys().next().value; + if (oldest === undefined) break; + this.items.delete(oldest); + } + } + + get size(): number { + return this.items.size; + } +} diff --git a/backend/apps/server/test/people.test.ts b/backend/apps/server/test/people.test.ts new file mode 100644 index 0000000..bb73242 --- /dev/null +++ b/backend/apps/server/test/people.test.ts @@ -0,0 +1,293 @@ +import { existsSync } from "node:fs"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SCENARIOS } from "@election2026/content"; +import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader"; +import { ApiError, PeopleListResponse, PersonRecordResponse, type RecordsFile } from "@election2026/protocol"; +import Fastify, { type FastifyInstance, type FastifyReply } from "fastify"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { z } from "zod"; +import { buildApp } from "../src/app.ts"; +import { DEFAULT_RECORDS_FILE, recordAbilities, registerPeople, searchKey } from "../src/people-routes.ts"; + +const fail = (reply: FastifyReply, status: number, error: string, details?: string[]): FastifyReply => + reply.code(status).send(details ? { error, details } : { error }); +const parse = (schema: T, body: unknown) => { + const r = schema.safeParse(body); + return r.success ? ({ ok: true, data: r.data } as const) : ({ ok: false, details: r.error.issues.map((i) => i.message) } as const); +}; + +const run = (over: Record = {}) => ({ + year: 2022, + date: "2022-11-26", + election: "直轄市議員", + office: "councilor", + indigenous: null, + county: "臺北市", + countyCode: "63000", + district: "第3選區", + number: 1, + party: "甲黨", + votes: 12_000, + share: 0.12, + elected: true, + incumbent: false, + ...over, +}); + +const person = (i: number, over: Record = {}, runs = [run()]) => ({ + id: `r-${i.toString(16).padStart(10, "0")}`, + name: `測試人${i}`, + gender: null, + birthYear: 1970, + confidence: "high", + counties: ["63000"], + parties: ["甲黨"], + stats: { runs: runs.length, wins: 1, firstYear: 2022, lastYear: 2022, maxVotes: 12_000 }, + runs, + scores: [{ key: "fame", value: 3.2, basis: "生涯單次最高 12,000 票" }], + ...over, +}); + +const FIXTURE = { + protocolVersion: "1.0.0", + generatedAt: "2026-10-26", + note: "分數是依公開選舉紀錄計算的遊戲數值,不代表對個人的評價", + sources: [{ title: "中央選舉委員會選舉資料庫", url: "https://data.cec.gov.tw/", retrievedAt: "2026-10-25" }], + scoreDefs: [{ key: "fame", label: "知名度", formula: "取對數", source: "中選會" }], + elections: [ + { folder: "a", year: 2022, date: "2022-11-26", election: "直轄市議員", office: "councilor", indigenous: null, candidates: 1, elected: 1, noVotes: 0 }, + { folder: "b", year: 2018, date: "2018-11-24", election: "直轄市長", office: "mayor", indigenous: null, candidates: 1, elected: 1, noVotes: 0 }, + { folder: "c", year: 2024, date: "2024-01-13", election: "總統副總統", office: "president", indigenous: null, candidates: 2, elected: 2, noVotes: 0 }, + { folder: "d", year: 2024, date: "2024-01-13", election: "不分區立法委員", office: "legislator", indigenous: null, candidates: 1, elected: 1, noVotes: 0 }, + ], + people: [ + // 120 位 2022 臺北市議員候選人(測分頁) + ...Array.from({ length: 120 }, (_, i) => person(i + 1)), + person(500, { name: "伊凡諾幹 Iban Nokan" }, [run({ indigenous: "山地原住民", district: "第8選區" })]), + // 2018 新北市長、2022 臺北市議員:縣市、選舉、年份要同一次參選都符合 + person(501, { name: "跨縣市", counties: ["63000", "65000"] }, [ + run({ year: 2018, date: "2018-11-24", election: "直轄市長", office: "mayor", county: "新北市", countyCode: "65000", district: null }), + run(), + ]), + // 2020 臺北市區域立委、2024 副總統:全國性的選舉沒有縣市 + person(502, { name: "副手", counties: ["63000"] }, [ + run({ year: 2020, date: "2020-01-11", election: "立法委員", office: "legislator", district: "第1選區", votes: 80_000 }), + run({ year: 2024, date: "2024-01-13", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 5_000_000, share: 0.4, runningMate: "正手" }), + ]), + // 2024 不分區立委:沒有個人得票,記名單排名與政黨票 + person(503, { name: "名單", counties: [] }, [ + run({ year: 2024, date: "2024-01-13", election: "不分區立法委員", office: "legislator", county: "全國", countyCode: null, district: null, votes: null, share: null, listRank: 3, partyVotes: 4_000_000, partyShare: 0.3 }), + ]), + ], +} satisfies Record; + +async function appWith(file: string): Promise { + const app = Fastify(); + registerPeople(app, { fail, parse, file }); + await app.ready(); + return app; +} + +describe("政治人物資料庫 API", () => { + let dir: string; + let app: FastifyInstance; + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), "people-")); + await writeFile(join(dir, "records.json"), JSON.stringify(FIXTURE), "utf-8"); + app = await appWith(join(dir, "records.json")); + }); + afterAll(async () => { + await app.close(); + await rm(dir, { recursive: true, force: true }); + }); + + const list = async (qs: string) => { + const res = await app.inject(`/api/people${qs}`); + expect(res.statusCode).toBe(200); + return PeopleListResponse.parse(res.json()); + }; + + it("每頁 50 人,附年份清單", async () => { + const first = await list(""); + expect(first.total).toBe(124); + expect(first.people).toHaveLength(50); + expect(first.years).toEqual([2024, 2022, 2018]); + expect(first.note).toContain("不代表對個人的評價"); + const last = await list("?page=3"); + expect(last.people).toHaveLength(24); + expect((await list("?page=9")).people).toHaveLength(0); + }); + + it("篩選:縣市、選舉種類、年份要同一次參選都符合", async () => { + expect((await list("?office=mayor")).people.map((p) => p.name)).toEqual(["跨縣市"]); + expect((await list("?county=65000&office=mayor&year=2018")).total).toBe(1); + expect((await list("?county=65000&office=councilor")).total).toBe(0); + expect((await list("?county=63000&year=2022")).total).toBe(122); + }); + + it("篩選:總統(含副總統)、立委(區域、原住民、不分區);全國性的選舉沒有縣市", async () => { + expect((await list("?office=president")).people.map((p) => p.name)).toEqual(["副手"]); + expect((await list("?office=legislator")).people.map((p) => p.name).sort()).toEqual(["副手", "名單"]); + expect((await list("?office=legislator&year=2024")).people.map((p) => p.name)).toEqual(["名單"]); + // 選了縣市:只剩那個縣市的區域立委,全國性的副總統、不分區不算 + expect((await list("?county=63000&office=legislator")).people.map((p) => p.name)).toEqual(["副手"]); + expect((await list("?county=63000&office=president")).total).toBe(0); + const [vice] = (await list(`?q=${encodeURIComponent("副手")}`)).people; + expect(vice!.latest).toBe("2024 全國 副總統"); + const [listed] = (await list(`?q=${encodeURIComponent("名單")}`)).people; + expect(listed!.latest).toBe("2024 全國 不分區立法委員"); + }); + + it("搜尋姓名:去空白、間隔號,不分大小寫", async () => { + expect((await list(`?q=${encodeURIComponent("iban nokan")}`)).people.map((p) => p.name)).toEqual(["伊凡諾幹 Iban Nokan"]); + expect((await list(`?q=${encodeURIComponent("測試人12")}`)).total).toBe(2); // 測試人12、測試人120 + expect(searchKey("柔夏.布待 Rosya")).toBe("柔夏布待rosya"); + }); + + it("列表顯示最近一次參選", async () => { + const [p] = (await list(`?q=${encodeURIComponent("跨縣市")}`)).people; + expect(p).toMatchObject({ runs: 2, latest: "2022 臺北市第3選區 直轄市議員", party: "甲黨" }); + }); + + it("不合法的查詢回 400", async () => { + for (const qs of ["?office=king", "?county=abc", "?page=0", "?year=abc"]) { + const res = await app.inject(`/api/people${qs}`); + expect(res.statusCode, qs).toBe(400); + expect(ApiError.safeParse(res.json()).success).toBe(true); + } + }); + + it("個人頁:分數附上算法與出處", async () => { + const res = await app.inject("/api/people/r-0000000001"); + expect(res.statusCode).toBe(200); + const body = PersonRecordResponse.parse(res.json()); + expect(body.person.scores[0]).toMatchObject({ key: "fame", label: "知名度", formula: "取對數", source: "中選會", value: 3.2 }); + expect(body.sources[0]!.title).toContain("中央選舉委員會"); + }); + + it("找不到的人回 404", async () => { + expect((await app.inject("/api/people/r-ffffffffff")).statusCode).toBe(404); + expect((await app.inject("/api/people/not-an-id")).statusCode).toBe(404); + }); +}); + +describe("資料庫檔案有問題時伺服器照常運作", () => { + it("檔案不在:空清單", async () => { + const app = await appWith(join(tmpdir(), "no-such-dir", "records.json")); + const res = await app.inject("/api/people"); + expect(res.statusCode).toBe(200); + expect(PeopleListResponse.parse(res.json()).total).toBe(0); + expect((await app.inject("/api/people/r-0000000001")).statusCode).toBe(404); + await app.close(); + }); + + it("格式不對:空清單", async () => { + const dir = await mkdtemp(join(tmpdir(), "people-bad-")); + await writeFile(join(dir, "a.json"), JSON.stringify({ people: [{ id: 1 }] }), "utf-8"); + await writeFile(join(dir, "b.json"), "{ 壞掉", "utf-8"); + for (const f of ["a.json", "b.json"]) { + const app = await appWith(join(dir, f)); + expect(PeopleListResponse.parse((await app.inject("/api/people")).json()).total).toBe(0); + await app.close(); + } + await rm(dir, { recursive: true, force: true }); + }); +}); + +const scenario = SCENARIOS[0]; +const built = existsSync(join(DEFAULT_PACKS_ROOT, scenario.packId, "manifest.json")) && existsSync(DEFAULT_RECORDS_FILE); + +describe.skipIf(!built)("實際的 records.json(election-data records 產生)", () => { + let app: FastifyInstance; + beforeAll(async () => { + app = await buildApp({ maxRuns: 5 }); + }); + afterAll(() => app.close()); + + it("2022 年臺北市議員候選人都查得到,個人頁有五項分數", async () => { + const res = await app.inject("/api/people?county=63000&office=councilor&year=2022"); + const body = PeopleListResponse.parse(res.json()); + expect(body.total).toBeGreaterThan(100); + expect(body.years).toContain(1994); + const detail = PersonRecordResponse.parse((await app.inject(`/api/people/${body.people[0]!.id}`)).json()); + expect(detail.person.scores.map((s) => s.key)).toEqual(["fame", "organization", "seniority", "strength", "finance"]); + expect(detail.person.scores.every((s) => s.formula.length > 0 && s.source.length > 0)).toBe(true); + }); + + it("總統副總統、立委也收:1996–2024 年每次總統選舉都有正副兩位當選", async () => { + const body = PeopleListResponse.parse((await app.inject("/api/people?office=president")).json()); + expect(body.total).toBeGreaterThan(30); + expect(body.years).toEqual(expect.arrayContaining([1995, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024])); + for (const year of [1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024]) { + const winners = PeopleListResponse.parse((await app.inject(`/api/people?office=president&year=${year}`)).json()); + const ids = winners.people.map((p) => p.id); + const runs = await Promise.all(ids.map(async (id) => PersonRecordResponse.parse((await app.inject(`/api/people/${id}`)).json()).person.runs)); + const elected = runs.flat().filter((r) => r.year === year && r.office === "president" && r.elected); + expect(elected.map((r) => r.election).sort(), String(year)).toEqual(["副總統", "總統"]); + } + }); +}); + +// 型別檢查:測試資料要符合 RecordsFile +const _typed: RecordsFile = FIXTURE as unknown as RecordsFile; +void _typed; + +describe("玩真實候選人的開局能力(依公開選舉紀錄)", () => { + const people = FIXTURE.people as unknown as Parameters[0]; + + it("只看那場選舉之前的紀錄:當選次數→組織、最高得票→媒體、從政年數→口才;財務、清廉一律 0", () => { + const veteran = person(900, { name: "老將" }, [ + run({ year: 2010, date: "2010-11-27", votes: 40_000 }), + run({ year: 2014, date: "2014-11-29", votes: 50_000 }), + run({ year: 2018, date: "2018-11-24", votes: 60_000 }), + run({ year: 2022, date: "2022-11-26", votes: 400_000 }), + ]) as unknown as (typeof people)[number]; + const r = recordAbilities([...people, veteran], "老將", "63000", "2022-11-26")!; + expect(r.abilities).toEqual({ media: 1, organization: 2, eloquence: 1, finance: 0, integrity: 0 }); + expect(r.basis).toContain("2022 年以前"); + // 第一次參選之前沒有紀錄 + expect(recordAbilities([...people, veteran], "老將", "63000", "2010-11-27")).toBeNull(); + }); + + it("同名同縣市有兩個人、或比對信心低:不給(寧可不給也不要給錯人)", () => { + const twin = person(901, { name: "測試人1" }) as unknown as (typeof people)[number]; + expect(recordAbilities([...people, twin], "測試人1", "63000", "2026-01-01")).toBeNull(); + const low = person(902, { name: "不確定", confidence: "low" }) as unknown as (typeof people)[number]; + expect(recordAbilities([low], "不確定", "63000", "2026-01-01")).toBeNull(); + // 別的縣市的同名者不算;總統選舉不限縣市 + expect(recordAbilities(people, "跨縣市", "66000", "2026-01-01")).toBeNull(); + expect(recordAbilities(people, "跨縣市", "00000", "2026-01-01")).not.toBeNull(); + }); + + it("同名的有好幾位:有這場選舉本身紀錄的那位優先(只用來認人,這一場不算進能力)", () => { + const rookie = person(910, { name: "同名" }, [run({ year: 2024, date: "2024-01-13", election: "立法委員", office: "legislator", votes: 90_000 })]); + const veteran = person(911, { name: "同名", birthYear: 1950 }, [run({ year: 2014, date: "2014-11-29" }), run({ year: 2018, date: "2018-11-24" })]); + const both = [...people, rookie, veteran] as unknown as typeof people; + // 2024 臺北市的立委選舉:是第一次參選的那位,之前沒有紀錄 → 不給 + expect(recordAbilities(both, "同名", "63000", "2024-01-13")).toBeNull(); + // 2022 臺北市議員:兩位都沒有那一天的紀錄,認不出來 → 不給 + expect(recordAbilities(both, "同名", "63000", "2022-11-26")).toBeNull(); + // 總統選舉:看那一天有總統副總統紀錄的那位 + const vice = person(912, { name: "同名" }, [ + run({ year: 2020, date: "2020-01-11", election: "立法委員", office: "legislator", votes: 80_000 }), + run({ year: 2024, date: "2024-01-13", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 5_000_000 }), + ]); + const r = recordAbilities([...both, vice] as unknown as typeof people, "同名", "00000", "2024-01-13")!; + expect(r.abilities).toEqual({ media: 1, organization: 1, eloquence: 0, finance: 0, integrity: 0 }); + }); + + it("總統、副總統的全國票數只讓媒體停在 2 級;不分區沒有個人得票,不算進媒體", () => { + const national = person(920, { name: "中央" }, [ + run({ year: 2012, date: "2012-01-14", election: "不分區立法委員", office: "legislator", county: "全國", countyCode: null, district: null, votes: null, share: null, listRank: 1 }), + run({ year: 2016, date: "2016-01-16", election: "立法委員", office: "legislator", votes: 20_000 }), + run({ year: 2020, date: "2020-01-11", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 8_000_000 }), + ]); + const all = [...people, national] as unknown as typeof people; + // 2020 年以前:不分區+區域立委,最高 20,000 票 → 媒體 0;當選 2 次 → 組織 1;2012→2016 四年 → 口才 1 + expect(recordAbilities(all, "中央", "63000", "2020-01-11")!.abilities).toEqual({ media: 0, organization: 1, eloquence: 1, finance: 0, integrity: 0 }); + // 2024 年:2020 副總統 800 萬票 → 媒體 2(上限,和大縣市長一樣) + expect(recordAbilities(all, "中央", "00000", "2024-01-13")!.abilities.media).toBe(2); + }); +}); diff --git a/backend/apps/server/test/server.test.ts b/backend/apps/server/test/server.test.ts new file mode 100644 index 0000000..c6c0ec1 --- /dev/null +++ b/backend/apps/server/test/server.test.ts @@ -0,0 +1,234 @@ +import { existsSync } from "node:fs"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SCENARIOS } from "@election2026/content"; +import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader"; +import { RogueView, ScenarioSummary } from "@election2026/protocol"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { FastifyInstance } from "fastify"; +import { buildApp } from "../src/app.ts"; + +const scenario = SCENARIOS[0]; +const built = existsSync(join(DEFAULT_PACKS_ROOT, scenario.packId, "manifest.json")); + +describe.skipIf(!built)("API", () => { + let app: FastifyInstance; + beforeAll(async () => { + app = await buildApp({ maxRuns: 5 }); + }); + afterAll(() => app.close()); + + const createRun = (body: unknown) => app.inject({ method: "POST", url: "/api/rogue/runs", payload: body as object }); + + it("列出劇本", async () => { + const res = await app.inject("/api/scenarios"); + expect(res.statusCode).toBe(200); + const list = res.json(); + expect(list.map((s: unknown) => ScenarioSummary.safeParse(s).success)).toEqual(list.map(() => true)); + }); + + it("劇本摘要附上錢的出處", async () => { + const [s] = (await app.inject("/api/scenarios")).json(); + expect(s.spendingCap).toBe(81_679_000); + expect(s.sources.length).toBeGreaterThan(0); + expect(s.candidates.every((c: { realFinance: unknown }) => c.realFinance !== null)).toBe(true); + }); + + it("地圖:資料包的拓撲", async () => { + const res = await app.inject(`/api/packs/${scenario.packId}/topology`); + expect(res.statusCode).toBe(200); + expect(res.json().type).toBe("Topology"); + expect((await app.inject("/api/packs/nope/topology")).statusCode).toBe(404); + }); + + it("經典模式的 API 已經拿掉", async () => { + expect((await app.inject({ method: "POST", url: "/api/matches", payload: {} })).statusCode).toBe(404); + }); + + it("選戰卡牌:開局、出牌、結束這週、選下一站;不合法的出牌回 400", async () => { + const even = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor-even")!; + const res = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: even.id, candidateId: even.candidates[0]!.id, seed: 5 } }); + expect(res.statusCode).toBe(201); + const { runId, view } = res.json() as { runId: string; view: unknown }; + const v = RogueView.parse(view); + expect(v.week).toBe(1); + expect(v.hand).toHaveLength(5); + expect(v.towns.length).toBeGreaterThan(10); + expect(v.towns.some((t) => t.traits.length > 0)).toBe(true); + // 相鄰的區由地圖拓撲算出:桃園區和龜山區相鄰 + expect(v.towns.find((t) => t.name === "桃園區")!.neighbors).toContain(v.towns.find((t) => t.name === "龜山區")!.code); + const card = v.hand.find((c) => c.target === "town" && !c.blocked)!; + const best = [...v.previews[card.uid]!].sort((a, b) => b.votes - a.votes)[0]!; + const played = await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/play`, payload: { uid: card.uid, target: best.target } }); + expect(played.statusCode).toBe(200); + const after = RogueView.parse(played.json()); + expect(after.hand).toHaveLength(4); + expect(after.log.reduce((a, e) => a + e.votes, 0)).toBeCloseTo(best.votes, -1); + const bad = await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/play`, payload: { uid: "nope", target: null } }); + expect(bad.statusCode).toBe(400); + const ended = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).json()); + expect(ended.phase).toBe("route"); + expect(ended.route!.length).toBe(3); + const next = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: "skip" } })).json()); + expect(next.week).toBe(2); + // 記者堵麥不擋出牌:出牌階段就有事件,結束這週前要回答 + expect(next.phase).toBe("plan"); + expect(next.scene!.kind).toBe("press"); + expect((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).statusCode).toBe(409); + expect((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: 9 } })).statusCode).toBe(409); + // 下一站:門上直接攤開的牌,選門+選牌一次完成 + const answered = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: 0 } })).json()); + expect(answered.scene).toBeNull(); + const week2 = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` })).json()); + const door = week2.route!.findIndex((r) => r.preview && (r.preview.kind === "card" || r.preview.kind === "advisor")); + expect(door).toBeGreaterThanOrEqual(0); + const week3 = RogueView.parse((await app.inject({ method: "POST", url: `/api/rogue/runs/${runId}/choose`, payload: { pick: door, option: 0 } })).json()); + expect(week3.week).toBe(3); + expect((await app.inject("/api/rogue/runs/00000000-0000-0000-0000-000000000000")).statusCode).toBe(404); + }); + + it("選戰卡牌:新手教學、圖鑑、逆風難度與勢均力敵", async () => { + const tut = await app.inject({ method: "POST", url: "/api/rogue/tutorial" }); + expect(tut.statusCode).toBe(201); + const t = RogueView.parse((tut.json() as { view: unknown }).view); + expect(t.options.tutorial).toBe(true); + expect(t.totalWeeks).toBe(3); + expect(t.towns).toHaveLength(3); + const cat = (await app.inject("/api/rogue/catalog")).json() as { cards: unknown[]; advisors: unknown[]; feats: unknown[]; ascension: string[] }; + expect(cat.cards.length).toBeGreaterThan(40); + expect(cat.advisors.length).toBeGreaterThanOrEqual(30); + expect(cat.ascension).toHaveLength(11); + const real = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor")!; + const hard = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: real.id, candidateId: real.candidates[0]!.id, seed: 1, ascension: 3, even: true } }); + expect(hard.statusCode).toBe(201); + expect(RogueView.parse((hard.json() as { view: unknown }).view).options.ascension).toBe(3); + }); + + it("選戰卡牌:帶政策島、能力、政策開局;每日一戰不帶;格式不對回 400", async () => { + const real = SCENARIOS.find((s) => s.id === "taoyuan-2022-mayor")!; + const base = { scenarioId: real.id, candidateId: real.candidates[0]!.id, seed: 7 }; + const meta = { + perks: [{ id: "vault", level: 1 }], + abilities: { eloquence: 1, organization: 0, media: 0, finance: 0, integrity: 0 }, + policies: [{ name: "長輩安心卡", target: "old", method: "subsidy", funding: "invest" }], + }; + const plain = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: base })).json().view); + const boosted = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, ...meta } })).json().view); + expect(boosted.money - plain.money).toBe(150); + expect(boosted.hand.some((c) => c.name === "長輩安心卡")).toBe(true); + const daily = RogueView.parse((await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, ...meta, daily: "2026-10-26" } })).json().view); + expect(daily.hand.some((c) => c.name === "長輩安心卡")).toBe(false); + const tooLong = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, policies: [{ ...meta.policies[0], name: "一".repeat(21) }] } }); + expect(tooLong.statusCode).toBe(400); + const badAbility = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { ...base, abilities: { ...meta.abilities, finance: 9 } } }); + expect(badAbility.statusCode).toBe(400); + const cat = (await app.inject("/api/rogue/catalog")).json() as { buildings: unknown[] }; + expect(cat.buildings).toHaveLength(12); + }); + + it("選戰卡牌:存檔之後換一台伺服器也讀得到", async () => { + const dir = await mkdtemp(join(tmpdir(), "rogue-save-")); + const first = await buildApp({ rogueSaveDir: dir }); + const { runId } = (await first.inject({ method: "POST", url: "/api/rogue/tutorial" })).json() as { runId: string }; + await first.inject({ method: "POST", url: `/api/rogue/runs/${runId}/end-week` }); + await first.close(); + // 等寫檔完成 + for (let k = 0; k < 20 && !existsSync(join(dir, `${runId}.json`)); k++) await new Promise((r) => setTimeout(r, 25)); + const second = await buildApp({ rogueSaveDir: dir }); + const res = await second.inject(`/api/rogue/runs/${runId}`); + expect(res.statusCode).toBe(200); + expect(RogueView.parse(res.json()).phase).toBe("route"); + await second.close(); + await rm(dir, { recursive: true, force: true }); + }); + + const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" }; + const custom = (over: Record = {}) => ({ + name: "林小桃", + party: null, + background: "網紅", + stats: { fame: 6, eloquence: 5, strategy: 4, wealth: 5, network: 5 }, + avatar, + replace: null, + ...over, + }); + + it("政治生涯:自創角色以新候選人加入,或取代同黨的候選人;帶過來的幕僚和牌", async () => { + const add = await createRun({ scenarioId: "local2022-10018", candidateId: "custom", custom: custom(), even: true, career: { stage: 2 } }); + expect(add.statusCode).toBe(201); + const a = RogueView.parse((add.json() as { view: unknown }).view); + expect(a.you.id).toBe("custom"); + expect(a.you.name).toBe("林小桃"); + expect(a.options.career).toEqual({ stage: 2, total: 5 }); + const rep = await createRun({ + scenarioId: scenario.id, + candidateId: "custom", + custom: custom({ party: "民主進步黨", replace: "cheng-yun-peng" }), + carry: { advisors: ["chief"], cards: [{ id: "rally", up: true }], money: 150 }, + }); + expect(rep.statusCode).toBe(201); + const r = RogueView.parse((rep.json() as { view: unknown }).view); + expect(r.rival.name).not.toBe("鄭運鵬"); + expect(r.advisors.map((x) => x.id)).toEqual(["chief"]); + expect(r.hand.some((c) => c.id === "rally" && c.up)).toBe(true); + const leg = await createRun({ scenarioId: "leg2024-63000-01-even", candidateId: "custom", custom: custom() }); + expect(leg.statusCode).toBe(201); + }); + + it("政治生涯的地方選舉:里長(真實的里、虛構的對手)、議員(那個里的議員選區,贏過最後一席就當選)", async () => { + const kao = { id: "local2022-64000", candidates: [{ id: "64000-1" }] }; + const viewOf = async (body: unknown) => { + const res = await createRun(body); + expect(res.statusCode).toBe(201); + return { ...RogueView.parse((res.json() as { view: unknown }).view), runId: (res.json() as { runId: string }).runId }; + }; + const village = await viewOf({ scenarioId: kao.id, candidateId: "custom", custom: custom(), seed: 4, career: { stage: 1 }, local: { kind: "village", village: null } }); + expect(village.office).toBe("里長"); + expect(village.towns).toHaveLength(3); + expect(village.totalWeeks).toBe(5); + expect(village.packId).toBe(""); + // 對手是遊戲自己的人物(不是真實候選人) + expect(village.rival.id).toBe("rival"); + expect(village.rival.party).toBeNull(); + const code = village.scenarioId.replace("village:", ""); + expect(code).toMatch(/^64000\d{6}$/); + const council = await viewOf({ scenarioId: kao.id, candidateId: "custom", custom: custom(), seed: 4, career: { stage: 2 }, local: { kind: "council", village: code } }); + expect(council.office).toBe("議員"); + expect(council.seats).toBeGreaterThan(1); + expect(council.threshold).toBeGreaterThan(0); + expect(council.towns.length).toBeGreaterThanOrEqual(3); + const area = (await app.inject(`/api/rogue/runs/${council.runId}/area`)).json() as { villages: string[]; groups: Record | null }; + expect(area.villages).toContain(code); + // 地方選舉一定要用自創角色 + const real = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: kao.id, candidateId: kao.candidates[0]!.id, local: { kind: "village", village: null } } }); + expect(real.statusCode).toBe(400); + const nowhere = await app.inject({ method: "POST", url: "/api/rogue/runs", payload: { scenarioId: kao.id, candidateId: "custom", custom: custom(), local: { kind: "council", village: "63000110001" } } }); + expect(nowhere.statusCode).toBe(400); + }); + + it("政治生涯:點數超過上限、用真實人物的名字、帶狀態牌都會被拒絕", async () => { + expect((await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom({ stats: { fame: 10, eloquence: 10, strategy: 10, wealth: 0, network: 0 } }) })).statusCode).toBe(400); + const res = await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom({ name: "蔣萬安" }) }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toContain("真實人物"); + expect((await createRun({ scenarioId: scenario.id, candidateId: "custom", custom: custom(), carry: { advisors: [], cards: [{ id: "favor", up: false }] } })).statusCode).toBe(400); + }); + + it("超過容量時淘汰最久沒動的一局(沒有存檔目錄時)", async () => { + const ids: string[] = []; + for (let i = 0; i < 6; i++) ids.push(((await app.inject({ method: "POST", url: "/api/rogue/tutorial" })).json() as { runId: string }).runId); + expect((await app.inject(`/api/rogue/runs/${ids[0]}`)).statusCode).toBe(404); + expect((await app.inject(`/api/rogue/runs/${ids[5]}`)).statusCode).toBe(200); + }); +}); + +describe("流量限制", () => { + it("超過每分鐘上限回 429", async () => { + const app = await buildApp({ rateLimit: 2 }); + const codes = []; + for (let i = 0; i < 3; i++) codes.push((await app.inject("/api/health")).statusCode); + expect(codes).toEqual([200, 200, 429]); + await app.close(); + }); +}); diff --git a/backend/apps/server/tsconfig.json b/backend/apps/server/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/apps/server/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/apps/server/vitest.config.ts b/backend/apps/server/vitest.config.ts new file mode 100644 index 0000000..5539adc --- /dev/null +++ b/backend/apps/server/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ test: { include: ["test/**/*.test.ts"] } }); diff --git a/backend/apps/sim/package.json b/backend/apps/sim/package.json new file mode 100644 index 0000000..4394e04 --- /dev/null +++ b/backend/apps/sim/package.json @@ -0,0 +1,22 @@ +{ + "name": "@election2026/sim", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "回測、參數校準與平衡報告(docs/13 M1)", + "scripts": { + "backtest": "node src/backtest.ts", + "typecheck": "tsc -p tsconfig.json", + "balance": "node src/balance.ts", + "calibrate-local": "node src/calibrate-local.ts", + "rogue-balance": "node src/rogue-balance.ts" + }, + "dependencies": { + "@election2026/content": "workspace:*", + "@election2026/engine": "workspace:*", + "@election2026/pack-loader": "workspace:*", + "@election2026/protocol": "workspace:*", + "@election2026/rogue": "workspace:*", + "@election2026/scenarios": "workspace:*" + } +} diff --git a/backend/apps/sim/src/backtest.ts b/backend/apps/sim/src/backtest.ts new file mode 100644 index 0000000..67b51c4 --- /dev/null +++ b/backend/apps/sim/src/backtest.ts @@ -0,0 +1,294 @@ +/** + * 歷史回測(docs/13 M1):node src/backtest.ts [--scenario taoyuan-2022-mayor] [--seeds 12] [--rounds 6] + * + * 1. 校準全國風向(mood):讓 AI 對打的全市得票率接近真實結果。 + * 2. 驗證:各區、各里的得票率和真實開票比較,並和「上一次選舉整體平移」的簡單預測法比較。 + * 風向是用全市總數校準的,所以全市數字會接近是當然的;真正的考驗是地理分布。 + */ +import { mkdir, writeFile } from "node:fs/promises"; +import { parseArgs } from "node:util"; +import { + aggregate, + autoplay, + computeVoteModel, + createMatch, + historicalShares, + type PackData, + type Scenario, + type World, +} from "@election2026/engine"; +import { loadWorld } from "./world.ts"; + +interface Shares { + county: number[]; + towns: number[][]; + villages: number[][]; +} + +const pct = (x: number, d = 1) => (x * 100).toFixed(d); +const wan = (x: number | null) => (x === null ? "—" : `${Math.round(x / 10_000).toLocaleString()} 萬`); +const mean = (xs: readonly number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const normalize = (row: readonly number[]) => { + const s = row.reduce((a, b) => a + b, 0) || 1; + return row.map((x) => x / s); +}; + +/** 真實結果:政黨票 → 候選人,依全市、區、里整理 */ +function actualShares(world: World): Shares & { valid: number[]; turnout: number } { + const { scenario, pack } = world; + const actual = scenario.actual; + if (!actual) throw new Error("這個劇本沒有真實結果可以比對"); + const ids = scenario.candidates.map((c) => c.id); + let ballots = 0; + let electors = 0; + const villageVotes = pack.villages.map((v) => { + const r = pack.history.byVillage[v.code]?.[actual.electionId]; + const row = ids.map(() => 0); + if (!r) return row; + ballots += r.ballots; + electors += r.electors; + for (const [party, n] of Object.entries(r.votes)) { + const i = ids.indexOf(actual.partyToCandidate?.[party] ?? ""); + if (i >= 0) row[i] += n; + } + return row; + }); + const sum = (rows: number[][]) => ids.map((_, c) => rows.reduce((s, r) => s + r[c], 0)); + return { + county: normalize(sum(villageVotes)), + towns: pack.towns.map((t) => normalize(sum(t.villages.map((v) => villageVotes[v])))), + villages: villageVotes.map(normalize), + valid: villageVotes.map((r) => r.reduce((a, b) => a + b, 0)), + turnout: ballots / (electors || 1), + }; +} + +/** 跑多場 AI 對打,取開票結果的平均 */ +interface MoneyStats { + raised: number; + spent: number; +} + +function simulate( + world: World, + seeds: readonly number[], +): Shares & { winners: Record; turnout: number; money: MoneyStats[] } { + const { scenario, pack } = world; + const ids = scenario.candidates.map((c) => c.id); + const county: number[][] = []; + const towns: number[][][] = []; + const villages: number[][][] = []; + const winners: Record = {}; + const turnout: number[] = []; + const money: MoneyStats[][] = []; + for (const seed of seeds) { + const end = autoplay(world, `backtest-${seed}`, seed); + const r = end.result; + if (!r) throw new Error(`第 ${seed} 場沒有開票結果`); + winners[r.winnerId] = (winners[r.winnerId] ?? 0) + 1; + turnout.push(r.ballots / r.electors); + // 募到的錢=期末現金+已花-起始資金-自掏腰包 + money.push( + scenario.candidates.map((c, i) => { + const s = end.candidates[i]; + return { raised: s.money + s.spent - c.startingMoney - (c.wealth - s.wealth), spent: s.spent }; + }), + ); + county.push(normalize(ids.map((id) => r.votes[id]))); + towns.push(pack.towns.map((t) => normalize(ids.map((id) => r.byTown[t.code][id])))); + villages.push(pack.villages.map((v) => normalize(ids.map((id) => r.byVillage[v.code][id])))); + } + const avg = (rows: number[][]) => ids.map((_, c) => mean(rows.map((r) => r[c]))); + return { + county: avg(county), + towns: pack.towns.map((_, t) => avg(towns.map((x) => x[t]))), + villages: pack.villages.map((_, v) => avg(villages.map((x) => x[v]))), + winners, + turnout: mean(turnout), + money: ids.map((_, c) => ({ raised: mean(money.map((m) => m[c].raised)), spent: mean(money.map((m) => m[c].spent)) })), + }; +} + +/** 沒有任何選戰行動時(開局狀態)的預期得票率:看選戰本身移動了多少 */ +function noCampaign(world: World): number[] { + const state = createMatch(world, "baseline", 1, world.scenario.candidates[0].id); + const model = computeVoteModel(state, world.scenario, world.pack, world.params, null); + const agg = aggregate(model, world.pack, world.scenario.candidates.length); + return normalize(agg.votes); +} + +/** + * 簡單對照組:上一次選舉的各區結果,整體平移到這次的全市得票率。 + * 上一次沒有推人的政黨(或無黨籍)各區一律用全市得票率。 + */ +function uniformSwing(pack: PackData, scenario: Scenario, prior: string, actualCounty: number[]): Shares { + const all = pack.villages.map((_, i) => i); + const countyPrior = historicalShares(pack, prior, all); + const predict = (villageIdx: number[]) => { + const local = historicalShares(pack, prior, villageIdx); + return normalize( + scenario.candidates.map((c, i) => { + const party = c.party ?? ""; + if (!(party in countyPrior)) return actualCounty[i]; + return Math.max(0.001, (local[party] ?? 0) + actualCounty[i] - countyPrior[party]); + }), + ); + }; + return { + county: predict(all), + towns: pack.towns.map((t) => predict(t.villages)), + villages: pack.villages.map((_, i) => predict([i])), + }; +} + +function mae(pred: number[][], truth: number[][], weights?: number[]): number { + let total = 0; + let w = 0; + pred.forEach((row, i) => { + const wi = weights?.[i] ?? 1; + row.forEach((p, c) => { + total += wi * Math.abs(p - truth[i][c]); + w += wi; + }); + }); + return total / (w || 1); +} + +/** 兩大候選人差距(票差率)在各里的相關係數,依有效票加權 */ +function marginCorrelation(pred: number[][], truth: number[][], a: number, b: number, weights: number[]): number { + const x = pred.map((r) => r[a] - r[b]); + const y = truth.map((r) => r[a] - r[b]); + const W = weights.reduce((s, v) => s + v, 0) || 1; + const mx = x.reduce((s, v, i) => s + v * weights[i], 0) / W; + const my = y.reduce((s, v, i) => s + v * weights[i], 0) / W; + let sxy = 0; + let sxx = 0; + let syy = 0; + x.forEach((xi, i) => { + sxy += weights[i] * (xi - mx) * (y[i] - my); + sxx += weights[i] * (xi - mx) ** 2; + syy += weights[i] * (y[i] - my) ** 2; + }); + return sxy / Math.sqrt(sxx * syy || 1); +} + +async function main(): Promise { + const { values } = parseArgs({ + options: { + scenario: { type: "string", default: "taoyuan-2022-mayor" }, + seeds: { type: "string", default: "12" }, + rounds: { type: "string", default: "6" }, + }, + }); + const started = Date.now(); + let world = await loadWorld(values.scenario); + const { scenario, pack } = world; + const ids = scenario.candidates.map((c) => c.id); + const truth = actualShares(world); + const nSeeds = Number(values.seeds); + const rounds = Number(values.rounds); + + // 1. 校準:多項 logit 下,效用加 ln(真實/模擬) 會把得票率往真實推 + // 投票率倍率同時校準:投票率影響各里的權重,所以和風向一起迭代 + let mood = { ...scenario.mood }; + let turnoutScale = scenario.turnoutScale; + const calibrationSeeds = [101, 102, 103, 104]; + const trace: { round: number; mood: typeof mood; turnoutScale: number; county: number[]; turnout: number }[] = []; + for (let round = 1; round <= rounds; round++) { + const sim = simulate(world, calibrationSeeds); + trace.push({ round, mood: { ...mood }, turnoutScale, county: sim.county, turnout: sim.turnout }); + console.log( + `校準第 ${round} 輪:${scenario.candidates.map((c, i) => `${c.name} ${pct(sim.county[i])}%`).join("、")};投票率 ${pct(sim.turnout)}%`, + ); + turnoutScale = Math.round(turnoutScale * (truth.turnout / sim.turnout) * 1000) / 1000; + const next = { ...mood }; + scenario.candidates.forEach((c, i) => { + next[c.slot] += Math.log(truth.county[i] / Math.max(sim.county[i], 1e-4)); + }); + const center = mean(Object.values(next)); + mood = Object.fromEntries(Object.entries(next).map(([k, v]) => [k, Math.round((v - center) * 1000) / 1000])) as typeof mood; + world = { ...world, scenario: { ...scenario, mood, turnoutScale } }; + } + + // 2. 驗證:用沒參與校準的種子 + const evalSeeds = Array.from({ length: nSeeds }, (_, i) => 1_000 + i); + const sim = simulate(world, evalSeeds); + const baseline = uniformSwing(pack, scenario, scenario.publicHistoryElection, truth.county); + const still = noCampaign(world); + const main2 = [...truth.county.keys()].sort((a, b) => truth.county[b] - truth.county[a]).slice(0, 2); + const metrics = (s: Shares) => ({ + countyMae: mae([s.county], [truth.county]), + townMae: mae(s.towns, truth.towns), + townMaeTop2: mae(s.towns.map((r) => main2.map((c) => r[c])), truth.towns.map((r) => main2.map((c) => r[c]))), + villageMae: mae(s.villages, truth.villages, truth.valid), + villageMarginCorr: marginCorrelation(s.villages, truth.villages, main2[0], main2[1], truth.valid), + }); + const report = { + scenario: scenario.id, + packId: pack.packId, + generatedAt: new Date().toISOString(), + seeds: evalSeeds, + calibratedMood: mood, + calibratedTurnoutScale: turnoutScale, + turnout: { actual: truth.turnout, simulated: sim.turnout }, + calibration: trace, + candidates: scenario.candidates.map((c, i) => ({ + id: c.id, + name: c.name, + actual: truth.county[i], + simulated: sim.county[i], + noCampaign: still[i], + wins: sim.winners[c.id] ?? 0, + money: { realIncome: c.realFinance?.income ?? null, realSpending: c.realFinance?.spending ?? null, ...sim.money[i] }, + })), + model: metrics(sim), + uniformSwing: metrics(baseline), + towns: pack.towns.map((t, ti) => ({ + code: t.code, + name: t.name, + actual: Object.fromEntries(ids.map((id, c) => [id, truth.towns[ti][c]])), + simulated: Object.fromEntries(ids.map((id, c) => [id, sim.towns[ti][c]])), + uniformSwing: Object.fromEntries(ids.map((id, c) => [id, baseline.towns[ti][c]])), + })), + seconds: (Date.now() - started) / 1000, + }; + + const lines = [ + `# 回測:${scenario.name}`, + "", + `資料包 ${pack.packId};校準後風向 ${JSON.stringify(mood)}、投票率倍率 ${turnoutScale};驗證 ${nSeeds} 場 AI 對打。`, + "", + `投票率:真實 ${pct(truth.turnout)}%、模擬 ${pct(sim.turnout)}%。`, + "", + "| 候選人 | 真實 | 模擬 | 沒有選戰時 | 勝場 |", + "|---|---:|---:|---:|---:|", + ...report.candidates.map((c) => `| ${c.name} | ${pct(c.actual, 2)}% | ${pct(c.simulated, 2)}% | ${pct(c.noCampaign, 2)}% | ${c.wins}/${nSeeds} |`), + "", + "| 候選人 | 真實收入 | 模擬總收入(起始+募款) | 真實支出 | 模擬支出 |", + "|---|---:|---:|---:|---:|", + ...report.candidates.map( + (c, i) => + `| ${c.name} | ${wan(c.money.realIncome)} | ${wan(scenario.candidates[i].startingMoney + c.money.raised)} | ${wan(c.money.realSpending)} | ${wan(c.money.spent)} |`, + ), + "", + "| 指標 | 模型 | 整體平移對照組 |", + "|---|---:|---:|", + `| 各區平均誤差(四人) | ${pct(report.model.townMae, 2)} pp | ${pct(report.uniformSwing.townMae, 2)} pp |`, + `| 各區平均誤差(前兩名) | ${pct(report.model.townMaeTop2, 2)} pp | ${pct(report.uniformSwing.townMaeTop2, 2)} pp |`, + `| 各里平均誤差(依票數加權) | ${pct(report.model.villageMae, 2)} pp | ${pct(report.uniformSwing.villageMae, 2)} pp |`, + `| 各里前兩名票差相關係數 | ${report.model.villageMarginCorr.toFixed(3)} | ${report.uniformSwing.villageMarginCorr.toFixed(3)} |`, + "", + `| 區 | ${scenario.candidates.map((c) => `${c.name} 真實/模擬`).join(" | ")} |`, + `|---|${scenario.candidates.map(() => "---:").join("|")}|`, + ...report.towns.map((t) => `| ${t.name} | ${ids.map((id) => `${pct(t.actual[id])}/${pct(t.simulated[id])}`).join(" | ")} |`), + "", + `耗時 ${report.seconds.toFixed(1)} 秒。`, + ]; + const outDir = new URL("../out/", import.meta.url); + await mkdir(outDir, { recursive: true }); + await writeFile(new URL(`backtest-${scenario.id}.json`, outDir), JSON.stringify(report, null, 2)); + await writeFile(new URL(`backtest-${scenario.id}.md`, outDir), lines.join("\n") + "\n"); + console.log(lines.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/balance.ts b/backend/apps/sim/src/balance.ts new file mode 100644 index 0000000..0fba0f0 --- /dev/null +++ b/backend/apps/sim/src/balance.ts @@ -0,0 +1,107 @@ +/** + * 平衡報告(docs/13 M1):node src/balance.ts [--scenario taoyuan-2022-mayor] [--seeds 30] + * + * 每位候選人輪流當「玩家」,分別用不同打法打完整場,其他陣營都是一般 AI。 + * 看策略能移動多少得票率、勝率多少,用來決定劇本難度與行動效果是否夠有感。 + */ +import { mkdir, writeFile } from "node:fs/promises"; +import { parseArgs } from "node:util"; +import { aiOrders, createMatch, makeRng, planOrders, playWeek, viewFor, type ScenarioCandidate, type World } from "@election2026/engine"; +import type { Order } from "@election2026/protocol"; +import { loadWorld } from "./world.ts"; + +type Strategy = "idle" | "smart" | ScenarioCandidate["aiStyle"]; + +const STRATEGIES: { id: Strategy; label: string }[] = [ + { id: "idle", label: "什麼都不做" }, + { id: "balanced", label: "均衡" }, + { id: "ground", label: "地面戰" }, + { id: "air", label: "空戰" }, + { id: "dirty", label: "奧步(買票、網軍)" }, + { id: "smart", label: "懂戰術(組合拳+打對台)" }, +]; + +interface Outcome { + share: number; + won: boolean; + scandal: boolean; +} + +function play(world: World, playerId: string, strategy: Strategy, seed: number): Outcome { + let state = createMatch(world, `balance-${seed}`, seed, playerId); + while (state.phase !== "finished") { + let orders: Order[]; + if (strategy === "idle") orders = []; + else if (strategy === "smart") orders = planOrders(viewFor(state, world, playerId), "balanced", makeRng(seed, "player", state.week), { tactics: true }); + else orders = planOrders(viewFor(state, world, playerId), strategy, makeRng(seed, "player", state.week)); + state = playWeek(state, world, { [playerId]: orders }).state; + } + const r = state.result!; + const total = Object.values(r.votes).reduce((a, b) => a + b, 0) || 1; + const ci = world.scenario.candidates.findIndex((c) => c.id === playerId); + return { + share: r.votes[playerId] / total, + won: r.winnerId === playerId && !r.voided, + scandal: state.candidates[ci].tags.includes("檢調約談") || state.candidates[ci].tags.includes("奧步"), + }; +} + +const pct = (x: number, d = 1) => `${(x * 100).toFixed(d)}%`; +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); + +async function main(): Promise { + const { values } = parseArgs({ + options: { scenario: { type: "string", default: "taoyuan-2022-mayor" }, seeds: { type: "string", default: "30" } }, + }); + const started = Date.now(); + const world = await loadWorld(values.scenario); + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 5_000 + i); + const rows: { candidate: string; strategy: string; share: number; delta: number; winRate: number; scandalRate: number }[] = []; + + for (const cand of world.scenario.candidates) { + // 對照組:玩家也交給劇本設定的 AI 性格 + const baseline = mean( + seeds.map((seed) => { + let state = createMatch(world, `balance-${seed}`, seed, cand.id); + while (state.phase !== "finished") state = playWeek(state, world, { [cand.id]: aiOrders(state, world, cand.id) }).state; + const r = state.result!; + return r.votes[cand.id] / (Object.values(r.votes).reduce((a, b) => a + b, 0) || 1); + }), + ); + for (const s of STRATEGIES) { + const outcomes = seeds.map((seed) => play(world, cand.id, s.id, seed)); + const share = mean(outcomes.map((o) => o.share)); + rows.push({ + candidate: cand.name, + strategy: s.label, + share, + delta: share - baseline, + winRate: mean(outcomes.map((o) => (o.won ? 1 : 0))), + scandalRate: mean(outcomes.map((o) => (o.scandal ? 1 : 0))), + }); + } + console.log(`${cand.name} 完成`); + } + + const lines = [ + `# 平衡報告:${world.scenario.name}`, + "", + `每種打法 ${seeds.length} 場,共 ${seeds.length * STRATEGIES.length * world.scenario.candidates.length} 場;其他陣營都是一般 AI。「比照 AI」是和玩家交給劇本預設 AI 時相比。`, + "", + "| 候選人 | 打法 | 平均得票率 | 比照 AI | 勝率 | 出包率 |", + "|---|---|---:|---:|---:|---:|", + ...rows.map( + (r) => + `| ${r.candidate} | ${r.strategy} | ${pct(r.share, 2)} | ${r.delta >= 0 ? "+" : ""}${(r.delta * 100).toFixed(2)} | ${pct(r.winRate, 0)} | ${pct(r.scandalRate, 0)} |`, + ), + "", + `耗時 ${((Date.now() - started) / 1000).toFixed(1)} 秒。`, + ]; + const outDir = new URL("../out/", import.meta.url); + await mkdir(outDir, { recursive: true }); + await writeFile(new URL(`balance-${world.scenario.id}.md`, outDir), lines.join("\n") + "\n"); + await writeFile(new URL(`balance-${world.scenario.id}.json`, outDir), JSON.stringify(rows, null, 2)); + console.log(lines.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/calibrate-local.ts b/backend/apps/sim/src/calibrate-local.ts new file mode 100644 index 0000000..cb7e547 --- /dev/null +++ b/backend/apps/sim/src/calibrate-local.ts @@ -0,0 +1,169 @@ +/** + * 管線劇本的校準(2022 縣市長、2024 區域立委、2024 總統): + * node src/calibrate-local.ts [--set 2024-legislator] [--only 63000-01,10018] [--rounds 7] [--seeds 3] + * + * 每場選舉: + * 1. 歷史重演:調整每位候選人的個人魅力與投票率倍率,讓 AI 對打的全市得票率接近 2022 年真實結果。 + * 2. 勢均力敵:從歷史重演的值出發,讓前兩名平分兩人的總得票率,其他人維持真實得票率。 + * 只用全市總數校準;各區、各里的誤差是驗證,寫進 calibration.json 與報告。 + */ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { parseArgs } from "node:util"; +import { scenariosFromSpec, CONTENT } from "@election2026/content"; +import { DEFAULT_PARAMS, autoplay, regionCodeOf, type PackData, type Scenario, type World } from "@election2026/engine"; +import { DEFAULT_SCENARIOS_ROOT, loadAllSpecs, loadCalibration, loadPack } from "@election2026/pack-loader"; +import type { LocalCalibration, LocalElectionSpec } from "@election2026/protocol"; + +type Entry = LocalCalibration["counties"][string]; + +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const normalize = (row: number[]) => { + const s = row.reduce((a, b) => a + b, 0) || 1; + return row.map((x) => x / s); +}; + +interface Sim { + county: number[]; + turnout: number; + towns: Map; + villages: Map; +} + +function simulate(world: World, seeds: number[]): Sim { + const ids = world.scenario.candidates.map((c) => c.id); + const county: number[][] = []; + const turnout: number[] = []; + const towns = new Map(); + const villages = new Map(); + for (const seed of seeds) { + const r = autoplay(world, `cal-${seed}`, seed).result!; + county.push(normalize(ids.map((id) => r.votes[id] ?? 0))); + turnout.push(r.ballots / r.electors); + for (const [code, row] of Object.entries(r.byTown)) towns.set(code, [...(towns.get(code) ?? []), normalize(ids.map((id) => row[id] ?? 0))]); + for (const [code, row] of Object.entries(r.byVillage)) villages.set(code, [...(villages.get(code) ?? []), normalize(ids.map((id) => row[id] ?? 0))]); + } + const avg = (rows: number[][]) => ids.map((_, c) => mean(rows.map((r) => r[c]!))); + return { + county: avg(county), + turnout: mean(turnout), + towns: new Map([...towns].map(([k, v]) => [k, avg(v)])), + villages: new Map([...villages].map(([k, v]) => [k, avg(v)])), + }; +} + +function truthOf(spec: LocalElectionSpec) { + const numbers = spec.candidates.map((c) => `#${c.number}`); + let electors = 0; + let ballots = 0; + const towns = new Map(); + const villages = new Map(); + for (const [code, v] of Object.entries(spec.byVillage)) { + electors += v.electors; + ballots += v.ballots; + const row = numbers.map((n) => v.votes[n] ?? 0); + const town = regionCodeOf(code, spec.regionLevel); + const prev = towns.get(town) ?? numbers.map(() => 0); + towns.set(town, prev.map((x, i) => x + row[i]!)); + villages.set(code, { shares: normalize(row), valid: v.valid }); + } + const total = numbers.map(() => 0); + for (const row of towns.values()) row.forEach((x, i) => (total[i]! += x)); + return { + county: normalize(total), + turnout: ballots / (electors || 1), + towns: new Map([...towns].map(([k, v]) => [k, normalize(v)])), + villages, + }; +} + +function scenarioWith(spec: LocalElectionSpec, entry: Entry, even: boolean): Scenario { + const list = scenariosFromSpec(spec, entry); + return list.find((s) => (s.hypothetical ?? false) === even) ?? list[0]!; +} + +function fit(world: World, spec: LocalElectionSpec, target: number[], start: Entry, rounds: number, seeds: number[], useEven: boolean, turnoutTarget: number | null): Entry { + let entry = { ...start }; + const key = useEven ? "evenAppeal" : "appeal"; + for (let round = 0; round < rounds; round++) { + const scenario = scenarioWith(spec, entry, useEven); + const sim = simulate({ ...world, scenario }, seeds); + const appeal = { ...(entry[key] ?? {}) }; + spec.candidates.forEach((c, i) => { + const next = (appeal[String(c.number)] ?? 0) + Math.log(Math.max(target[i]!, 1e-4) / Math.max(sim.county[i]!, 1e-4)); + appeal[String(c.number)] = Math.max(-8, Math.min(6, next)); + }); + const center = mean(Object.values(appeal)); + for (const k of Object.keys(appeal)) appeal[k] = Math.round((appeal[k]! - center) * 1000) / 1000; + entry = { ...entry, [key]: appeal }; + if (turnoutTarget !== null) entry.turnoutScale = Math.round(entry.turnoutScale * (turnoutTarget / sim.turnout) * 1000) / 1000; + } + return entry; +} + +function errors(sim: Sim, truth: ReturnType): Entry["error"] { + const mae = (a: number[], b: number[]) => mean(a.map((x, i) => Math.abs(x - b[i]!))); + const county = mae(sim.county, truth.county); + const town = mean([...truth.towns].filter(([k]) => sim.towns.has(k)).map(([k, v]) => mae(sim.towns.get(k)!, v))); + let vSum = 0; + let vWeight = 0; + for (const [code, t] of truth.villages) { + const s = sim.villages.get(code); + if (!s) continue; + vSum += mae(s, t.shares) * t.valid; + vWeight += t.valid; + } + const r = (x: number) => Math.round(x * 10_000) / 100; + return { county: r(county), town: r(town), village: r(vSum / (vWeight || 1)) }; +} + +async function main(): Promise { + const { values } = parseArgs({ + options: { only: { type: "string" }, set: { type: "string" }, rounds: { type: "string", default: "7" }, seeds: { type: "string", default: "3" } }, + }); + const only = values.only ? new Set(values.only.split(",")) : null; + const rounds = Number(values.rounds); + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 301 + i); + const evalSeeds = [901, 902, 903]; + const specs = (await loadAllSpecs()).filter(({ key, set }) => (!only || only.has(key)) && (!values.set || values.set === set)); + const results = new Map(); + const lines = ["# 管線劇本校準", "", "| 選舉 | 候選人 | 全區誤差 | 各區誤差 | 各里誤差 | 投票率倍率 | 秒 |", "|---|---:|---:|---:|---:|---:|---:|"]; + + for (const { key, set, spec } of specs) { + if (!results.has(set)) results.set(set, { ...((await loadCalibration(set))?.counties ?? {}) }); + const counties = results.get(set)!; + const started = Date.now(); + const pack: PackData = await loadPack(spec.packId, undefined, { + regionLevel: spec.regionLevel, + villages: spec.kind === "legislator" ? new Set(Object.keys(spec.byVillage)) : undefined, + }); + const truth = truthOf(spec); + const world: World = { scenario: scenarioWith(spec, { turnoutScale: 0.78, appeal: {}, evenAppeal: null, error: { county: 0, town: 0, village: 0 } }, false), pack, content: CONTENT, params: DEFAULT_PARAMS }; + const start: Entry = counties[key] ?? { turnoutScale: 0.78, appeal: {}, evenAppeal: null, error: { county: 0, town: 0, village: 0 } }; + let entry = fit(world, spec, truth.county, { ...start, evenAppeal: null }, rounds, seeds, false, truth.turnout); + const check = simulate({ ...world, scenario: scenarioWith(spec, entry, false) }, evalSeeds); + entry = { ...entry, error: errors(check, truth) }; + // 勢均力敵:前兩名平分兩人的總得票率 + const order = [...truth.county.keys()].sort((a, b) => truth.county[b]! - truth.county[a]!); + if (spec.candidates.length >= 2) { + const even = [...truth.county]; + const top = (even[order[0]!]! + even[order[1]!]!) / 2; + even[order[0]!] = top; + even[order[1]!] = top; + entry = fit(world, spec, even, { ...entry, evenAppeal: { ...entry.appeal } }, Math.max(4, rounds - 2), seeds, true, null); + } + counties[key] = entry; + const secs = (Date.now() - started) / 1000; + const line = `| ${spec.areaName}${spec.kind === "mayor" ? spec.office : spec.kind === "president" ? "總統" : "立委"} | ${spec.candidates.length} | ${entry.error.county} | ${entry.error.town} | ${entry.error.village} | ${entry.turnoutScale} | ${secs.toFixed(0)} |`; + lines.push(line); + console.log(line); + // 每個縣市做完就存,中斷也不會白做 + await writeFile(join(DEFAULT_SCENARIOS_ROOT, set, "calibration.json"), JSON.stringify({ generatedAt: new Date().toISOString(), counties } satisfies LocalCalibration, null, 1)); + } + lines.push("", "誤差單位是百分點(各候選人得票率與真實結果的平均絕對誤差)。只用全市總數校準,各區、各里是驗證。"); + const outDir = new URL("../out/", import.meta.url); + await mkdir(outDir, { recursive: true }); + await writeFile(new URL("calibrate-local.md", outDir), lines.join("\n") + "\n"); +} + +await main(); diff --git a/backend/apps/sim/src/career-balance.ts b/backend/apps/sim/src/career-balance.ts new file mode 100644 index 0000000..8265f91 --- /dev/null +++ b/backend/apps/sim/src/career-balance.ts @@ -0,0 +1,60 @@ +/** + * 政治生涯地方選舉(里長、議員)平衡報告:node src/career-balance.ts [--seeds 120] + * + * 幾個縣市各挑幾個里,用自創角色(民進黨、國民黨、無黨籍)跑里長、議員兩關, + * 看打得好的玩家(greedy)和隨手玩(casual)的勝率。逆風照政治生涯:里長 0 級、議員 1 級。 + */ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { parseArgs } from "node:util"; +import { CUSTOM_ID, withCustomCandidate } from "@election2026/content"; +import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader"; +import { runBot, type BotName } from "@election2026/rogue"; +import { COUNCIL_WEEKS, VILLAGE_WEEKS, councilSetup, districtOfVillage, villageSetup, type CouncilDistrict } from "@election2026/rogue/local"; +import type { TopologyLike } from "@election2026/rogue/setup"; +import { loadWorld } from "./world.ts"; + +const COUNTIES = ["local2022-63000", "local2022-64000", "local2022-10007", "local2022-10015"]; +const PARTIES = ["民主進步黨", "中國國民黨", null] as const; +const BOTS: BotName[] = ["casual", "greedy"]; +const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" } as const; + +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const pct = (x: number) => `${(x * 100).toFixed(0)}%`; + +async function main(): Promise { + const { values } = parseArgs({ options: { seeds: { type: "string", default: "120" } } }); + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 7_000 + i); + const council = (JSON.parse(await readFile(new URL("../../../data/build/council/2022.json", import.meta.url), "utf-8")) as { districts: CouncilDistrict[] }).districts; + const rows: string[] = ["| 縣市 | 政黨 | 關卡 | 隨手玩 | 打得好 |", "|---|---|---|---:|---:|"]; + for (const id of COUNTIES) { + const base = await loadWorld(id); + const topology = JSON.parse(await readFile(join(DEFAULT_PACKS_ROOT, base.scenario.packId, "topology.json"), "utf-8")) as TopologyLike; + for (const party of PARTIES) { + const scenario = withCustomCandidate(base.scenario, { name: "測試人", party, background: "基層里長", stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: { ...avatar }, replace: null }, new Set()); + const world = { ...base, scenario }; + const empty = (): Partial> => Object.fromEntries(BOTS.map((b) => [b, []])); + const results: Record>> = { 里長: empty(), 議員: empty() }; + for (const seed of seeds.slice(0, Math.ceil(seeds.length / 4))) { + // 每個種子挑一個里:里長、議員各跑幾局 + const village = villageSetup(world, CUSTOM_ID, null, seed); + const code = village.scenarioId.slice("village:".length); + const district = districtOfVillage(council, code); + for (let k = 0; k < 4; k++) { + for (const bot of BOTS) { + results.里長![bot]!.push(runBot(village, seed * 10 + k, bot, { ascension: 0, weeks: VILLAGE_WEEKS }).result!.won ? 1 : 0); + if (district) { + const c = councilSetup(world, CUSTOM_ID, district, seed, topology).setup; + results.議員![bot]!.push(runBot(c, seed * 10 + k, bot, { ascension: 1, weeks: COUNCIL_WEEKS }).result!.won ? 1 : 0); + } + } + } + } + for (const stage of ["里長", "議員"]) rows.push(`| ${base.scenario.region.countyName} | ${party ?? "無黨籍"} | ${stage} | ${pct(mean(results[stage]!.casual!))} | ${pct(mean(results[stage]!.greedy!))} |`); + console.log(`${base.scenario.region.countyName} ${party ?? "無黨籍"} 完成`); + } + } + console.log(rows.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/even.ts b/backend/apps/sim/src/even.ts new file mode 100644 index 0000000..022fe00 --- /dev/null +++ b/backend/apps/sim/src/even.ts @@ -0,0 +1,50 @@ +/** + * 「勢均力敵」假設劇本的風向校準:node src/even.ts [--scenario taoyuan-2022-mayor] [--rounds 10] + * + * 其他設定都和歷史劇本相同,只調全國風向,讓前兩名在 AI 對打下平均打平; + * 第三名以後的得票率維持真實結果。輸出的風向值寫進 content 的假設劇本。 + */ +import { parseArgs } from "node:util"; +import { autoplay, type World } from "@election2026/engine"; +import { loadWorld } from "./world.ts"; + +function countyShares(world: World, seeds: readonly number[]): number[] { + const ids = world.scenario.candidates.map((c) => c.id); + const rows = seeds.map((seed) => { + const r = autoplay(world, `even-${seed}`, seed).result!; + const total = ids.reduce((s, id) => s + r.votes[id], 0) || 1; + return ids.map((id) => r.votes[id] / total); + }); + return ids.map((_, c) => rows.reduce((s, r) => s + r[c], 0) / rows.length); +} + +async function main(): Promise { + const { values } = parseArgs({ + options: { scenario: { type: "string", default: "taoyuan-2022-mayor" }, rounds: { type: "string", default: "10" } }, + }); + let world = await loadWorld(values.scenario); + const { scenario } = world; + // 目標:真實結果的前兩名平分兩人的總得票率,其他人維持真實得票率 + const base = countyShares(world, [101, 102, 103, 104]); + const order = [...base.keys()].sort((a, b) => base[b] - base[a]); + const target = [...base]; + const top = (base[order[0]] + base[order[1]]) / 2; + target[order[0]] = top; + target[order[1]] = top; + + let mood = { ...scenario.mood }; + for (let round = 1; round <= Number(values.rounds); round++) { + const sim = countyShares(world, [201, 202, 203, 204]); + console.log(`第 ${round} 輪:${scenario.candidates.map((c, i) => `${c.name} ${(sim[i] * 100).toFixed(1)}%`).join("、")}`); + const next = { ...mood }; + scenario.candidates.forEach((c, i) => { + next[c.slot] += Math.log(target[i] / Math.max(sim[i], 1e-4)); + }); + const center = Object.values(next).reduce((a, b) => a + b, 0) / Object.keys(next).length; + mood = Object.fromEntries(Object.entries(next).map(([k, v]) => [k, Math.round((v - center) * 1000) / 1000])) as typeof mood; + world = { ...world, scenario: { ...scenario, mood } }; + } + console.log(`風向:${JSON.stringify(mood)}`); +} + +await main(); diff --git a/backend/apps/sim/src/party-balance.ts b/backend/apps/sim/src/party-balance.ts new file mode 100644 index 0000000..ebbfafc --- /dev/null +++ b/backend/apps/sim/src/party-balance.ts @@ -0,0 +1,68 @@ +/** + * 出身與黨的資源平衡報告(18 第 53 項):node src/party-balance.ts [--seeds 40] + * + * 政治生涯的條件(勢均力敵開局、自創角色、能力照捏人物點數+出身+黨的資源), + * 同一個角色分別掛大黨、民眾黨、小黨跑立委、縣市長兩種關卡,看打得好(greedy)和隨手玩(casual)的勝率。 + * 目標:打得好的玩家,各黨勝率差在 10 個百分點以內(小黨另外多拿經驗)。 + */ +import { parseArgs } from "node:util"; +import { CUSTOM_ID, withCustomCandidate } from "@election2026/content"; +import { originAbilities, partyKind, type Background } from "@election2026/protocol"; +import { runBot, type BotName } from "@election2026/rogue"; +import { buildSetup } from "@election2026/rogue/setup"; +import { loadWorld } from "./world.ts"; + +const SCENARIOS = ["leg2024-68000-01", "leg2024-64000-04", "local2022-66000", "local2022-10007"]; +const PARTIES = ["民主進步黨", "台灣民眾黨", "時代力量", null] as const; +const BACKGROUNDS: Background[] = ["律師", "基層里長", "網紅"]; +const BOTS: BotName[] = ["casual", "greedy"]; +const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" } as const; +const stats = { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }; + +/** 政治生涯升級拿到的技能點(POINTS=4 約等於立委關的 Lv 5):輪流加在口才、組織、媒體 */ +function withPoints(a: ReturnType, n: number): ReturnType { + const out = { ...a }; + const order = ["eloquence", "organization", "media"] as const; + for (let k = 0; k < n; k++) out[order[k % 3]!] = Math.min(5, out[order[k % 3]!] + 1); + return out; +} + +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const pct = (x: number) => `${(x * 100).toFixed(0)}%`; + +async function main(): Promise { + const { values } = parseArgs({ options: { seeds: { type: "string", default: "40" } } }); + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 9_000 + i); + const totals: Record>> = {}; + const rows: string[] = ["| 劇本 | 政黨 | 隨手玩 | 打得好 |", "|---|---|---:|---:|"]; + for (const id of SCENARIOS) { + const base = await loadWorld(id); + for (const party of PARTIES) { + const same = party ? base.scenario.candidates.find((c) => c.party === party) : undefined; + const won: Partial> = { casual: [], greedy: [] } as Partial>; + for (const background of BACKGROUNDS) { + const custom = { name: "測試人", party, background, stats, avatar: { ...avatar }, replace: same?.id ?? null }; + const world = { ...base, scenario: withCustomCandidate(base.scenario, custom, new Set()) }; + // REAL=1:政治生涯的條件(照真實底盤、最多落後 15 點,有大絕招) + const setup = buildSetup(world, CUSTOM_ID, process.env.REAL ? { even: false, maxGap: Number(process.env.GAP ?? 0.15) } : { even: true }); + const origin = { background, party, kind: partyKind(party) }; + for (const seed of seeds) { + for (const bot of BOTS) { + const s = runBot(setup, seed, bot, process.env.BASELINE ? { ascension: 2, even: true } : { ascension: 2, even: !process.env.REAL, abilities: withPoints(originAbilities(custom), Number(process.env.POINTS ?? 0)), origin }); + won[bot]!.push(s.result!.won ? 1 : 0); + } + } + } + const key = partyKind(party) === "major" ? "大黨" : partyKind(party) === "tpp" ? "民眾黨" : party ? "小黨" : "無黨籍"; + totals[key] ??= { casual: [], greedy: [] } as Partial>; + for (const bot of BOTS) totals[key]![bot]!.push(...won[bot]!); + rows.push(`| ${base.scenario.name.replace(/:.*$/, "")} | ${party ?? "無黨籍"} | ${pct(mean(won.casual!))} | ${pct(mean(won.greedy!))} |`); + console.log(`${id} ${party ?? "無黨籍"} 完成`); + } + } + rows.push("", "| 合計 | 隨手玩 | 打得好 |", "|---|---:|---:|"); + for (const [k, v] of Object.entries(totals)) rows.push(`| ${k} | ${pct(mean(v.casual!))} | ${pct(mean(v.greedy!))} |`); + console.log(rows.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/rogue-balance.ts b/backend/apps/sim/src/rogue-balance.ts new file mode 100644 index 0000000..3a33f6c --- /dev/null +++ b/backend/apps/sim/src/rogue-balance.ts @@ -0,0 +1,70 @@ +/** + * 選戰卡牌(新玩法)平衡報告:node src/rogue-balance.ts [--scenario taoyuan-2022-mayor-even] [--seeds 200] + * + * 每位主要候選人各讓幾種模擬玩家打很多局: + * - 打得好(greedy)要比亂打(random)、不理對手(naive)多拿好幾個百分點 → 技術有差 + * - 只拿某一派牌的玩家(地面、空戰、攻擊)勝率不能差太多 → 沒有一招通吃 + */ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { parseArgs } from "node:util"; +import { TRAIT_LABELS, runBot, type BotName } from "@election2026/rogue"; +import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader"; +import { buildSetup, type TopologyLike } from "@election2026/rogue/setup"; +import { loadWorld } from "./world.ts"; + +const BOTS: { id: BotName; label: string }[] = [ + { id: "idle", label: "什麼都不做" }, + { id: "random", label: "亂出牌" }, + { id: "naive", label: "都打在人最多的區、不理對手" }, + { id: "casual", label: "隨手玩:照順序出、打在推薦第一名" }, + { id: "greedy", label: "看預估數字挑最划算的(打得好)" }, + { id: "ground", label: "打得好+只拿地面牌" }, + { id: "air", label: "打得好+只拿空戰牌" }, + { id: "attack", label: "打得好+只拿攻防牌" }, +]; + +const pct = (x: number, d = 1) => `${(x * 100).toFixed(d)}%`; +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); + +async function main(): Promise { + const { values } = parseArgs({ + options: { scenario: { type: "string", default: "taoyuan-2022-mayor-even" }, seeds: { type: "string", default: "200" }, ascension: { type: "string", default: "0" }, even: { type: "boolean", default: false }, bots: { type: "string" } }, + }); + const ascension = Number(values.ascension); + const started = Date.now(); + const world = await loadWorld(values.scenario); + const topology = JSON.parse(await readFile(join(DEFAULT_PACKS_ROOT, world.scenario.packId, "topology.json"), "utf-8")) as TopologyLike; + const bots = values.bots ? BOTS.filter((b) => values.bots!.split(",").includes(b.id)) : BOTS; + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 9_000 + i); + const majors = world.scenario.candidates.filter((c) => c.slot === "a" || c.slot === "b"); + const lines = [`# 選戰卡牌平衡報告:${world.scenario.name}${ascension ? `(逆風 ${ascension} 級)` : ""}`, "", `每種玩家 ${seeds.length} 局。得票率是你在全部投票裡的比例;差距是你減對手。`, ""]; + const json: unknown[] = []; + + for (const cand of majors) { + const setup = buildSetup(world, cand.id, { topology, even: values.even }); + const voters = setup.towns.reduce((a, t) => a + t.voters, 0); + lines.push(`## 玩 ${setup.you.name}(對手 ${setup.rival.name})`, ""); + lines.push(`預計投票 ${Math.round(voters).toLocaleString()} 人;各區特色:${setup.towns.map((t) => `${t.name}${t.traits.length ? `(${t.traits.map((x) => TRAIT_LABELS[x]).join("、")})` : ""}`).join("、")}`, ""); + lines.push("| 玩家 | 平均得票率 | 平均差距 | 勝率 |", "|---|---:|---:|---:|"); + for (const bot of bots) { + const runs = seeds.map((seed) => runBot(setup, seed, bot.id, { ascension }).result!); + const share = mean(runs.map((r) => r.youShare)); + const margin = mean(runs.map((r) => r.youShare - r.rivalShare)); + const win = mean(runs.map((r) => (r.won ? 1 : 0))); + lines.push(`| ${bot.label} | ${pct(share, 2)} | ${margin >= 0 ? "+" : ""}${(margin * 100).toFixed(2)} | ${pct(win, 0)} |`); + json.push({ candidate: cand.name, bot: bot.id, ascension, share, margin, win }); + } + lines.push(""); + console.log(`${cand.name} 完成`); + } + lines.push(`耗時 ${((Date.now() - started) / 1000).toFixed(1)} 秒。`); + const outDir = new URL("../out/", import.meta.url); + await mkdir(outDir, { recursive: true }); + const name = `rogue-balance-${world.scenario.id}${ascension ? `-a${ascension}` : ""}`; + await writeFile(new URL(`${name}.md`, outDir), lines.join("\n") + "\n"); + await writeFile(new URL(`${name}.json`, outDir), JSON.stringify(json, null, 2)); + console.log(lines.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/ultimate-balance.ts b/backend/apps/sim/src/ultimate-balance.ts new file mode 100644 index 0000000..48aef8f --- /dev/null +++ b/backend/apps/sim/src/ultimate-balance.ts @@ -0,0 +1,65 @@ +/** + * 大絕招平衡報告(18 第 57 項):node src/ultimate-balance.ts [--seeds 24] + * + * 用政治生涯的條件(自創角色、能力照出身與黨的資源),把開局差距硬調成落後 0、5、10、15 個百分點, + * 比較有沒有大絕招時,打得好(greedy,小遊戲 75–95 分)和隨手玩(casual,40–70 分)的勝率。 + * 目標:落後 10 點時,打得好的人約一半能翻盤、隨手玩約一成五;沒落後時大絕招幾乎不影響。 + */ +import { parseArgs } from "node:util"; +import { CUSTOM_ID, withCustomCandidate } from "@election2026/content"; +import { originAbilities, partyKind } from "@election2026/protocol"; +import { runBot, type BotName, type RogueSetup } from "@election2026/rogue"; +import { buildSetup } from "@election2026/rogue/setup"; +import { loadWorld } from "./world.ts"; + +const SCENARIOS = ["leg2024-68000-01", "leg2024-64000-04", "local2022-66000", "local2022-10007"]; +const GAPS = [0, 5, 10, 15]; +const BOTS: BotName[] = ["casual", "greedy"]; +const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" } as const; + +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const pct = (x: number) => `${(x * 100).toFixed(0)}%`; + +/** 每一區你少 gap/2、對手多 gap/2(已表態的比例) */ +function withGap(setup: RogueSetup, gap: number): RogueSetup { + const d = gap / 200; + return { + ...setup, + towns: setup.towns.map((t) => { + const you = Math.max(0.02, t.lean.you - d); + const rival = t.lean.rival + (t.lean.you - you); + return { ...t, lean: { you, rival, others: t.lean.others } }; + }), + }; +} + +async function main(): Promise { + const { values } = parseArgs({ options: { seeds: { type: "string", default: "24" } } }); + const seeds = Array.from({ length: Number(values.seeds) }, (_, i) => 11_000 + i); + const rows = ["| 開局落後 | 沒有大絕招・隨手玩 | 沒有大絕招・打得好 | 有大絕招・隨手玩 | 有大絕招・打得好 |", "|---:|---:|---:|---:|---:|"]; + const worlds = await Promise.all(SCENARIOS.map((id) => loadWorld(id))); + for (const gap of GAPS) { + const won: Record = {}; + for (const base of worlds) { + const party = "民主進步黨"; + const same = base.scenario.candidates.find((c) => c.party === party); + const custom = { name: "測試人", party, background: "律師" as const, stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: { ...avatar }, replace: same?.id ?? null }; + const world = { ...base, scenario: withCustomCandidate(base.scenario, custom, new Set()) }; + const setup = withGap(buildSetup(world, CUSTOM_ID, { even: true }), gap); + const origin = { background: custom.background, party, kind: partyKind(party) }; + for (const seed of seeds) { + for (const bot of BOTS) { + for (const ult of [false, true]) { + const s = runBot(setup, seed, bot, { ascension: 2, even: true, abilities: originAbilities(custom), origin, noUltimate: !ult }); + (won[`${ult}-${bot}`] ??= []).push(s.result!.won ? 1 : 0); + } + } + } + } + rows.push(`| ${gap} 點 | ${pct(mean(won["false-casual"]!))} | ${pct(mean(won["false-greedy"]!))} | ${pct(mean(won["true-casual"]!))} | ${pct(mean(won["true-greedy"]!))} |`); + console.log(`落後 ${gap} 點 完成`); + } + console.log(rows.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/village-balance.ts b/backend/apps/sim/src/village-balance.ts new file mode 100644 index 0000000..f2b12ed --- /dev/null +++ b/backend/apps/sim/src/village-balance.ts @@ -0,0 +1,53 @@ +/** + * 里長關平衡報告(18 第 55 項):node src/village-balance.ts [--villages 12] [--runs 4] + * + * 照政治生涯第一關的條件:自創角色 Lv 1(能力照捏人物點數+出身+黨的資源)、逆風 0、5 週。 + * 每個縣市隨機挑幾個里,看打得好(greedy)、隨手玩(casual)、完全不出牌(idle)的勝率和得票差。 + */ +import { parseArgs } from "node:util"; +import { CUSTOM_ID, withCustomCandidate } from "@election2026/content"; +import { originAbilities, partyKind } from "@election2026/protocol"; +import { runBot, type BotName } from "@election2026/rogue"; +import { VILLAGE_WEEKS, villageSetup } from "@election2026/rogue/local"; +import { loadWorld } from "./world.ts"; + +const COUNTIES = ["taoyuan-2022-mayor", "local2022-63000", "local2022-64000", "local2022-10007", "local2022-10015"]; +const PARTIES = ["民主進步黨", "中國國民黨", null] as const; +const BOTS: BotName[] = ["idle", "casual", "greedy"]; +const avatar = { skin: "#eebd98", hair: "bob", hairColor: "#2f2520", outfit: "blouse", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: true, beard: false, bg: "#dfe8f0" } as const; +const stats = { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }; + +const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1); +const pct = (x: number) => `${(x * 100).toFixed(0)}%`; + +async function main(): Promise { + const { values } = parseArgs({ options: { villages: { type: "string", default: "12" }, runs: { type: "string", default: "4" } } }); + const rows = ["| 縣市 | 政黨 | 不出牌 | 隨手玩 | 打得好 | 打得好的平均得票差 |", "|---|---|---:|---:|---:|---:|"]; + const all: Partial> = { idle: [], casual: [], greedy: [] } as Partial>; + for (const id of COUNTIES) { + const base = await loadWorld(id); + for (const party of PARTIES) { + const custom = { name: "測試人", party, background: "基層里長" as const, stats, avatar: { ...avatar }, replace: null }; + const world = { ...base, scenario: withCustomCandidate(base.scenario, custom, new Set()) }; + const won: Partial> = { idle: [], casual: [], greedy: [] } as Partial>; + const margins: number[] = []; + for (let v = 0; v < Number(values.villages); v++) { + const setup = villageSetup(world, CUSTOM_ID, null, 5_000 + v); + for (let k = 0; k < Number(values.runs); k++) { + for (const bot of BOTS) { + const s = runBot(setup, 5_000 + v * 10 + k, bot, { ascension: 0, weeks: VILLAGE_WEEKS, abilities: originAbilities(custom), origin: { background: custom.background, party, kind: partyKind(party) } }); + won[bot]!.push(s.result!.won ? 1 : 0); + all[bot]!.push(s.result!.won ? 1 : 0); + if (bot === "greedy") margins.push(s.result!.youShare - s.result!.rivalShare); + } + } + } + rows.push(`| ${base.scenario.region.countyName} | ${party ?? "無黨籍"} | ${pct(mean(won.idle!))} | ${pct(mean(won.casual!))} | ${pct(mean(won.greedy!))} | ${(mean(margins) * 100).toFixed(1)} 點 |`); + console.log(`${base.scenario.region.countyName} ${party ?? "無黨籍"} 完成`); + } + } + rows.push(`| 合計 | | ${pct(mean(all.idle!))} | ${pct(mean(all.casual!))} | ${pct(mean(all.greedy!))} | |`); + console.log(rows.join("\n")); +} + +await main(); diff --git a/backend/apps/sim/src/world.ts b/backend/apps/sim/src/world.ts new file mode 100644 index 0000000..d860471 --- /dev/null +++ b/backend/apps/sim/src/world.ts @@ -0,0 +1,11 @@ +import { CONTENT } from "@election2026/content"; +import { loadScenarioRegistry } from "@election2026/scenarios"; +import { DEFAULT_PARAMS, type Scenario, type World } from "@election2026/engine"; +import { loadPack } from "@election2026/pack-loader"; + +export async function loadWorld(scenarioId: string, mood?: Scenario["mood"]): Promise { + const scenario = (await loadScenarioRegistry()).find(scenarioId); + if (!scenario) throw new Error(`找不到劇本 ${scenarioId}`); + const pack = await loadPack(scenario.packId); + return { scenario: mood ? { ...scenario, mood } : scenario, pack, content: CONTENT, params: DEFAULT_PARAMS }; +} diff --git a/backend/apps/sim/tsconfig.json b/backend/apps/sim/tsconfig.json new file mode 100644 index 0000000..a598f69 --- /dev/null +++ b/backend/apps/sim/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src"] +} diff --git a/backend/data/pipeline/config/people/acting_heads.yaml b/backend/data/pipeline/config/people/acting_heads.yaml new file mode 100644 index 0000000..d207bda --- /dev/null +++ b/backend/data/pipeline/config/people/acting_heads.yaml @@ -0,0 +1,31 @@ +# 代理中的縣市首長(手動維護) +# +# 內政部地方公職人員資訊專區只列當選人,不含停職與代理資訊,所以代理首長在這裡補上。 +# 規則同 party_chairs.yaml:每筆都要有實際擷取並確認過的來源。 +# 2026-10-25 查核:新竹市長高虹安已於 2025-12 復職(內政部專區仍列為市長),目前沒有代理; +# 宜蘭縣由副縣長林茂盛代理縣長。 + +acting: + - name: 林茂盛 + category: official + county: 宜蘭縣 + positions: + - title: 代理縣長 + org: 宜蘭縣政府 + from: "2024-12-31" + to: null + - title: 副縣長 + org: 宜蘭縣政府 + from: null + to: null + education: + - 台灣科技大學營建所碩士 + - 東吳大學法律研究所碩士 + sources: + - id: yilan-acting-magistrate + title: 宜蘭縣政府 代理縣長介紹 + agency: 宜蘭縣政府 + url: https://www.e-land.gov.tw/cp.aspx?n=2700 + license: 宜蘭縣政府網站資料開放宣告 + retrievedAt: "2026-10-25" + quote: "宜蘭縣政府代理縣長 林茂盛…經歷:宜蘭縣政府代理縣長(113年12月31日迄今)、宜蘭縣政府副縣長" diff --git a/backend/data/pipeline/config/people/overrides.yaml b/backend/data/pipeline/config/people/overrides.yaml new file mode 100644 index 0000000..ed9a765 --- /dev/null +++ b/backend/data/pipeline/config/people/overrides.yaml @@ -0,0 +1,32 @@ +# 更正(手動維護):官方資料已知過時的欄位 +# +# 目前只支援 field: party。內政部地方公職人員資訊專區的黨籍是 111 年選舉時的黨籍, +# 之後的退黨、恢復黨籍不會反映;查證到異動時在這裡更正,並附上實際擷取過的來源。 +# value: null 代表「目前不屬於原政黨、現屬政黨未經查證」。 + +overrides: + - name: 鍾東錦 + field: party + value: 中國國民黨 + note: 2025-09-14 恢復中國國民黨黨籍(內政部專區仍為 111 年選舉時的「無」) + sources: + - id: udn-20251216-chung-tung-chin + title: 鍾東錦:不放棄爭取苗栗實中(新聞報導,2025-12-16) + agency: 聯合新聞網 + url: https://udn.com/news/story/124678/9205131 + license: 新聞報導(僅引用事實,未轉載內容) + retrievedAt: "2026-10-25" + quote: "鍾東錦今年9月14日恢復黨籍" + + - name: 高虹安 + field: party + value: null + note: 2024-07-26 宣布退出台灣民眾黨;截至 2026-10-25 未查得恢復黨籍的資料(內政部專區仍為台灣民眾黨) + sources: + - id: gvm-20240726-kao-hung-an + title: 高虹安宣布退出台灣民眾黨(新聞報導,2024-07-26) + agency: 遠見雜誌 + url: https://www.gvm.com.tw/article/114603 + license: 新聞報導(僅引用事實,未轉載內容) + retrievedAt: "2026-10-25" + quote: "高虹安並宣布「即刻退出台灣民眾黨,謝謝各界的關心。」" diff --git a/backend/data/pipeline/config/people/party_chairs.yaml b/backend/data/pipeline/config/people/party_chairs.yaml new file mode 100644 index 0000000..b9db536 --- /dev/null +++ b/backend/data/pipeline/config/people/party_chairs.yaml @@ -0,0 +1,88 @@ +# 政黨主席(手動維護) +# +# 規則: +# - 每一筆都要有至少一個 sources,且是實際擷取頁面、確認頁面文字後才填入(retrievedAt 為擷取日)。 +# - 不憑記憶填寫;黨主席異動時更新本檔並更新 retrievedAt。 +# - from:只有在來源寫明就任日期時才填,否則為 null。 +# - quote:來源頁面上確認的原文片段,方便日後複查。 + +chairs: + - name: 賴清德 + party: 民主進步黨 + title: 黨主席 + from: null + sources: + - id: dpp-chair-and-officers + title: 民主進步黨 主席及黨務主管 + agency: 民主進步黨 + url: https://www.dpp.org.tw/about/political + license: 政黨官方網站(僅引用事實資料) + retrievedAt: "2026-10-25" + quote: "主席及黨務主管|主席|賴清德|秘書長|徐國勇" + + - name: 鄭麗文 + party: 中國國民黨 + title: 黨主席 + from: null + sources: + - id: kmt-chair + title: 中國國民黨 主席(現任主席) + agency: 中國國民黨 + url: https://www1.kmt.org.tw/people.aspx?mid=18 + license: 政黨官方網站(僅引用事實資料) + retrievedAt: "2026-10-25" + quote: "現任主席|歷屆主席|主席|鄭麗文" + - id: kmt-press-20261025 + title: 中國國民黨新聞稿(115.10.25) + agency: 中國國民黨文化傳播委員會 + url: https://www.kmt.org.tw/2026/10/1128_0409609873.html + license: 政黨官方網站(僅引用事實資料) + retrievedAt: "2026-10-25" + quote: "中國國民黨主席鄭麗文今(25)日出席…" + + - name: 黃國昌 + party: 台灣民眾黨 + title: 黨主席 + from: null + sources: + - id: udn-20261007-tpp-chair + title: 民眾黨主席黃國昌出席記者會(新聞報導,2026-10-07) + agency: 聯合新聞網 + url: https://udn.com/news/story/6656/9800691 + license: 新聞報導(僅引用事實,未轉載內容) + retrievedAt: "2026-10-25" + quote: "雙十國慶即將到來,民眾黨主席黃國昌今天說…(2026-10-07)" + note: 台灣民眾黨官網(www.tpp.org.tw)有防爬蟲阻擋(HTTP 403),改用新聞報導 + - id: cna-20260204-tpp-chair + title: 2026選舉 民眾黨徵召黃國昌參選新北市長(新聞報導) + agency: 中央通訊社 + url: https://www.cna.com.tw/news/aipl/202602040186.aspx + license: 新聞報導(僅引用事實,未轉載內容) + retrievedAt: "2026-10-25" + quote: "徵召民眾黨主席黃國昌參選2026年新北市長(2026-02-04)" + + - name: 王婉諭 + party: 時代力量 + title: 黨主席 + from: null + sources: + - id: npp-20261010 + title: 時代力量新聞稿(2026-10-10) + agency: 時代力量 + url: https://newpowerparty.tw/archives/31242 + license: 政黨官方網站(僅引用事實資料) + retrievedAt: "2026-10-25" + quote: "時代力量黨主席王婉諭今(10)日應國慶籌備委員會邀請…" + + - name: 王興煥 + party: 台灣基進 + title: 黨主席 + from: null + sources: + - id: tsp-chair + title: 台灣基進 主席的話 + agency: 台灣基進 + url: https://www.statebuilding.tw/about/chairman + license: 政黨官方網站(僅引用事實資料) + retrievedAt: "2026-10-25" + quote: "台灣基進黨主席 王興煥" diff --git a/backend/data/pipeline/pyproject.toml b/backend/data/pipeline/pyproject.toml new file mode 100644 index 0000000..109b926 --- /dev/null +++ b/backend/data/pipeline/pyproject.toml @@ -0,0 +1,49 @@ +[build-system] +requires = ["setuptools>=75"] +build-backend = "setuptools.build_meta" + +[project] +name = "election-data" +version = "0.1.0" +description = "凍蒜 2026 資料管線:政府開放資料 → 資料包、人物資料庫、AI 評分" +requires-python = ">=3.12" +dependencies = [ + "pandas>=3.0", + "numpy>=2.0", + "httpx>=0.28", + "openpyxl>=3.1", + "odfpy>=1.4", + "shapely>=2.0", + "pyshp>=2.3", + "jsonschema>=4.23", + "pyyaml>=6.0", + "anthropic>=0.70", +] + +[project.optional-dependencies] +dev = ["pytest>=8", "pytest-cov>=5", "ruff>=0.6", "black>=24"] + +[project.scripts] +election-data = "election_data.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +markers = [ + "unit: 純函式測試,不連網", + "integration: 讀取實際下載的資料檔", + "network: 需要連網", +] +addopts = "-m 'not network'" + +[tool.ruff] +line-length = 110 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "SIM"] + +[tool.black] +line-length = 110 diff --git a/backend/data/pipeline/src/election_data/__init__.py b/backend/data/pipeline/src/election_data/__init__.py new file mode 100644 index 0000000..c8b0e08 --- /dev/null +++ b/backend/data/pipeline/src/election_data/__init__.py @@ -0,0 +1 @@ +"""凍蒜 2026 資料管線。""" diff --git a/backend/data/pipeline/src/election_data/attributes.py b/backend/data/pipeline/src/election_data/attributes.py new file mode 100644 index 0000000..04c04d9 --- /dev/null +++ b/backend/data/pipeline/src/election_data/attributes.py @@ -0,0 +1,177 @@ +"""村里與鄉鎮的屬性來源:寺廟教會、綜稅所得、普查、客家重點區。 + +注意:宗教資料含負責人姓名與電話,這裡只讀座標,不保留任何個人資料(docs/14)。 +""" + +from __future__ import annotations + +import csv +import io +import logging +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +import openpyxl + +from .codes import normalize_name +from .config import INCOME_YEAR_ROC, RAW_DIR +from .fetch import FetchResult, download + +log = logging.getLogger(__name__) + +TEMPLE_URL = "https://religion.moi.gov.tw/Report/temple.xml" +CHURCH_URL = "https://religion.moi.gov.tw/Report/church.xml" +INCOME_URL = "https://www.fia.gov.tw/WEB/fia/ias/ias{year}/{year}_165-9.csv" +HAKKA_URL = "https://cloud.hakka.gov.tw/Pub/Opendata/DTST20230500026.csv" +# 主計總處 109 年普查縣市別報告統計表,目錄以縣市區分 +CENSUS_BASE = {"68000": "https://ws.dgbas.gov.tw/001/Upload/463/relfile/11065/230883/"} + + +# ---------- 宗教 ---------- + + +def _coordinates(xml_path: Path) -> Iterator[tuple[float, float]]: + for _, elem in ET.iterparse(xml_path, events=("end",)): + if elem.tag.startswith("OpenData"): + x, y = elem.findtext("WGS84X"), elem.findtext("WGS84Y") + elem.clear() + try: + lon, lat = float(x or ""), float(y or "") + except ValueError: + continue + if 118 < lon < 123 and 21 < lat < 27: # 排除空值與明顯錯誤的座標 + yield lon, lat + + +def load_religious_sites() -> ( + tuple[list[tuple[float, float]], list[tuple[float, float]], FetchResult, FetchResult] +): + temples = download(TEMPLE_URL, RAW_DIR / "moi" / "temple.xml") + churches = download(CHURCH_URL, RAW_DIR / "moi" / "church.xml") + return list(_coordinates(temples.path)), list(_coordinates(churches.path)), temples, churches + + +# ---------- 綜稅所得 ---------- + + +@dataclass(frozen=True) +class VillageIncome: + site: str # 縣市+鄉鎮,例如 桃園市桃園區 + village: str + households: int + mean: float # 千元 + median: float # 千元 + + +def parse_income(text: str) -> list[VillageIncome]: + out = [] + for row in csv.DictReader(io.StringIO(text.lstrip(""))): + keys = {k.strip().lstrip(""): v for k, v in row.items() if k} + village = (keys.get("村里") or "").strip() + if not village or village in {"合計", "其他"}: + continue + try: + out.append( + VillageIncome( + normalize_name(keys["縣市別"]), + normalize_name(village), + int(keys["納稅單位(戶)"]), + float(keys["平均數"]), + float(keys["中位數"]), + ) + ) + except (KeyError, ValueError): + log.debug("略過無法解析的所得列:%s", row) + return out + + +def load_income(year: str = INCOME_YEAR_ROC) -> tuple[list[VillageIncome], FetchResult]: + result = download(INCOME_URL.format(year=year), RAW_DIR / "fia" / f"income_{year}.csv") + return parse_income(result.path.read_text(encoding="utf-8-sig")), result + + +# ---------- 客家重點區 ---------- + + +def parse_hakka(text: str) -> dict[str, float]: + """TOWNCODE → 客家人口比例(只有比例 ≥ 1/3 的 70 個鄉鎮)。""" + out = {} + for row in csv.DictReader(io.StringIO(text.lstrip(""))): + code, ratio = (row.get("AreaCode") or "").strip(), (row.get("Ratio") or "").strip() + if len(code) == 8 and ratio: + out[code] = float(ratio) + return out + + +def load_hakka() -> tuple[dict[str, float], FetchResult]: + result = download(HAKKA_URL, RAW_DIR / "hakka" / "key_areas.csv") + return parse_hakka(result.path.read_text(encoding="utf-8-sig")), result + + +# ---------- 普查 ---------- + + +@dataclass(frozen=True) +class TownCensus: + name: str + resident_population: int + language: dict[str, float] # 主要或次要使用語言的比例(可複選) + education: dict[str, float] + + +LANG_COLUMNS = ("mandarin", "taiwanese", "hakka", "indigenous", "other") +EDU_COLUMNS = ("elementary_or_less", "junior_high", "senior_high", "college_or_more") + + +def _town_rows(xlsx: Path) -> dict[str, list]: + """鄉鎮列的開頭是兩個全形空白加名稱;回傳 名稱 → 數值欄位(第一個工作表)。""" + wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) + ws = wb[wb.sheetnames[0]] + rows: dict[str, list] = {} + for row in ws.iter_rows(values_only=True): + values = [c for c in row if c is not None] + if not values or not isinstance(values[0], str): + continue + label = values[0] + if label.startswith("  ") and not label.strip().isascii(): + rows.setdefault(normalize_name(label), values[1:]) + wb.close() + return rows + + +def _num(value: object) -> float: + try: + return float(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return 0.0 + + +def load_census(county_code: str) -> tuple[dict[str, TownCensus], FetchResult]: + base = CENSUS_BASE.get(county_code) + if base is None: + raise KeyError(f"尚未設定 {county_code} 的普查表網址(attributes.CENSUS_BASE)") + folder = RAW_DIR / "census2020" / county_code + t001 = download(base + "t001.xlsx", folder / "t001.xlsx") + t006 = download(base + "t006.xlsx", folder / "t006.xlsx") + t010 = download(base + "t010.xlsx", folder / "t010.xlsx") + pop, lang, edu = _town_rows(t001.path), _town_rows(t006.path), _town_rows(t010.path) + out = {} + for name, values in pop.items(): + lang_row = lang.get(name, []) + language = {} + if len(lang_row) >= 11: + primary, secondary = lang_row[1:6], lang_row[6:11] + language = { + key: min(1.0, (_num(p) + _num(s)) / 100) + for key, p, s in zip(LANG_COLUMNS, primary, secondary, strict=True) + } + edu_row = edu.get(name, []) + education = {} + if len(edu_row) >= 5 and _num(edu_row[0]) > 0: + total = _num(edu_row[0]) + education = {key: _num(v) / total for key, v in zip(EDU_COLUMNS, edu_row[1:5], strict=True)} + out[name] = TownCensus(name, int(_num(values[0])), language, education) + log.info("普查:%d 個鄉鎮市區", len(out)) + return out, t001 diff --git a/backend/data/pipeline/src/election_data/cec.py b/backend/data/pipeline/src/election_data/cec.py new file mode 100644 index 0000000..b69fc4a --- /dev/null +++ b/backend/data/pipeline/src/election_data/cec.py @@ -0,0 +1,73 @@ +"""讀取中選會選舉資料庫(votedata.zip),不需要解壓縮。 + +壓縮檔內的檔名是 UTF-8,但沒有設定 UTF-8 旗標,所以要從 cp437 轉回來。 +每個選舉資料夾有:elbase(地名)、elcand(候選人)、elctks(得票)、elprof(投票概況)、elpaty(政黨)。 +""" + +from __future__ import annotations + +import csv +import io +import zipfile +from collections.abc import Iterator +from dataclasses import dataclass +from functools import cached_property +from pathlib import Path + +from .config import RAW_DIR +from .fetch import FetchResult, download + +VOTEDATA_URL = "https://data.cec.gov.tw/選舉資料庫/votedata.zip" +VOTEDATA_PATH = RAW_DIR / "cec" / "votedata.zip" +_ROOT = "votedata/votedata/voteData/" + + +def fetch_votedata() -> FetchResult: + return download(VOTEDATA_URL, VOTEDATA_PATH, timeout=600) + + +def _decode_name(info: zipfile.ZipInfo) -> str: + if info.flag_bits & 0x800: + return info.filename + try: + return info.filename.encode("cp437").decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError): + # 已經是正確的 Unicode(例如帶有 Unicode Path 額外欄位)或不是 UTF-8 位元組 + return info.filename + + +@dataclass(frozen=True) +class CecArchive: + path: Path + + @cached_property + def _index(self) -> dict[str, zipfile.ZipInfo]: + with zipfile.ZipFile(self.path) as zf: + return {_decode_name(i): i for i in zf.infolist()} + + def folders(self) -> list[str]: + """列出 voteData 底下的選舉資料夾(相對路徑)。""" + out = set() + for name in self._index: + if name.startswith(_ROOT) and name.endswith("/elbase.csv"): + out.add(name[len(_ROOT) : -len("/elbase.csv")]) + return sorted(out) + + def has(self, folder: str, kind: str) -> bool: + return f"{_ROOT}{folder}/{kind}.csv" in self._index + + def rows(self, folder: str, kind: str) -> Iterator[list[str]]: + """逐列讀取,例如 rows("2024總統立委/總統", "elctks")。""" + name = f"{_ROOT}{folder}/{kind}.csv" + info = self._index.get(name) + if info is None: + raise FileNotFoundError(f"壓縮檔中沒有 {name}") + with zipfile.ZipFile(self.path) as zf, zf.open(info) as raw: + text = io.TextIOWrapper(raw, encoding="utf-8-sig", newline="") + for row in csv.reader(text): + if row: + yield [cell.strip().strip("'") for cell in row] + + +def open_archive() -> CecArchive: + return CecArchive(fetch_votedata().path) diff --git a/backend/data/pipeline/src/election_data/cells.py b/backend/data/pipeline/src/election_data/cells.py new file mode 100644 index 0000000..6c1fe35 --- /dev/null +++ b/backend/data/pipeline/src/election_data/cells.py @@ -0,0 +1,93 @@ +"""估計每個村里 30 個選民群(5 年齡層 × 6 政黨傾向)的人數(docs/03、docs/10)。 + +1. 生態推論:用所有村里的「年齡結構」與「政黨傾向比例」做加權最小平方, + 估計各年齡層的政黨傾向分布 P(傾向 | 年齡)。不需要調查資料。 +2. 疊代比例調整(IPF):以 P(傾向 | 年齡) × 年齡人數為種子, + 調整到同時符合該里的年齡人數與政黨傾向比例。 +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + +import numpy as np + +FLOOR = 0.01 + + +@dataclass(frozen=True) +class AgeLeanModel: + """P(傾向 | 年齡):列 = 年齡層,欄 = 傾向,每列總和為 1。""" + + ages: tuple[str, ...] + leans: tuple[str, ...] + matrix: np.ndarray + + def to_json(self) -> dict[str, dict[str, float]]: + return { + a: {lean: round(float(self.matrix[i, j]), 4) for j, lean in enumerate(self.leans)} + for i, a in enumerate(self.ages) + } + + +def fit_age_lean( + age_counts: Sequence[Mapping[str, float]], + lean_shares: Sequence[Mapping[str, float]], + ages: Sequence[str], + leans: Sequence[str], + ridge: float = 0.0, +) -> AgeLeanModel: + """加權最小平方:lean_share[v, l] ≈ Σ_a age_share[v, a] × β[a, l],權重為成年人口。 + + ridge > 0 時往「各年齡層都等於整體平均」收斂:生態推論在年齡結構高度共線時很不穩定, + 沒有收斂限制會估出不合理的極端值(見 report.md)。權重先正規化成平均 1,ridge 以村里數為尺度。 + """ + if len(age_counts) != len(lean_shares) or not age_counts: + raise ValueError("年齡與政黨傾向的村里數必須相同且不為零") + counts = np.array([[row[a] for a in ages] for row in age_counts], dtype=float) + totals = counts.sum(axis=1) + keep = totals > 0 + shares = counts[keep] / totals[keep, None] + targets = np.array([[row[lean] for lean in leans] for row in lean_shares], dtype=float)[keep] + w = totals[keep] / totals[keep].mean() + prior = (targets * w[:, None]).sum(axis=0) / w.sum() + lhs = shares.T @ (shares * w[:, None]) + ridge * np.eye(len(ages)) + rhs = shares.T @ (targets * w[:, None]) + ridge * np.tile(prior, (len(ages), 1)) + beta = np.linalg.solve(lhs, rhs) + beta = np.clip(beta, FLOOR, None) + beta = beta / beta.sum(axis=1, keepdims=True) + return AgeLeanModel(tuple(ages), tuple(leans), beta) + + +def ipf( + seed: np.ndarray, row_targets: np.ndarray, col_targets: np.ndarray, tol: float = 1e-6, max_iter: int = 200 +) -> np.ndarray: + """疊代比例調整。列、欄目標總和必須相同(允許浮點誤差)。""" + if seed.shape != (row_targets.size, col_targets.size): + raise ValueError("種子矩陣形狀與目標不符") + if not np.isclose(row_targets.sum(), col_targets.sum(), rtol=1e-6, atol=1e-6): + raise ValueError(f"列總和 {row_targets.sum()} 與欄總和 {col_targets.sum()} 不同") + m = np.maximum(seed.astype(float), 1e-9) + for _ in range(max_iter): + row_sum = m.sum(axis=1) + m = m * np.divide(row_targets, row_sum, out=np.zeros_like(row_sum), where=row_sum > 0)[:, None] + col_sum = m.sum(axis=0) + m = m * np.divide(col_targets, col_sum, out=np.zeros_like(col_sum), where=col_sum > 0)[None, :] + if np.abs(m.sum(axis=1) - row_targets).max() < tol * max(1.0, row_targets.sum()): + break + return m + + +def village_cells( + model: AgeLeanModel, age_counts: Mapping[str, float], lean_share: Mapping[str, float] +) -> list[float]: + """回傳 30 個數字(年齡為外層),總和 = 該里成年人口。""" + rows = np.array([age_counts[a] for a in model.ages], dtype=float) + total = rows.sum() + if total <= 0: + return [0.0] * (len(model.ages) * len(model.leans)) + cols = np.array([lean_share[lean] for lean in model.leans], dtype=float) * total + seed = model.matrix * rows[:, None] + fitted = ipf(seed, rows, cols) + return [round(float(x), 2) for x in fitted.reshape(-1)] diff --git a/backend/data/pipeline/src/election_data/cli.py b/backend/data/pipeline/src/election_data/cli.py new file mode 100644 index 0000000..a9bfb95 --- /dev/null +++ b/backend/data/pipeline/src/election_data/cli.py @@ -0,0 +1,134 @@ +"""命令列: +election-data pack --county 68000 [--exclude 2022-mayor] [--before 2022-11-26] +election-data donations --election 111年直轄市市長選舉 --area 桃園市 +election-data local2022 +election-data races2024 +election-data local --year 2018 +election-data races --year 2020 +election-data pack --county 00000 --historic --since 2008-01-01 --before 2012-01-14 +election-data records +""" + +from __future__ import annotations + +import argparse +import logging + +from .donations import build_donations +from .elections import ALL_ELECTIONS, ELECTIONS, HISTORIC_ELECTIONS +from .local2022 import COUNTY_NAMES, LOCAL_RACES, build_local, build_local_2022 +from .pack import NATIONAL, build_pack +from .parties import build_parties +from .races2024 import NATIONAL_RACES, build_legislators, build_president +from .records.build import build_records + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="election-data", description="凍蒜 2026 資料管線") + sub = parser.add_subparsers(dest="command", required=True) + pack = sub.add_parser("pack", help="產生資料包") + pack.add_argument( + "--county", + default="68000", + help=f"縣市代碼,可用逗號分隔多個(預設 68000 桃園市;{NATIONAL} 為全國;all 為全部縣市)", + ) + pack.add_argument( + "--exclude", + action="append", + default=[], + help="計算政黨傾向時排除的選舉 id(可重複),產生歷史回測用的資料包,例如 2022-mayor", + ) + pack.add_argument( + "--before", + help="只用這一天(YYYY-MM-DD)以前的選舉,產生不含未來資料的回測資料包,例如 2022-11-26", + ) + pack.add_argument( + "--older", action="store_true", help="加入 2016、2018 年的選舉(給 2018、2020 年劇本的資料包)" + ) + pack.add_argument( + "--historic", + action="store_true", + help="再加入 1995–2014 年的選舉(給 2016 年以前劇本的資料包;舊代碼用名稱對照,見 legacy.py)", + ) + pack.add_argument( + "--since", + help="只讀這一天(YYYY-MM-DD)以後的選舉;更早的不讀進資料包(--historic 時用來挑上一輪的選舉)", + ) + pack.add_argument( + "--past-only", + action="store_true", + help="搭配 --before:之後的選舉完全不讀(history.json 不放之後的開票結果,資料包比較小)", + ) + donations = sub.add_parser("donations", help="下載並整理監察院政治獻金收支結算表") + donations.add_argument("--election", required=True, help="選舉名稱,例如 111年直轄市市長選舉") + donations.add_argument("--area", required=True, help="選舉區,例如 桃園市") + sub.add_parser("local2022", help="產生 2022 縣市長選舉的劇本資料(全台,候選人層級的得票)") + sub.add_parser("races2024", help="產生 2024 總統與區域立委的劇本資料") + local = sub.add_parser("local", help="產生縣市長選舉的劇本資料(全台)") + local.add_argument("--year", type=int, choices=sorted(LOCAL_RACES), default=2022) + sub.add_parser("parties", help="產生歷屆推出過候選人的政黨清單(自創角色選政黨用)") + races = sub.add_parser("races", help="產生總統與區域立委的劇本資料") + races.add_argument("--year", type=int, choices=sorted(NATIONAL_RACES), default=2024) + sub.add_parser( + "records", + help="產生歷屆參選人資料庫(縣市長、議員、總統副總統、立委)與資歷分數(people/records.json)" + "和議員選區檔(council/<年>.json);只讀本機資料", + ) + parser.add_argument("-v", "--verbose", action="store_true") + args = parser.parse_args(argv) + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, format="%(asctime)s %(levelname)s %(message)s" + ) + if args.command == "pack": + used = ALL_ELECTIONS if args.older else ELECTIONS + extra = {} + if args.historic: + used = ALL_ELECTIONS + HISTORIC_ELECTIONS + extra["historic"] = True + if args.since: + used = tuple(e for e in used if e.date >= args.since) + extra["since"] = args.since + if args.past_only: + if not args.before: + parser.error("--past-only 要搭配 --before") + used = tuple(e for e in used if e.date < args.before) + extra["until"] = args.before + counties = [c for part in args.county.split(",") for c in (COUNTY_NAMES if part == "all" else [part])] + for county in counties: + exclude = set(args.exclude) + name = None + if args.before: + exclude |= {e.id for e in used if e.date >= args.before} + name = f"{county}-before-{args.before}" + out = build_pack(county, exclude=tuple(sorted(exclude)), name=name, older=args.older, **extra) + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "local2022": + for out in build_local_2022(): + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "parties": + for out in build_parties(): + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "local": + for out in build_local(args.year): + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "races": + race = NATIONAL_RACES[args.year] + legislators = build_legislators(year=args.year) if race.folder else [] + if not race.folder: + logging.getLogger(__name__).info("%d 年只做總統(區域立委沒有整理)", args.year) + for out in [build_president(year=args.year), *legislators]: + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "races2024": + for out in [build_president(), *build_legislators()]: + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "records": + for out in build_records(): + logging.getLogger(__name__).info("輸出:%s", out) + elif args.command == "donations": + out = build_donations(args.election, args.area) + logging.getLogger(__name__).info("輸出:%s", out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/data/pipeline/src/election_data/codes.py b/backend/data/pipeline/src/election_data/codes.py new file mode 100644 index 0000000..4e9ac84 --- /dev/null +++ b/backend/data/pipeline/src/election_data/codes.py @@ -0,0 +1,87 @@ +"""行政區代碼與名稱的轉換。 + +- 主鍵是 11 碼村里代碼(VILLCODE),國土測繪中心與戶政司共用。 +- 中選會用 5 段代碼:省市 2 + 縣市 3 + 鄉鎮 3 + 村里 4; + 前三段相接,再接村里段的後 3 碼,就是 VILLCODE(docs/10)。 + 只有 2014 年以後的資料夾是這樣;更早的是中選會自己的流水號,要用名稱對照(legacy.py)。 +""" + +from __future__ import annotations + +import re +import unicodedata + +_SPACE = re.compile(r"[\s ]+") + +#: 2014 年的資料把跨村里投開票所寫成村里段 9999(2016 年起改用 A001 這類含字母的代碼) +CROSS_VILLAGE_2014 = "9999" + +#: 縣市名稱 → 目前的縣市代碼。舊縣市(2010、2014 年改制前)對到改制後的直轄市 +COUNTY_CODE_BY_NAME = { + "臺北市": "63000", "高雄市": "64000", "新北市": "65000", "臺中市": "66000", "臺南市": "67000", + "桃園市": "68000", "宜蘭縣": "10002", "新竹縣": "10004", "苗栗縣": "10005", "彰化縣": "10007", + "南投縣": "10008", "雲林縣": "10009", "嘉義縣": "10010", "屏東縣": "10013", "臺東縣": "10014", + "花蓮縣": "10015", "澎湖縣": "10016", "基隆市": "10017", "新竹市": "10018", "嘉義市": "10020", + "連江縣": "09007", "金門縣": "09020", + # 改制前的舊縣市 + "臺北縣": "65000", "桃園縣": "68000", "臺中縣": "66000", "臺南縣": "67000", "高雄縣": "64000", +} # fmt: skip + + +def county_code(prv: str, city: str) -> str: + return f"{prv}{city}" + + +def town_code(prv: str, city: str, town: str) -> str: + return f"{prv}{city}{town}" + + +def town_residual_code(town8: str) -> str: + """「鄉鎮代碼+000」:知道票在哪個鄉鎮、但對不到任何現存村里時用的代碼。 + 真正的村里段從 001 開始,所以不會和任何村里撞號;資料包把它當成孤兒代碼(只算進總數)。""" + return f"{town8}000" + + +def county_residual_code(county5: str) -> str: + """「縣市代碼+000000」:只知道票在哪個縣市(舊資料的村里列有缺漏時)""" + return f"{county5}000000" + + +def is_town_residual(code: str) -> bool: + """鄉鎮或縣市層級的殘差代碼(不是真的村里)""" + return len(code) == 11 and code.endswith("000") + + +def is_cross_village(village: str) -> bool: + """村里段是跨村里投開票所的代碼:含字母(A001、0A01),或 2014 年的 9999""" + return not village.isdigit() or village == CROSS_VILLAGE_2014 + + +def cec_village_code(prv: str, city: str, town: str, village: str) -> str | None: + """中選會代碼轉 VILLCODE。跨村里投開票所(見 is_cross_village)回傳 None。""" + if is_cross_village(village) or village == "0000" or town == "000": + return None + if int(village) >= 1000: + raise ValueError(f"村里段超過 3 位數,無法轉換:{prv}/{city}/{town}/{village}") + code = f"{prv}{city}{town}{village[-3:]}" + if len(code) != 11: + raise ValueError(f"代碼長度不是 11:{code}") + return code + + +def normalize_name(name: str) -> str: + """地名比對用:全形轉半形、去空白、「台」統一為「臺」。""" + text = unicodedata.normalize("NFKC", name) + text = _SPACE.sub("", text) + return text.replace("台", "臺") + + +def roc_to_iso_date(roc: str) -> str | None: + """民國日期(例如 0481006 或 48/10/06)轉 ISO 日期。""" + digits = re.sub(r"\D", "", roc) + if len(digits) not in (6, 7): + return None + year, month, day = int(digits[:-4]), int(digits[-4:-2]), int(digits[-2:]) + if not (1 <= month <= 12 and 1 <= day <= 31): + return None + return f"{year + 1911:04d}-{month:02d}-{day:02d}" diff --git a/backend/data/pipeline/src/election_data/config.py b/backend/data/pipeline/src/election_data/config.py new file mode 100644 index 0000000..0391e2d --- /dev/null +++ b/backend/data/pipeline/src/election_data/config.py @@ -0,0 +1,28 @@ +"""路徑與資料快照設定。""" + +from __future__ import annotations + +from pathlib import Path + +PIPELINE_DIR = Path(__file__).resolve().parents[2] +REPO_ROOT = PIPELINE_DIR.parents[1] +RAW_DIR = REPO_ROOT / "data" / "raw" +BUILD_DIR = REPO_ROOT / "data" / "build" +SCHEMA_DIR = REPO_ROOT / "packages" / "protocol" / "schema" +CONFIG_DIR = PIPELINE_DIR / "config" + +PROTOCOL_VERSION = "1.0.0" + +# 人口資料快照:民國 115 年 9 月(2026-09) +POPULATION_MONTH_ROC = "11509" +POPULATION_MONTH_ISO = "2026-09" + +# 村里界圖版本(國土測繪中心) +BOUNDARY_VERSION = "1150817" + +# 綜稅所得統計年度(民國) +INCOME_YEAR_ROC = "112" + +# 部分政府網站的憑證鏈不在一般的根憑證清單中。只有這些主機允許在驗證失敗時改用不驗證的連線, +# 下載後會記錄 SHA-256 與 tlsVerified=false,方便日後比對。 +UNVERIFIED_TLS_HOSTS = frozenset({"www.stat.gov.tw", "ws.dgbas.gov.tw"}) diff --git a/backend/data/pipeline/src/election_data/donations.py b/backend/data/pipeline/src/election_data/donations.py new file mode 100644 index 0000000..12cca35 --- /dev/null +++ b/backend/data/pipeline/src/election_data/donations.py @@ -0,0 +1,112 @@ +"""監察院政治獻金:擬參選人的收支結算表(首次申報),給劇本設定起始資金與募款能力。 + +來源:監察院政治獻金公開查閱平臺 https://ardata.cy.gov.tw ,政府資料開放授權條款第 1 版。 +政治獻金專戶只記錄捐款與用捐款支付的支出;政黨直接支付、候選人自付的費用不一定在內, +所以這裡的數字是競選花費的下限。 +""" + +from __future__ import annotations + +import csv +import io +import json +import zipfile +from dataclasses import asdict, dataclass +from pathlib import Path +from urllib.parse import urlencode + +from .config import BUILD_DIR, RAW_DIR +from .fetch import download + +API = "https://ardata.cy.gov.tw/api/v1/Search/download" +SUMMARY_FILE = "election_incomes and expenditures_first.csv" + +INCOME_FIELDS = { + "individual": "個人捐贈收入", + "business": "營利事業捐贈收入", + "party": "政黨捐贈收入", + "civic": "人民團體捐贈收入", + "anonymous": "匿名捐贈收入", + "other": "其他收入", +} +SPENDING_FIELDS = { + "personnel": "人事費用支出", + "advertising": "宣傳支出", + "soundTrucks": "租用宣傳車輛支出", + "offices": "租用競選辦事處支出", + "rallies": "集會支出", + "travel": "交通旅運支出", + "misc": "雜支支出", + "returned": "返還捐贈支出", + "toTreasury": "繳庫支出", + "publicRelations": "公共關係費用支出", +} + + +@dataclass(frozen=True) +class CandidateFinance: + name: str + income: int + spending: int + incomeBreakdown: dict[str, int] + spendingBreakdown: dict[str, int] + + +def download_url(election_name: str, area: str) -> str: + query = { + "ElectionName": election_name, + "ElectionArea": area, + "AccountNumber": "", + "YearOrSerial": "1", + "Version": "", + "SearchType": "2", + "DownloadType": "3", + } + return f"{API}?{urlencode(query)}" + + +def _money(text: str) -> int: + return round(float(text.replace(",", "") or 0)) + + +def parse_summary(text: str) -> list[CandidateFinance]: + """解析收支結算表 CSV(UTF-8,可能有 BOM)。""" + rows = csv.DictReader(io.StringIO(text.lstrip(""))) + out = [] + for row in rows: + out.append( + CandidateFinance( + name=row["擬參選人"].strip(), + income=_money(row["收入小計"]), + spending=_money(row["支出小計"]), + incomeBreakdown={k: _money(row[v]) for k, v in INCOME_FIELDS.items()}, + spendingBreakdown={k: _money(row[v]) for k, v in SPENDING_FIELDS.items()}, + ) + ) + return out + + +def build_donations(election_name: str, area: str, out_root: Path = BUILD_DIR / "finance") -> Path: + url = download_url(election_name, area) + fetched = download(url, RAW_DIR / "ardata" / f"{election_name}-{area}.zip") + with zipfile.ZipFile(fetched.path) as z: + text = z.read(SUMMARY_FILE).decode("utf-8") + candidates = parse_summary(text) + out_root.mkdir(parents=True, exist_ok=True) + out = out_root / f"{election_name}-{area}.json" + payload = { + "election": election_name, + "area": area, + "report": "首次申報收支結算表", + "source": { + "title": "監察院政治獻金公開查閱平臺", + "url": url, + "retrievedAt": fetched.retrieved_at, + "sha256": fetched.sha256, + "license": "政府資料開放授權條款第 1 版", + }, + "note": "政治獻金專戶只記錄捐款與用捐款支付的支出,是競選花費的下限", + "candidates": [asdict(c) for c in candidates], + } + out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + return out diff --git a/backend/data/pipeline/src/election_data/elections.py b/backend/data/pipeline/src/election_data/elections.py new file mode 100644 index 0000000..074aa55 --- /dev/null +++ b/backend/data/pipeline/src/election_data/elections.py @@ -0,0 +1,694 @@ +"""歷屆選舉結果 → 每個村里的得票(依政黨加總)、投票數、選舉人數。 + +使用中選會資料中的「村里小計」列(投開票所欄為 0000、村里欄不為 0000)。 +跨村里投開票所(村里段含字母,例如 0A01;2014 年是 9999)在 elbase 中列出涵蓋的村里名稱, +依各村里的權重(成年人口)以最大餘數法分配,並在結果中標示 allocated。 +2014 年以前的資料夾用中選會自己的流水號代碼,改用名稱對照(legacy.py)。 +""" + +from __future__ import annotations + +import logging +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field + +from .cec import CecArchive +from .codes import ( + cec_village_code, + county_code, + county_residual_code, + is_cross_village, + normalize_name, + town_residual_code, +) +from .legacy import Gazetteer, legacy_places + +log = logging.getLogger(__name__) + +PARTY_A = "民主進步黨" +PARTY_B = "中國國民黨" +PARTY_C = "台灣民眾黨" +INDEPENDENT = "無黨籍" +OTHER = "其他" +# 保留名稱的政黨;其餘小黨合併為「其他」 +KEPT_PARTIES = frozenset({PARTY_A, PARTY_B, PARTY_C, "時代力量", "親民黨", "台灣基進", "新黨", "台灣綠黨"}) + +_LOCAL = "2022-111年地方公職人員選舉" + + +@dataclass(frozen=True) +class ElectionDef: + id: str + name: str + date: str + office: str + folders: tuple[str, ...] + weight: float + #: 檔名後綴:2016 年的檔案叫 elbase_P1.csv、elctks_T4.csv(elpaty.csv 沒有後綴) + suffix: str = "" + #: 2014 年以前的資料夾:代碼是中選會的流水號,要用名稱對到村里代碼(legacy.py) + legacy_codes: bool = False + #: 算政黨傾向時併進兩大黨一側的政黨群組:((群組, PARTY_A 或 PARTY_B), ...)。 + #: 只影響資料包的政黨傾向,history.json 仍是原本的政黨(見 pack._observations)。 + blocs: tuple[tuple[str, str], ...] = () + + +ELECTIONS: tuple[ElectionDef, ...] = ( + ElectionDef( + "2024-president", "2024 總統副總統選舉", "2024-01-13", "president", ("2024總統立委/總統",), 0.25 + ), + ElectionDef( + "2024-party-list", + "2024 立委不分區政黨票", + "2024-01-13", + "party_list", + ("2024總統立委/不分區政黨",), + 0.15, + ), + ElectionDef( + "2022-mayor", + "2022 直轄市長、縣市長選舉", + "2022-11-26", + "mayor", + (f"{_LOCAL}/C1/prv", f"{_LOCAL}/C1/city"), + 0.20, + ), + ElectionDef( + "2022-councilor", + "2022 直轄市議員、縣市議員(區域)", + "2022-11-26", + "councilor", + (f"{_LOCAL}/T1/prv", f"{_LOCAL}/T1/city"), + 0.15, + ), + ElectionDef( + "2020-president", "2020 總統副總統選舉", "2020-01-11", "president", ("2020總統立委/總統",), 0.15 + ), + ElectionDef( + "2020-party-list", + "2020 立委不分區政黨票", + "2020-01-11", + "party_list", + ("2020總統立委/不分區政黨",), + 0.10, + ), +) + +_LOCAL_2018 = "2018-107年地方公職人員選舉" + +#: 較舊的選舉:只在 2018、2020 年劇本的資料包(--older)中使用,現有的資料包不受影響。 +#: 2016 年里的代碼約 2.7% 後來合併或改編,那些票數會列為孤兒代碼(見報告)。 +OLDER_ELECTIONS: tuple[ElectionDef, ...] = ( + ElectionDef( + "2018-mayor", + "2018 直轄市長、縣市長選舉", + "2018-11-24", + "mayor", + (f"{_LOCAL_2018}/直轄市市長", f"{_LOCAL_2018}/縣市市長"), + 0.20, + ), + ElectionDef( + "2018-councilor", + "2018 直轄市議員、縣市議員(區域)", + "2018-11-24", + "councilor", + (f"{_LOCAL_2018}/直轄市區域議員", f"{_LOCAL_2018}/縣市區域議員"), + 0.15, + ), + ElectionDef( + "2016-president", + "2016 總統副總統選舉", + "2016-01-16", + "president", + ("2016總統立委/總統",), + 0.25, + suffix="_P1", + ), + ElectionDef( + "2016-party-list", + "2016 立委不分區政黨票", + "2016-01-16", + "party_list", + ("2016總統立委/不分區政黨",), + 0.15, + suffix="_T4", + ), +) +ALL_ELECTIONS: tuple[ElectionDef, ...] = ELECTIONS + OLDER_ELECTIONS + +_LOCAL_2014 = "2014-103年地方公職人員選舉" +_LOCAL_2010 = "20101127-五都市長議員及里長" +_LOCAL_2009 = "20091205-縣市長縣市議員及鄉鎮長" + +#: 1995–2014 年的選舉:只在 2016 年以前劇本的資料包(--historic)中使用。 +#: 2014 年起的資料夾是內政部代碼;更早的是中選會流水號,用名稱對照(legacy_codes)。 +#: 「2010 縣市長」合併 2010-11-27 五都市長與 2009-12-05 其他縣市長,兩者合起來剛好是全台一輪。 +HISTORIC_ELECTIONS: tuple[ElectionDef, ...] = ( + ElectionDef( + "2014-mayor", + "2014 直轄市長、縣市長選舉", + "2014-11-29", + "mayor", + (f"{_LOCAL_2014}/直轄市市長", f"{_LOCAL_2014}/縣市市長"), + 0.20, + ), + ElectionDef( + "2014-councilor", + "2014 直轄市議員、縣市議員(區域)", + "2014-11-29", + "councilor", + (f"{_LOCAL_2014}/直轄市區域議員", f"{_LOCAL_2014}/縣市區域議員"), + 0.15, + ), + ElectionDef( + "2012-president", + "2012 總統副總統選舉", + "2012-01-14", + "president", + ("20120114-總統及立委/總統",), + 0.25, + legacy_codes=True, + ), + ElectionDef( + "2012-party-list", + "2012 立委不分區政黨票", + "2012-01-14", + "party_list", + ("20120114-總統及立委/不分區政黨",), + 0.15, + legacy_codes=True, + ), + ElectionDef( + "2010-mayor", + "2010 五都市長、2009 縣市長選舉", + "2010-11-27", + "mayor", + (f"{_LOCAL_2010}/市長", f"{_LOCAL_2009}/縣市長"), + 0.20, + legacy_codes=True, + ), + ElectionDef( + "2010-councilor", + "2010 五都議員、2009 縣市議員(區域)", + "2010-11-27", + "councilor", + (f"{_LOCAL_2010}/區域議員", f"{_LOCAL_2009}/區域議員"), + 0.15, + legacy_codes=True, + ), + ElectionDef( + "2008-president", + "2008 總統副總統選舉", + "2008-03-22", + "president", + ("20080322-總統",), + 0.25, + legacy_codes=True, + ), + ElectionDef( + "2008-party-list", + "2008 立委不分區政黨票", + "2008-01-12", + "party_list", + ("2008立委/不分區政黨",), + 0.15, + legacy_codes=True, + ), + # 2008 年以前:只放有村里小計的資料夾。1994 省長、1997 與 2001 縣市長只有縣市總數,不能拿來算村里的傾向。 + # 區域立委是單記不可讓渡投票(一區多席),各黨候選人得票加總當成政黨票的替代。 + ElectionDef( + "2006-mayor", + "2006 北高市長、2005 縣市長選舉", + "2006-12-09", + "mayor", + ("2006直轄市長", "2005縣市長"), + 0.20, + legacy_codes=True, + ), + ElectionDef( + "2004-president", + "2004 總統副總統選舉", + "2004-03-20", + "president", + ("2004 11任總統",), + 0.25, + legacy_codes=True, + ), + ElectionDef( + "2001-legislator", + "2001 立委(區域,第 5 屆)", + "2001-12-01", + "legislator", + ("5屆立委/區域",), + 0.15, + legacy_codes=True, + # 2004 年國民黨連戰與親民黨宋楚瑜搭檔參選(中選會 2004 年候選人檔:宋楚瑜是連戰的副手), + # 所以算 2004 劇本的政黨傾向時,親民黨的票算在國民黨一側 + blocs=(("親民黨", PARTY_B),), + ), + ElectionDef( + "2000-president", + "2000 總統副總統選舉", + "2000-03-18", + "president", + ("2000年10任總統",), + 0.25, + legacy_codes=True, + # 同上:2000 年宋楚瑜以連署(無黨籍)參選,2004 年是連戰的副手。無黨籍的票 98% 是宋楚瑜的 + # (另一位無黨籍許信良 0.6%),算傾向時併到國民黨一側 + blocs=((INDEPENDENT, PARTY_B),), + ), + ElectionDef( + "1998-legislator", + "1998 立委(區域,第 4 屆)", + "1998-12-05", + "legislator", + ("4屆立委/區域",), + 0.15, + legacy_codes=True, + ), + ElectionDef( + "1996-president", + "1996 總統副總統選舉", + "1996-03-23", + "president", + ("9任總統",), + 0.25, + legacy_codes=True, + ), + ElectionDef( + "1995-legislator", + "1995 立委(區域,第 3 屆)", + "1995-12-02", + "legislator", + ("3屆立委/區域",), + 0.15, + legacy_codes=True, + ), +) +#: 所有定義過的選舉(依 id 查詢用;資料包用哪些見 pack.build_pack) +EVERY_ELECTION: tuple[ElectionDef, ...] = ALL_ELECTIONS + HISTORIC_ELECTIONS + + +def election_by_id(election_id: str) -> ElectionDef: + for e in EVERY_ELECTION: + if e.id == election_id: + return e + raise KeyError(f"未定義的選舉:{election_id}") + + +@dataclass(frozen=True) +class VillageResult: + electors: int + ballots: int + valid: int + votes: Mapping[str, int] + allocated: bool = False + + def to_json(self) -> dict: + return { + "electors": self.electors, + "ballots": self.ballots, + "valid": self.valid, + "votes": dict(self.votes), + "allocated": self.allocated, + } + + +@dataclass(frozen=True) +class ElectionData: + election: ElectionDef + by_village: Mapping[str, VillageResult] + cec_valid_by_county: Mapping[str, int] + party_totals_by_county: Mapping[str, Mapping[str, int]] + skipped_rows: int = 0 + notes: tuple[str, ...] = field(default_factory=tuple) + + +#: 2008 年以前的 elpaty 裡表示「沒有政黨」的寫法:「無」,總統選舉的「連署」(公民連署參選) +_NO_PARTY_OLD = frozenset({"無", "連署"}) + + +def is_independent(name: str) -> bool: + return name.startswith("無黨籍") or "未經政黨推薦" in name or name in _NO_PARTY_OLD + + +def candidate_party(name: str) -> str | None: + """候選人的政黨名稱;無黨籍(含舊資料的「無」「連署」)回傳 None""" + return None if not name or is_independent(name) else name + + +def party_group(name: str) -> str: + if name in KEPT_PARTIES: + return name + if is_independent(name): + return INDEPENDENT + return OTHER + + +def _party_names(archive: CecArchive, folder: str) -> dict[str, str]: + return {row[0]: row[1] for row in archive.rows(folder, "elpaty") if len(row) >= 2} + + +def _candidate_parties( + archive: CecArchive, folder: str, suffix: str = "" +) -> dict[tuple[str, str, str, str], str]: + """(省市, 縣市, 選區, 號次) → 政黨群組。正副搭檔只取正手(副手欄為 Y 的略過)。""" + names = _party_names(archive, folder) + out: dict[tuple[str, str, str, str], str] = {} + for row in archive.rows(folder, "elcand" + suffix): + prv, city, district, number, party_code = row[0], row[1], row[2], row[5], row[7] + is_running_mate = len(row) > 15 and row[15] == "Y" + key = (prv, city, district, number) + if is_running_mate or key in out: + continue + out[key] = party_group(names.get(party_code, OTHER)) + return out + + +def _lookup_party(parties: Mapping[tuple[str, str, str, str], str], row: list[str]) -> str: + prv, city, district, number = row[0], row[1], row[2], row[6] + for key in ((prv, city, district, number), ("00", "000", district, number), (prv, city, "00", number)): + if key in parties: + return parties[key] + raise KeyError(f"找不到候選人政黨:{row[:7]}") + + +def _lookup_party_loose(parties: Mapping[tuple[str, str, str, str], str], row: list[str]) -> str | None: + """縣市總計列的選區欄不一定和候選人檔一致:同一縣市(或全國)同號次只有一個政黨時才算對到""" + try: + return _lookup_party(parties, row) + except KeyError: + found = { + party + for (prv, city, _, number), party in parties.items() + if number == row[6] and (prv, city) in {(row[0], row[1]), ("00", "000")} + } + return found.pop() if len(found) == 1 else None + + +def apportion(total: int, weights: list[float]) -> list[int]: + """最大餘數法:把整數 total 依權重分成整數,總和不變。權重全為 0 時平均分配。""" + if not weights: + return [] + w = [max(0.0, x) for x in weights] + s = sum(w) or float(len(w)) + w = w if sum(w) > 0 else [1.0] * len(w) + raw = [total * x / s for x in w] + base = [int(r) for r in raw] + remainder = total - sum(base) + order = sorted(range(len(raw)), key=lambda i: raw[i] - base[i], reverse=True) + for i in order[:remainder]: + base[i] += 1 + return base + + +def _cross_village_map( + archive: CecArchive, + folder: str, + village_names: Mapping[tuple[str, str], str] | None = None, + suffix: str = "", +) -> dict[tuple[str, str, str, str], list[str]]: + """跨村里代碼 → 涵蓋的 VILLCODE 清單。 + + 先用同一份 elbase 中有數字代碼的村里名稱對照;對不到時改用 village_names + ((鄉鎮代碼 8 碼, 村里名稱) → VILLCODE,通常來自戶政資料)。連江縣的村只出現在跨村里代碼中,需要後者。 + """ + by_name: dict[tuple[str, str], str] = dict(village_names or {}) + cross: dict[tuple[str, str, str, str], list[str]] = {} + rows = list(archive.rows(folder, "elbase" + suffix)) + for prv, city, _, town, village, name in (r[:6] for r in rows): + code = cec_village_code(prv, city, town, village) + if code: + by_name[(f"{prv}{city}{town}", normalize_name(name))] = code + for prv, city, _, town, village, name in (r[:6] for r in rows): + if not is_cross_village(village) or town == "000": + continue + town8 = f"{prv}{city}{town}" + if name.startswith("各里"): + # 例:「各里平地、山地原住民」——全區原住民選民的專屬投開票所,涵蓋該區所有村里 + codes = sorted({code for (t, _), code in by_name.items() if t == town8}) + else: + names = [normalize_name(n) for n in name.replace(",", "、").split("、") if n.strip()] + codes = [by_name[(town8, n)] for n in names if (town8, n) in by_name] + if codes: + cross[(prv, city, town, village)] = codes + else: + # 涵蓋的里都已合併或改名:票數記在鄉鎮層級(不分給現存的里,但總數和中選會一致) + cross[(prv, city, town, village)] = [town_residual_code(town8)] + log.warning( + "%s 的跨村里代碼 %s/%s/%s/%s 對不到任何村里,票數記在鄉鎮層級:%s", + folder, + prv, + city, + town, + village, + name, + ) + return cross + + +@dataclass(frozen=True) +class _Places: + """一個資料夾的代碼解讀:中選會的 (省市, 縣市) → 縣市代碼;村里小計列 → VILLCODE 清單""" + + counties: Mapping[tuple[str, str], str] | None + villages: Mapping[tuple[str, str, str, str], Sequence[str]] + #: 舊資料夾才有:(省市, 縣市, 鄉鎮) → 目前的鄉鎮代碼;(省市, 縣市, 村里流水號) → VILLCODE + towns: Mapping[tuple[str, str, str], str] | None = None + by_number: Mapping[tuple[str, str, str], Sequence[str]] | None = None + + def county(self, row: list[str]) -> str | None: + if self.counties is None: + return county_code(row[0], row[1]) + return self.counties.get((row[0], row[1])) + + def targets(self, row: list[str]) -> list[str] | None: + key = (row[0], row[1], row[3], row[4]) + if self.towns is not None: + found = self.villages.get(key) or (self.by_number or {}).get((key[0], key[1], key[3])) + if found: + return list(found) + # 開票列有、elbase 沒列出的村里(2008 年有幾筆):只知道鄉鎮 + town8 = self.towns.get(key[:3]) + return [town_residual_code(town8)] if town8 else None + code = cec_village_code(row[0], row[1], row[3], row[4]) + if code: + return [code] + found = self.villages.get(key) + return list(found) if found else None + + +def _places( + archive: CecArchive, + folder: str, + election: ElectionDef, + village_names: Mapping[tuple[str, str], str] | None, + gazetteer: Gazetteer | None, +) -> _Places: + if not election.legacy_codes: + return _Places(None, _cross_village_map(archive, folder, village_names, election.suffix)) + if gazetteer is None: + raise ValueError(f"{election.id} 是 2014 年以前的資料(中選會流水號代碼),需要 gazetteer 用名稱對照") + legacy = legacy_places(archive, folder, gazetteer, election.suffix) + return _Places(legacy.counties, legacy.villages, legacy.towns, legacy.by_number) + + +def is_subtotal_box(tbox: str) -> bool: + """投開票所欄為 0 表示小計列;2020 年起寫成 0000,2016、2018 年寫成 0""" + return tbox.strip("0") == "" + + +def _is_village_subtotal(row: list[str]) -> bool: + return row[3] != "000" and row[4] != "0000" and is_subtotal_box(row[5]) + + +def _is_county_total(row: list[str]) -> bool: + return row[3] == "000" and row[4] == "0000" and is_subtotal_box(row[5]) + + +def _by_district[T](rows: Mapping[str, T]) -> list[T]: + """縣市總計列:有選區 00 的那一列就用它,否則各選區相加""" + return [rows["00"]] if "00" in rows else list(rows.values()) + + +@dataclass +class _LegacyTotals: + """舊資料夾的縣市總計列,鍵是 (目前的縣市代碼, 中選會的省市+縣市),再依選區分開。 + + 村里列有缺漏時(例如 2004 年臺中市西區有幾個里只有投票概況、沒有得票列),差額記到 + 「縣市代碼+000000」:只算進總數,不分給任何村里。舊資料的鄉鎮小計列有錯置(2004 年桃園縣),不拿來用。 + """ + + votes: dict[tuple[str, str], dict[str, dict[str, int]]] = field( + default_factory=lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(int))) + ) + prof: dict[tuple[str, str], dict[str, tuple[int, int, int]]] = field( + default_factory=lambda: defaultdict(dict) + ) + + def reconcile( + self, + votes: dict[str, dict[str, int]], + prof: dict[str, tuple[int, int, int]], + party_totals: dict[str, dict[str, int]], + ) -> set[str]: + filled: set[str] = set() + + def add_prof(code: str, e: int, b: int, v: int) -> None: + prev = prof.get(code, (0, 0, 0)) + prof[code] = (prev[0] + e, prev[1] + b, prev[2] + v) + + # 只有投票概況、沒有得票列的村里:投票概況也移到縣市層級,和得票的差額放在一起 + for code in [c for c in prof if c not in votes]: + add_prof(county_residual_code(code[:5]), *prof.pop(code)) + filled.add(code[:5]) + target_votes: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) + for (cc, _), by_district in self.votes.items(): + for row in _by_district(by_district): + for party, n in row.items(): + target_votes[cc][party] += n + have_votes: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) + for code, row in votes.items(): + for party, n in row.items(): + have_votes[code[:5]][party] += n + for cc, row in target_votes.items(): + for party, n in row.items(): + short = n - have_votes[cc].get(party, 0) + if short > 0: + votes[county_residual_code(cc)][party] += short + party_totals[cc][party] += short + filled.add(cc) + target_prof: dict[str, list[int]] = defaultdict(lambda: [0, 0, 0]) + for (cc, _), by_district in self.prof.items(): + for row in _by_district(by_district): + target_prof[cc] = [a + b for a, b in zip(target_prof[cc], row, strict=True)] + have_prof: dict[str, list[int]] = defaultdict(lambda: [0, 0, 0]) + for code, row in prof.items(): + have_prof[code[:5]] = [a + b for a, b in zip(have_prof[code[:5]], row, strict=True)] + for cc, row in target_prof.items(): + short = [max(0, t - h) for t, h in zip(row, have_prof[cc], strict=True)] + if any(short): + add_prof(county_residual_code(cc), *short) + filled.add(cc) + return filled + + +def load_election( + archive: CecArchive, + election: ElectionDef, + county: str | None = None, + weights: Mapping[str, float] | None = None, + village_names: Mapping[tuple[str, str], str] | None = None, + by_candidate: bool = False, + gazetteer: Gazetteer | None = None, +) -> ElectionData: + """weights:跨村里投開票所分配用的村里權重(建議用成年人口);沒有提供時平均分配。 + village_names:跨村里名稱對照的備援,見 _cross_village_map。 + by_candidate:得票改以候選人號次(例如 "#3")為鍵,而不是政黨;同一選區有多位無黨籍時用得到。 + gazetteer:2014 年以前的資料夾(legacy_codes)一定要有,用名稱對到村里代碼(legacy.py)。""" + votes: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) + prof: dict[str, tuple[int, int, int]] = {} + cec_valid: dict[str, int] = defaultdict(int) + # (資料夾, 中選會縣市代碼) → 目前的縣市代碼與各選區的有效票;舊縣市可能兩個併成一個(臺中縣+臺中市) + county_rows_by_district: dict[tuple[str, str, str], dict[str, int]] = defaultdict(dict) + party_totals: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) + allocated: set[str] = set() + skipped = 0 + + def split(total: int, codes: list[str]) -> list[int]: + return apportion(total, [weights.get(c, 0.0) if weights else 1.0 for c in codes]) + + legacy_totals: _LegacyTotals | None = None + for folder in election.folders: + parties = _candidate_parties(archive, folder, election.suffix) + places = _places(archive, folder, election, village_names, gazetteer) + if places.towns is not None: + legacy_totals = legacy_totals or _LegacyTotals() + for row in archive.rows(folder, "elctks" + election.suffix): + village_row = _is_village_subtotal(row) + if not (village_row or (legacy_totals and places.towns is not None and _is_county_total(row))): + continue + cc = places.county(row) + if county is not None and cc != county: + continue + if not village_row: + # 舊資料夾的縣市總計列(核對用);全國列不用 + party = f"#{row[6]}" if by_candidate else _lookup_party_loose(parties, row) + if cc and cc != "00000" and party and legacy_totals: + legacy_totals.votes[(cc, row[0] + row[1])][row[2]][party] += int(row[7]) + continue + codes = places.targets(row) if cc else None + if not codes: + skipped += 1 + continue + party = f"#{row[6]}" if by_candidate else _lookup_party(parties, row) + for code, n in zip(codes, split(int(row[7]), codes), strict=True): + votes[code][party] += n + party_totals[cc][party] += int(row[7]) + if len(codes) > 1: + allocated.update(codes) + for row in archive.rows(folder, "elprof" + election.suffix): + cc = places.county(row) + if cc is None or (county is not None and cc != county): + continue + valid, ballots, electors = int(row[6]), int(row[8]), int(row[9]) + if _is_village_subtotal(row): + codes = places.targets(row) + if not codes: + continue + parts = zip( + codes, split(electors, codes), split(ballots, codes), split(valid, codes), strict=True + ) + for code, e, b, v in parts: + prev = prof.get(code, (0, 0, 0)) + # 多席次選舉一個村里只屬於一個選區,所以不會重複加總 + prof[code] = (prev[0] + e, prev[1] + b, prev[2] + v) + elif _is_county_total(row): + # 依資料夾分開記錄:2022 年直轄市、縣市各有一個資料夾,各自都有一列「全國」 + county_rows_by_district[(folder, county_code(row[0], row[1]), cc)][row[2]] = valid + if legacy_totals and places.towns is not None and cc != "00000": + legacy_totals.prof[(cc, row[0] + row[1])][row[2]] = (electors, ballots, valid) + if legacy_totals: + filled = legacy_totals.reconcile(votes, prof, party_totals) + if filled: + log.info("%s:%d 個縣市的村里列少於縣市總計,差額記在縣市層級", election.id, len(filled)) + for (_, _, cc), by_district in county_rows_by_district.items(): + cec_valid[cc] += by_district.get("00", sum(by_district.values())) + notes: list[str] = [] + if skipped: + notes.append(f"略過 {skipped} 列跨村里或無法轉換代碼的得票") + log.warning("%s:略過 %d 列無法轉換為村里代碼的得票", election.id, skipped) + if allocated: + notes.append(f"{len(allocated)} 個村里含有依權重分配的跨村里投開票所票數") + by_village = { + code: VillageResult( + electors=prof.get(code, (0, 0, 0))[0], + ballots=prof.get(code, (0, 0, 0))[1], + valid=prof.get(code, (0, 0, 0))[2], + votes=dict(v), + allocated=code in allocated, + ) + for code, v in votes.items() + } + log.info("%s:%d 個村里", election.id, len(by_village)) + return ElectionData( + election, + by_village, + dict(cec_valid), + {k: dict(v) for k, v in party_totals.items()}, + skipped, + tuple(notes), + ) + + +def load_all( + archive: CecArchive, + county: str | None = None, + elections: Iterable[ElectionDef] = ELECTIONS, + weights: Mapping[str, float] | None = None, + village_names: Mapping[tuple[str, str], str] | None = None, + gazetteer: Gazetteer | None = None, +) -> list[ElectionData]: + return [load_election(archive, e, county, weights, village_names, gazetteer=gazetteer) for e in elections] diff --git a/backend/data/pipeline/src/election_data/fetch.py b/backend/data/pipeline/src/election_data/fetch.py new file mode 100644 index 0000000..6a33019 --- /dev/null +++ b/backend/data/pipeline/src/election_data/fetch.py @@ -0,0 +1,188 @@ +"""下載與快取。每個下載檔旁邊有一份 `.meta.json`,記錄網址、時間、SHA-256、TLS 是否驗證。""" + +from __future__ import annotations + +import hashlib +import json +import logging +import re +import ssl +import time +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import UTC, datetime +from functools import cache +from pathlib import Path +from urllib.parse import urlencode, urlsplit + +import certifi +import httpx + +from .config import UNVERIFIED_TLS_HOSTS + +log = logging.getLogger(__name__) + +USER_AGENT = "election-2026-data-pipeline/0.1 (+research; contact via repository)" + + +@dataclass(frozen=True) +class FetchResult: + path: Path + url: str + retrieved_at: str + sha256: str + tls_verified: bool + from_cache: bool + + +def _meta_path(dest: Path) -> Path: + return dest.with_name(dest.name + ".meta.json") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _is_tls_error(exc: Exception) -> bool: + cause: BaseException | None = exc + while cause is not None: + if isinstance(cause, ssl.SSLError): + return True + cause = cause.__cause__ or cause.__context__ + return "CERTIFICATE_VERIFY_FAILED" in str(exc) + + +@cache +def _ssl_context() -> ssl.SSLContext: + """仍然驗證憑證鏈與主機名稱,但關掉 Python 3.13 起預設的 X509 嚴格模式: + 多個政府網站的憑證缺少 Subject Key Identifier,嚴格模式會直接拒絕。""" + ctx = ssl.create_default_context(cafile=certifi.where()) + ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT + return ctx + + +def _stream_to(url: str, tmp: Path, verify: bool, timeout: float) -> None: + with ( + httpx.Client( + verify=_ssl_context() if verify else False, + timeout=timeout, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + ) as client, + client.stream("GET", url) as resp, + ): + resp.raise_for_status() + with tmp.open("wb") as fh: + for chunk in resp.iter_bytes(1 << 16): + fh.write(chunk) + + +def _cached(dest: Path) -> FetchResult | None: + meta_file = _meta_path(dest) + if dest.exists() and meta_file.exists(): + meta = json.loads(meta_file.read_text(encoding="utf-8")) + return FetchResult(dest, meta["url"], meta["retrievedAt"], meta["sha256"], meta["tlsVerified"], True) + return None + + +def _finish( + dest: Path, tmp: Path, url: str, verify: bool, extra: Mapping[str, str] | None = None +) -> FetchResult: + tmp.replace(dest) + retrieved_at = datetime.now(UTC).date().isoformat() + sha = _sha256(dest) + meta = { + "url": url, + **(extra or {}), + "retrievedAt": retrieved_at, + "sha256": sha, + "tlsVerified": verify, + "bytes": dest.stat().st_size, + } + _meta_path(dest).write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8") + log.info("已下載 %s(%d bytes)", dest.name, meta["bytes"]) + return FetchResult(dest, url, retrieved_at, sha, verify, False) + + +def download(url: str, dest: Path, *, timeout: float = 180.0, retries: int = 3) -> FetchResult: + """下載到 dest;若已有快取(檔案與 meta 都在)就直接回傳。""" + if cached := _cached(dest): + return cached + + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(dest.name + ".part") + host = urlsplit(url).hostname or "" + verify = True + last_error: Exception | None = None + for attempt in range(1, retries + 1): + try: + _stream_to(url, tmp, verify, timeout) + break + except Exception as exc: # noqa: BLE001 - 需要判斷各種網路錯誤 + last_error = exc + if verify and _is_tls_error(exc) and host in UNVERIFIED_TLS_HOSTS: + log.warning("TLS 驗證失敗,%s 在允許清單中,改用不驗證的連線並記錄。", host) + verify = False + continue + log.warning("下載失敗(第 %d 次):%s:%s", attempt, url, exc) + time.sleep(2 * attempt) + else: + raise RuntimeError(f"下載失敗:{url}") from last_error + return _finish(dest, tmp, url, verify) + + +_CSRF = re.compile(r' None: + with httpx.Client( + verify=_ssl_context(), timeout=timeout, follow_redirects=True, headers={"User-Agent": USER_AGENT} + ) as client: + page = client.get(page_url) + page.raise_for_status() + token = _CSRF.search(page.text) + data = {**form, **({"_csrf": token.group(1)} if token else {})} + resp = client.post(url, data=data, headers={"Referer": page_url}) + resp.raise_for_status() + if "html" in resp.headers.get("content-type", ""): + raise RuntimeError("回應是網頁而不是檔案(可能是參數錯誤或被網站擋下)") + tmp.write_bytes(resp.content) + + +def download_form( + page_url: str, + url: str, + dest: Path, + form: Mapping[str, str], + *, + timeout: float = 180.0, + retries: int = 3, +) -> FetchResult: + """先開 page_url 取得 cookie 與 CSRF token(),再把表單 POST 到 url 下載檔案。 + 戶政司「人口統計資料」的下載頁是這種做法。快取規則同 download;meta 的網址附上表單參數。""" + if cached := _cached(dest): + return cached + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(dest.name + ".part") + last_error: Exception | None = None + for attempt in range(1, retries + 1): + try: + _post_form(page_url, url, form, tmp, timeout) + break + except Exception as exc: # noqa: BLE001 - 需要判斷各種網路錯誤 + last_error = exc + log.warning("下載失敗(第 %d 次):%s:%s", attempt, url, exc) + time.sleep(2 * attempt) + else: + raise RuntimeError(f"下載失敗:{url}") from last_error + return _finish(dest, tmp, f"{url}?{urlencode(form)}", True, {"method": "POST", "page": page_url}) + + +def fetch_json(url: str, dest: Path, **kwargs: float) -> tuple[dict, FetchResult]: + """下載 JSON 並解析;快取規則同 download。""" + result = download(url, dest, **kwargs) + return json.loads(result.path.read_text(encoding="utf-8")), result diff --git a/backend/data/pipeline/src/election_data/genders.py b/backend/data/pipeline/src/election_data/genders.py new file mode 100644 index 0000000..afa7a15 --- /dev/null +++ b/backend/data/pipeline/src/election_data/genders.py @@ -0,0 +1,58 @@ +"""候選人性別(給遊戲裡的 Q 版頭像挑男女用)。 + +來源是中選會選舉資料庫 votedata.zip 每個選舉的 elcand.csv:第 9 欄性別(1 男、2 女)。 +同名的人取最近一次選舉的資料。只輸出「姓名 → m/f」,不輸出生日、學歷等個資。 +執行:python -m election_data.genders +""" + +from __future__ import annotations + +import csv +import io +import json +import logging +import re +import zipfile +from pathlib import Path + +from .cec import VOTEDATA_PATH, _decode_name +from .config import BUILD_DIR + +OUT = BUILD_DIR / "people" / "genders.json" +#: 中選會檔案用私用區字元表示的罕用字 +PUA = {"": "聰"} + + +def _year(path: str) -> int: + m = re.search(r"(\d{4})", path) + return int(m.group(1)) if m else 0 + + +def build_genders(archive: Path = VOTEDATA_PATH, out: Path = OUT) -> Path: + found: dict[str, tuple[int, str]] = {} + with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = _decode_name(info) + if not name.endswith("elcand.csv"): + continue + year = _year(name) + text = z.read(info).decode("utf-8-sig", errors="replace") + for row in csv.reader(io.StringIO(text)): + if len(row) < 9: + continue + person = "".join(PUA.get(ch, ch) for ch in row[6].strip()) + sex = {"1": "m", "2": "f"}.get(row[8].strip()) + if not person or not sex: + continue + if person not in found or found[person][0] <= year: + found[person] = (year, sex) + out.parent.mkdir(parents=True, exist_ok=True) + data = {k: v[1] for k, v in sorted(found.items())} + out.write_text(json.dumps(data, ensure_ascii=False, indent=0), encoding="utf-8") + logging.getLogger(__name__).info("%d 位候選人的性別 → %s", len(data), out) + return out + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(message)s") + build_genders() diff --git a/backend/data/pipeline/src/election_data/geo.py b/backend/data/pipeline/src/election_data/geo.py new file mode 100644 index 0000000..314c65c --- /dev/null +++ b/backend/data/pipeline/src/election_data/geo.py @@ -0,0 +1,144 @@ +"""村里界圖:讀取、面積、點落多邊形、輸出 TopoJSON(以 mapshaper 簡化)。""" + +from __future__ import annotations + +import io +import json +import logging +import math +import subprocess +import zipfile +from collections import defaultdict +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import shapefile +import shapely +from shapely import STRtree, points +from shapely.geometry import mapping, shape +from shapely.geometry.base import BaseGeometry +from shapely.ops import unary_union + +from .config import BOUNDARY_VERSION, RAW_DIR, REPO_ROOT +from .fetch import FetchResult, download + +log = logging.getLogger(__name__) + +VILLAGE_ZIP_URL = "https://www.tgos.tw/tgos/VirtualDir/Product/a04697c8-64db-450a-a105-3eb471c45abd/村(里)界(TWD97經緯度).zip" +_SHP_STEM = f"VILLAGE_NLSC_{BOUNDARY_VERSION}" +_M_PER_DEG_LAT = 110_574.0 +_M_PER_DEG_LON_EQ = 111_320.0 + + +@dataclass(frozen=True) +class VillageShape: + code: str + name: str + town_code: str + town_name: str + county_code: str + county_name: str + geometry: BaseGeometry + + +def fetch_boundaries() -> FetchResult: + return download(VILLAGE_ZIP_URL, RAW_DIR / "nlsc" / f"village_{BOUNDARY_VERSION}.zip", timeout=600) + + +def load_villages(zip_path: Path, county_code: str | None = None) -> list[VillageShape]: + """同一個村里代碼有多個多邊形時合併成一個。""" + with zipfile.ZipFile(zip_path) as zf: + reader = shapefile.Reader( + shp=io.BytesIO(zf.read(f"{_SHP_STEM}.shp")), + shx=io.BytesIO(zf.read(f"{_SHP_STEM}.shx")), + dbf=io.BytesIO(zf.read(f"{_SHP_STEM}.dbf")), + encoding="utf-8", + ) + parts: dict[str, list[BaseGeometry]] = defaultdict(list) + attrs: dict[str, tuple[str, str, str, str, str]] = {} + for sr in reader.iterShapeRecords(): + rec = sr.record + if county_code and rec["COUNTYCODE"] != county_code: + continue + code = rec["VILLCODE"] + parts[code].append(shape(sr.shape.__geo_interface__)) + attrs[code] = ( + rec["VILLNAME"], + rec["TOWNCODE"], + rec["TOWNNAME"], + rec["COUNTYCODE"], + rec["COUNTYNAME"], + ) + out = [ + VillageShape(code, *attrs[code], unary_union(geoms) if len(geoms) > 1 else geoms[0]) + for code, geoms in parts.items() + ] + log.info("村里界圖:%d 個村里", len(out)) + return sorted(out, key=lambda v: v.code) + + +def area_km2(geom: BaseGeometry) -> float: + """以多邊形中心緯度做等距投影計算面積,村里尺度誤差遠小於 1%。""" + lat0 = geom.centroid.y + scale = np.array([_M_PER_DEG_LON_EQ * math.cos(math.radians(lat0)), _M_PER_DEG_LAT]) + return shapely.transform(geom, lambda coords: coords * scale).area / 1_000_000 + + +def count_points_in( + villages: Sequence[VillageShape], lon_lat: Iterable[tuple[float, float]] +) -> dict[str, int]: + """每個村里內的點數(寺廟、教會)。""" + coords = np.array(list(lon_lat), dtype=float) + counts: dict[str, int] = {v.code: 0 for v in villages} + if coords.size == 0: + return counts + tree = STRtree([v.geometry for v in villages]) + pt_idx, poly_idx = tree.query(points(coords), predicate="within") + seen: set[int] = set() + for p, g in zip(pt_idx.tolist(), poly_idx.tolist(), strict=True): + if p in seen: # 落在邊界上的點只算一次 + continue + seen.add(p) + counts[villages[g].code] += 1 + return counts + + +def write_topology(villages: Sequence[VillageShape], out_file: Path, simplify: str = "6%") -> None: + """輸出兩個圖層:villages(村里)與 towns(由村里合併的鄉鎮市區)。""" + out_file.parent.mkdir(parents=True, exist_ok=True) + geojson = out_file.with_suffix(".src.geojson") + features = [ + { + "type": "Feature", + "properties": {"code": v.code, "name": v.name, "townCode": v.town_code, "townName": v.town_name}, + "geometry": mapping(v.geometry), + } + for v in villages + ] + geojson.write_text(json.dumps({"type": "FeatureCollection", "features": features}, ensure_ascii=False)) + cmd = [ + "pnpm", + "exec", + "mapshaper", + "-i", + str(geojson), + "name=villages", + "-simplify", + simplify, + "keep-shapes", + "-dissolve", + "townCode", + "copy-fields=townName", + "+", + "name=towns", + "-o", + str(out_file), + "format=topojson", + "target=*", + "quantization=100000", + ] + subprocess.run(cmd, cwd=REPO_ROOT, check=True, capture_output=True, text=True) + geojson.unlink() + log.info("已輸出地圖 %s(%d KB)", out_file.name, out_file.stat().st_size // 1024) diff --git a/backend/data/pipeline/src/election_data/impute.py b/backend/data/pipeline/src/election_data/impute.py new file mode 100644 index 0000000..9d220ab --- /dev/null +++ b/backend/data/pipeline/src/election_data/impute.py @@ -0,0 +1,65 @@ +"""缺值補值:新設的里沒有歷史得票、所得等資料時,依序用相鄰的里、同鄉鎮、全縣市的加權平均。 + +每一筆補值都會在村里旗標中註明來源(docs/10:資料不足時要標示,不默默填值)。 +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass + +import numpy as np +from shapely import STRtree + +from .geo import VillageShape + +_TOUCH_BUFFER_DEG = 1e-4 # 約 10 公尺,容許界線的微小縫隙 + + +@dataclass(frozen=True) +class Imputed[T]: + value: T + source: str # "neighbors" | "town" | "county" + + +class NeighborIndex: + def __init__(self, shapes: Sequence[VillageShape]) -> None: + self._shapes = list(shapes) + self._tree = STRtree([s.geometry for s in self._shapes]) + self._by_code = {s.code: i for i, s in enumerate(self._shapes)} + + def neighbors(self, code: str) -> list[str]: + idx = self._by_code.get(code) + if idx is None: + return [] + geom = self._shapes[idx].geometry.buffer(_TOUCH_BUFFER_DEG) + hits = self._tree.query(geom, predicate="intersects") + return [self._shapes[i].code for i in hits.tolist() if i != idx] + + +def _weighted(values: Sequence[np.ndarray], weights: Sequence[float]) -> np.ndarray | None: + w = np.array(weights, dtype=float) + if not values or w.sum() <= 0: + return None + return (np.array(values) * w[:, None]).sum(axis=0) / w.sum() + + +def impute( + code: str, + known: Mapping[str, np.ndarray], + weights: Mapping[str, float], + index: NeighborIndex, + same_town: Callable[[str], Sequence[str]], + same_county: Sequence[str], +) -> Imputed[np.ndarray] | None: + """known:已有值的村里(向量);weights:加權用(成年人口)。""" + for source, pool in ( + ("neighbors", index.neighbors(code)), + ("town", same_town(code)), + ("county", same_county), + ): + candidates = [c for c in pool if c in known and c != code] + mean = _weighted([known[c] for c in candidates], [weights.get(c, 0.0) for c in candidates]) + if mean is not None: + return Imputed(mean, source) + return None diff --git a/backend/data/pipeline/src/election_data/lean.py b/backend/data/pipeline/src/election_data/lean.py new file mode 100644 index 0000000..d570845 --- /dev/null +++ b/backend/data/pipeline/src/election_data/lean.py @@ -0,0 +1,112 @@ +"""把歷屆得票轉成 6 種政黨傾向的比例,並計算基本投票率(docs/03、docs/10)。 + +參數是初始值,M1 用歷史回測校準。換算方式: +- 甲、乙兩大黨:多屆加權平均得票率 m,波動越大,核心比例越低。 + 核心 = m × c;非核心部分再分成「傾向」與「中間」。 +- 第三勢力:大多算「傾向」,一部分算「中間」。 +- 無黨籍、小黨的票算「中間」。 +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass + +from .elections import PARTY_A, PARTY_B, PARTY_C + +LEAN_KEYS = ("a_core", "a_lean", "middle", "b_lean", "b_core", "c_lean") + + +@dataclass(frozen=True) +class LeanParams: + core_fraction: float = 0.65 + volatility_penalty: float = 2.0 + core_min: float = 0.40 + core_max: float = 0.80 + noncore_to_middle: float = 0.30 + third_to_middle: float = 0.20 + + def to_json(self) -> dict[str, float]: + return asdict(self) + + +@dataclass(frozen=True) +class Observation: + """某個村里在某次選舉的結果。""" + + weight: float + valid: int + ballots: int + electors: int + votes: Mapping[str, int] + contested: frozenset[str] # 這次選舉在該縣市有推出候選人的政黨 + + +def _weighted_mean_std(pairs: Sequence[tuple[float, float]]) -> tuple[float, float]: + total = sum(w for w, _ in pairs) + if total <= 0: + return 0.0, 0.0 + mean = sum(w * x for w, x in pairs) / total + var = sum(w * (x - mean) ** 2 for w, x in pairs) / total + return mean, math.sqrt(var) + + +def party_mean_shares(observations: Sequence[Observation]) -> dict[str, tuple[float, float]]: + """每個政黨的加權平均得票率與標準差,只用該黨有參選的選舉。""" + out: dict[str, tuple[float, float]] = {} + for party in (PARTY_A, PARTY_B, PARTY_C): + pairs = [ + (o.weight, o.votes.get(party, 0) / o.valid) + for o in observations + if o.valid > 0 and party in o.contested + ] + out[party] = _weighted_mean_std(pairs) + return out + + +def lean_shares( + observations: Sequence[Observation], params: LeanParams | None = None +) -> dict[str, float] | None: + params = params or LeanParams() + if not any(o.valid > 0 for o in observations): + return None + stats = party_mean_shares(observations) + m_a, v_a = stats[PARTY_A] + m_b, v_b = stats[PARTY_B] + m_c, _ = stats[PARTY_C] + total = m_a + m_b + m_c + if total > 1: + m_a, m_b, m_c = m_a / total, m_b / total, m_c / total + m_other = max(0.0, 1.0 - (m_a + m_b + m_c)) + + def split(mean: float, vol: float) -> tuple[float, float, float]: + core_frac = min( + params.core_max, max(params.core_min, params.core_fraction - params.volatility_penalty * vol) + ) + core = mean * core_frac + noncore = mean - core + return core, noncore * (1 - params.noncore_to_middle), noncore * params.noncore_to_middle + + a_core, a_lean, a_mid = split(m_a, v_a) + b_core, b_lean, b_mid = split(m_b, v_b) + c_lean = m_c * (1 - params.third_to_middle) + middle = a_mid + b_mid + m_c * params.third_to_middle + m_other + shares = { + "a_core": a_core, + "a_lean": a_lean, + "middle": middle, + "b_lean": b_lean, + "b_core": b_core, + "c_lean": c_lean, + } + norm = sum(shares.values()) + return {k: v / norm for k, v in shares.items()} + + +def base_turnout(observations: Sequence[Observation]) -> float | None: + pairs = [(o.weight, o.ballots / o.electors) for o in observations if o.electors > 0] + if not pairs: + return None + mean, _ = _weighted_mean_std(pairs) + return min(1.0, mean) diff --git a/backend/data/pipeline/src/election_data/legacy.py b/backend/data/pipeline/src/election_data/legacy.py new file mode 100644 index 0000000..83448d5 --- /dev/null +++ b/backend/data/pipeline/src/election_data/legacy.py @@ -0,0 +1,198 @@ +"""2014 年以前的中選會資料:代碼是中選會自己的流水號,不是內政部的行政區代碼。 + +例如 2012 年新北市是 02/000、2008 年臺北縣是 03/001,鄉鎮與村里段也是流水號, +所以只能用「縣市+鄉鎮市區+村里」的名稱對到目前的村里代碼(VILLCODE): + +- 縣市:名稱對到目前的縣市代碼,改制前的舊縣市也算(臺北縣 → 新北市,見 codes.COUNTY_CODE_BY_NAME)。 +- 鄉鎮市區:去掉最後一個字(市、鎮、鄉、區)比對,例如「板橋市」對到「板橋區」;目前的鄉鎮優先。 +- 村里:去掉最後的「村」「里」比對;常見的異體字(舘/館、脚/腳……)先統一。 + 目前的名稱裡有私用區字元(罕用字)時,那個字當萬用字元,同一個鄉鎮裡只有一個符合才算對到。 +- 目前的名稱優先,對不到再找 2018 年以後各時點的戶政名稱(之後合併的舊里會對到舊代碼,列為孤兒代碼)。 +- 還是對不到的里(多半是 2018 年以前就合併或改名),票數記在「鄉鎮代碼+000」: + 只知道在哪個鄉鎮,不分配給任何現存的里,但各縣市總數仍然和中選會一致。 +""" + +from __future__ import annotations + +import logging +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field + +from .cec import CecArchive +from .codes import COUNTY_CODE_BY_NAME, normalize_name, town_residual_code +from .config import POPULATION_MONTH_ROC +from .population import VillagePopulation, load_population + +log = logging.getLogger(__name__) + +NATIONAL = "00000" +#: 地名對照用的戶政資料時點:村里人口開放資料最早是 107 年 1 月,再加上 2018–2024 年各次選舉前後 +GAZETTEER_MONTHS = ("10701", "10710", "10911", "11212") +_TOWN_SUFFIX = "市鎮鄉區" +_VILLAGE_SUFFIX = "村里" +#: 合併或改名、名稱對不上的舊鄉鎮:(當年的縣市名稱, 舊名稱去尾字) → 目前的鄉鎮名稱。 +#: 要用當年的縣市名稱分辨:舊臺南市的中區、西區在 2004 年合併成中西區(臺中市的中區、西區還在); +#: 高雄縣三民鄉後來改名那瑪夏,縣市合併後不能和高雄市三民區搞混。 +TOWN_ALIASES = {("臺南市", "中"): "中西區", ("臺南市", "西"): "中西區", ("高雄縣", "三民"): "那瑪夏區"} +#: 同一個字在不同年份的寫法(舊資料 → 目前戶政資料的寫法不一定,兩邊都統一成右邊) +_VARIANTS = str.maketrans({"舘": "館", "脚": "腳", "槺": "糠", "壳": "殼", "峯": "峰"}) + + +def _is_private_use(ch: str) -> bool: + return 0xE000 <= ord(ch) <= 0xF8FF or 0xF0000 <= ord(ch) <= 0x10FFFD + + +def stem(name: str, suffixes: str) -> str: + """比對用的名稱:統一寫法後去掉最後一個表示層級的字(「板橋市」→「板橋」、「三芝村」→「三芝」)""" + text = normalize_name(name).translate(_VARIANTS) + return text[:-1] if len(text) >= 2 and text[-1] in suffixes else text + + +@dataclass(frozen=True) +class Gazetteer: + """地名對照表,由戶政司各時點的村里名單組成。 + + towns:縣市代碼 → 鄉鎮名稱(去尾字)→ 鄉鎮代碼(目前的排前面) + villages:鄉鎮代碼 → 村里名稱(去尾字)→ 村里代碼(目前的名稱優先) + """ + + towns: Mapping[str, Mapping[str, tuple[str, ...]]] + villages: Mapping[str, Mapping[str, str]] + current_towns: frozenset[str] + + @classmethod + def from_snapshots(cls, snapshots: Sequence[Iterable[VillagePopulation]]) -> Gazetteer: + """snapshots 由舊到新排列,最後一份是目前的戶政資料(越新越優先)""" + towns: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list)) + villages: dict[str, dict[str, str]] = defaultdict(dict) + current: set[str] = set() + for i, snapshot in enumerate(snapshots): + is_current = i == len(snapshots) - 1 + for p in snapshot: + town8 = p.code[:8] + if is_current: + current.add(town8) + names = towns[p.code[:5]][stem(p.site[3:], _TOWN_SUFFIX)] + if town8 not in names: + names.append(town8) + villages[town8][stem(p.village, _VILLAGE_SUFFIX)] = p.code + frozen_towns = { + county: { + key: tuple(sorted(codes, key=lambda c: (c not in current, c))) + for key, codes in by_stem.items() + } + for county, by_stem in towns.items() + } + return cls(frozen_towns, {k: dict(v) for k, v in villages.items()}, frozenset(current)) + + def town(self, county: str, name: str, old_county: str = "") -> str | None: + """舊鄉鎮名稱 → 鄉鎮代碼;同名的目前鄉鎮只有一個時才算對到。old_county:當年的縣市名稱""" + key = stem(name, _TOWN_SUFFIX) + alias = TOWN_ALIASES.get((normalize_name(old_county), key)) + if alias: + key = stem(alias, _TOWN_SUFFIX) + found = self.towns.get(county, {}).get(key, ()) + current = [c for c in found if c in self.current_towns] + pool = current or list(found) + return pool[0] if len(pool) == 1 else None + + def village(self, town8: str, name: str) -> str | None: + by_stem = self.villages.get(town8, {}) + key = stem(name, _VILLAGE_SUFFIX) + if key in by_stem: + return by_stem[key] + # 目前的名稱有私用區字元:那個字當萬用字元 + hits = [ + code + for known, code in by_stem.items() + if len(known) == len(key) + and any(_is_private_use(ch) for ch in known) + and all(a == b or _is_private_use(a) for a, b in zip(known, key, strict=True)) + ] + return hits[0] if len(set(hits)) == 1 else None + + def all_villages(self, town8: str) -> list[str]: + return sorted({c for c in self.villages.get(town8, {}).values() if c[:8] == town8}) + + +def load_gazetteer(months: Sequence[str] = GAZETTEER_MONTHS) -> Gazetteer: + snapshots = [load_population(m)[0] for m in months] + return Gazetteer.from_snapshots([*snapshots, load_population(POPULATION_MONTH_ROC)[0]]) + + +@dataclass(frozen=True) +class LegacyPlaces: + """一個舊資料夾的代碼解讀結果""" + + #: (省市, 縣市) → 目前的縣市代碼;「全國」(00, 000) → 00000 + counties: Mapping[tuple[str, str], str] + #: (省市, 縣市, 鄉鎮, 村里) → VILLCODE(跨村里投開票所有多個;對不到的里是「鄉鎮代碼+000」) + villages: Mapping[tuple[str, str, str, str], tuple[str, ...]] + #: (省市, 縣市, 鄉鎮) → 目前的鄉鎮代碼 + towns: Mapping[tuple[str, str, str], str] + #: (省市, 縣市, 村里) → VILLCODE:舊資料的村里段是全縣市流水號,號碼在縣市內唯一時才收。 + #: 2004 年的投票概況檔有幾個里的鄉鎮欄錯位(記到下一個鄉鎮),用號碼還找得回來。 + by_number: Mapping[tuple[str, str, str], tuple[str, ...]] = field(default_factory=dict) + #: 只對到鄉鎮的村里列數、鄉鎮也對不到的村里列數 + town_only: int = 0 + unmatched: int = 0 + + +def legacy_places(archive: CecArchive, folder: str, gazetteer: Gazetteer, suffix: str = "") -> LegacyPlaces: + rows = list(archive.rows(folder, "elbase" + suffix)) + counties: dict[tuple[str, str], str] = {} + county_names: dict[tuple[str, str], str] = {} + for prv, city, district, town, village, name in (r[:6] for r in rows): + # 縣市列:選區欄 00(議員資料夾另有「臺北市第01選區」這類選區列) + if district != "00" or town != "000" or village != "0000": + continue + county_names[(prv, city)] = name + if (prv, city) == ("00", "000"): + counties[(prv, city)] = NATIONAL + elif code := COUNTY_CODE_BY_NAME.get(normalize_name(name)): + counties[(prv, city)] = code + else: + log.warning("%s:縣市名稱對不到目前的縣市:%s/%s %s", folder, prv, city, name) + town_names = {(r[0], r[1], r[3]): r[5] for r in rows if r[3] != "000" and r[4] == "0000"} + towns: dict[tuple[str, str, str], str] = {} + missing_towns: set[str] = set() + for (prv, city, town), town_name in town_names.items(): + county = counties.get((prv, city)) + town8 = gazetteer.town(county, town_name, county_names.get((prv, city), "")) if county else None + if town8: + towns[(prv, city, town)] = town8 + else: + missing_towns.add(f"{county or prv + city} {town_name}") + villages: dict[tuple[str, str, str, str], tuple[str, ...]] = {} + town_only = unmatched = 0 + for prv, city, _, town, village, name in (r[:6] for r in rows): + if town == "000" or village == "0000": + continue + town8 = towns.get((prv, city, town)) + if town8 is None: + unmatched += 1 + continue + if name.startswith("各里"): + # 全區原住民選民的專屬投開票所,涵蓋該區所有村里 + codes = gazetteer.all_villages(town8) + else: + parts = [n for n in name.replace(",", "、").split("、") if n.strip()] + codes = [c for c in (gazetteer.village(town8, n) for n in parts) if c] + if not codes: + codes = [town_residual_code(town8)] + town_only += 1 + villages[(prv, city, town, village)] = tuple(codes) + if missing_towns: + log.warning( + "%s:%d 個鄉鎮名稱對不到目前的鄉鎮:%s", folder, len(missing_towns), sorted(missing_towns) + ) + if town_only: + log.info("%s:%d 個村里對不到現在的里,票數只記到鄉鎮", folder, town_only) + numbers: dict[tuple[str, str, str], list[tuple[str, ...]]] = defaultdict(list) + for (prv, city, _, village), codes in villages.items(): + numbers[(prv, city, village)].append(codes) + by_number = {key: found[0] for key, found in numbers.items() if len(found) == 1} + return LegacyPlaces( + counties, villages, towns, by_number=by_number, town_only=town_only, unmatched=unmatched + ) diff --git a/backend/data/pipeline/src/election_data/local2022.py b/backend/data/pipeline/src/election_data/local2022.py new file mode 100644 index 0000000..86e7f05 --- /dev/null +++ b/backend/data/pipeline/src/election_data/local2022.py @@ -0,0 +1,202 @@ +"""直轄市長、縣市長選舉的劇本資料(全台;2022、2018、2014 年)。 + +每個縣市一個檔案 data/build/scenarios/<年>-local/<縣市代碼>.json: +候選人(號次、姓名、政黨)、各里的候選人得票(多位無黨籍也分得開)、法定競選經費上限、政治獻金收支。 +遊戲規則與能力值不在這裡;這裡只放可以查證的事實(docs/10)。 +""" + +from __future__ import annotations + +import json +import logging +import math +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path + +from .cec import CecArchive, fetch_votedata +from .codes import county_code, normalize_name +from .config import BUILD_DIR +from .elections import candidate_party, election_by_id, load_election +from .fetch import FetchResult +from .pack import NAME_SNAPSHOTS_ROC +from .population import FIRST_VILLAGE_MONTH, load_county_population, load_population + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class LocalRace: + election_id: str + date: str + #: 競選經費上限的人口基準:投票月前第六個月的月底,選罷法施行細則 + cap_month: str + #: 監察院政治獻金平臺上的選舉名稱年份(民國) + finance_year: str + out_dir: Path + + +LOCAL_RACES = { + 2022: LocalRace("2022-mayor", "2022-11-26", "11105", "111", BUILD_DIR / "scenarios" / "2022-local"), + 2018: LocalRace("2018-mayor", "2018-11-24", "10705", "107", BUILD_DIR / "scenarios" / "2018-local"), + # 2014:桃園縣這次升格,選的是第一屆桃園市長(直轄市長的經費上限);人口基準 2014-05 還叫桃園縣。 + # 監察院平臺沒有 103 年候選人的政治獻金申報,候選人的 finance 都是 null。 + 2014: LocalRace("2014-mayor", "2014-11-29", "10305", "103", BUILD_DIR / "scenarios" / "2014-local"), +} +ELECTION_ID = LOCAL_RACES[2022].election_id +SPECIAL_MUNICIPALITIES = {"63000", "64000", "65000", "66000", "67000", "68000"} +OUT_DIR = LOCAL_RACES[2022].out_dir +FINANCE_DIR = BUILD_DIR / "finance" + +#: 中選會檔案用私用區字元表示的罕用字 +PUA = {"": "聰"} + +COUNTY_NAMES = { + "63000": "臺北市", "64000": "高雄市", "65000": "新北市", "66000": "臺中市", "67000": "臺南市", + "68000": "桃園市", "10002": "宜蘭縣", "10004": "新竹縣", "10005": "苗栗縣", "10007": "彰化縣", + "10008": "南投縣", "10009": "雲林縣", "10010": "嘉義縣", "10013": "屏東縣", "10014": "臺東縣", + "10015": "花蓮縣", "10016": "澎湖縣", "10017": "基隆市", "10018": "新竹市", "10020": "嘉義市", + "09007": "連江縣", "09020": "金門縣", +} # fmt: skip + + +@dataclass(frozen=True) +class Candidate: + number: int + name: str + party: str | None # None:無黨籍及未經政黨推薦 + + +def office_of(county: str) -> str: + return "市長" if county in SPECIAL_MUNICIPALITIES or county in {"10017", "10018", "10020"} else "縣長" + + +def spending_cap(county: str, population: int) -> int: + """選罷法第 41 條:人口總數 × 70% × 20 元(千元以下進位) + +固定金額(直轄市長 5,000 萬、縣市長 3,000 萬)""" + variable = math.ceil(population * 0.7 * 20 / 1000) * 1000 + return variable + (50_000_000 if county in SPECIAL_MUNICIPALITIES else 30_000_000) + + +def clean_name(name: str) -> str: + return "".join(PUA.get(ch, ch) for ch in name).strip() + + +def load_candidates(archive: CecArchive, election_id: str = ELECTION_ID) -> dict[str, list[Candidate]]: + election = election_by_id(election_id) + out: dict[str, list[Candidate]] = defaultdict(list) + for folder in election.folders: + parties = {row[0]: row[1] for row in archive.rows(folder, "elpaty") if len(row) >= 2} + for row in archive.rows(folder, "elcand" + election.suffix): + if len(row) > 15 and row[15] == "Y": # 副手 + continue + party = parties.get(row[7], "") + out[county_code(row[0], row[1])].append( + Candidate(int(row[5]), clean_name(row[6]), candidate_party(party)) + ) + return {k: sorted(v, key=lambda c: c.number) for k, v in out.items()} + + +def load_finance(county: str, roc_year: str = "111") -> dict[str, dict[str, int]]: + name = COUNTY_NAMES[county] + kind = "直轄市市長選舉" if county in SPECIAL_MUNICIPALITIES else "縣(市)長選舉" + election = f"{roc_year}年{kind}" + path = FINANCE_DIR / f"{election}-{name}.json" + if not path.exists(): + log.warning("%s 沒有政治獻金資料(先執行 election-data donations)", name) + return {} + data = json.loads(path.read_text(encoding="utf-8")) + return { + clean_name(c["name"]): {"income": c["income"], "spending": c["spending"]} for c in data["candidates"] + } + + +def cap_population(month: str) -> tuple[dict[str, int], str, FetchResult]: + """經費上限的人口基準:縣市代碼 → 月底戶籍人口(另有全國 00000),以及來源名稱。 + + 107 年 1 月起用村里人口開放資料加總;更早的月份沒有村里資料,改用戶政司的縣市統計表 + (兩者在 107 年 5 月逐縣市核對一致)。""" + if month >= FIRST_VILLAGE_MONTH: + pop, res = load_population(month) + totals: dict[str, int] = defaultdict(int) + for p in pop: + totals[p.code[:5]] += p.total + totals["00000"] = sum(p.total for p in pop) + return dict(totals), f"戶政司村里人口 {month}", res + found = load_county_population(month) + return found.totals, f"{found.title} {found.month}", found.source + + +def build_local_2022(out_dir: Path = OUT_DIR) -> list[Path]: + return build_local(2022, out_dir) + + +def build_local(year: int, out_dir: Path | None = None) -> list[Path]: + race = LOCAL_RACES[year] + out_dir = out_dir or race.out_dir + vote = fetch_votedata() + archive = CecArchive(vote.path) + pop_now, _ = load_population() + population, cap_title, cap_res = cap_population(race.cap_month) + adults = {p.code: float(p.adults) for p in pop_now} + names: dict[tuple[str, str], str] = {} + for month in NAME_SNAPSHOTS_ROC: + older, _ = load_population(month) + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in older} + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in pop_now} + + election = election_by_id(race.election_id) + results = load_election(archive, election, None, weights=adults, village_names=names, by_candidate=True) + candidates = load_candidates(archive, race.election_id) + + out_dir.mkdir(parents=True, exist_ok=True) + written: list[Path] = [] + for county, cands in sorted(candidates.items()): + finance = load_finance(county, race.finance_year) + by_village = { + code: {"electors": r.electors, "ballots": r.ballots, "valid": r.valid, "votes": dict(r.votes)} + for code, r in results.by_village.items() + if code.startswith(county) + } + payload = { + "electionId": race.election_id, + "electionDate": race.date, + "kind": "mayor", + "countyCode": county, + "countyName": COUNTY_NAMES[county], + "areaName": COUNTY_NAMES[county], + "office": office_of(county), + "regionLevel": "town", + "packId": f"{county}-before-{race.date}", + "spendingCap": spending_cap(county, population[county]), + "capPopulation": population[county], + "candidates": [ + {"number": c.number, "name": c.name, "party": c.party, "finance": finance.get(c.name)} + for c in cands + ], + "byVillage": by_village, + "cecValid": results.cec_valid_by_county.get(county), + "sources": { + "results": { + "title": "中選會選舉資料庫 votedata", + "url": vote.url, + "retrievedAt": vote.retrieved_at, + }, + "population": {"title": cap_title, "retrievedAt": cap_res.retrieved_at}, + "finance": "監察院政治獻金公開查閱平臺(election-data donations)", + }, + } + path = out_dir / f"{county}.json" + path.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + written.append(path) + total = sum(sum(v["votes"].values()) for v in by_village.values()) + log.info( + "%s %s:%d 位候選人、%d 個里、有效票 %d(中選會 %s)", + county, + COUNTY_NAMES[county], + len(cands), + len(by_village), + total, + payload["cecValid"], + ) + return written diff --git a/backend/data/pipeline/src/election_data/pack.py b/backend/data/pipeline/src/election_data/pack.py new file mode 100644 index 0000000..415a704 --- /dev/null +++ b/backend/data/pipeline/src/election_data/pack.py @@ -0,0 +1,495 @@ +"""組裝資料包(docs/11 的 AreaDataPack):村里、鄉鎮、選民群、歷屆得票、地圖、來源。 + +- 年齡 × 政黨傾向的關聯一律用全國村里估計(較穩定),再套用到指定縣市。 +- 缺值依序用相鄰村里、同鄉鎮、全縣市補值,並在旗標中標示來源。 +""" + +from __future__ import annotations + +import json +import logging +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, replace +from datetime import UTC, datetime +from pathlib import Path + +import numpy as np + +from . import attributes as attrs +from .cec import CecArchive, fetch_votedata +from .cells import AgeLeanModel, fit_age_lean, village_cells +from .codes import normalize_name +from .config import BOUNDARY_VERSION, BUILD_DIR, INCOME_YEAR_ROC, POPULATION_MONTH_ISO, PROTOCOL_VERSION +from .elections import ( + ALL_ELECTIONS, + ELECTIONS, + HISTORIC_ELECTIONS, + PARTY_A, + PARTY_B, + PARTY_C, + ElectionData, + ElectionDef, + VillageResult, + load_all, +) +from .fetch import FetchResult +from .geo import VillageShape, area_km2, count_points_in, fetch_boundaries, load_villages, write_topology +from .impute import NeighborIndex, impute +from .lean import LEAN_KEYS, LeanParams, Observation, base_turnout, lean_shares +from .legacy import Gazetteer, load_gazetteer +from .population import AGE_BANDS, VillageIndigenous, VillagePopulation, load_indigenous, load_population +from .report import write_report +from .sources import SourceRef, source_ref +from .validate import validate + +log = logging.getLogger(__name__) + +AGE_KEYS = tuple(name for name, _, _ in AGE_BANDS) +FACTION_STRENGTH_DEFAULT = 0.5 # 沒有開放資料,設計值(docs/10) +AGE_LEAN_RIDGE = 50.0 # 生態推論的收斂強度;在誤差幾乎不變的前提下避免極端值(見 report.md) +CENSUS_MONTH_ROC = "10911" # 普查標準日 2020-11-08,用同月戶籍人口算外流比例 +NAME_SNAPSHOTS_ROC = ("10710", "10911", "11212") # 2018、2020、2024 選舉前後的里名,給跨村里對照用 +NATIONAL = "00000" + + +@dataclass(frozen=True) +class Inputs: + county: str + population_all: list[VillagePopulation] + population: list[VillagePopulation] + population_census_month: list[VillagePopulation] + indigenous: dict[str, VillageIndigenous] + elections: list[ElectionData] # 全國 + shapes: list[VillageShape] + temples: list[tuple[float, float]] + churches: list[tuple[float, float]] + income: dict[tuple[str, str], attrs.VillageIncome] + hakka: dict[str, float] + census: dict[str, attrs.TownCensus] + sources: list[SourceRef] + + +def _in_county(code: str, county: str) -> bool: + return county == NATIONAL or code.startswith(county) + + +_ELECTION_CACHE: dict[tuple[Path, tuple[ElectionDef, ...]], list[ElectionData]] = {} + + +def _load_elections( + path: Path, + elections: tuple[ElectionDef, ...], + weights: dict[str, float], + names: dict[tuple[str, str], str], + gazetteer: Gazetteer | None = None, +) -> list[ElectionData]: + """全國的歷屆得票;同一個程序連續做多個縣市的資料包時只讀一次""" + key = (path, elections) + if key not in _ELECTION_CACHE: + _ELECTION_CACHE[key] = load_all( + CecArchive(path), None, elections, weights=weights, village_names=names, gazetteer=gazetteer + ) + return _ELECTION_CACHE[key] + + +def load_inputs(county: str, elections_used: Sequence[ElectionDef] = ELECTIONS) -> Inputs: + scope = None if county == NATIONAL else county + pop_all, pop_res = load_population() + pop_census, _ = load_population(CENSUS_MONTH_ROC) + indigenous, ind_res = load_indigenous() + vote_res = fetch_votedata() + adults_all = {p.code: float(p.adults) for p in pop_all} + # 跨村里投開票所的名稱對照:先用歷史時點的里名,再用目前的里名覆蓋(目前優先)。 + # 舊選舉可能引用已合併或改名的里;對到的舊代碼若已不存在,會在報告中列為「孤兒代碼」。 + names_all: dict[tuple[str, str], str] = {} + for month in NAME_SNAPSHOTS_ROC: + older, _ = load_population(month) + names_all |= {(p.code[:8], normalize_name(p.village)): p.code for p in older} + names_all |= {(p.code[:8], normalize_name(p.village)): p.code for p in pop_all} + # 2014 年以前的資料夾要用名稱對照(legacy.py) + gazetteer = load_gazetteer() if any(e.legacy_codes for e in elections_used) else None + elections = _load_elections(vote_res.path, tuple(elections_used), adults_all, names_all, gazetteer) + boundary_res = fetch_boundaries() + shapes = load_villages(boundary_res.path, scope) + temples, churches, temple_res, church_res = attrs.load_religious_sites() + income, income_res = attrs.load_income() + hakka, hakka_res = attrs.load_hakka() + census: dict[str, attrs.TownCensus] = {} + census_res: FetchResult | None = None + if scope and scope in attrs.CENSUS_BASE: + census, census_res = attrs.load_census(scope) + else: + log.warning("%s 沒有設定普查表,鄉鎮的語言、教育、外流比例會是空值", county) + + def ref(sid: str, res: FetchResult, version: str | None = None) -> SourceRef: + note = None if res.tls_verified else "下載時 TLS 憑證無法驗證,已記錄 SHA-256" + return source_ref(sid, res.retrieved_at, version=version, note=note) + + sources = [ + ref("cec-votedata", vote_res, version=f"{min(e.date for e in elections_used)[:4]}–2024"), + ref("ris-odrp014", pop_res, version=POPULATION_MONTH_ISO), + ref("ris-odrp013", ind_res, version=POPULATION_MONTH_ISO), + ref("nlsc-village", boundary_res, version=BOUNDARY_VERSION), + ref("fia-income", income_res, version=f"{INCOME_YEAR_ROC} 年度"), + ref("hakka-key-areas", hakka_res), + ref("moi-temples", temple_res), + ref("moi-churches", church_res), + ] + if census_res: + sources.append(ref("dgbas-census-2020", census_res, version="109 年")) + return Inputs( + county=county, + population_all=pop_all, + population=[p for p in pop_all if _in_county(p.code, county)], + population_census_month=[p for p in pop_census if _in_county(p.code, county)], + indigenous={i.code: i for i in indigenous if _in_county(i.code, county)}, + elections=elections, + shapes=shapes, + temples=temples, + churches=churches, + income={(i.site, i.village): i for i in income}, + hakka=hakka, + census=census, + sources=sources, + ) + + +def _merge_blocs(votes: Mapping[str, int], blocs: Mapping[str, str]) -> dict[str, int]: + out: dict[str, int] = defaultdict(int) + for party, n in votes.items(): + out[blocs.get(party, party)] += n + return dict(out) + + +def _observations(code: str, elections: Sequence[ElectionData]) -> list[Observation]: + out = [] + for data in elections: + result = data.by_village.get(code) + if result is None: + continue + blocs = dict(data.election.blocs) + totals = _merge_blocs(data.party_totals_by_county.get(code[:5], {}), blocs) + contested = frozenset(p for p, total in totals.items() if total > 0) + votes = _merge_blocs(result.votes, blocs) if blocs else result.votes + out.append( + Observation(data.election.weight, result.valid, result.ballots, result.electors, votes, contested) + ) + return out + + +def fit_national_model( + inputs: Inputs, params: LeanParams +) -> tuple[AgeLeanModel, dict[str, dict[str, float]]]: + """回傳全國的年齡 × 傾向模型,以及每個有選舉資料的村里的政黨傾向。""" + leans: dict[str, dict[str, float]] = {} + for p in inputs.population_all: + share = lean_shares(_observations(p.code, inputs.elections), params) + if share is not None and p.adults > 0: + leans[p.code] = share + rows = [p for p in inputs.population_all if p.code in leans] + model = fit_age_lean( + [p.band_counts() for p in rows], + [leans[p.code] for p in rows], + AGE_KEYS, + LEAN_KEYS, + ridge=AGE_LEAN_RIDGE, + ) + log.info("年齡 × 政黨傾向:以全國 %d 個村里估計", len(rows)) + return model, leans + + +@dataclass(frozen=True) +class VillageMetrics: + """單一村里的衍生數值與補值旗標。""" + + lean: dict[str, float] + turnout: float + electors: int + income_median: float + income_mean: float + flags: tuple[str, ...] + + +def derive_metrics(inputs: Inputs, leans: dict[str, dict[str, float]]) -> dict[str, VillageMetrics]: + def latest_result(code: str) -> VillageResult | None: + """這個里最近一次有結果的選舉(例如嘉義市 2022 市長延期重選,不在主檔裡,就往前找)""" + return next((d.by_village[code] for d in inputs.elections if code in d.by_village), None) + + pops = {p.code: p for p in inputs.population} + adults = {c: float(p.adults) for c, p in pops.items()} + index = NeighborIndex(inputs.shapes) + by_town: dict[str, list[str]] = defaultdict(list) + for code in pops: + by_town[code[:8]].append(code) + county_codes = list(pops) + + known_lean = {c: np.array([leans[c][k] for k in LEAN_KEYS]) for c in pops if c in leans} + known_turnout = {} + known_electors_ratio = {} + for code in pops: + t = base_turnout(_observations(code, inputs.elections)) + if t is not None: + known_turnout[code] = np.array([t]) + res = latest_result(code) + if res and adults[code] > 0: + known_electors_ratio[code] = np.array([res.electors / adults[code]]) + known_income = {} + for code, p in pops.items(): + inc = inputs.income.get((normalize_name(p.site), normalize_name(p.village))) + if inc: + known_income[code] = np.array([inc.median, inc.mean]) + + def fill(code: str, known: dict[str, np.ndarray], label: str, flags: list[str]) -> np.ndarray: + if code in known: + return known[code] + found = impute(code, known, adults, index, lambda c: by_town[c[:8]], county_codes) + if found is None: + raise RuntimeError(f"{code} 的 {label} 無法補值(全縣市都沒有資料)") + flags.append(f"{label}_imputed:{found.source}") + return found.value + + out = {} + for code, p in pops.items(): + flags: list[str] = [] + missing = [d.election.id for d in inputs.elections if code not in d.by_village] + if missing: + flags.append("missing_elections:" + ",".join(missing)) + if any(d.by_village[code].allocated for d in inputs.elections if code in d.by_village): + flags.append("cross_village_votes_allocated") + lean = fill(code, known_lean, "lean", flags) + turnout = fill(code, known_turnout, "turnout", flags) + ratio = fill(code, known_electors_ratio, "electors", flags) + income = fill(code, known_income, "income", flags) + latest_res = latest_result(code) + electors = latest_res.electors if latest_res else round(float(ratio[0]) * p.adults) + lean_dict = {k: float(v) for k, v in zip(LEAN_KEYS, lean / lean.sum(), strict=True)} + out[code] = VillageMetrics( + lean_dict, float(turnout[0]), electors, float(income[0]), float(income[1]), tuple(flags) + ) + return out + + +def build_pack( + county: str, + out_root: Path = BUILD_DIR / "packs", + exclude: tuple[str, ...] = (), + name: str | None = None, + older: bool = False, + historic: bool = False, + since: str | None = None, + until: str | None = None, +) -> Path: + """exclude:計算政黨傾向與投票率時排除的選舉(歷史回測用,避免「先看答案」)。 + 被排除的選舉仍保留在 history.json,用來和模擬結果比對。name:資料包名稱(預設由縣市與排除清單組成)。 + older:加入 2016、2018 年的選舉(2018、2020 年劇本的資料包用)。 + historic:再加入 1995–2014 年的選舉(2016 年以前劇本的資料包用)。 + since:這一天以前的選舉完全不讀(不進模型、也不進 history.json),用來只留「上一輪」的選舉。 + until:這一天(含)以後的選舉完全不讀;歷史劇本用,資料包不放之後的開票結果。""" + used = ALL_ELECTIONS + HISTORIC_ELECTIONS if historic else ALL_ELECTIONS if older else ELECTIONS + if since: + used = tuple(e for e in used if e.date >= since) + if until: + used = tuple(e for e in used if e.date < until) + unknown = set(exclude) - {e.id for e in used} + if unknown: + raise ValueError(f"未知的選舉:{sorted(unknown)}") + inputs = load_inputs(county, used) + model_inputs = replace(inputs, elections=[d for d in inputs.elections if d.election.id not in exclude]) + params = LeanParams() + model, leans = fit_national_model(model_inputs, params) + metrics = derive_metrics(model_inputs, leans) + shapes = {s.code: s for s in inputs.shapes} + temple_counts = count_points_in(inputs.shapes, inputs.temples) + church_counts = count_points_in(inputs.shapes, inputs.churches) + + villages, cells = [], {} + for p in inputs.population: + m = metrics[p.code] + shape = shapes.get(p.code) + flags = list(m.flags) + ([] if shape else ["no_boundary"]) + area = area_km2(shape.geometry) if shape else 0.0 + temples = temple_counts.get(p.code, 0) + indig = inputs.indigenous.get(p.code) + villages.append( + { + "code": p.code, + "name": p.village, + "townCode": p.code[:8], + "townName": shape.town_name if shape else p.site[3:], + "countyCode": p.code[:5], + "countyName": shape.county_name if shape else p.site[:3], + "population": { + "total": p.total, + "adults": p.adults, + "byAgeBand": p.band_counts(), + "indigenousLowland": indig.lowland if indig else 0, + "indigenousHighland": indig.highland if indig else 0, + }, + "electors": m.electors, + "baseTurnout": round(m.turnout, 4), + "lean": {k: round(v, 4) for k, v in m.lean.items()}, + "attributes": { + "areaKm2": round(area, 4), + "densityPerKm2": round(p.total / area, 1) if area > 0 else 0.0, + "templeCount": temples, + "churchCount": church_counts.get(p.code, 0), + "templesPer1000": round(temples / (p.total / 1000), 3) if p.total else 0.0, + "hakkaShare": inputs.hakka.get(p.code[:8]), + "incomeMedian": round(m.income_median, 1), + "incomeMean": round(m.income_mean, 1), + "factionStrength": FACTION_STRENGTH_DEFAULT, + }, + "flags": flags, + } + ) + cells[p.code] = village_cells(model, p.band_counts(), m.lean) + + towns = _towns(inputs) + history, orphans = _history(inputs, {p.code for p in inputs.population}) + return _write(inputs, villages, towns, cells, history, orphans, model, params, out_root, exclude, name) + + +def _towns(inputs: Inputs) -> list[dict]: + by_town: dict[str, list[VillagePopulation]] = defaultdict(list) + for p in inputs.population: + by_town[p.code[:8]].append(p) + registered_2020: dict[str, int] = defaultdict(int) + for p in inputs.population_census_month: + registered_2020[p.code[:8]] += p.total + town_names = {s.town_code: s.town_name for s in inputs.shapes} + out = [] + for code, members in sorted(by_town.items()): + name = town_names.get(code, members[0].site[3:]) + census = inputs.census.get(normalize_name(name)) + outflow = None + if census and registered_2020.get(code): + outflow = round(max(0.0, 1 - census.resident_population / registered_2020[code]), 4) + out.append( + { + "code": code, + "name": name, + "countyCode": code[:5], + "population": sum(m.total for m in members), + "villageCodes": sorted(m.code for m in members), + "residentPopulation": census.resident_population if census else None, + "outflowRatio": outflow, + "languageShares": {k: round(v, 4) for k, v in (census.language if census else {}).items()}, + "educationShares": {k: round(v, 4) for k, v in (census.education if census else {}).items()}, + "hakkaShare": inputs.hakka.get(code), + } + ) + return out + + +def _history(inputs: Inputs, codes: set[str]) -> tuple[dict, list[tuple[str, str, int]]]: + """回傳 (history, orphans)。orphans:對到已不存在的舊里代碼的票(選舉, 代碼, 有效票)。""" + by_village: dict[str, dict[str, dict]] = defaultdict(dict) + reconciliation = [] + orphans: list[tuple[str, str, int]] = [] + current_all = {p.code for p in inputs.population_all} + for data in inputs.elections: + pack_valid_by_county: dict[str, int] = defaultdict(int) + for code, result in data.by_village.items(): + pack_valid_by_county[code[:5]] += result.valid + if code in codes: + by_village[code][data.election.id] = result.to_json() + elif code not in current_all and _in_county(code, inputs.county): + orphans.append((data.election.id, code, result.valid)) + for cc, cec_valid in sorted(data.cec_valid_by_county.items()): + if not _in_county(cc, inputs.county): + continue + # 中選會的全國列代碼是 00000,對應資料包的全部村里加總 + pack_valid = ( + sum(pack_valid_by_county.values()) if cc == NATIONAL else pack_valid_by_county.get(cc, 0) + ) + reconciliation.append( + { + "electionId": f"{data.election.id}@{cc}", + "cecValid": cec_valid, + "packValid": pack_valid, + "diff": pack_valid - cec_valid, + } + ) + meta = [ + {"id": e.id, "name": e.name, "date": e.date, "office": e.office, "weight": e.weight} + for e in (d.election for d in inputs.elections) + ] + return {"elections": meta, "byVillage": dict(by_village), "reconciliation": reconciliation}, orphans + + +def _write( + inputs: Inputs, + villages: list[dict], + towns: list[dict], + cells: dict[str, list[float]], + history: dict, + orphans: list[tuple[str, str, int]], + model: AgeLeanModel, + params: LeanParams, + out_root: Path, + exclude: tuple[str, ...] = (), + name: str | None = None, +) -> Path: + county = inputs.county + county_name = "全國" if county == NATIONAL else (villages[0]["countyName"] if villages else county) + pack_name = name or county + "".join(f"-ex-{e}" for e in sorted(exclude)) + out_dir = out_root / pack_name + out_dir.mkdir(parents=True, exist_ok=True) + pack_codes = {v["code"] for v in villages} + write_topology([s for s in inputs.shapes if s.code in pack_codes], out_dir / "topology.json") + files = { + "villages": ("villages.json", {"protocolVersion": PROTOCOL_VERSION, "villages": villages}), + "towns": ("towns.json", {"protocolVersion": PROTOCOL_VERSION, "towns": towns}), + "cells": ( + "cells.json", + { + "protocolVersion": PROTOCOL_VERSION, + "cells": {"ages": list(AGE_KEYS), "leans": list(LEAN_KEYS), "values": cells}, + }, + ), + "history": ("history.json", {"protocolVersion": PROTOCOL_VERSION, "history": history}), + "sources": ( + "sources.json", + {"protocolVersion": PROTOCOL_VERSION, "sources": [s.to_json() for s in inputs.sources]}, + ), + } + for name, payload in files.values(): + validate(payload, name.replace(".json", ".schema.json")) + (out_dir / name).write_text( + json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8" + ) + manifest = { + "protocolVersion": PROTOCOL_VERSION, + "packId": f"{pack_name}-{POPULATION_MONTH_ISO}", + "createdAt": datetime.now(UTC).isoformat(timespec="seconds"), + "scope": {"countyCode": county, "countyName": county_name}, + "snapshot": {"population": POPULATION_MONTH_ISO, "boundaries": BOUNDARY_VERSION}, + "partySlots": {"a": PARTY_A, "b": PARTY_B, "c": PARTY_C}, + "files": {key: name for key, (name, _) in files.items()} | {"topology": "topology.json"}, + "parameters": { + "lean": params.to_json(), + "electionWeights": { + d.election.id: d.election.weight for d in inputs.elections if d.election.id not in exclude + }, + "excludedElections": sorted(exclude), + "ageLeanModel": model.to_json(), + "ageLeanRidge": AGE_LEAN_RIDGE, + "ageLeanScope": "全國村里", + "incomeUnit": "千元", + "factionStrengthDefault": FACTION_STRENGTH_DEFAULT, + "turnoutDefinition": "投票數 ÷ 選舉人數,多屆加權平均", + }, + "counts": { + "villages": len(villages), + "towns": len(towns), + "villagesWithFlags": sum(1 for v in villages if v["flags"]), + }, + } + validate(manifest, "manifest.schema.json") + (out_dir / "manifest.json").write_text( + json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8" + ) + write_report(out_dir, manifest, villages, towns, history, orphans, inputs.shapes) + log.info("資料包完成:%s", out_dir) + return out_dir diff --git a/backend/data/pipeline/src/election_data/parties.py b/backend/data/pipeline/src/election_data/parties.py new file mode 100644 index 0000000..8b1fdef --- /dev/null +++ b/backend/data/pipeline/src/election_data/parties.py @@ -0,0 +1,100 @@ +"""台灣歷屆選舉推出過候選人的政黨(給自創角色選政黨用)。 + +來源:中選會選舉資料庫(votedata.zip,政府資料開放授權條款)。逐一讀每個選舉資料夾的 +elpaty(政黨代號 → 名稱)和 elcand(候選人),只算真的有候選人掛這個政黨參選的; +2024 年資料夾裡的全部登記政黨名冊、沒推過人的不算。 +「無黨籍」「連署」和 2005 年任務型國代的「某某等 N 人聯盟」不是政黨,排除。 + +輸出 build/parties/parties.json,並產生 packages/protocol/src/parties.ts(前後端共用的清單)。 +""" + +from __future__ import annotations + +import json +import logging +import re +from collections import defaultdict +from pathlib import Path + +from .cec import open_archive +from .config import BUILD_DIR + +log = logging.getLogger(__name__) + +OUT = BUILD_DIR / "parties" / "parties.json" +TS_OUT = Path(__file__).resolve().parents[4] / "packages" / "protocol" / "src" / "parties.ts" +NOT_PARTIES = {"無", "無黨籍及未經政黨推薦", "連署", "全國民主非政黨聯盟"} +ALLIANCE = re.compile(r"等\d+人聯盟$") +#: 中選會「當選註記」:* 當選、! 婦女保障名額當選 +ELECTED_MARKS = {"*", "!"} + + +def collect() -> list[dict[str, object]]: + archive = open_archive() + stats: dict[str, dict[str, object]] = defaultdict(lambda: {"candidates": 0, "elected": 0, "years": set()}) + for folder in archive.folders(): + if not (archive.has(folder, "elpaty") and archive.has(folder, "elcand")): + continue + year_match = re.match(r"(\d{4})", folder) + year = int(year_match.group(1)) if year_match else None + names = {row[0].strip(): row[1].strip() for row in archive.rows(folder, "elpaty") if len(row) >= 2} + for row in archive.rows(folder, "elcand"): + if len(row) < 15: + continue + name = names.get(row[7].strip()) + if not name or name in NOT_PARTIES or ALLIANCE.search(name): + continue + s = stats[name] + s["candidates"] = int(s["candidates"]) + 1 # type: ignore[call-overload] + if row[14].strip() in ELECTED_MARKS: + s["elected"] = int(s["elected"]) + 1 # type: ignore[call-overload] + if year: + s["years"].add(year) # type: ignore[union-attr] + out = [] + for name, s in stats.items(): + years = sorted(s["years"]) # type: ignore[arg-type] + first, last = (years[0], years[-1]) if years else (None, None) + out.append( + { + "name": name, + "candidates": s["candidates"], + "elected": s["elected"], + "first": first, + "last": last, + } + ) + out.sort(key=lambda p: (-int(p["candidates"]), str(p["name"]))) # type: ignore[call-overload] + return out + + +def _ts(parties: list[dict[str, object]]) -> str: + rows = "\n".join(f" {json.dumps(p, ensure_ascii=False)}," for p in parties) + return f"""/** + * 台灣歷屆選舉推出過候選人的政黨(中選會選舉資料庫 1994–2024,依推出的候選人數排序)。 + * 由 backend/data/pipeline 的 `election-data parties` 產生,不要手改。 + * candidates:推出的候選人數;elected:當選人數;first、last:第一次、最近一次推人參選的年份。 + */ +export interface PartyRecord {{ + name: string; + candidates: number; + elected: number; + first: number | null; + last: number | null; +}} + +export const PARTY_RECORDS: readonly PartyRecord[] = [ +{rows} +]; + +export const PARTY_NAMES: readonly string[] = PARTY_RECORDS.map((p) => p.name); +""" + + +def build_parties() -> list[Path]: + parties = collect() + OUT.parent.mkdir(parents=True, exist_ok=True) + data = {"source": "中選會選舉資料庫 votedata.zip", "parties": parties} + OUT.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") + TS_OUT.write_text(_ts(parties), encoding="utf-8") + log.info("政黨 %d 個", len(parties)) + return [OUT, TS_OUT] diff --git a/backend/data/pipeline/src/election_data/people/__init__.py b/backend/data/pipeline/src/election_data/people/__init__.py new file mode 100644 index 0000000..f423bbe --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/__init__.py @@ -0,0 +1,10 @@ +"""人物資料庫(docs/15):現任立委、縣市長、內閣、政黨主席、2026 縣市長候選人。 + +執行:`python -m election_data.people`,輸出 data/build/people/{people.json, sources.json, report.md}。 +""" + +from __future__ import annotations + +from .build import AS_OF, BuildResult, build_people + +__all__ = ["AS_OF", "BuildResult", "build_people"] diff --git a/backend/data/pipeline/src/election_data/people/__main__.py b/backend/data/pipeline/src/election_data/people/__main__.py new file mode 100644 index 0000000..040da14 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/__main__.py @@ -0,0 +1,31 @@ +"""python -m election_data.people [--as-of YYYY-MM-DD] [--skip-wikidata]""" + +from __future__ import annotations + +import argparse +import logging + +from .build import AS_OF, build_people + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="產生人物資料庫(people.json、sources.json、report.md)") + parser.add_argument("--as-of", default=AS_OF, help="資料快照日期(YYYY-MM-DD)") + parser.add_argument("--skip-wikidata", action="store_true", help="不查詢 Wikidata(離線或除錯用)") + parser.add_argument("-v", "--verbose", action="store_true") + args = parser.parse_args(argv) + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + # httpx 在 INFO 會印出完整網址(SPARQL 查詢很長) + logging.getLogger("httpx").setLevel(logging.WARNING) + result = build_people(args.as_of, use_wikidata=not args.skip_wikidata) + log = logging.getLogger(__name__) + log.info("完成:%d 位人物", result.count) + log.info("輸出:%s、%s、%s", result.people_path, result.sources_path, result.report_path) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/data/pipeline/src/election_data/people/build.py b/backend/data/pipeline/src/election_data/people/build.py new file mode 100644 index 0000000..03e2ce2 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/build.py @@ -0,0 +1,188 @@ +"""產生 data/build/people/{people.json, sources.json, report.md}。""" + +from __future__ import annotations + +import json +import logging +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from ..cec import CecArchive, fetch_votedata +from ..config import BUILD_DIR, CONFIG_DIR, PROTOCOL_VERSION, RAW_DIR +from ..sources import SourceRef, source_ref +from ..validate import validate +from .cabinet import fetch_cabinet +from .candidates import CandidateLoad, fetch_candidates +from .catalog import ( + CEC_2026_ELCAND, + CEC_2026_QUALIFIED, + EY_AGENCY_HEADS, + EY_MINISTERS_WITHOUT_PORTFOLIO, + EY_PREMIER, + EY_SECRETARY_SPOKESPERSON, + EY_VICE_PREMIER, + LY_TERM11, + MOI_COUNTY, + MOI_MUNICIPAL, + WIKIDATA, +) +from .cec_results import load_cec_results +from .enrich import CEC_SOURCE_ID, attach_name_only, attach_strong, index_results +from .legislators import fetch_legislators +from .manual import load_manual +from .mayors import fetch_mayors +from .merge import apply_overrides, merge_claims +from .model import PersonDraft +from .output import assign_ids, people_file, referenced_source_ids +from .report import ReportInput, render_report +from .wd_match import WdNote, match_wikidata +from .wikidata import fetch_items + +log = logging.getLogger(__name__) + +EY_SPECS = ( + EY_PREMIER, + EY_VICE_PREMIER, + EY_MINISTERS_WITHOUT_PORTFOLIO, + EY_SECRETARY_SPOKESPERSON, + EY_AGENCY_HEADS, +) + +AS_OF = "2026-10-25" +SKIPPED_WIKIDATA = "本次執行略過 Wikidata(--skip-wikidata)。" +KNOWN_GAPS: tuple[str, ...] = ( + "立法院 ID9 的「經歷」是沒有分隔的自由文字,沒有解析成職位;過去的職位只收錄有明確起訖日期的立委任期。", + "行政院部會首長頁面沒有到任日期,也沒有性別;性別只採用官方資料(立法院、中選會)," + "未曾參選或擔任立委的官員性別為 null。", + "內政部專區的黨籍是 111 年選舉時的黨籍;查證到的異動已在 config/people/overrides.yaml 更正," + "其餘縣市長的現任黨籍沒有逐一查證。", + "內政部專區不含停職、代理資訊。宜蘭縣長林姿妙停職中,由副縣長林茂盛代理(config/people/acting_heads.yaml);" + "協定沒有「停職」欄位,林姿妙仍以縣長列出。新竹市長高虹安已於 2025-12 復職。", + "縣市長的就職日期沒有出現在擷取的官方頁面上,所以縣市長職位的 from 為 null;" + "政黨主席的就任日期同樣為 null。", + "職位的 to 為 null 代表「現任」;只有年份或年月的經歷無法用協定的 YYYY-MM-DD 表示," + "因此未收錄(見最終報告的協定建議)。", + "2022 嘉義市長重行選舉的中選會檔案沒有性別與出生日期。", + "不分區立委的選舉紀錄來自政黨名單(elrepm),votes、share 為 null(不是個人得票)。", + "Wikidata 的出生日期只採用精確到日的值;只有年份的(例如王興煥)不填。", + "立委的委員會只收錄最新會期。", + "docs/15 的 M0 範圍另有總統、副總統、五院院長與副市長,本批未收錄。", +) + + +@dataclass(frozen=True) +class BuildResult: + people_path: Path + sources_path: Path + report_path: Path + count: int + + +def _write_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def _candidate_status(cand: CandidateLoad, persons: list[PersonDraft]) -> list[str]: + by_office = Counter(e.office for e in cand.entries) + merged = sum(1 for p in persons if "candidate_2026" in p.roles and len(p.roles) > 1) + lines = [ + f"已匯入中選會 {cand.qualified_on} 審定的候選人名單({CEC_2026_QUALIFIED.url}):" + f"直轄市長 {by_office.get('直轄市長', 0)} 人、縣市長 {by_office.get('縣市長', 0)} 人," + f"共 {len(cand.entries)} 人," + f"涵蓋 {len({e.county for e in cand.entries})} 個縣市。", + f"其中 {merged} 人同時是現任立委、縣市長或其他已收錄的人物(已合併,見下方合併紀錄)。", + ] + if cand.elcand_offices: + lines.append(f"已改用正式公告的 elcand 檔:{'、'.join(cand.elcand_offices)}。") + pending = [o for o in ("直轄市長", "縣市長") if o not in cand.elcand_offices] + if pending: + lines.append( + "正式公告待發布(直轄市長 11/12、縣市長 11/17):" + f"{'、'.join(pending)}候選人的號次、政黨、性別、出生日期為 pending。" + "號次已於 10/23 抽籤,但本批沒有匯入各選委會的抽籤結果。" + ) + lines.append( + "公告後把 elcand 格式的檔案放到 data/raw/people/cec2026/{municipal,county}/elcand.csv" + "(可附 elbase.csv、elpaty.csv)再重新執行,即會改用正式資料。" + ) + return lines + + +def _sources(refs: list[SourceRef], used: set[str]) -> dict[str, Any]: + by_id: dict[str, SourceRef] = {} + for ref in refs: + by_id.setdefault(ref.id, ref) + missing = used - by_id.keys() + if missing: + raise ValueError(f"people.json 引用了 sources.json 沒有的來源:{sorted(missing)}") + return { + "protocolVersion": PROTOCOL_VERSION, + "sources": [by_id[i].to_json() for i in sorted(used)], + } + + +def build_people(as_of: str = AS_OF, *, use_wikidata: bool = True) -> BuildResult: + raw = RAW_DIR / "people" + out_dir = BUILD_DIR / "people" + refs: list[SourceRef] = [] + + legislators, ly_res = fetch_legislators(raw) + refs.append(LY_TERM11.ref(ly_res.retrieved_at)) + mayors, moi_res = fetch_mayors(raw) + refs += [spec.ref(moi_res[spec.id].retrieved_at) for spec in (MOI_MUNICIPAL, MOI_COUNTY)] + cabinet, ey_res = fetch_cabinet(raw) + refs += [spec.ref(ey_res[spec.id].retrieved_at) for spec in EY_SPECS] + manual = load_manual(CONFIG_DIR / "people") + refs += list(manual.sources) + cand = fetch_candidates(raw) + refs.append(CEC_2026_QUALIFIED.ref(cand.press_release.retrieved_at)) + refs.append(CEC_2026_ELCAND.ref(as_of)) + + persons, merge_notes = merge_claims([*legislators, *mayors, *cabinet, *manual.claims, *cand.claims]) + persons, override_notes = apply_overrides(persons, manual.overrides) + merge_notes += override_notes + + votedata = fetch_votedata() + refs.append(source_ref(CEC_SOURCE_ID, votedata.retrieved_at)) + index = index_results(load_cec_results(CecArchive(votedata.path))) + persons, match_notes, done = attach_strong(persons, index) + + wd_notes: list[WdNote] = [] + if use_wikidata: + items, wd_date = fetch_items((p.name for p in persons), raw / "wikidata") + persons, wd_notes = match_wikidata(persons, items) + refs.append(WIKIDATA.ref(wd_date or as_of)) + persons, name_only_notes = attach_name_only(persons, index, done) + match_notes += name_only_notes + + ids = assign_ids(persons) + doc = people_file(persons, ids, PROTOCOL_VERSION, as_of) + sources = _sources(refs, referenced_source_ids(doc)) + validate(doc, "people.schema.json") + validate(sources, "sources.schema.json") + + report = render_report( + ReportInput( + as_of=as_of, + doc=doc, + roles_by_id={pid: p.roles for pid, p in zip(ids, persons, strict=True)}, + merge_notes=merge_notes, + match_notes=match_notes, + wd_notes=wd_notes, + candidate_status=_candidate_status(cand, persons), + known_gaps=KNOWN_GAPS if use_wikidata else (*KNOWN_GAPS, SKIPPED_WIKIDATA), + ) + ) + people_path, sources_path, report_path = ( + out_dir / "people.json", + out_dir / "sources.json", + out_dir / "report.md", + ) + _write_json(people_path, doc) + _write_json(sources_path, sources) + report_path.write_text(report, encoding="utf-8") + log.info("已輸出 %d 位人物 → %s", len(doc["people"]), people_path) + return BuildResult(people_path, sources_path, report_path, len(doc["people"])) diff --git a/backend/data/pipeline/src/election_data/people/cabinet.py b/backend/data/pipeline/src/election_data/people/cabinet.py new file mode 100644 index 0000000..570f865 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/cabinet.py @@ -0,0 +1,192 @@ +"""行政院內閣:院長、副院長、政務委員、秘書長、發言人、部會首長(行政院網站,只有 HTML)。""" + +from __future__ import annotations + +import html +import logging +import re +from dataclasses import dataclass +from pathlib import Path + +from ..fetch import FetchResult +from .catalog import ( + EY_AGENCY_HEADS, + EY_MINISTERS_WITHOUT_PORTFOLIO, + EY_PREMIER, + EY_SECRETARY_SPOKESPERSON, + EY_VICE_PREMIER, + PeopleSourceSpec, +) +from .downloads import fetch as download +from .education import parse_education +from .htmltext import html_lines +from .model import EducationRec, PersonClaim, PositionRec +from .names import display_name + +log = logging.getLogger(__name__) + +# 長的職稱放前面,避免「代理主任委員」被當成「主任委員」 +TITLES: tuple[str, ...] = tuple( + sorted( + ( + "代理主任委員", + "代理委員長", + "代理部長", + "代理院長", + "代理總裁", + "代理主計長", + "代理人事長", + "主任委員", + "政務委員", + "委員長", + "副院長", + "秘書長", + "發言人", + "主計長", + "人事長", + "部長", + "院長", + "總裁", + ), + key=len, + reverse=True, + ) +) +_MEMBER = re.compile( + r'\s*]*>(?P[^<]+)\s*\s*(?P[^<]+)', + re.S, +) +_LEADER = re.compile(r"^行政院(?P[\u4e00-\u9fff]{2,5}?)(?P副院長|院長)$") +_ROC_DAY = re.compile(r"民國\s*(\d{2,3})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日") + + +@dataclass(frozen=True) +class Member: + org: str + name: str + title: str + + +@dataclass(frozen=True) +class Leader: + name: str + title: str + education: tuple[str, ...] + start: str | None + + +def split_name_title(text: str) -> tuple[str, str]: + """「劉世芳部長」→(劉世芳, 部長); + 「曾智勇 Ljaucu‧Zingrur 主任委員」→(曾智勇 Ljaucu‧Zingrur, 主任委員)。""" + cleaned = display_name(html.unescape(text)) + for title in TITLES: + if cleaned.endswith(title) and len(cleaned) > len(title): + return display_name(cleaned[: -len(title)]), title + raise ValueError(f"無法從「{text}」分出姓名與職稱") + + +def parse_members(page: str) -> list[Member]: + out = [] + for m in _MEMBER.finditer(page): + name, title = split_name_title(m["person"]) + out.append(Member(display_name(html.unescape(m["org"])), name, title)) + return out + + +def roc_day(text: str) -> str | None: + m = _ROC_DAY.search(text) + if not m: + return None + return f"{int(m[1]) + 1911:04d}-{int(m[2]):02d}-{int(m[3]):02d}" + + +def _pairs(lines: list[str]) -> list[tuple[str, str]]: + """學經歷區塊是「期間、內容」交錯的行。""" + out: list[tuple[str, str]] = [] + period = "" + for line in lines: + if line.startswith("民國"): + period = line + else: + out.append((period, line)) + period = "" + return out + + +def parse_leader(page: str) -> Leader: + lines = [ + line.replace(" ", "") if line.replace(" ", "") in ("學歷", "經歷") else line + for line in html_lines(page) + ] + head = next(((i, m) for i, line in enumerate(lines) if (m := _LEADER.match(line))), None) + if head is None: + raise ValueError("行政院首長頁面找不到「行政院○○○院長」標題") + i, m = head + rest = lines[i + 1 :] + edu_start = rest.index("學歷") + 1 if "學歷" in rest else len(rest) + exp_start = rest.index("經歷") + 1 if "經歷" in rest else len(rest) + end = next((k for k, line in enumerate(rest) if line.startswith("以上內容之著作權")), len(rest)) + education = tuple(text for _, text in _pairs(rest[edu_start : exp_start - 1])) + current_title = f"行政院{m['title']}" + start = next( + (roc_day(period) for period, text in _pairs(rest[exp_start:end]) if text == current_title), None + ) + return Leader(display_name(m["name"]), m["title"], education, start) + + +def _education(lines: tuple[str, ...], src: tuple[str, ...]) -> tuple[EducationRec, ...]: + out: list[EducationRec] = [] + for line in lines: + for degree, school in parse_education(line): + rec = EducationRec(degree, school, src) + if rec not in out: + out.append(rec) + return tuple(out) + + +def member_claim(member: Member, source_id: str) -> PersonClaim: + return PersonClaim( + name=member.name, + role="official", + category="official", + name_source=source_id, + positions=(PositionRec(member.title, member.org, None, None, (source_id,)),), + ) + + +def leader_claim(leader: Leader, source_id: str) -> PersonClaim: + src = (source_id,) + return PersonClaim( + name=leader.name, + role="official", + category="official", + name_source=source_id, + positions=(PositionRec(leader.title, "行政院", leader.start, None, src),), + education=_education(leader.education, src), + ) + + +def _page_id(spec: PeopleSourceSpec) -> str: + return spec.url.rsplit("/", 1)[-1] + + +def fetch_cabinet(raw_dir: Path) -> tuple[list[PersonClaim], dict[str, FetchResult]]: + claims: list[PersonClaim] = [] + results: dict[str, FetchResult] = {} + for spec in (EY_PREMIER, EY_VICE_PREMIER): + res = download(spec.url, raw_dir / "ey" / f"{_page_id(spec)}.html") + results[spec.id] = res + claims.append(leader_claim(parse_leader(res.path.read_text(encoding="utf-8")), spec.id)) + for spec, minimum in ( + (EY_MINISTERS_WITHOUT_PORTFOLIO, 1), + (EY_SECRETARY_SPOKESPERSON, 1), + (EY_AGENCY_HEADS, 20), + ): + res = download(spec.url, raw_dir / "ey" / f"{_page_id(spec)}.html") + results[spec.id] = res + members = parse_members(res.path.read_text(encoding="utf-8")) + if len(members) < minimum: + raise ValueError(f"{spec.title} 只解析到 {len(members)} 人,頁面格式可能已改變:{spec.url}") + claims.extend(member_claim(member, spec.id) for member in members) + log.info("內閣:%d 筆職位", len(claims)) + return claims, results diff --git a/backend/data/pipeline/src/election_data/people/candidates.py b/backend/data/pipeline/src/election_data/people/candidates.py new file mode 100644 index 0000000..827e6b7 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/candidates.py @@ -0,0 +1,192 @@ +"""2026(115 年)直轄市長、縣市長候選人。 + +- 目前可用的官方名單:中選會 115-10-16 審定候選人資格的新聞稿(只有縣市與姓名)。 + 中選會網站是前端渲染,內容來自 `api/central/article/{id}`。 +- 正式公告(直轄市長 11/12、縣市長 11/17)後,若取得 elcand 格式的檔案,放在 + data/raw/people/cec2026/{municipal,county}/elcand.csv(可附 elbase.csv、elpaty.csv), + 就會改用該檔(含號次、政黨、性別、出生日期)。 +""" + +from __future__ import annotations + +import csv +import json +import logging +import re +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from ..codes import roc_to_iso_date +from ..fetch import FetchResult +from .catalog import CEC_2026_ELCAND, CEC_2026_QUALIFIED +from .downloads import fetch as download +from .htmltext import html_lines +from .model import PersonClaim, PositionRec, Sourced +from .names import county_key, display_name + +log = logging.getLogger(__name__) + +CEC_ARTICLE_API = "https://web.cec.gov.tw/api/central/article/65213" +MUNICIPAL = "直轄市長" +COUNTY = "縣市長" +ELECTION_ORG = {MUNICIPAL: "115年直轄市長選舉", COUNTY: "115年縣(市)長選舉"} +ELCAND_DIRS = {MUNICIPAL: "municipal", COUNTY: "county"} + +_SECTION = re.compile( + r"^[一二三四五六]、(?P<office>直轄市長|縣\(市\)長|縣(市)長)候選人部分.*?受理登記計(?P<n>\d+)人" +) +_OTHER_SECTION = re.compile(r"^[一二三四五六七八九]、") +_COUNTY_LINE = re.compile( + r"^([一二三四五六七八九十]+)(?P<county>.+?[市縣])(?P<n>\d+)人[::](?P<names>.+?)。?$" +) +_GENDER = {"1": "M", "2": "F"} +_INDEPENDENT_CODES = frozenset({"999", "0", ""}) + + +@dataclass(frozen=True) +class CandidateEntry: + name: str + county: str + office: str # 直轄市長 / 縣市長 + source_id: str + number: int | None = None + party: str | None = None + party_known: bool = False + gender: str | None = None + birth_date: str | None = None + + +def article_html(api_json: dict) -> tuple[str, str | None]: + """中選會文章 API → (內文 HTML, 發布日期 YYYY-MM-DD)。""" + data = api_json.get("data") or {} + blocks = json.loads(data.get("content") or "{}").get("content") or [] + body = "".join(b.get("content", "") for b in blocks if b.get("blockType") == "Text") + begin = str(data.get("beginTime") or "") + date = f"{begin[:4]}-{begin[4:6]}-{begin[6:8]}" if re.fullmatch(r"\d{8}", begin) else None + return body, date + + +def parse_press_release(body_html: str, source_id: str) -> list[CandidateEntry]: + """解析審定名單;每個縣市的人數與總數都要和姓名數一致,否則丟出錯誤。""" + entries: list[CandidateEntry] = [] + office: str | None = None + expected: dict[str, int] = {} + for line in html_lines(body_html): + if m := _SECTION.match(line): + office = MUNICIPAL if m["office"] == MUNICIPAL else COUNTY + expected[office] = int(m["n"]) + continue + if _OTHER_SECTION.match(line): + office = None + continue + if office and (m := _COUNTY_LINE.match(line)): + names = [display_name(n) for n in m["names"].split("、") if n.strip()] + if len(names) != int(m["n"]): + raise ValueError(f"{m['county']} 應有 {m['n']} 人,解析到 {len(names)} 人:{line}") + county = county_key(m["county"]) + entries += [CandidateEntry(n, county, office, source_id) for n in names] + for kind, total in expected.items(): + got = sum(e.office == kind for e in entries) + if got != total: + raise ValueError(f"{kind}候選人應有 {total} 人,解析到 {got} 人") + if not entries: + raise ValueError("中選會新聞稿中找不到候選人名單") + return entries + + +def parse_elcand( + elcand: Iterable[Sequence[str]], + elbase: Iterable[Sequence[str]], + elpaty: Iterable[Sequence[str]], + office: str, + source_id: str, +) -> list[CandidateEntry]: + """中選會 elcand 格式: + 省市,縣市,選區,鄉鎮,村里,號次,姓名,政黨代號,性別,出生日期,年齡,出生地,學歷,現任,當選註記,副手。""" + counties = { + (r[0], r[1]): county_key(r[5]) for r in elbase if len(r) >= 6 and r[3] == "000" and r[4] == "0000" + } + parties = {r[0]: r[1] for r in elpaty if len(r) >= 2} + out = [] + for row in elcand: + if len(row) < 10 or row[15:16] == ["Y"]: + continue + county = counties.get((row[0], row[1])) + if county is None: + raise ValueError(f"elcand 的縣市代碼 {row[0]}/{row[1]} 在 elbase 找不到") + code = row[7].strip() + out.append( + CandidateEntry( + name=display_name(row[6]), + county=county, + office=office, + source_id=source_id, + number=int(row[5]) if row[5].strip().isdigit() else None, + party=None if code in _INDEPENDENT_CODES else parties.get(code, code), + party_known=True, + gender=_GENDER.get(row[8].strip()), + birth_date=roc_to_iso_date(row[9]), + ) + ) + return out + + +def to_claim(entry: CandidateEntry, qualified_on: str | None) -> PersonClaim: + src = (entry.source_id,) + number = f"(號次 {entry.number})" if entry.number is not None else "" + title = f"{entry.county}長候選人{number}" + return PersonClaim( + name=entry.name, + role="candidate_2026", + category="politician", + name_source=entry.source_id, + county=entry.county, + gender=Sourced(entry.gender, src) if entry.gender else None, + birth_date=Sourced(entry.birth_date, src) if entry.birth_date else None, + party=Sourced(entry.party, src) if entry.party_known else None, + positions=(PositionRec(title, ELECTION_ORG[entry.office], qualified_on, None, src),), + ) + + +def _read_csv(path: Path) -> list[list[str]]: + if not path.exists(): + return [] + with path.open(encoding="utf-8-sig", newline="") as fh: + return [[c.strip().strip("'") for c in row] for row in csv.reader(fh) if row] + + +def load_elcand_dir(base: Path, office: str) -> list[CandidateEntry]: + folder = base / ELCAND_DIRS[office] + rows = _read_csv(folder / "elcand.csv") + if not rows: + return [] + entries = parse_elcand( + rows, _read_csv(folder / "elbase.csv"), _read_csv(folder / "elpaty.csv"), office, CEC_2026_ELCAND.id + ) + log.info("使用正式公告的 elcand 檔:%s(%d 人)", folder, len(entries)) + return entries + + +@dataclass(frozen=True) +class CandidateLoad: + claims: tuple[PersonClaim, ...] + entries: tuple[CandidateEntry, ...] + press_release: FetchResult + elcand_offices: tuple[str, ...] + qualified_on: str | None + + +def fetch_candidates(raw_dir: Path) -> CandidateLoad: + result = download(CEC_ARTICLE_API, raw_dir / "cec2026" / "article_65213.json") + body, qualified_on = article_html(json.loads(result.path.read_text(encoding="utf-8"))) + entries = parse_press_release(body, CEC_2026_QUALIFIED.id) + elcand_offices = [] + for office in (MUNICIPAL, COUNTY): + official = load_elcand_dir(raw_dir / "cec2026", office) + if official: + elcand_offices.append(office) + entries = [e for e in entries if e.office != office] + official + claims = tuple(to_claim(e, qualified_on) for e in entries) + log.info("2026 縣市長候選人:%d 人", len(claims)) + return CandidateLoad(claims, tuple(entries), result, tuple(elcand_offices), qualified_on) diff --git a/backend/data/pipeline/src/election_data/people/catalog.py b/backend/data/pipeline/src/election_data/people/catalog.py new file mode 100644 index 0000000..7160b94 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/catalog.py @@ -0,0 +1,110 @@ +"""人物資料用到的資料來源(不放進共用的 sources.CATALOG)。 + +手動維護的 YAML(黨主席、代理首長、更正)自帶來源,見 manual.py。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from ..sources import LICENSE_OGDL, SourceRef + + +@dataclass(frozen=True) +class PeopleSourceSpec: + id: str + title: str + agency: str + url: str + license: str + note: str | None = None + + def ref(self, retrieved_at: str, note: str | None = None) -> SourceRef: + return SourceRef( + id=self.id, + title=self.title, + agency=self.agency, + url=self.url, + license=self.license, + retrieved_at=retrieved_at, + note=note or self.note, + ) + + +LY_TERM11 = PeopleSourceSpec( + "ly-legislators-term11", + "第11屆立法委員基本資料(開放資料 ID9)", + "立法院", + "https://data.ly.gov.tw/getds.action?id=9", + LICENSE_OGDL, + "含姓名、性別、黨籍、選區、委員會、學歷、到職與離職;離職者只用來補充其他來源已收錄的人", +) +MOI_MUNICIPAL = PeopleSourceSpec( + "moi-local-officials-municipal-mayors", + "地方公職人員資訊專區-直轄市長", + "內政部", + "https://www.moi.gov.tw/LocalOfficial.aspx?n=578&TYP=KND0004", + "內政部政府網站資料開放宣告", + "黨籍欄為該屆(111年)選舉時的黨籍,之後的變動不會反映;不含停職、代理資訊", +) +MOI_COUNTY = PeopleSourceSpec( + "moi-local-officials-county-mayors", + "地方公職人員資訊專區-縣市長", + "內政部", + "https://www.moi.gov.tw/LocalOfficial.aspx?n=579&TYP=KND0005", + "內政部政府網站資料開放宣告", + "黨籍欄為該屆(111年)選舉時的黨籍,之後的變動不會反映;不含停職、代理資訊", +) +_EY_LICENSE = "行政院網站著作權聲明(僅擷取姓名、職稱、學經歷等事實資料)" +EY_PREMIER = PeopleSourceSpec( + "ey-premier", "行政院院長", "行政院", "https://www.ey.gov.tw/Page/3C927BC7FA83C969", _EY_LICENSE +) +EY_VICE_PREMIER = PeopleSourceSpec( + "ey-vice-premier", "行政院副院長", "行政院", "https://www.ey.gov.tw/Page/4E333C98644BB79B", _EY_LICENSE +) +EY_MINISTERS_WITHOUT_PORTFOLIO = PeopleSourceSpec( + "ey-ministers-without-portfolio", + "行政院政務委員", + "行政院", + "https://www.ey.gov.tw/Page/B49E392542E2F582", + _EY_LICENSE, +) +EY_SECRETARY_SPOKESPERSON = PeopleSourceSpec( + "ey-secretary-general-spokesperson", + "行政院秘書長、發言人", + "行政院", + "https://www.ey.gov.tw/Page/AC17C70FEBCEFD1F", + _EY_LICENSE, +) +EY_AGENCY_HEADS = PeopleSourceSpec( + "ey-agency-heads", + "行政院部會首長", + "行政院", + "https://www.ey.gov.tw/Page/7AC6136EBB87A125", + _EY_LICENSE, +) +CEC_2026_QUALIFIED = PeopleSourceSpec( + "cec-2026-candidates-qualified", + "中選會審定115年直轄市長、直轄市議員、縣(市)長及縣(市)議員選舉候選人資格(新聞稿)", + "中央選舉委員會", + "https://web.cec.gov.tw/central/article/65213", + "中央選舉委員會政府網站資料開放宣告", + "115-10-16 委員會議審定的候選人名單,只有姓名與縣市;號次、政黨、性別、出生日期待正式公告" + "(直轄市長 11/12、縣市長 11/17)", +) +CEC_2026_ELCAND = PeopleSourceSpec( + "cec-2026-candidates-elcand", + "115年地方公職人員選舉候選人(elcand 格式)", + "中央選舉委員會", + "https://web.cec.gov.tw/", + "中央選舉委員會政府網站資料開放宣告", + "正式公告的候選人資料;檔案放在 data/raw/people/cec2026/ 時才會使用", +) +WIKIDATA = PeopleSourceSpec( + "wikidata", + "Wikidata(SPARQL 查詢)", + "Wikimedia Foundation", + "https://query.wikidata.org/", + "CC0 1.0", + "只在官方資料沒有時補出生日期(精確到日);QID 依姓名、台灣、職位或政黨保守比對", +) diff --git a/backend/data/pipeline/src/election_data/people/cec_results.py b/backend/data/pipeline/src/election_data/people/cec_results.py new file mode 100644 index 0000000..19cf6af --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/cec_results.py @@ -0,0 +1,243 @@ +"""中選會選舉資料庫中,人物選舉紀錄需要的幾場選舉(逐候選人的得票、得票率、當選)。 + +elctks 同時有多個彙總層級的列;候選人在選區的總票數取「鄉鎮=000、村里=0000、投開票所=0000」 +那一列(全國性選舉取省市=00 的全國列),並用各投開票所加總驗證,不一致就丟出錯誤。 + +注意:2022 的 C1/prv 資料夾其實是直轄市長、C1/city 是縣市長(以內容為準,見 MUNICIPAL_CHECK)。 +""" + +from __future__ import annotations + +import csv +import io +import zipfile +from collections import defaultdict +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from ..cec import CecArchive +from ..codes import roc_to_iso_date +from .legislators import AT_LARGE, MOUNTAIN, PLAINS +from .names import county_key, display_name + +_GENDER = {"1": "M", "2": "F"} +_INDEPENDENT = frozenset({"999", "無", "無黨籍", "無黨籍及未經政黨推薦", ""}) +CHIAYI_2022_DIR = "votedata/votedata/2022年_嘉義市長重行選舉/" +NATIONAL = "全國" + + +@dataclass(frozen=True) +class CecResult: + election: str + # legislator_district / legislator_mountain / legislator_plains / legislator_at_large / president / mayor + kind: str + district: str + county: str | None + name: str + party: str | None + gender: str | None + birth_date: str | None + education: str | None + votes: int | None + share: float | None + elected: bool + running_mate: bool = False + + +@dataclass(frozen=True) +class ElectionSpec: + folder: str + election: str + kind: str + district: str | None # 固定的選區標籤(全國性選舉);None 代表依縣市/選區編號決定 + + +SPECS: tuple[ElectionSpec, ...] = ( + ElectionSpec("2024總統立委/區域立委", "2024 立法委員選舉(區域)", "legislator_district", None), + ElectionSpec("2024總統立委/山地立委", "2024 立法委員選舉(山地原住民)", "legislator_mountain", MOUNTAIN), + ElectionSpec("2024總統立委/平地立委", "2024 立法委員選舉(平地原住民)", "legislator_plains", PLAINS), + ElectionSpec("2024總統立委/總統", "2024 總統副總統選舉", "president", NATIONAL), + ElectionSpec("2022-111年地方公職人員選舉/C1/prv", "2022 直轄市長選舉", "mayor", None), + ElectionSpec("2022-111年地方公職人員選舉/C1/city", "2022 縣(市)長選舉", "mayor", None), +) +AT_LARGE_FOLDER = "2024總統立委/不分區政黨" +AT_LARGE_ELECTION = "2024 立法委員選舉(全國不分區及僑居國外國民)" +MUNICIPAL_CHECK = ("2022-111年地方公職人員選舉/C1/prv", "臺北市") + + +def _is_total(row: Sequence[str]) -> bool: + return row[3] == "000" and row[4] == "0000" and row[5] == "0000" + + +def candidate_totals(elctks: Iterable[Sequence[str]], national: bool) -> dict[tuple[str, ...], int]: + """(省市, 縣市, 選區, 號次) → 選區總票數。 + + 全國性選舉的鍵是 ("00", "000", "00", 號次)。以投開票所加總驗證。""" + totals: dict[tuple[str, ...], int] = {} + sums: dict[tuple[str, ...], int] = defaultdict(int) + for row in elctks: + votes = int(row[7]) + if national: + if row[0] == "00" and _is_total(row): + totals[("00", "000", "00", row[6])] = votes + elif row[5] != "0000": + sums[("00", "000", "00", row[6])] += votes + elif _is_total(row) and row[0] != "00": + totals[(row[0], row[1], row[2], row[6])] = votes + elif row[5] != "0000" and row[0] != "00": + sums[(row[0], row[1], row[2], row[6])] += votes + bad = [k for k, v in totals.items() if sums.get(k) != v] + if bad: + raise ValueError(f"elctks 選區總票數與投開票所加總不一致:{bad[:3]}") + return totals + + +def _county_names(elbase: Iterable[Sequence[str]]) -> dict[tuple[str, str], str]: + return { + (r[0], r[1]): county_key(r[5]) for r in elbase if r[2] == "00" and r[3] == "000" and r[4] == "0000" + } + + +def _district_label(spec: ElectionSpec, county: str | None, area: str, districts_per_county: dict) -> str: + if spec.district: + return spec.district + if spec.kind == "legislator_district" and county: + if districts_per_county.get(county, 0) > 1: + return f"{county}第{int(area)}選舉區" + return f"{county}選舉區" + return county or "?" + + +def load_election(archive: CecArchive, spec: ElectionSpec) -> list[CecResult]: + parties = {r[0]: r[1] for r in archive.rows(spec.folder, "elpaty")} + counties = _county_names(archive.rows(spec.folder, "elbase")) + cands = list(archive.rows(spec.folder, "elcand")) + national = spec.district is not None + totals = candidate_totals(archive.rows(spec.folder, "elctks"), national) + per_county: dict[str, set[str]] = defaultdict(set) + for r in cands: + per_county[counties.get((r[0], r[1]), "?")].add(r[2]) + districts_per_county = {k: len(v) for k, v in per_county.items()} + + def key(r: Sequence[str]) -> tuple[str, ...]: + return ("00", "000", "00", r[5]) if national else (r[0], r[1], r[2], r[5]) + + valid: dict[tuple[str, ...], int] = defaultdict(int) + # 副手(副總統候選人)的當選註記是空的,當選與否跟著同號次的主要候選人 + ticket_elected: dict[tuple[str, ...], bool] = {} + for r in cands: + if r[15] != "Y": + valid[key(r)[:3]] += totals[key(r)] + ticket_elected[key(r)] = r[14] == "*" + out = [] + for r in cands: + county = None if national else counties.get((r[0], r[1])) + votes = totals[key(r)] + total = valid[key(r)[:3]] + out.append( + CecResult( + election=spec.election, + kind=spec.kind, + district=_district_label(spec, county, r[2], districts_per_county), + county=county, + name=display_name(r[6]), + party=None if r[7] in _INDEPENDENT else parties.get(r[7], r[7]), + gender=_GENDER.get(r[8]), + birth_date=roc_to_iso_date(r[9]), + education=r[12] or None, + votes=votes, + share=round(votes / total, 6) if total else None, + elected=ticket_elected.get(key(r), False) if r[15] == "Y" else r[14] == "*", + running_mate=r[15] == "Y", + ) + ) + return out + + +def load_at_large(archive: CecArchive) -> list[CecResult]: + """不分區政黨名單(elrepm):政黨代號,排名,姓名,性別,出生日期,年齡,出生地,學歷,現任,當選註記。""" + parties = {r[0]: r[1] for r in archive.rows(AT_LARGE_FOLDER, "elpaty")} + return [ + CecResult( + election=AT_LARGE_ELECTION, + kind="legislator_at_large", + district=AT_LARGE, + county=None, + name=display_name(r[2]), + party=parties.get(r[0], r[0]), + gender=_GENDER.get(r[3]), + birth_date=roc_to_iso_date(r[4]), + education=r[7] or None, + votes=None, + share=None, + elected=r[9] == "*", + ) + for r in archive.rows(AT_LARGE_FOLDER, "elrepm") + ] + + +def _member_name(info: zipfile.ZipInfo) -> str: + if info.flag_bits & 0x800: + return info.filename + try: + return info.filename.encode("cp437").decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError): + return info.filename + + +def _zip_csv(zip_path: Path, member: str) -> list[list[str]]: + with zipfile.ZipFile(zip_path) as zf: + info = next((i for i in zf.infolist() if _member_name(i) == member), None) + if info is None: + raise FileNotFoundError(f"壓縮檔中沒有 {member}") + text = zf.read(info).decode("utf-8-sig") + return [[c.strip() for c in row] for row in csv.reader(io.StringIO(text)) if row] + + +def load_chiayi_2022(zip_path: Path) -> list[CecResult]: + """2022 嘉義市長重行選舉(2022-12-18):cand.csv(號次,名字,政黨名稱)+ prof.csv(各投開票所得票)。""" + cand = _zip_csv(zip_path, CHIAYI_2022_DIR + "cand.csv")[1:] + prof = _zip_csv(zip_path, CHIAYI_2022_DIR + "prof.csv") + n = len(cand) + votes = [0] * n + valid = 0 + for row in prof[1:]: + if not row[2].isdigit(): + continue + counts = [int(row[3 + i].replace(",", "")) for i in range(n)] + if sum(counts) != int(row[3 + n].replace(",", "")): + raise ValueError(f"嘉義市長重行選舉第 {row[2]} 投開票所的有效票數與候選人得票加總不一致") + votes = [a + b for a, b in zip(votes, counts, strict=True)] + valid += sum(counts) + winner = max(range(n), key=lambda i: votes[i]) + return [ + CecResult( + election="2022 縣(市)長選舉(嘉義市重行選舉)", + kind="mayor", + district="嘉義市", + county="嘉義市", + name=display_name(row[1]), + party=None if row[2] in _INDEPENDENT else row[2], + gender=None, + birth_date=None, + education=None, + votes=votes[i], + share=round(votes[i] / valid, 6), + elected=i == winner, + ) + for i, row in enumerate(cand) + ] + + +def load_cec_results(archive: CecArchive) -> list[CecResult]: + folder, county = MUNICIPAL_CHECK + municipal = {r[5] for r in archive.rows(folder, "elbase")} + if county not in municipal: + raise ValueError(f"{folder} 預期是直轄市長選舉(含{county}),資料夾內容可能已改變") + out: list[CecResult] = [] + for spec in SPECS: + out.extend(load_election(archive, spec)) + out.extend(load_at_large(archive)) + out.extend(load_chiayi_2022(archive.path)) + return out diff --git a/backend/data/pipeline/src/election_data/people/downloads.py b/backend/data/pipeline/src/election_data/people/downloads.py new file mode 100644 index 0000000..4bfd1fd --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/downloads.py @@ -0,0 +1,87 @@ +"""人物資料的下載:一般情況交給 fetch.download;少數主機需要舊式 TLS 重新協商。 + +data.ly.gov.tw 的伺服器要求 TLS「legacy renegotiation」,OpenSSL 3 預設拒絕 +(UNSAFE_LEGACY_RENEGOTIATION_DISABLED)。只對允許清單中的主機開啟 OP_LEGACY_SERVER_CONNECT, +仍然驗證憑證鏈與主機名稱;快取檔與 .meta.json 的格式和 fetch.download 相同, +另外記錄 legacyRenegotiation=true。之後的執行直接讀快取。 +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import ssl +import time +from datetime import UTC, datetime +from pathlib import Path +from urllib.parse import urlsplit + +import certifi +import httpx + +from ..fetch import USER_AGENT, FetchResult, download + +log = logging.getLogger(__name__) + +LEGACY_RENEGOTIATION_HOSTS = frozenset({"data.ly.gov.tw"}) + + +def _legacy_context() -> ssl.SSLContext: + ctx = ssl.create_default_context(cafile=certifi.where()) + ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT + ctx.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0x4) + return ctx + + +def _download_legacy(url: str, dest: Path, timeout: float, retries: int) -> FetchResult: + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(dest.name + ".part") + last: Exception | None = None + for attempt in range(1, retries + 1): + try: + with ( + httpx.Client( + verify=_legacy_context(), + timeout=timeout, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + ) as client, + client.stream("GET", url) as resp, + ): + resp.raise_for_status() + with tmp.open("wb") as fh: + for chunk in resp.iter_bytes(1 << 16): + fh.write(chunk) + break + except httpx.HTTPError as exc: + last = exc + log.warning("下載失敗(第 %d 次):%s:%s", attempt, url, exc) + time.sleep(2 * attempt) + else: + raise RuntimeError(f"下載失敗:{url}") from last + tmp.replace(dest) + body = dest.read_bytes() + retrieved_at = datetime.now(UTC).date().isoformat() + sha = hashlib.sha256(body).hexdigest() + meta = { + "url": url, + "retrievedAt": retrieved_at, + "sha256": sha, + "tlsVerified": True, + "legacyRenegotiation": True, + "bytes": len(body), + } + meta_file = dest.with_name(dest.name + ".meta.json") + meta_file.write_text(json.dumps(meta, ensure_ascii=False, indent=2), "utf-8") + log.info("已下載 %s(%d bytes,舊式 TLS 重新協商)", dest.name, len(body)) + return FetchResult(dest, url, retrieved_at, sha, True, False) + + +def fetch(url: str, dest: Path, *, timeout: float = 180.0, retries: int = 3) -> FetchResult: + """有快取就用快取;允許清單中的主機改用舊式 TLS 重新協商下載,其餘交給 fetch.download。""" + meta = dest.with_name(dest.name + ".meta.json") + host = urlsplit(url).hostname or "" + if host in LEGACY_RENEGOTIATION_HOSTS and not (dest.exists() and meta.exists()): + return _download_legacy(url, dest, timeout, retries) + return download(url, dest, timeout=timeout, retries=retries) diff --git a/backend/data/pipeline/src/election_data/people/education.py b/backend/data/pipeline/src/election_data/people/education.py new file mode 100644 index 0000000..2a6e7ea --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/education.py @@ -0,0 +1,94 @@ +"""學歷字串解析。 + +官方資料的學歷是自由文字(立法院 ID9 的 degree、內政部與行政院頁面的學歷欄),格式不一。 +原則:只採用字面上明確的學位;看不出學位的就標「未註明」,不推測。 +""" + +from __future__ import annotations + +import html +import re + +UNSPECIFIED = "未註明" + +_SPLIT = re.compile(r"[;;\n]+") +_LIST_SPLIT = re.compile(r"[、//]") +_YEARS = re.compile(r"[((][^()()]*\d[^()()]*[))]") +_WS = re.compile(r"[\s ]+") +# 證照、考試不是學歷 +_NOT_EDUCATION = re.compile(r"及格|證照|執照|執業|考試|檢定") +_SCHOOL_ONLY = re.compile(r"(國小|小學|國中|初中|高中|女中|中學|高職|商職|工職|家商|高工|高商)$") +_TRAILING_DEGREE = re.compile( + r"(?:[法文理工商醫農]學)?(?:雙)?(?:博士候選人|博士|碩士(?:在職專班|學位班|班)?|學士)(?:學位)?$" +) +_TRAILING_NOISE = re.compile(r"(?:學位|畢業|畢|結業|肄業)$") + +# (判斷用的正規式, 學位名稱);依序比對,先符合者為準。學制層級的規則比對去掉「畢業」後的文字。 +_RULES: tuple[tuple[re.Pattern[str], str], ...] = ( + (re.compile(r"博士後"), ""), # 博士後研究不是學位,略過 + (re.compile(r"博士候選人"), "博士候選人"), + (re.compile(r"博士"), "博士"), + (re.compile(r"碩士|E?MBA"), "碩士"), + (re.compile(r"學士"), "學士"), + (re.compile(r"結業$"), "結業"), + (re.compile(r"肄業$"), "肄業"), + (re.compile(r"(大學|學院).*系(畢業|畢)$"), "學士"), +) +_LEVEL_RULES: tuple[tuple[re.Pattern[str], str], ...] = ( + (re.compile(r"(專科|師專|藥專|工專|商專|專校)"), "專科"), + (re.compile(r"(國小|小學)$"), "國小"), + (re.compile(r"(國中|初中|國中部)$"), "國中"), + ( + re.compile(r"(高中|女中|中學|高職|商職|工職|家商|高工|高商|高中部|[一二三四]中|高級.*(中學|學校))$"), + "高中職", + ), +) + + +def _segments(text: str) -> list[str]: + out: list[str] = [] + for raw in _SPLIT.split(html.unescape(text)): + seg = _WS.sub(" ", raw).strip(" ,,。、;;") + if not seg: + continue + parts = [p.strip(" 、") for p in _LIST_SPLIT.split(seg)] + if len(parts) > 1 and all(p and _SCHOOL_ONLY.search(p) for p in parts): + out.extend(parts) + else: + out.append(seg) + return out + + +def classify(segment: str) -> str | None: + """回傳學位名稱;不是學歷(或應略過)時回傳 None。""" + if _NOT_EDUCATION.search(segment): + return None + for pattern, degree in _RULES: + if pattern.search(segment): + return degree or None + core = _TRAILING_NOISE.sub("", segment).strip() + for pattern, degree in _LEVEL_RULES: + if pattern.search(core): + return degree + return UNSPECIFIED + + +def school_of(segment: str) -> str | None: + text = _YEARS.sub("", segment).strip() + for _ in range(2): + text = _TRAILING_NOISE.sub("", text).strip() + text = _TRAILING_DEGREE.sub("", text).strip() + return text or None + + +def parse_education(text: str) -> list[tuple[str, str | None]]: + """把學歷文字拆成 (學位, 學校) 串列;重複的項目只留一次,保留原順序。""" + out: list[tuple[str, str | None]] = [] + for seg in _segments(text): + degree = classify(_YEARS.sub("", seg).strip()) + if degree is None: + continue + item = (degree, school_of(seg)) + if item not in out: + out.append(item) + return out diff --git a/backend/data/pipeline/src/election_data/people/enrich.py b/backend/data/pipeline/src/election_data/people/enrich.py new file mode 100644 index 0000000..37fb161 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/enrich.py @@ -0,0 +1,162 @@ +"""把中選會選舉紀錄接到人物上。 + +兩層比對: +1. 強比對:同名,且選區或縣市脈絡一致(立委的選區、縣市長與候選人的縣市)。 +2. 只有姓名:人物沒有對應的脈絡(例如部會首長、黨主席、總統選舉)。只有在該場選舉中同名者唯一, + 且人物已知的出生日期(官方或 Wikidata)與中選會的出生日期完全相同時才接受;否則列入報告,不猜。 +同一場選舉有多個可能的紀錄時一律不接,列為模稜兩可。 +""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Sequence +from dataclasses import dataclass, replace + +from .cec_results import CecResult +from .model import EducationRec, ElectionRec, PersonDraft, Sourced +from .names import han_key, name_key + +CEC_SOURCE_ID = "cec-votedata" +_SKIP_EDUCATION = frozenset({"其他", "不識字", ""}) + + +@dataclass(frozen=True) +class MatchNote: + name: str + kind: str # strong / name_only / unverified / ambiguous / conflict / different_birth + election: str + detail: str + + +def _key(name: str) -> str: + return han_key(name) or name_key(name) + + +def index_results(results: Sequence[CecResult]) -> dict[str, list[CecResult]]: + out: dict[str, list[CecResult]] = defaultdict(list) + for r in results: + out[_key(r.name)].append(r) + return out + + +def is_strong(person: PersonDraft, r: CecResult) -> bool: + if r.kind == "president": + return False + if r.district in person.districts: + return True + return r.county is not None and r.county in person.counties + + +def _official(value: Sourced | None) -> bool: + return value is not None and value.value is not None and value.source_ids != ("wikidata",) + + +def conflicts_with(person: PersonDraft, r: CecResult) -> list[str]: + """官方資料已有的性別、出生日期與中選會紀錄不同時,回傳差異說明(不接這筆紀錄)。""" + out = [] + if r.gender and person.gender and person.gender.value and person.gender.value != r.gender: + out.append(f"性別 {person.gender.value} ≠ 中選會 {r.gender}") + if r.birth_date and _official(person.birth_date) and person.birth_date.value != r.birth_date: # type: ignore[union-attr] + out.append(f"出生日期 {person.birth_date.value} ≠ 中選會 {r.birth_date}") # type: ignore[union-attr] + return out + + +def apply_result(person: PersonDraft, r: CecResult) -> PersonDraft: + """接上一筆選舉紀錄;官方性別、出生日期為空時以中選會資料補上。呼叫前先檢查 conflicts_with。""" + src = (CEC_SOURCE_ID,) + label = f"{r.election}(副總統候選人)" if r.running_mate else r.election + record = ElectionRec(label, r.district, r.party, r.votes, r.share, r.elected, src) + gender = person.gender + if r.gender: + gender = gender.with_source(CEC_SOURCE_ID) if gender and gender.value else Sourced(r.gender, src) + birth = person.birth_date + if r.birth_date: + birth = birth.with_source(CEC_SOURCE_ID) if _official(birth) else Sourced(r.birth_date, src) # type: ignore[union-attr] + education = person.education + if not education and r.education and r.education not in _SKIP_EDUCATION: + education = (EducationRec(r.education, None, src),) + return replace( + person, + gender=gender, + birth_date=birth, + education=education, + elections=(*person.elections, record), + ) + + +def _by_election(results: Sequence[CecResult]) -> dict[str, list[CecResult]]: + out: dict[str, list[CecResult]] = defaultdict(list) + for r in results: + out[r.election].append(r) + return out + + +def attach_strong( + persons: Sequence[PersonDraft], index: dict[str, list[CecResult]] +) -> tuple[list[PersonDraft], list[MatchNote], dict[int, set[str]]]: + """回傳(更新後的人物, 紀錄, 每個人已比對到的選舉)。""" + out, notes = [], [] + done: dict[int, set[str]] = {} + for i, person in enumerate(persons): + done[i] = set() + strong = [r for r in index.get(_key(person.name), []) if is_strong(person, r)] + for election, rs in _by_election(strong).items(): + exact = [r for r in rs if r.district in person.districts] + chosen = exact if len(exact) == 1 else rs + if len(chosen) != 1: + where = "、".join(r.district for r in rs) + notes.append(MatchNote(person.name, "ambiguous", election, f"同縣市有多筆同名紀錄:{where}")) + continue + if diffs := conflicts_with(person, chosen[0]): + notes.append(MatchNote(person.name, "conflict", election, ";".join(diffs) + ",未採用")) + continue + person = apply_result(person, chosen[0]) + notes.append(MatchNote(person.name, "strong", election, chosen[0].district)) + done[i].add(election) + out.append(person) + return out, notes, done + + +def attach_name_only( + persons: Sequence[PersonDraft], + index: dict[str, list[CecResult]], + done: dict[int, set[str]], +) -> tuple[list[PersonDraft], list[MatchNote]]: + out, notes = [], [] + for i, person in enumerate(persons): + for election, rs in _by_election(index.get(_key(person.name), [])).items(): + if election in done.get(i, set()): + continue + birth = person.birth_date.value if person.birth_date else None + if len(rs) != 1: + notes.append( + MatchNote(person.name, "ambiguous", election, f"該場選舉有 {len(rs)} 位同名候選人") + ) + continue + r = rs[0] + if birth and r.birth_date and birth == r.birth_date and not conflicts_with(person, r): + person = apply_result(person, r) + notes.append( + MatchNote(person.name, "name_only", election, f"姓名唯一且出生日期相同({birth})") + ) + elif birth and r.birth_date: + notes.append( + MatchNote( + person.name, + "different_birth", + election, + f"同名但出生日期不同({birth} / {r.birth_date})", + ) + ) + else: + notes.append( + MatchNote( + person.name, + "unverified", + election, + f"同名({r.district}),缺出生日期無法確認,未採用", + ) + ) + out.append(person) + return out, notes diff --git a/backend/data/pipeline/src/election_data/people/htmltext.py b/backend/data/pipeline/src/election_data/people/htmltext.py new file mode 100644 index 0000000..257b11d --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/htmltext.py @@ -0,0 +1,61 @@ +"""把 HTML 轉成逐行文字,給機關網站的簡單頁面解析用(不執行 JavaScript)。""" + +from __future__ import annotations + +import re +from html.parser import HTMLParser + +_SKIP_TAGS = frozenset({"script", "style", "noscript", "template"}) +_WS = re.compile(r"[ \t\r\f\v  ]+") + + +class _LineCollector(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self._chunks: list[str] = [] + self._skip_depth = 0 + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag in _SKIP_TAGS: + self._skip_depth += 1 + self._chunks.append("\n") + + def handle_endtag(self, tag: str) -> None: + if tag in _SKIP_TAGS and self._skip_depth: + self._skip_depth -= 1 + self._chunks.append("\n") + + def handle_data(self, data: str) -> None: + if not self._skip_depth: + self._chunks.append(data) + + def lines(self) -> list[str]: + text = "".join(self._chunks) + out = [] + for raw in text.split("\n"): + line = _WS.sub(" ", raw).strip() + if line: + out.append(line) + return out + + +def html_lines(html: str) -> list[str]: + """去掉 script/style 後,以標籤為界切成非空白的文字行。""" + parser = _LineCollector() + parser.feed(html) + parser.close() + return parser.lines() + + +def section(lines: list[str], start: str, stops: tuple[str, ...]) -> list[str]: + """取出標題 start 之後、下一個 stops 標題之前的各行(找不到 start 時回傳空串列)。""" + try: + i = lines.index(start) + except ValueError: + return [] + out = [] + for line in lines[i + 1 :]: + if line in stops: + break + out.append(line) + return out diff --git a/backend/data/pipeline/src/election_data/people/legislators.py b/backend/data/pipeline/src/election_data/people/legislators.py new file mode 100644 index 0000000..0dd332d --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/legislators.py @@ -0,0 +1,126 @@ +"""現任立法委員(立法院開放資料 ID9,第 11 屆)。""" + +from __future__ import annotations + +import json +import logging +import re +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from ..fetch import FetchResult +from .catalog import LY_TERM11 +from .downloads import fetch as download +from .education import parse_education +from .model import EducationRec, PersonClaim, PositionRec, Sourced +from .names import county_key, display_name + +log = logging.getLogger(__name__) + +LY_ID9_URL = "https://data.ly.gov.tw/odw/ID9Action.action?term=11&fileType=json" +TERM = 11 +AT_LARGE = "全國不分區及僑居國外國民" +MOUNTAIN = "山地原住民選舉區" +PLAINS = "平地原住民選舉區" + +_NUMBERED = re.compile(r"^(?P<county>.+?[縣市])第(?P<no>\d+)選舉區$") +_SINGLE = re.compile(r"^(?P<county>.+?[縣市])選舉區$") +_SESSION = re.compile(r"第\d+屆第(?P<session>\d+)會期[::](?P<committee>[^;;]+)") +_GENDER = {"男": "M", "女": "F"} +_INDEPENDENT = frozenset({"無黨籍", "無", ""}) + + +@dataclass(frozen=True) +class District: + label: str + county: str | None + + +def parse_district(area_name: str) -> District: + """立法院的選區名稱 → 正規化的選區標籤與縣市。""" + area = county_key(area_name.strip()) + if area.startswith("全國不分區"): + return District(AT_LARGE, None) + if area.startswith("山地原住民"): + return District(MOUNTAIN, None) + if area.startswith("平地原住民"): + return District(PLAINS, None) + if m := _NUMBERED.match(area): + return District(f"{m['county']}第{int(m['no'])}選舉區", m["county"]) + if m := _SINGLE.match(area): + return District(f"{m['county']}選舉區", m["county"]) + raise ValueError(f"無法解析的立委選區:{area_name!r}") + + +def ly_date(value: str) -> str | None: + """2024/02/01 → 2024-02-01。""" + m = re.fullmatch(r"\s*(\d{4})[/-](\d{1,2})[/-](\d{1,2})\s*", value or "") + return f"{int(m[1]):04d}-{int(m[2]):02d}-{int(m[3]):02d}" if m else None + + +def latest_session(records: Iterable[Mapping[str, Any]]) -> int: + sessions = [int(m["session"]) for r in records for m in _SESSION.finditer(r.get("committee", ""))] + return max(sessions, default=0) + + +def committees_in_session(committee_text: str, session: int) -> list[str]: + out: list[str] = [] + for m in _SESSION.finditer(committee_text): + name = m["committee"].strip() + if int(m["session"]) == session and name and name not in out: + out.append(name) + return out + + +def parse_record(record: Mapping[str, Any], session: int, source_id: str) -> PersonClaim: + src = (source_id,) + district = parse_district(record["areaName"]) + current = record.get("leaveFlag", "否") != "是" + start = ly_date(record.get("onboardDate", "")) + end = None if current else ly_date(record.get("leaveDate", "")) + positions = [PositionRec(f"立法委員(第{TERM}屆,{district.label})", "立法院", start, end, src)] + if current: + positions += [ + PositionRec(f"{name}委員(第{TERM}屆第{session}會期)", "立法院", None, None, src) + for name in committees_in_session(record.get("committee", ""), session) + ] + party_name = record.get("party", "").strip() + gender = _GENDER.get(record.get("sex", "").strip()) + return PersonClaim( + name=display_name(record["name"]), + role="legislator", + category="politician", + name_source=source_id, + current=current, + county=district.county, + district=district.label, + gender=Sourced(gender, src) if gender else None, + party=Sourced(None if party_name in _INDEPENDENT else party_name, src), + positions=tuple(positions), + education=tuple( + EducationRec(degree, school, src) for degree, school in parse_education(record.get("degree", "")) + ), + ) + + +def parse_legislators(records: list[Mapping[str, Any]], source_id: str) -> list[PersonClaim]: + session = latest_session(records) + return [parse_record(r, session, source_id) for r in records] + + +def load_ly_json(path: Path) -> list[dict[str, Any]]: + # 立法院 API 回應前面有空白行 + data = json.loads(path.read_text(encoding="utf-8").strip()) + records = data.get("dataList") + if not isinstance(records, list) or not records: + raise ValueError(f"立法院 ID9 回應沒有 dataList:{path}") + return records + + +def fetch_legislators(raw_dir: Path) -> tuple[list[PersonClaim], FetchResult]: + result = download(LY_ID9_URL, raw_dir / "ly" / f"id9_term{TERM}.json") + claims = parse_legislators(load_ly_json(result.path), LY_TERM11.id) + log.info("立法委員:%d 筆(現任 %d)", len(claims), sum(c.current for c in claims)) + return claims, result diff --git a/backend/data/pipeline/src/election_data/people/manual.py b/backend/data/pipeline/src/election_data/people/manual.py new file mode 100644 index 0000000..bce07f7 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/manual.py @@ -0,0 +1,198 @@ +"""手動維護的人物資料(config/people/*.yaml):黨主席、代理首長、欄位更正。""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import yaml + +from ..sources import SourceRef +from .education import parse_education +from .model import EducationRec, PersonClaim, PositionRec, Sourced +from .names import county_key, display_name + +_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}$") +_SUPPORTED_OVERRIDES = frozenset({"party"}) + + +class ManualDataError(ValueError): + pass + + +@dataclass(frozen=True) +class Override: + name: str + field: str + value: str | None + note: str + source_ids: tuple[str, ...] + + +@dataclass(frozen=True) +class ManualData: + claims: tuple[PersonClaim, ...] + overrides: tuple[Override, ...] + sources: tuple[SourceRef, ...] + + +def _require(entry: Mapping[str, Any], key: str, where: str) -> Any: + value = entry.get(key) + if value in (None, "", []): + raise ManualDataError(f"{where}:缺少必填欄位 {key}") + return value + + +def _date(value: Any, where: str) -> str | None: + if value is None: + return None + text = str(value) + if not _ISO.match(text): + raise ManualDataError(f"{where}:日期格式應為 YYYY-MM-DD,實際為 {value!r}") + return text + + +def parse_sources(entries: list[Mapping[str, Any]], where: str) -> list[SourceRef]: + refs = [] + for i, src in enumerate(entries or []): + at = f"{where}.sources[{i}]" + url = str(_require(src, "url", at)) + if not url.startswith("https://"): + raise ManualDataError(f"{at}:網址必須是 https:{url}") + note_parts = [str(src["note"])] if src.get("note") else [] + if src.get("quote"): + note_parts.append(f"確認文字:{src['quote']}") + refs.append( + SourceRef( + id=str(_require(src, "id", at)), + title=str(_require(src, "title", at)), + agency=str(_require(src, "agency", at)), + url=url, + license=str(_require(src, "license", at)), + retrieved_at=_date(_require(src, "retrievedAt", at), at) or "", + note=";".join(note_parts) or None, + ) + ) + if not refs: + raise ManualDataError(f"{where}:至少要有一個 sources") + return refs + + +def _positions(entries: list[Mapping[str, Any]], src: tuple[str, ...], where: str) -> tuple[PositionRec, ...]: + out = [] + for i, pos in enumerate(entries): + at = f"{where}.positions[{i}]" + out.append( + PositionRec( + str(_require(pos, "title", at)), + str(_require(pos, "org", at)), + _date(pos.get("from"), at), + _date(pos.get("to"), at), + src, + ) + ) + return tuple(out) + + +def _education(lines: list[str], src: tuple[str, ...]) -> tuple[EducationRec, ...]: + return tuple(EducationRec(d, s, src) for line in lines for d, s in parse_education(str(line))) + + +def parse_party_chairs(doc: Mapping[str, Any]) -> tuple[list[PersonClaim], list[SourceRef]]: + claims, refs = [], [] + for i, entry in enumerate(doc.get("chairs") or []): + where = f"party_chairs.yaml chairs[{i}]" + sources = parse_sources(entry.get("sources"), where) + src = tuple(s.id for s in sources) + party = str(_require(entry, "party", where)) + title = str(entry.get("title") or "黨主席") + claims.append( + PersonClaim( + name=display_name(str(_require(entry, "name", where))), + role="party_chair", + category="politician", + name_source=src[0], + party=Sourced(party, src), + positions=(PositionRec(title, party, _date(entry.get("from"), where), None, src),), + ) + ) + refs.extend(sources) + return claims, refs + + +def parse_acting_heads(doc: Mapping[str, Any]) -> tuple[list[PersonClaim], list[SourceRef]]: + claims, refs = [], [] + for i, entry in enumerate(doc.get("acting") or []): + where = f"acting_heads.yaml acting[{i}]" + sources = parse_sources(entry.get("sources"), where) + src = tuple(s.id for s in sources) + category = str(entry.get("category") or "official") + if category not in ("politician", "official"): + raise ManualDataError(f"{where}:category 只能是 politician 或 official") + claims.append( + PersonClaim( + name=display_name(str(_require(entry, "name", where))), + role="acting_head", + category=category, # type: ignore[arg-type] + name_source=src[0], + county=county_key(str(entry["county"])) if entry.get("county") else None, + positions=_positions(_require(entry, "positions", where), src, where), + education=_education(entry.get("education") or [], src), + ) + ) + refs.extend(sources) + return claims, refs + + +def parse_overrides(doc: Mapping[str, Any]) -> tuple[list[Override], list[SourceRef]]: + out, refs = [], [] + for i, entry in enumerate(doc.get("overrides") or []): + where = f"overrides.yaml overrides[{i}]" + field = str(_require(entry, "field", where)) + if field not in _SUPPORTED_OVERRIDES: + raise ManualDataError(f"{where}:不支援的欄位 {field}") + sources = parse_sources(entry.get("sources"), where) + value = entry.get("value") + out.append( + Override( + name=display_name(str(_require(entry, "name", where))), + field=field, + value=None if value is None else str(value), + note=str(entry.get("note") or ""), + source_ids=tuple(s.id for s in sources), + ) + ) + refs.extend(sources) + return out, refs + + +def _load(path: Path) -> Mapping[str, Any]: + if not path.exists(): + return {} + doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if not isinstance(doc, Mapping): + raise ManualDataError(f"{path} 的最上層應該是物件") + return doc + + +def _dedupe_sources(refs: list[SourceRef]) -> tuple[SourceRef, ...]: + seen: dict[str, SourceRef] = {} + for ref in refs: + if ref.id in seen and seen[ref.id] != ref: + raise ManualDataError(f"來源 id {ref.id} 重複且內容不同") + seen[ref.id] = ref + return tuple(seen.values()) + + +def load_manual(config_dir: Path) -> ManualData: + chairs, chair_refs = parse_party_chairs(_load(config_dir / "party_chairs.yaml")) + acting, acting_refs = parse_acting_heads(_load(config_dir / "acting_heads.yaml")) + overrides, override_refs = parse_overrides(_load(config_dir / "overrides.yaml")) + return ManualData( + claims=tuple(chairs + acting), + overrides=tuple(overrides), + sources=_dedupe_sources(chair_refs + acting_refs + override_refs), + ) diff --git a/backend/data/pipeline/src/election_data/people/mayors.py b/backend/data/pipeline/src/election_data/people/mayors.py new file mode 100644 index 0000000..6af250e --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/mayors.py @@ -0,0 +1,142 @@ +"""現任直轄市長、縣市長(內政部地方公職人員資訊專區)。 + +清單頁的每一筆有姓名、縣市、機關、職稱、黨籍與詳細資訊連結;詳細頁另有學歷與簡歷。 +該專區的「轉出 ODS」是 ASP.NET 表單按鈕,清單頁本身已含完整資料,所以直接解析 HTML。 +""" + +from __future__ import annotations + +import html +import logging +import re +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import parse_qs, urljoin, urlsplit + +from ..fetch import FetchResult +from .catalog import MOI_COUNTY, MOI_MUNICIPAL, PeopleSourceSpec +from .downloads import fetch as download +from .education import parse_education +from .htmltext import html_lines, section +from .model import EducationRec, PersonClaim, PositionRec, Sourced +from .names import county_key, display_name + +log = logging.getLogger(__name__) + +MOI_BASE = "https://www.moi.gov.tw/" +LISTS: tuple[tuple[PeopleSourceSpec, str, int], ...] = ( + (MOI_MUNICIPAL, "LocalOfficial.aspx?n=578&TYP=KND0004&PageSize=50", 6), + (MOI_COUNTY, "LocalOfficial.aspx?n=579&TYP=KND0005&PageSize=50", 16), +) +_BLOCK = re.compile( + r'<div class="caption">\s*<span>(?P<name>.*?)</span>.*?' + r'<div class="locate">\s*<span>(?P<county>.*?)</span>.*?' + r'<div class="position">(?P<position>.*?)</div>.*?' + r'<div class="group">\s*<span>(?P<party>.*?)</span>.*?' + r'<div class="more-btn">.*?href="(?P<href>[^"]+)"', + re.S, +) +_SPAN = re.compile(r"<span>(.*?)</span>", re.S) +_DETAIL_STOPS = ("黨籍", "選舉屆次", "學歷", "簡歷", "辦公地址", "聯絡電話(辦公)", "電子信箱") +_INDEPENDENT = frozenset({"無", "無黨籍", ""}) + + +@dataclass(frozen=True) +class MoiEntry: + name: str + county: str + org: str + title: str + party: str | None + detail_url: str + + +@dataclass(frozen=True) +class MoiDetail: + party: str | None + term: str | None + education: tuple[str, ...] + + +def _text(fragment: str) -> str: + return html.unescape(re.sub(r"<[^>]+>", "", fragment)).strip() + + +def parse_list(page: str) -> list[MoiEntry]: + entries = [] + for m in _BLOCK.finditer(page): + spans = [_text(s) for s in _SPAN.findall(m["position"])] + if len(spans) < 2: + raise ValueError(f"內政部清單的職稱欄位格式不符:{m['position']!r}") + party = _text(m["party"]) + entries.append( + MoiEntry( + name=display_name(_text(m["name"])), + county=county_key(_text(m["county"])), + org=spans[0], + title=spans[1], + party=None if party in _INDEPENDENT else party, + detail_url=urljoin(MOI_BASE, html.unescape(m["href"])), + ) + ) + return entries + + +def parse_detail(page: str) -> MoiDetail: + lines = html_lines(page) + party = section(lines, "黨籍", _DETAIL_STOPS) + term = section(lines, "選舉屆次", _DETAIL_STOPS) + education = section(lines, "學歷", _DETAIL_STOPS) + party_value = party[0] if party else None + return MoiDetail( + party=None if party_value in _INDEPENDENT else party_value, + term=term[0] if term else None, + education=tuple(education), + ) + + +def to_claim(entry: MoiEntry, detail: MoiDetail | None, source_id: str) -> PersonClaim: + src = (source_id,) + education: list[EducationRec] = [] + for line in detail.education if detail else (): + for degree, school in parse_education(line): + rec = EducationRec(degree, school, src) + if rec not in education: + education.append(rec) + return PersonClaim( + name=entry.name, + role="mayor", + category="politician", + name_source=source_id, + county=entry.county, + party=Sourced(entry.party, src), + positions=(PositionRec(entry.title, entry.org, None, None, src),), + education=tuple(education), + ) + + +def _detail_dest(raw_dir: Path, url: str) -> Path: + parent = parse_qs(urlsplit(url).query).get("_PARENT_ID", ["unknown"])[0] + return raw_dir / "moi" / f"detail_{re.sub(r'[^A-Za-z0-9]', '', parent)}.html" + + +def fetch_mayors(raw_dir: Path) -> tuple[list[PersonClaim], dict[str, FetchResult]]: + claims: list[PersonClaim] = [] + results: dict[str, FetchResult] = {} + for spec, path, expected in LISTS: + url = urljoin(MOI_BASE, path) + listing = download(url, raw_dir / "moi" / f"{path.split('TYP=')[1].split('&')[0]}.html") + results[spec.id] = listing + entries = parse_list(listing.path.read_text(encoding="utf-8")) + if len(entries) != expected: + log.warning("%s:預期 %d 筆,實際 %d 筆", spec.title, expected, len(entries)) + if not entries: + raise ValueError(f"{spec.title} 清單解析不到任何人:{url}") + for entry in entries: + detail_file = download(entry.detail_url, _detail_dest(raw_dir, entry.detail_url)) + detail = parse_detail(detail_file.path.read_text(encoding="utf-8")) + if detail.party != entry.party: + log.warning("%s 的黨籍在清單與詳細頁不一致:%s / %s", entry.name, entry.party, detail.party) + claims.append(to_claim(entry, detail, spec.id)) + log.info("縣市首長:%d 人", len(claims)) + return claims, results diff --git a/backend/data/pipeline/src/election_data/people/merge.py b/backend/data/pipeline/src/election_data/people/merge.py new file mode 100644 index 0000000..294cf73 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/merge.py @@ -0,0 +1,188 @@ +"""把各來源的 PersonClaim 合併成人物。 + +同名才可能是同一人;同名但縣市脈絡衝突(例如兩個不同縣市的候選人)、或同一種現任職位出現兩次時, +不合併並記錄下來。已離職的立委只用來補充其他來源已收錄的同名人物(例如轉任部長、擔任黨主席)。 +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, replace + +from .manual import Override +from .model import EducationRec, PersonClaim, PersonDraft, PositionRec, Sourced +from .names import han_key, name_key + +# 合併時的優先順序:顯示姓名、黨籍以排在前面的來源為準 +ROLE_ORDER: tuple[str, ...] = ( + "legislator", + "mayor", + "acting_head", + "party_chair", + "official", + "candidate_2026", +) +# 這些現任職位同一人不會有兩個 +_EXCLUSIVE_ROLES = frozenset({"legislator", "mayor", "candidate_2026"}) + + +@dataclass(frozen=True) +class MergeNote: + name: str + kind: str # merged / not_merged / departed_attached / departed_dropped / override / override_missing + detail: str + + +def _role_rank(claim: PersonClaim) -> int: + return ROLE_ORDER.index(claim.role) if claim.role in ROLE_ORDER else len(ROLE_ORDER) + + +def _key(claim_name: str) -> str: + return han_key(claim_name) or name_key(claim_name) + + +def compatible(cluster: Sequence[PersonClaim], claim: PersonClaim) -> bool: + counties = {c.county for c in cluster if c.county} + if claim.county and counties and claim.county not in counties: + return False + roles = {c.role for c in cluster if c.current} + return not (claim.current and claim.role in _EXCLUSIVE_ROLES and claim.role in roles) + + +def _cluster(claims: Iterable[PersonClaim]) -> tuple[list[list[PersonClaim]], list[MergeNote]]: + clusters: list[list[PersonClaim]] = [] + notes: list[MergeNote] = [] + current = sorted((c for c in claims if c.current), key=_role_rank) + departed = [c for c in claims if not c.current] + by_key: dict[str, list[list[PersonClaim]]] = {} + for claim in current: + groups = by_key.setdefault(_key(claim.name), []) + fits = [g for g in groups if compatible(g, claim)] + if len(fits) == 1: + fits[0].append(claim) + continue + if groups: + reason = "多個同名人物都可能是同一人" if fits else "同名但縣市或現任職位衝突" + notes.append( + MergeNote(claim.name, "not_merged", f"{claim.role}({claim.county or '-'}):{reason}") + ) + group = [claim] + groups.append(group) + clusters.append(group) + for claim in departed: + groups = by_key.get(_key(claim.name), []) + fits = [g for g in groups if compatible(g, claim)] + if len(fits) == 1: + fits[0].append(claim) + roles = "、".join(sorted({c.role for c in fits[0] if c is not claim})) + notes.append(MergeNote(claim.name, "departed_attached", f"已離職立委,併入現任的{roles}")) + else: + notes.append(MergeNote(claim.name, "departed_dropped", "已離職立委,且沒有其他現任職位,未收錄")) + for group in clusters: + roles = sorted({c.role for c in group if c.current}) + if len(roles) > 1: + notes.append(MergeNote(group[0].name, "merged", "+".join(roles))) + return clusters, notes + + +def _first(values: Iterable[Sourced | None]) -> tuple[Sourced | None, list[Sourced]]: + present = [v for v in values if v is not None] + if not present: + return None, [] + chosen = present[0] + conflicts = [] + for other in present[1:]: + if other.value == chosen.value: + for sid in other.source_ids: + chosen = chosen.with_source(sid) + else: + conflicts.append(other) + return chosen, conflicts + + +def _merge_education(items: Iterable[EducationRec]) -> tuple[EducationRec, ...]: + out: dict[tuple[str, str | None], EducationRec] = {} + for item in items: + key = (item.degree, item.school) + if key in out: + merged = tuple(dict.fromkeys(out[key].source_ids + item.source_ids)) + out[key] = replace(out[key], source_ids=merged) + else: + out[key] = item + return tuple(out.values()) + + +def _merge_positions(items: Iterable[PositionRec]) -> tuple[PositionRec, ...]: + return tuple(dict.fromkeys(items)) + + +def _describe(value: Sourced | None) -> str: + if value is None: + return "None" + return f"{value.value}({','.join(value.source_ids)})" + + +def build_draft(group: Sequence[PersonClaim]) -> tuple[PersonDraft, list[MergeNote]]: + ordered = sorted(group, key=lambda c: (not c.current, _role_rank(c))) + head = ordered[0] + notes = [] + gender, g_conf = _first(c.gender for c in ordered) + birth, b_conf = _first(c.birth_date for c in ordered) + party, p_conf = _first(c.party for c in ordered if c.current) + for label, conflicts, chosen in ( + ("性別", g_conf, gender), + ("出生日期", b_conf, birth), + ("黨籍", p_conf, party), + ): + for other in conflicts: + notes.append( + MergeNote( + head.name, + "conflict", + f"{label}不一致:採用 {_describe(chosen)},另有 {_describe(other)}", + ) + ) + draft = PersonDraft( + name=head.name, + category="politician" if any(c.category == "politician" for c in group) else "official", + roles=frozenset(c.role for c in group if c.current), + name_sources=tuple(dict.fromkeys(c.name_source for c in ordered)), + counties=frozenset(c.county for c in group if c.county), + districts=frozenset(c.district for c in group if c.district), + gender=gender, + birth_date=birth, + party=party, + positions=_merge_positions(p for c in ordered for p in c.positions), + education=_merge_education(e for c in ordered for e in c.education), + elections=tuple(e for c in ordered for e in c.elections), + ) + return draft, notes + + +def merge_claims(claims: Iterable[PersonClaim]) -> tuple[list[PersonDraft], list[MergeNote]]: + clusters, notes = _cluster(list(claims)) + drafts = [] + for group in clusters: + draft, extra = build_draft(group) + drafts.append(draft) + notes.extend(extra) + return drafts, notes + + +def apply_overrides( + drafts: Sequence[PersonDraft], overrides: Iterable[Override] +) -> tuple[list[PersonDraft], list[MergeNote]]: + out = list(drafts) + notes = [] + for ov in overrides: + hits = [i for i, d in enumerate(out) if _key(d.name) == _key(ov.name)] + if len(hits) != 1: + notes.append( + MergeNote(ov.name, "override_missing", f"找到 {len(hits)} 位同名人物,未套用 {ov.field} 更正") + ) + continue + i = hits[0] + before = out[i].party.value if out[i].party else None + out[i] = replace(out[i], party=Sourced(ov.value, ov.source_ids), notes=(*out[i].notes, ov.note)) + notes.append(MergeNote(ov.name, "override", f"黨籍 {before} → {ov.value}:{ov.note}")) + return out, notes diff --git a/backend/data/pipeline/src/election_data/people/model.py b/backend/data/pipeline/src/election_data/people/model.py new file mode 100644 index 0000000..5fe3cf0 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/model.py @@ -0,0 +1,111 @@ +"""人物資料的中間紀錄(不可變)。輸出格式對應 packages/protocol/src/people.ts。""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Literal + +Category = Literal["politician", "official"] +Gender = Literal["M", "F"] + + +@dataclass(frozen=True) +class Sourced: + """附出處的純量值。value 為 None 但有出處時,代表「已查證為無」(例如無黨籍)。""" + + value: str | None + source_ids: tuple[str, ...] + + def with_source(self, source_id: str) -> Sourced: + if source_id in self.source_ids: + return self + return Sourced(self.value, (*self.source_ids, source_id)) + + +@dataclass(frozen=True) +class PositionRec: + title: str + org: str + start: str | None + end: str | None + source_ids: tuple[str, ...] + + def to_json(self) -> dict[str, Any]: + return { + "title": self.title, + "org": self.org, + "from": self.start, + "to": self.end, + "sourceIds": list(self.source_ids), + } + + +@dataclass(frozen=True) +class EducationRec: + degree: str + school: str | None + source_ids: tuple[str, ...] + + def to_json(self) -> dict[str, Any]: + return {"degree": self.degree, "school": self.school, "sourceIds": list(self.source_ids)} + + +@dataclass(frozen=True) +class ElectionRec: + election: str + district: str | None + party: str | None + votes: int | None + share: float | None + elected: bool + source_ids: tuple[str, ...] + + def to_json(self) -> dict[str, Any]: + return { + "election": self.election, + "district": self.district, + "party": self.party, + "votes": self.votes, + "share": self.share, + "elected": self.elected, + "sourceIds": list(self.source_ids), + } + + +@dataclass(frozen=True) +class PersonClaim: + """單一來源對某個人的描述;合併後才成為一個人物。""" + + name: str + role: str # legislator / mayor / official / party_chair / candidate_2026 / acting_head + category: Category + name_source: str + current: bool = True # False:已離職的立委,只用來補充其他來源已收錄的人 + county: str | None = None # 比對選舉紀錄用的縣市脈絡 + district: str | None = None # 立委選區,例如「臺北市第1選舉區」「山地原住民」「全國不分區」 + gender: Sourced | None = None + birth_date: Sourced | None = None + party: Sourced | None = None + positions: tuple[PositionRec, ...] = () + education: tuple[EducationRec, ...] = () + elections: tuple[ElectionRec, ...] = () + + +@dataclass(frozen=True) +class PersonDraft: + """合併後、輸出前的人物。""" + + name: str + category: Category + roles: frozenset[str] + name_sources: tuple[str, ...] + counties: frozenset[str] = frozenset() + districts: frozenset[str] = frozenset() + gender: Sourced | None = None + birth_date: Sourced | None = None + party: Sourced | None = None + wikidata_id: Sourced | None = None + positions: tuple[PositionRec, ...] = () + education: tuple[EducationRec, ...] = () + elections: tuple[ElectionRec, ...] = () + notes: tuple[str, ...] = field(default=()) diff --git a/backend/data/pipeline/src/election_data/people/names.py b/backend/data/pipeline/src/election_data/people/names.py new file mode 100644 index 0000000..6c2a537 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/names.py @@ -0,0 +1,61 @@ +"""人名與地名的比對鍵。 + +人名比對只做「不改變身分」的正規化:全形轉半形、去空白、去掉原住民族名中的間隔號、 +統一少數異體字。台/臺在人名裡是有意義的字(例如「黃宏成台灣阿成…」),所以人名不轉換; +地名才用 codes.normalize_name 把「台」統一成「臺」。 +""" + +from __future__ import annotations + +import re +import unicodedata + +from ..codes import normalize_name as normalize_place + +# 原住民族名常見的各種間隔號與點 +_DOTS = re.compile(r"[‧・·•..‧・・]") +_SPACE = re.compile(r"[\s ]+") +_HAN = re.compile(r"[㐀-鿿豈-﫿]") + +# 同一個人在不同機關的資料中可能用不同的異體字 +_VARIANTS = str.maketrans({"啓": "啟", "姸": "妍", "温": "溫", "峯": "峰", "羣": "群", "銹": "鏽"}) + + +def name_key(name: str) -> str: + """人名比對鍵:保留漢字與族名拼音,去掉空白、間隔號,拼音轉小寫。""" + text = unicodedata.normalize("NFKC", name) + text = _SPACE.sub("", text) + text = _DOTS.sub("", text) + return text.translate(_VARIANTS).lower() + + +def slug_name(name: str) -> str: + """id 用的姓名:與 name_key 相同,但不統一異體字(保留原用字)。""" + text = _DOTS.sub("", _SPACE.sub("", unicodedata.normalize("NFKC", name))) + return text.lower() + + +def han_key(name: str) -> str: + """只取漢字部分(例如「伍麗華Saidhai‧Tahovecahe」→「伍麗華」),作為次要比對鍵。""" + return "".join(_HAN.findall(name_key(name))) + + +def display_name(name: str) -> str: + """顯示用姓名:去頭尾空白、全形空白轉半形;不改變用字。""" + return _SPACE.sub(" ", unicodedata.normalize("NFKC", name)).strip() + + +def county_key(name: str) -> str: + """縣市名稱比對鍵(台→臺)。""" + return normalize_place(name) + + +def wikidata_label_variants(name: str) -> tuple[str, ...]: + """查 Wikidata 標籤時用的姓名寫法:原始寫法、只有漢字的寫法、異體字統一後的寫法。""" + base = display_name(name) + out = [base] + han_original = "".join(_HAN.findall(unicodedata.normalize("NFKC", name))) + for candidate in (han_original, han_original.translate(_VARIANTS)): + if candidate and candidate not in out: + out.append(candidate) + return tuple(out) diff --git a/backend/data/pipeline/src/election_data/people/output.py b/backend/data/pipeline/src/election_data/people/output.py new file mode 100644 index 0000000..286ffa9 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/output.py @@ -0,0 +1,116 @@ +"""PersonDraft → people.json 的 Person(packages/protocol/src/people.ts)。""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Sequence +from typing import Any + +from .model import PersonDraft, Sourced +from .names import name_key, slug_name + +STAT_KEYS: tuple[str, ...] = ( + "awareness", + "network", + "affinity", + "eloquence", + "strategy", + "online", + "image", + "wealth", + "stamina", +) + + +def slug_id(p: PersonDraft) -> str: + year = p.birth_date.value[:4] if p.birth_date and p.birth_date.value else "x" + return f"tw-{p.category}-{slug_name(p.name)}-{year}" + + +def _sort_key(p: PersonDraft) -> tuple[str, ...]: + """同 id 的人物排序(決定 -2、-3 的歸屬),只用資料內容,不受輸入順序影響。""" + return ( + name_key(p.name), + p.birth_date.value or "" if p.birth_date else "", + p.name, + ",".join(sorted(p.roles)), + ",".join(sorted(p.counties)), + ",".join(sorted(p.districts)), + ",".join(f"{x.org}/{x.title}" for x in p.positions), + ) + + +def assign_ids(persons: Sequence[PersonDraft]) -> list[str]: + """有 Wikidata QID 就用 QID;否則用 tw-<類別>-<姓名>-<出生年或 x>。同 id 依固定排序加上 -2、-3。""" + base = [p.wikidata_id.value if p.wikidata_id and p.wikidata_id.value else slug_id(p) for p in persons] + groups: dict[str, list[int]] = defaultdict(list) + for i, b in enumerate(base): + groups[b].append(i) + ids = list(base) + for b, idx in groups.items(): + if len(idx) > 1: + for n, i in enumerate(sorted(idx, key=lambda k: _sort_key(persons[k]))): + ids[i] = b if n == 0 else f"{b}-{n + 1}" + if len(set(ids)) != len(ids): + raise ValueError("人物 id 不唯一") + return ids + + +def _field_sources(p: PersonDraft) -> dict[str, list[str]]: + out: dict[str, list[str]] = {"name": list(p.name_sources)} + scalars: dict[str, Sourced | None] = { + "gender": p.gender, + "birthDate": p.birth_date, + "party": p.party, + "wikidataId": p.wikidata_id, + } + for field, value in scalars.items(): + if value is not None and (value.value is not None or field == "party"): + out[field] = list(value.source_ids) + return out + + +def _value(v: Sourced | None) -> str | None: + return v.value if v else None + + +def person_json(p: PersonDraft, person_id: str, as_of: str) -> dict[str, Any]: + return { + "id": person_id, + "kind": "real", + "category": p.category, + "name": p.name, + "gender": _value(p.gender), + "birthDate": _value(p.birth_date), + "party": _value(p.party), + "wikidataId": _value(p.wikidata_id), + "positions": [x.to_json() for x in p.positions], + "education": [x.to_json() for x in p.education], + "electionHistory": [x.to_json() for x in p.elections], + "stats": dict.fromkeys(STAT_KEYS), + "scoring": [], + "fieldSources": _field_sources(p), + "asOf": as_of, + } + + +def people_file( + persons: Sequence[PersonDraft], ids: Sequence[str], protocol_version: str, as_of: str +) -> dict[str, Any]: + rows = sorted(zip(ids, persons, strict=True), key=lambda t: (t[1].category, name_key(t[1].name), t[0])) + return { + "protocolVersion": protocol_version, + "asOf": as_of, + "people": [person_json(p, pid, as_of) for pid, p in rows], + } + + +def referenced_source_ids(doc: dict[str, Any]) -> set[str]: + out: set[str] = set() + for person in doc["people"]: + for ids in person["fieldSources"].values(): + out.update(ids) + for key in ("positions", "education", "electionHistory"): + for item in person[key]: + out.update(item["sourceIds"]) + return out diff --git a/backend/data/pipeline/src/election_data/people/report.py b/backend/data/pipeline/src/election_data/people/report.py new file mode 100644 index 0000000..10bb4f0 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/report.py @@ -0,0 +1,166 @@ +"""data/build/people/report.md:覆蓋率、比對結果、待確認事項。""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from typing import Any + +from .enrich import MatchNote +from .merge import MergeNote +from .wd_match import WdNote + +ROLE_LABELS = { + "legislator": "現任立法委員", + "mayor": "直轄市長、縣市長(內政部專區)", + "acting_head": "代理縣市長", + "official": "行政院內閣", + "party_chair": "政黨主席", + "candidate_2026": "2026 縣市長候選人", +} + + +@dataclass(frozen=True) +class ReportInput: + as_of: str + doc: dict[str, Any] + roles_by_id: dict[str, frozenset[str]] + merge_notes: Sequence[MergeNote] + match_notes: Sequence[MatchNote] + wd_notes: Sequence[WdNote] + candidate_status: Sequence[str] + known_gaps: Sequence[str] + + +_NAME_DETAIL = "- {n.name}:{n.detail}" +_MATCH_DETAIL = "- {n.name}|{n.election}|{n.kind}|{n.detail}" + + +def _pct(n: int, total: int) -> str: + return f"{n}/{total}({n / total:.0%})" if total else "0/0" + + +def _table(header: Sequence[str], rows: Iterable[Sequence[Any]]) -> list[str]: + lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)] + lines += ["| " + " | ".join(str(c) for c in row) + " |" for row in rows] + return lines + + +def _counts(inp: ReportInput) -> list[str]: + people = inp.doc["people"] + by_cat = Counter(p["category"] for p in people) + by_role = Counter(r for roles in inp.roles_by_id.values() for r in roles) + multi = sum(1 for roles in inp.roles_by_id.values() if len(roles) > 1) + cats = f"politician {by_cat['politician']}、official {by_cat['official']}" + out = [f"- 人物總數:**{len(people)}**({cats})"] + out += [f"- 同時具有多種身分(已合併):{multi} 人", ""] + out += _table(("身分", "人數"), ((ROLE_LABELS.get(k, k), v) for k, v in sorted(by_role.items()))) + return out + + +def _coverage(inp: ReportInput) -> list[str]: + people = inp.doc["people"] + n = len(people) + + def has(field: str, src: str | None = None) -> int: + return sum( + 1 + for p in people + if p[field] is not None and (src is None or src in p["fieldSources"].get(field, [])) + ) + + wd_birth = sum(1 for p in people if p["fieldSources"].get("birthDate") == ["wikidata"]) + party_known = sum(1 for p in people if "party" in p["fieldSources"]) + rows = [ + ("性別(官方)", _pct(has("gender"), n)), + ("出生日期(全部)", _pct(has("birthDate"), n)), + (" 其中官方(中選會)", _pct(has("birthDate") - wd_birth, n)), + (" 其中只來自 Wikidata", _pct(wd_birth, n)), + ("黨籍已查證(含無黨籍)", _pct(party_known, n)), + ("Wikidata QID", _pct(has("wikidataId"), n)), + ("學歷(至少一筆)", _pct(sum(1 for p in people if p["education"]), n)), + ("選舉紀錄(至少一筆)", _pct(sum(1 for p in people if p["electionHistory"]), n)), + ] + return _table(("欄位", "覆蓋"), rows) + + +def _note_lines(notes: Iterable[Any], kinds: set[str], fmt: str) -> list[str]: + lines = [fmt.format(n=n) for n in notes if n.kind in kinds] + return lines or ["- (無)"] + + +def render_report(inp: ReportInput) -> str: + match_counts = Counter(n.kind for n in inp.match_notes) + wd_counts = Counter(n.kind for n in inp.wd_notes) + parts: list[str] = [ + "# 人物資料庫 M0 報告", + "", + f"資料快照日期:{inp.as_of} | 產生程式:`python -m election_data.people`", + "", + "## 人數", + "", + *_counts(inp), + "", + "## 欄位覆蓋率", + "", + *_coverage(inp), + "", + "## 2026 縣市長候選人", + "", + *[f"- {line}" for line in inp.candidate_status], + "", + "## 跨來源合併", + "", + "同名且縣市脈絡不衝突時合併為同一人。請人工確認下列合併:", + "", + *_note_lines(inp.merge_notes, {"merged", "departed_attached"}, "- {n.name}:{n.detail}"), + "", + "未合併或未收錄:", + "", + *_note_lines(inp.merge_notes, {"not_merged", "departed_dropped", "override_missing"}, _NAME_DETAIL), + "", + "黨籍更正(config/people/overrides.yaml)與來源間不一致:", + "", + *_note_lines(inp.merge_notes, {"override", "conflict"}, "- {n.name}:{n.detail}"), + "", + "## 選舉紀錄比對(中選會)", + "", + f"- 強比對(同名+選區或縣市):{match_counts['strong']} 筆", + f"- 只有姓名、以出生日期確認:{match_counts['name_only']} 筆", + f"- 同名但出生日期不同(判定為不同人):{match_counts['different_birth']} 筆", + "", + "以出生日期確認的比對:", + "", + *_note_lines(inp.match_notes, {"name_only"}, "- {n.name}|{n.election}|{n.detail}"), + "", + "模稜兩可、無法確認、資料衝突或同名不同人(未採用,請人工複查):", + "", + *_note_lines( + inp.match_notes, {"ambiguous", "unverified", "conflict", "different_birth"}, _MATCH_DETAIL + ), + "", + "## Wikidata 比對", + "", + f"- 符合:{wd_counts['matched']};較弱規則符合(medium):{wd_counts['matched_medium']};" + f"模稜兩可:{wd_counts['ambiguous']};未找到:{wd_counts['unmatched']};" + f"QID 重複:{wd_counts['duplicate_qid']}", + "", + "medium(同名臺灣人唯一且有政府職位,請人工複查):", + "", + *_note_lines(inp.wd_notes, {"matched_medium"}, "- {n.name} → {n.qid}:{n.detail}"), + "", + "模稜兩可或 QID 重複(未採用):", + "", + *_note_lines(inp.wd_notes, {"ambiguous", "duplicate_qid"}, "- {n.name}:{n.detail}"), + "", + "未找到(wikidataId 為 null):", + "", + *_note_lines(inp.wd_notes, {"unmatched"}, "- {n.name}:{n.detail}"), + "", + "## 已知缺口與注意事項", + "", + *[f"- {gap}" for gap in inp.known_gaps], + "", + ] + return "\n".join(parts) diff --git a/backend/data/pipeline/src/election_data/people/wd_match.py b/backend/data/pipeline/src/election_data/people/wd_match.py new file mode 100644 index 0000000..e7f1ea5 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/wd_match.py @@ -0,0 +1,147 @@ +"""人物與 Wikidata 項目的保守比對。 + +接受一個 Wikidata 項目的條件(全部都要符合): +- 標籤或別名與姓名相同; +- 若人物已有官方出生日期,項目的出生日期(精確到日)不得不同; +- 至少一項證據:職位標籤含人物職位的關鍵字(例如「立法委員」、縣市名、部會名)、政黨相同、 + 或出生日期相同(只有出生日期相同時,項目還要標示國籍為臺灣 Q865)。 +符合的項目超過一個就視為模稜兩可,不採用。 + +部會首長沒有黨籍也常缺職位資料,另有一條較弱的規則(記為 medium):同名且國籍為臺灣的項目只有一個, +而且該項目有政府職位。報告會列出所有 medium 比對,方便人工複查。 +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from collections.abc import Sequence +from dataclasses import dataclass, replace + +from .model import PersonDraft, Sourced +from .names import county_key, han_key, name_key +from .wikidata import WdItem + +WIKIDATA_SOURCE_ID = "wikidata" +TAIWAN = "Q865" +_OFFICE_WORDS = ( + "部長", + "委員", + "院長", + "署長", + "局長", + "主計長", + "人事長", + "總裁", + "秘書長", + "發言人", + "市長", + "縣長", +) + + +@dataclass(frozen=True) +class WdNote: + name: str + kind: str # matched / matched_medium / ambiguous / unmatched / duplicate_qid + qid: str | None + detail: str + + +def _norm(text: str) -> str: + return county_key(text) + + +def evidence_terms(p: PersonDraft) -> frozenset[str]: + terms: set[str] = set() + if "legislator" in p.roles or p.districts: + terms.add("立法委員") + terms.update(_norm(c) for c in p.counties) + for pos in p.positions: + org = _norm(pos.org) + if org == "行政院": + terms.add("政務委員" if pos.title == "政務委員" else f"行政院{pos.title}") + elif "official" in p.roles and not org.startswith(("立法院", "115年")): + terms.add(org) + return frozenset(terms) + + +def _official_birth(p: PersonDraft) -> str | None: + if p.birth_date and p.birth_date.value and p.birth_date.source_ids != (WIKIDATA_SOURCE_ID,): + return p.birth_date.value + return None + + +def _evidence(p: PersonDraft, item: WdItem, terms: frozenset[str]) -> list[str]: + reasons = [] + labels = [_norm(x) for x in item.positions] + hits = sorted({t for t in terms for label in labels if t in label}) + if hits: + reasons.append("職位:" + "/".join(hits)) + if p.party and p.party.value and _norm(p.party.value) in {_norm(x) for x in item.parties}: + reasons.append("政黨:" + p.party.value) + birth = _official_birth(p) + if birth and birth in item.day_births() and (reasons or TAIWAN in item.countries): + reasons.append("出生日期:" + birth) + return reasons + + +def candidates_for(p: PersonDraft, by_key: dict[str, list[WdItem]]) -> list[WdItem]: + keys = {name_key(p.name), han_key(p.name)} - {""} + seen: dict[str, WdItem] = {} + for k in keys: + for item in by_key.get(k, []): + seen[item.qid] = item + return list(seen.values()) + + +def match_one(p: PersonDraft, items: Sequence[WdItem]) -> WdNote: + birth = _official_birth(p) + terms = evidence_terms(p) + allowed = [it for it in items if not (birth and it.day_births() and birth not in it.day_births())] + scored = [(it, r) for it in allowed if (r := _evidence(p, it, terms))] + if len(scored) > 1: + with_birth = [(it, r) for it, r in scored if any(x.startswith("出生日期") for x in r)] + scored = with_birth if len(with_birth) == 1 else scored + if len(scored) == 1: + item, reasons = scored[0] + return WdNote(p.name, "matched", item.qid, "、".join(reasons)) + if len(scored) > 1: + return WdNote(p.name, "ambiguous", None, "多個符合:" + "、".join(it.qid for it, _ in scored)) + if p.category == "official" and p.roles <= {"official", "acting_head"}: + taiwanese = [it for it in allowed if TAIWAN in it.countries] + if len(taiwanese) == 1 and any(w in pos for pos in taiwanese[0].positions for w in _OFFICE_WORDS): + item = taiwanese[0] + return WdNote( + p.name, + "matched_medium", + item.qid, + "同名臺灣人唯一且有政府職位:" + "/".join(item.positions[:3]), + ) + detail = f"{len(items)} 個同名項目" if items else "查無同名項目" + if len(items) != len(allowed): + detail += f"({len(items) - len(allowed)} 個出生日期不符)" + return WdNote(p.name, "unmatched", None, detail) + + +def match_wikidata( + persons: Sequence[PersonDraft], items: Sequence[WdItem] +) -> tuple[list[PersonDraft], list[WdNote]]: + by_key: dict[str, list[WdItem]] = defaultdict(list) + for item in items: + for k in item.label_keys: + by_key[k].append(item) + notes = [match_one(p, candidates_for(p, by_key)) for p in persons] + counts = Counter(n.qid for n in notes if n.qid) + for i, note in enumerate(notes): + if note.qid and counts[note.qid] > 1: + notes[i] = WdNote(note.name, "duplicate_qid", None, f"{note.qid} 同時符合多位人物,不採用") + item_by_qid = {it.qid: it for it in items} + out = [] + for p, note in zip(persons, notes, strict=True): + if note.qid: + p = replace(p, wikidata_id=Sourced(note.qid, (WIKIDATA_SOURCE_ID,))) + births = item_by_qid[note.qid].day_births() + if _official_birth(p) is None and len(births) == 1: + p = replace(p, birth_date=Sourced(next(iter(births)), (WIKIDATA_SOURCE_ID,))) + out.append(p) + return out, notes diff --git a/backend/data/pipeline/src/election_data/people/wikidata.py b/backend/data/pipeline/src/election_data/people/wikidata.py new file mode 100644 index 0000000..7fc1a26 --- /dev/null +++ b/backend/data/pipeline/src/election_data/people/wikidata.py @@ -0,0 +1,185 @@ +"""Wikidata(CC0)查詢與快取。 + +- 依 Wikimedia User-Agent 政策送出可辨識的 User-Agent;聯絡方式用環境變數 ELECTION_DATA_CONTACT 設定。 +- 查詢結果快取在 data/raw/people/wikidata/,旁邊的 .meta.json 格式與 fetch.download 相同。 +- 每批查詢之間間隔 5 秒;429 或 5xx 時依 Retry-After 退避重試(每次最多等 90 秒)。 +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import os +import time +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from urllib.parse import urlencode + +import httpx + +from .names import name_key, wikidata_label_variants + +log = logging.getLogger(__name__) + +SPARQL_URL = "https://query.wikidata.org/sparql" +BATCH_SIZE = 40 +_PAUSE_SECONDS = 5.0 +_MAX_WAIT_SECONDS = 90.0 +_LANGS = ("zh", "zh-tw", "zh-hant") +_LANG_FILTER = 'IN ("zh-tw", "zh-hant", "zh")' +# 查詢文字是快取鍵的一部分,修改時快取會失效(需要重新查詢) +_POSITION_CLAUSE = ( + f"OPTIONAL {{ ?item wdt:P39 ?pos . ?pos rdfs:label ?posLabel . FILTER(LANG(?posLabel) {_LANG_FILTER}) }}" +) +_PARTY_CLAUSE = ( + "OPTIONAL { ?item wdt:P102 ?pty . ?pty rdfs:label ?partyLabel . " + f"FILTER(LANG(?partyLabel) {_LANG_FILTER}) }}" +) +_DEFAULT_CONTACT = "research pipeline for a Taiwan election simulation game; set ELECTION_DATA_CONTACT" + + +def user_agent() -> str: + contact = os.environ.get("ELECTION_DATA_CONTACT", _DEFAULT_CONTACT) + return f"election-2026-people-pipeline/0.1 ({contact}) httpx/{httpx.__version__}" + + +@dataclass(frozen=True) +class WdItem: + qid: str + label_keys: frozenset[str] + births: tuple[tuple[str, int], ...] # (YYYY-MM-DD, 精確度;11 = 日) + positions: tuple[str, ...] + parties: tuple[str, ...] + countries: frozenset[str] + + def day_births(self) -> frozenset[str]: + return frozenset(d for d, precision in self.births if precision >= 11) + + +def _escape(text: str) -> str: + return text.replace("\\", "\\\\").replace('"', '\\"') + + +def build_query(names: Sequence[str]) -> str: + values = " ".join( + f'"{_escape(v)}"@{lang}' for n in names for v in wikidata_label_variants(n) for lang in _LANGS + ) + return f"""SELECT ?item ?name + (GROUP_CONCAT(DISTINCT CONCAT(STR(?birth), "/", STR(?prec)); separator="|") AS ?births) + (GROUP_CONCAT(DISTINCT ?posLabel; separator="|") AS ?positions) + (GROUP_CONCAT(DISTINCT ?partyLabel; separator="|") AS ?parties) + (GROUP_CONCAT(DISTINCT STRAFTER(STR(?country), "entity/"); separator="|") AS ?countries) +WHERE {{ + VALUES ?name {{ {values} }} + ?item rdfs:label|skos:altLabel ?name ; wdt:P31 wd:Q5 . + OPTIONAL {{ ?item p:P569/psv:P569 ?bv . ?bv wikibase:timeValue ?birth ; wikibase:timePrecision ?prec . }} + {_POSITION_CLAUSE} + {_PARTY_CLAUSE} + OPTIONAL {{ ?item wdt:P27 ?country }} +}} GROUP BY ?item ?name""" + + +def _split(value: str) -> list[str]: + return [v for v in value.split("|") if v] + + +def parse_bindings(payload: dict) -> list[WdItem]: + """SPARQL JSON → 每個 QID 一筆(同一 QID 的多個標籤合併)。""" + merged: dict[str, dict[str, set]] = {} + for b in payload.get("results", {}).get("bindings", []): + qid = b["item"]["value"].rsplit("/", 1)[-1] + slot = merged.setdefault( + qid, {"keys": set(), "births": set(), "pos": set(), "party": set(), "c": set()} + ) + slot["keys"].add(name_key(b["name"]["value"])) + for raw in _split(b.get("births", {}).get("value", "")): + date, _, precision = raw.partition("/") + if len(date) >= 10 and precision.isdigit() and not date.startswith("-"): + slot["births"].add((date[:10], int(precision))) + slot["pos"].update(_split(b.get("positions", {}).get("value", ""))) + slot["party"].update(_split(b.get("parties", {}).get("value", ""))) + slot["c"].update(_split(b.get("countries", {}).get("value", ""))) + return [ + WdItem( + qid=qid, + label_keys=frozenset(s["keys"]), + births=tuple(sorted(s["births"])), + positions=tuple(sorted(s["pos"])), + parties=tuple(sorted(s["party"])), + countries=frozenset(s["c"]), + ) + for qid, s in sorted(merged.items()) + ] + + +def _write_cache(dest: Path, url: str, body: bytes) -> None: + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(body) + meta = { + "url": url, + "retrievedAt": datetime.now(UTC).date().isoformat(), + "sha256": hashlib.sha256(body).hexdigest(), + "tlsVerified": True, + "bytes": len(body), + } + dest.with_name(dest.name + ".meta.json").write_text( + json.dumps(meta, ensure_ascii=False, indent=2), "utf-8" + ) + + +def run_query(query: str, cache_dir: Path, *, retries: int = 4) -> tuple[dict, str, bool]: + """回傳(JSON, 擷取日期, 是否來自快取)。""" + digest = hashlib.sha256(query.encode("utf-8")).hexdigest()[:20] + dest = cache_dir / f"sparql_{digest}.json" + meta_file = dest.with_name(dest.name + ".meta.json") + if dest.exists() and meta_file.exists(): + meta = json.loads(meta_file.read_text(encoding="utf-8")) + return json.loads(dest.read_text(encoding="utf-8")), meta["retrievedAt"], True + url = f"{SPARQL_URL}?{urlencode({'query': query})}" + headers = {"User-Agent": user_agent(), "Accept": "application/sparql-results+json"} + last: Exception | None = None + for attempt in range(1, retries + 1): + try: + resp = httpx.get(SPARQL_URL, params={"query": query}, headers=headers, timeout=120.0) + if resp.status_code in (429, 500, 502, 503, 504): + wait = float(resp.headers.get("Retry-After", 5 * attempt)) + log.warning("Wikidata 回應 %d,%.0f 秒後重試", resp.status_code, wait) + time.sleep(min(wait, _MAX_WAIT_SECONDS)) + continue + resp.raise_for_status() + payload = resp.json() + _write_cache(dest, url[:2000], resp.content) + time.sleep(_PAUSE_SECONDS) + return payload, datetime.now(UTC).date().isoformat(), False + except (httpx.HTTPError, ValueError) as exc: + last = exc + log.warning("Wikidata 查詢失敗(第 %d 次):%s", attempt, exc) + time.sleep(2 * attempt) + raise RuntimeError("Wikidata 查詢失敗") from last + + +def fetch_items(names: Iterable[str], cache_dir: Path) -> tuple[list[WdItem], str | None]: + """依姓名分批查詢;回傳所有候選項目與最早的擷取日期。""" + unique = sorted(dict.fromkeys(names)) + items: dict[str, WdItem] = {} + dates: list[str] = [] + for start in range(0, len(unique), BATCH_SIZE): + payload, retrieved_at, cached = run_query(build_query(unique[start : start + BATCH_SIZE]), cache_dir) + dates.append(retrieved_at) + for item in parse_bindings(payload): + if item.qid in items: + old = items[item.qid] + item = WdItem( + item.qid, + old.label_keys | item.label_keys, + item.births, + item.positions, + item.parties, + item.countries, + ) + items[item.qid] = item + log.info("Wikidata 批次 %d:%s", start // BATCH_SIZE + 1, "快取" if cached else "已查詢") + return list(items.values()), min(dates) if dates else None diff --git a/backend/data/pipeline/src/election_data/population.py b/backend/data/pipeline/src/election_data/population.py new file mode 100644 index 0000000..7b99bf2 --- /dev/null +++ b/backend/data/pipeline/src/election_data/population.py @@ -0,0 +1,233 @@ +"""戶政司村里人口:單一年齡(ODRP014)與原住民身分(ODRP013)。""" + +from __future__ import annotations + +import logging +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass + +from .codes import COUNTY_CODE_BY_NAME, normalize_name +from .config import POPULATION_MONTH_ROC, RAW_DIR +from .fetch import FetchResult, download_form, fetch_json + +log = logging.getLogger(__name__) + +API = "https://www.ris.gov.tw/rs-opendata/api/v1/datastore/{dataset}/{month}?page={page}" + +#: 村里單一年齡人口(ODRP014)最早的月份;更早的月份(2016 年以前的經費上限)改用戶政司的縣市統計表 +FIRST_VILLAGE_MONTH = "10701" +#: 戶政司「人口統計資料」下載頁:要先開這頁拿 CSRF token,再 POST 下載 +STAT_PAGE = "https://www.ris.gov.tw/info-popudata/app/awFastDownload/toMain_panel" +STAT_VIEW = "https://www.ris.gov.tw/info-popudata/app/awFastDownload/view" + + +@dataclass(frozen=True) +class CountyTable: + """戶政司人口統計資料的一種表""" + + code: str # 下載頁的表代號 + title: str + first: str # 最早的民國年月 + + +#: 97 年 1 月起:每月一份「各縣市戶數人口數性別比例及人口密度統計表」(工作表「縣市別」) +MONTHLY_TABLE = CountyTable("m0s1", "戶政司 各縣市戶數、人口數統計表", "09701") +#: 87–96 年:每年一份「村里鄰戶數及人口數」,每個月一張工作表(例如 8809),有各縣市的月底人口 +YEARLY_TABLE = CountyTable("m1s1", "戶政司 縣市村里鄰戶數及人口數", "08701") +#: 更早只有年底數字:「縣市人口按性別及五齡組」,63 年起每年一張工作表 +YEAR_END_TABLE = CountyTable("y0s1", "戶政司 縣市人口按性別及五齡組(年底)", "06312") + +# 選民群的年齡層(docs/03):年齡下限與上限(含) +AGE_BANDS: tuple[tuple[str, int, int], ...] = ( + ("20-29", 20, 29), + ("30-39", 30, 39), + ("40-49", 40, 49), + ("50-64", 50, 64), + ("65+", 65, 200), +) + + +@dataclass(frozen=True) +class VillagePopulation: + code: str + site: str # 例:桃園市桃園區 + village: str + total: int + by_age: tuple[int, ...] # 0..99 歲,最後一格是 100 歲以上(共 101 格) + + def band_counts(self) -> dict[str, int]: + out: dict[str, int] = {} + for name, low, high in AGE_BANDS: + out[name] = sum(self.by_age[low : min(high, 100) + 1]) + return out + + @property + def adults(self) -> int: + return sum(self.by_age[20:]) + + +@dataclass(frozen=True) +class VillageIndigenous: + code: str + lowland: int # 平地原住民 + highland: int # 山地原住民 + + +def _pages(dataset: str, month: str) -> tuple[list[Mapping[str, str]], FetchResult]: + rows: list[Mapping[str, str]] = [] + first: FetchResult | None = None + page, total_pages = 1, 1 + while page <= total_pages: + url = API.format(dataset=dataset, month=month, page=page) + data, result = fetch_json(url, RAW_DIR / "ris" / f"{dataset.lower()}_{month}_p{page}.json") + first = first or result + if not str(data.get("responseCode", "")).endswith("-S"): + raise RuntimeError(f"{dataset} 第 {page} 頁回應異常:{data.get('responseMessage')}") + total_pages = int(data["totalPage"]) + rows.extend(data["responseData"]) + page += 1 + assert first is not None + log.info("%s %s:共 %d 筆", dataset, month, len(rows)) + return rows, first + + +def _int(value: str | None) -> int: + return int(value) if value not in (None, "") else 0 + + +def parse_population(rows: Iterable[Mapping[str, str]]) -> list[VillagePopulation]: + out = [] + for r in rows: + ages = [ + _int(r.get(f"people_age_{a:03d}_m")) + _int(r.get(f"people_age_{a:03d}_f")) for a in range(100) + ] + ages.append(_int(r.get("people_age_100up_m")) + _int(r.get("people_age_100up_f"))) + total = _int(r["people_total"]) + if sum(ages) != total: + log.warning("%s 年齡加總 %d 與總人口 %d 不符", r["district_code"], sum(ages), total) + out.append(VillagePopulation(r["district_code"], r["site_id"], r["village"], total, tuple(ages))) + return out + + +def parse_indigenous(rows: Iterable[Mapping[str, str]]) -> list[VillageIndigenous]: + return [ + VillageIndigenous( + r["district_code"], + _int(r.get("indigenous_plain_total_m")) + _int(r.get("indigenous_plain_total_f")), + _int(r.get("indigenous_mountain_total_m")) + _int(r.get("indigenous_mountain_total_f")), + ) + for r in rows + ] + + +def load_population(month: str = POPULATION_MONTH_ROC) -> tuple[list[VillagePopulation], FetchResult]: + rows, result = _pages("ODRP014", month) + return parse_population(rows), result + + +def load_indigenous(month: str = POPULATION_MONTH_ROC) -> tuple[list[VillageIndigenous], FetchResult]: + rows, result = _pages("ODRP013", month) + return parse_indigenous(rows), result + + +def parse_county_population(rows: Sequence[Sequence[object]], month: str) -> dict[str, int]: + """「縣市別」工作表 → 目前的縣市代碼 → 月底人口;總計列記為 00000。 + + 改制前的舊縣市加到改制後的直轄市(臺中縣+臺中市 → 66000)。 + 省(臺灣省、福建省)是小計,東沙、南沙群島沒有戶籍人口,都略過。 + """ + text = _text + roc_year, roc_month = int(month[:3]), int(month[3:]) + if not any(f"{roc_year}年{roc_month}月" in text(c) for row in rows[:4] for c in row): + raise ValueError(f"縣市人口統計表的年月不是 {month}") + column = next( + (i for row in rows[:6] for i, c in enumerate(row) if text(c) == "人口數"), + None, + ) + if column is None: + raise ValueError("縣市人口統計表找不到「人口數」欄") + out: dict[str, int] = defaultdict(int) + for row in rows: + name = text(row[0]) if row else "" + if name == "總計": + out["00000"] = int(float(str(row[column]))) + elif code := COUNTY_CODE_BY_NAME.get(name): + out[code] += int(float(str(row[column]))) + if "00000" not in out: + raise ValueError("縣市人口統計表沒有總計列") + counted = sum(v for k, v in out.items() if k != "00000") + if counted != out["00000"]: + raise ValueError(f"各縣市人口加總 {counted} 與總計 {out['00000']} 不符") + return dict(out) + + +def _text(cell: object) -> str: + return "" if cell is None or (isinstance(cell, float) and cell != cell) else normalize_name(str(cell)) + + +def parse_year_end_population(rows: Sequence[Sequence[object]], roc_year: int) -> dict[str, int]: + """「縣市人口按性別及五齡組」的一年:每個地區三列(計、男、女),名稱寫在「男」那一列, + 總人口在「計」那一列的「總計」欄。""" + if not any(f"{roc_year}年底" in _text(c) for row in rows[:3] for c in row): + raise ValueError(f"年底人口表的年份不是 {roc_year}") + column = next((i for row in rows[:5] for i, c in enumerate(row) if _text(c) == "總計"), None) + if column is None: + raise ValueError("年底人口表找不到「總計」欄") + out: dict[str, int] = defaultdict(int) + for i, row in enumerate(rows[1:], start=1): + name = _text(row[0]) if row else "" + code = "00000" if name == "總計" else COUNTY_CODE_BY_NAME.get(name) + if code is None: + continue + total_row = rows[i - 1] + if _text(total_row[1]) != "計": + raise ValueError(f"年底人口表的 {name} 上一列不是「計」") + out[code] += int(float(str(total_row[column]))) + counted = sum(v for k, v in out.items() if k != "00000") + if "00000" not in out or counted != out["00000"]: + raise ValueError(f"年底人口表各縣市加總 {counted} 與總計 {out.get('00000')} 不符") + return dict(out) + + +@dataclass(frozen=True) +class CountyPopulation: + totals: dict[str, int] + source: FetchResult + #: 實際用到的民國年月(87 年以前只有年底數字,可能和要求的月份不同) + month: str + title: str + + +def load_county_population(month: str) -> CountyPopulation: + """某個月底各縣市(目前的縣市代碼)與全國(00000)的戶籍人口,給 2018 年以前的經費上限用。 + + 97 年起用月報;87–96 年用每年一份、每月一張工作表的村里鄰戶數表;更早的月份沒有月報, + 改用最接近的年底數字(同一年年底)。""" + import pandas as pd + + def fetch(table: CountyTable, d5c: str, name: str) -> FetchResult: + return download_form( + STAT_PAGE, + STAT_VIEW, + RAW_DIR / "ris-stat" / f"{table.code}_{name}.ods", + {"type": "ods", "m4c": table.code, "d5c": d5c}, + ) + + roc_year = int(month[:3]) + if month >= MONTHLY_TABLE.first: + res = fetch(MONTHLY_TABLE, month, month) + sheet = pd.read_excel(res.path, engine="odf", sheet_name="縣市別", header=None) + return CountyPopulation( + parse_county_population(sheet.values.tolist(), month), res, month, MONTHLY_TABLE.title + ) + if month >= YEARLY_TABLE.first: + res = fetch(YEARLY_TABLE, f"{month[:3]}00", month[:3]) + sheet = pd.read_excel(res.path, engine="odf", sheet_name=f"{roc_year}{month[3:]}", header=None) + return CountyPopulation( + parse_county_population(sheet.values.tolist(), month), res, month, YEARLY_TABLE.title + ) + res = fetch(YEAR_END_TABLE, "", "all") + sheet = pd.read_excel(res.path, engine="odf", sheet_name=str(roc_year), header=None) + totals = parse_year_end_population(sheet.values.tolist(), roc_year) + return CountyPopulation(totals, res, f"{month[:3]}12", YEAR_END_TABLE.title) diff --git a/backend/data/pipeline/src/election_data/races2024.py b/backend/data/pipeline/src/election_data/races2024.py new file mode 100644 index 0000000..b07d31f --- /dev/null +++ b/backend/data/pipeline/src/election_data/races2024.py @@ -0,0 +1,413 @@ +"""總統、區域立委的劇本資料(全台)。總統:1996 年第一次直選到 2024 年;區域立委:2020、2024 年。 + +輸出(格式同 local2022,見 protocol 的 LocalElectionSpec): + data/build/scenarios/<年>-president/00000.json + data/build/scenarios/<年>-legislator/<縣市代碼>-<選區>.json +原住民立委(全國不分區的複數選區)與不分區政黨票不在這裡。 +2014 年以前的總統選舉用中選會流水號代碼,各里得票用名稱對到目前的村里(legacy.py); +對不到的票記在鄉鎮或縣市層級,各縣市總數和中選會一致(總統劇本的地圖本來就是一個縣市一區)。 +""" + +from __future__ import annotations + +import json +import logging +import math +from collections import Counter, defaultdict +from collections.abc import Hashable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path + +from .cec import CecArchive, fetch_votedata +from .codes import cec_village_code, county_code, normalize_name +from .config import BUILD_DIR +from .elections import ( + _cross_village_map, + apportion, + candidate_party, + election_by_id, + is_subtotal_box, + load_election, +) +from .geo import VillageShape, fetch_boundaries, load_villages +from .impute import NeighborIndex +from .legacy import load_gazetteer +from .local2022 import COUNTY_NAMES, FINANCE_DIR, cap_population, clean_name +from .pack import NAME_SNAPSHOTS_ROC +from .population import VillagePopulation, load_population + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class NationalRace: + year: int + date: str + #: 競選經費上限的人口基準:投票月前第六個月的月底 + cap_month: str + #: 監察院政治獻金平臺上的選舉名稱年份(民國);2018 年以前的選舉平臺上沒有候選人的申報 + finance_year: str + #: 區域立委的中選會資料夾,例如「2024總統立委」;None 表示這一年只做總統 + #: (2016 年以前沒有村里層級的月人口可算立委選區的經費上限,2008 年以前還是一區多席) + folder: str | None = None + + @property + def legislator_folder(self) -> str: + if self.folder is None: + raise ValueError(f"{self.year} 年沒有整理區域立委") + return f"{self.folder}/區域立委" + + @property + def out_president(self) -> Path: + return BUILD_DIR / "scenarios" / f"{self.year}-president" + + @property + def out_legislator(self) -> Path: + return BUILD_DIR / "scenarios" / f"{self.year}-legislator" + + +#: 2024:人口基準 2023-07-31。2020:2019-07-31,用這個基準重算 2020 年總統選舉, +#: 得到中選會公告的 4 億 3,029 萬 7 千元,驗證無誤。 +#: 2016 年以前:人口基準用戶政司的縣市統計表(population.load_county_population); +#: 1996 年的基準月(1995 年 9 月)沒有月報,用 1995 年底。 +NATIONAL_RACES = { + 2024: NationalRace(2024, "2024-01-13", "11207", "113", "2024總統立委"), + 2020: NationalRace(2020, "2020-01-11", "10807", "109", "2020總統立委"), + 2016: NationalRace(2016, "2016-01-16", "10407", "105"), + 2012: NationalRace(2012, "2012-01-14", "10007", "101"), + 2008: NationalRace(2008, "2008-03-22", "09609", "097"), + 2004: NationalRace(2004, "2004-03-20", "09209", "093"), + 2000: NationalRace(2000, "2000-03-18", "08809", "089"), + 1996: NationalRace(1996, "1996-03-23", "08409", "085"), +} +OUT_PRESIDENT = NATIONAL_RACES[2024].out_president +OUT_LEGISLATOR = NATIONAL_RACES[2024].out_legislator + + +def president_cap(population: int) -> int: + """總統副總統選罷法第 38 條:人口總數 × 70% × 20 元(千元以下進位)+ 1 億元""" + return math.ceil(population * 0.7 * 20 / 1000) * 1000 + 100_000_000 + + +def legislator_cap(population: int) -> int: + """選罷法第 41 條:選區人口 × 70% × 基本金額 30 元(千元以下進位)+ 1,000 萬元。 + 基本金額依選罷法施行細則;與中選會公告的逐區數字尚待核對。""" + return math.ceil(population * 0.7 * 30 / 1000) * 1000 + 10_000_000 + + +@dataclass +class District: + county: str + code: str + name: str + candidates: list[dict] = field(default_factory=list) + villages: dict[str, dict] = field(default_factory=dict) + + +def _finance(election: str, area: str) -> dict[str, dict[str, int]]: + path = FINANCE_DIR / f"{election}-{area}.json" + if not path.exists(): + log.warning("沒有政治獻金資料:%s %s", election, area or "(全國)") + return {} + data = json.loads(path.read_text(encoding="utf-8")) + # 總統選舉的申報以「正、副」兩人並列(例如「賴清德、蕭美琴」),用正手的名字對照 + return { + clean_name(c["name"]).split("、")[0]: {"income": c["income"], "spending": c["spending"]} + for c in data["candidates"] + } + + +def _party_names(archive: CecArchive, folder: str) -> dict[str, str]: + return {row[0]: row[1] for row in archive.rows(folder, "elpaty") if len(row) >= 2} + + +def _party(names: dict[str, str], code: str) -> str | None: + return candidate_party(names.get(code, "")) + + +def _write(path: Path, payload: dict) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + return path + + +def remap_population(old: Sequence[VillagePopulation], now: Sequence[VillagePopulation]) -> dict[str, int]: + """舊月份的村里人口,鄉鎮代碼和現在不同時改用里名對照到目前的代碼。 + + 例如 2019 年高雄市三民區、鳳山區各分兩個戶政所(64000051、64000052), + 里的代碼和現在(64000050)不一樣,但同一區裡的里名不變。 + 鄉鎮代碼現在還在的里維持原代碼(已合併的舊里,得票也記在舊代碼上)。 + """ + towns = {p.code[:8] for p in now} + by_name: dict[tuple[str, str], list[str]] = defaultdict(list) + for p in now: + by_name[(p.code[:7], normalize_name(p.village))].append(p.code) + out: dict[str, int] = defaultdict(int) + for p in old: + match = [] if p.code[:8] in towns else by_name.get((p.code[:7], normalize_name(p.village)), []) + # 對不到的保留原代碼:全國總數不變(總統的經費上限用得到),只是不會算進任何選區 + out[match[0] if len(match) == 1 else p.code] += p.total + return dict(out) + + +def _inputs(cap_month: str): + vote = fetch_votedata() + archive = CecArchive(vote.path) + pop_now, _ = load_population() + pop_cap, cap_res = load_population(cap_month) + adults = {p.code: float(p.adults) for p in pop_now} + names: dict[tuple[str, str], str] = {} + for month in NAME_SNAPSHOTS_ROC: + older, _ = load_population(month) + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in older} + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in pop_now} + population = remap_population(pop_cap, pop_now) + sites = {p.code: p.site for p in pop_now} + return vote, archive, adults, names, population, cap_res, sites + + +def build_president(out_dir: Path | None = None, year: int = 2024) -> Path: + race = NATIONAL_RACES[year] + out_dir = out_dir or race.out_president + election = election_by_id(f"{year}-president") + folder, suffix = election.folders[0], election.suffix + vote = fetch_votedata() + archive = CecArchive(vote.path) + pop_now, _ = load_population() + adults = {p.code: float(p.adults) for p in pop_now} + names: dict[tuple[str, str], str] = {} + for month in NAME_SNAPSHOTS_ROC: + older, _ = load_population(month) + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in older} + names |= {(p.code[:8], normalize_name(p.village)): p.code for p in pop_now} + population, cap_title, cap_res = cap_population(race.cap_month) + parties = _party_names(archive, folder) + rows = list(archive.rows(folder, "elcand" + suffix)) + mates = {row[5]: clean_name(row[6]) for row in rows if len(row) > 15 and row[15] == "Y"} + finance = _finance(f"{race.finance_year.lstrip('0')}年總統、副總統選舉", "") + candidates = [ + { + "number": int(row[5]), + "name": clean_name(row[6]), + "party": _party(parties, row[7]), + "runningMate": mates.get(row[5]), + "finance": finance.get(clean_name(row[6])), + } + for row in rows + if not (len(row) > 15 and row[15] == "Y") + ] + gazetteer = load_gazetteer() if election.legacy_codes else None + results = load_election( + archive, election, None, weights=adults, village_names=names, by_candidate=True, gazetteer=gazetteer + ) + total_pop = population["00000"] + by_village = { + code: {"electors": r.electors, "ballots": r.ballots, "valid": r.valid, "votes": dict(r.votes)} + for code, r in results.by_village.items() + } + payload = { + "electionId": f"{year}-president", + "electionDate": race.date, + "kind": "president", + "countyCode": "00000", + "countyName": "全國", + "areaName": "全國", + "office": "總統", + "regionLevel": "county", + "packId": f"00000-before-{race.date}", + "spendingCap": president_cap(total_pop), + "capPopulation": total_pop, + "candidates": sorted(candidates, key=lambda c: c["number"]), + "byVillage": by_village, + # 中選會「全國」那一列的有效票(各縣市列不重複加總) + "cecValid": results.cec_valid_by_county.get("00000"), + "sources": { + "results": { + "title": "中選會選舉資料庫 votedata", + "url": vote.url, + "retrievedAt": vote.retrieved_at, + }, + "population": {"title": cap_title, "retrievedAt": cap_res.retrieved_at}, + "finance": "監察院政治獻金公開查閱平臺(election-data donations)", + }, + } + return _write(out_dir / "00000.json", payload) + + +def _district_results( + archive: CecArchive, adults: dict[str, float], names: dict, folder: str +) -> dict[tuple[str, str], District]: + """各選區各里的候選人得票(跨村里投開票所依成年人口比例分配,與 load_election 相同)""" + cross = _cross_village_map(archive, folder, names) + districts: dict[tuple[str, str], District] = {} + for row in archive.rows(folder, "elbase"): + if row[3] == "000" and row[2] != "00": + key = (county_code(row[0], row[1]), row[2]) + districts[key] = District(key[0], row[2], row[5]) + + def targets(row: list[str]) -> list[str] | None: + code = cec_village_code(row[0], row[1], row[3], row[4]) + return [code] if code else cross.get((row[0], row[1], row[3], row[4])) + + def split(total: int, codes: list[str]) -> list[int]: + return apportion(total, [adults.get(c, 0.0) for c in codes]) + + votes: dict[tuple[str, str], dict[str, dict[str, int]]] = defaultdict( + lambda: defaultdict(lambda: defaultdict(int)) + ) + for row in archive.rows(folder, "elctks"): + if row[3] == "000" or row[4] == "0000" or not is_subtotal_box(row[5]): + continue + codes = targets(row) + if not codes: + continue + key = (county_code(row[0], row[1]), row[2]) + for code, n in zip(codes, split(int(row[7]), codes), strict=True): + votes[key][code][f"#{row[6]}"] += n + prof: dict[tuple[str, str], dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0, 0])) + for row in archive.rows(folder, "elprof"): + if row[3] == "000" or row[4] == "0000" or not is_subtotal_box(row[5]): + continue + codes = targets(row) + if not codes: + continue + key = (county_code(row[0], row[1]), row[2]) + valid, ballots, electors = int(row[6]), int(row[8]), int(row[9]) + for code, e, b, v in zip( + codes, split(electors, codes), split(ballots, codes), split(valid, codes), strict=True + ): + acc = prof[key][code] + acc[0] += e + acc[1] += b + acc[2] += v + for key, district in districts.items(): + for code, v in votes[key].items(): + e, b, val = prof[key].get(code, [0, 0, 0]) + district.villages[code] = {"electors": e, "ballots": b, "valid": val, "votes": dict(v)} + return districts + + +def district_towns(villages: set[str], sites: dict[str, str], county_name: str) -> list[dict]: + """選區涵蓋的鄉鎮市區;只涵蓋部分里的標 partial(例如臺北市第 1 選區的士林區)""" + by_town: dict[str, set[str]] = defaultdict(set) + for code in sites: + by_town[code[:8]].add(code) + towns = [] + for town in sorted({v[:8] for v in villages}): + members = by_town.get(town, set()) + site = next((sites[c] for c in sorted(members)), "") + towns.append( + { + "code": town, + "name": site.removeprefix(county_name) or town, + "partial": bool(members - villages), + } + ) + return towns + + +def assign_orphans[K: Hashable]( + district_of: Mapping[str, K], shapes: Sequence[VillageShape], index: NeighborIndex +) -> dict[str, K]: + """沒有開票紀錄的里(選舉後才分出來的新里)歸到相鄰的里最多的那個選區。 + + 先看同鄉鎮市區的鄰居,沒有才看同縣市的鄰居;鄰居也是新里時,一輪一輪往外推。 + """ + pending = sorted(s.code for s in shapes if s.code not in district_of) + assigned: dict[str, K] = {} + while pending: + rest = [] + for code in pending: + near = [n for n in index.neighbors(code) if n[:5] == code[:5]] + for group in ([n for n in near if n[:8] == code[:8]], near): + votes = Counter( + d for d in (district_of.get(n, assigned.get(n)) for n in group) if d is not None + ) + if votes: + assigned[code] = min(votes, key=lambda d: (-votes[d], str(d))) + break + else: + rest.append(code) + if len(rest) == len(pending): + log.warning("找不到相鄰選區的里:%s", rest) + break + pending = rest + return assigned + + +def build_legislators(out_dir: Path | None = None, year: int = 2024) -> list[Path]: + race = NATIONAL_RACES[year] + out_dir = out_dir or race.out_legislator + vote, archive, adults, names, population, cap_res, sites = _inputs(race.cap_month) + parties = _party_names(archive, race.legislator_folder) + districts = _district_results(archive, adults, names, race.legislator_folder) + finance: dict[str, dict[str, dict[str, int]]] = {} + for row in archive.rows(race.legislator_folder, "elcand"): + key = (county_code(row[0], row[1]), row[2]) + if key not in districts: + continue + county = key[0] + if county not in finance: + finance[county] = _finance(f"{race.finance_year}年立法委員選舉", COUNTY_NAMES[county]) + name = clean_name(row[6]) + districts[key].candidates.append( + { + "number": int(row[5]), + "name": name, + "party": _party(parties, row[7]), + "finance": finance[county].get(name), + } + ) + # 新設的里:沒有開票紀錄,但地圖上有,歸到相鄰的選區(選舉人數記 0) + shapes = load_villages(fetch_boundaries().path) + district_of = {v: key for key, d in districts.items() for v in d.villages} + # 只處理一般的村里(代碼全是數字);界線圖裡的離島、河川、港區代碼(S01、R01、P01、I01)不是村里 + counties = {k[0] for k in districts} + in_scope = [sh for sh in shapes if sh.code.isdigit() and sh.county_code in counties] + for code, key in assign_orphans(district_of, in_scope, NeighborIndex(shapes)).items(): + districts[key].villages[code] = {"electors": 0, "ballots": 0, "valid": 0, "votes": {}} + log.info("新設的里 %s 歸入 %s 第 %s 選區", code, COUNTY_NAMES[key[0]], key[1]) + written = [] + for (county, code), d in sorted(districts.items()): + if not d.candidates or not d.villages: + continue + pop = sum(population.get(v, 0) for v in d.villages) + number = int(code) + area = ( + f"{COUNTY_NAMES[county]}第 {number} 選舉區" + if len([k for k in districts if k[0] == county]) > 1 + else COUNTY_NAMES[county] + ) + payload = { + "electionId": f"{year}-legislator", + "electionDate": race.date, + "kind": "legislator", + "countyCode": county, + "countyName": COUNTY_NAMES[county], + "areaName": area, + "districtCode": code, + "towns": district_towns(set(d.villages), sites, COUNTY_NAMES[county]), + "office": "立法委員", + "regionLevel": "town", + "packId": f"{county}-before-{race.date}", + "spendingCap": legislator_cap(pop), + "capPopulation": pop, + "candidates": sorted(d.candidates, key=lambda c: c["number"]), + "byVillage": d.villages, + "cecValid": None, + "sources": { + "results": { + "title": "中選會選舉資料庫 votedata", + "url": vote.url, + "retrievedAt": vote.retrieved_at, + }, + "population": { + "title": f"戶政司村里人口 {race.cap_month}", + "retrievedAt": cap_res.retrieved_at, + }, + "finance": "監察院政治獻金公開查閱平臺(election-data donations)", + }, + } + written.append(_write(out_dir / f"{county}-{code}.json", payload)) + log.info("區域立委:%d 個選區", len(written)) + return written diff --git a/backend/data/pipeline/src/election_data/records/__init__.py b/backend/data/pipeline/src/election_data/records/__init__.py new file mode 100644 index 0000000..d1f1c50 --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/__init__.py @@ -0,0 +1,12 @@ +"""歷屆參選人的選舉紀錄與客觀資歷分數(docs:政治人物資料庫)。 + +只用中選會選舉資料庫的公開紀錄(加上監察院政治獻金收支結算表)計算,不用 AI、不寫評價: + +- folders.py:要讀的中選會資料夾(1994–2022 省長、直轄市長、縣市長、省議員、直轄市議員、縣市議員; + 1996–2024 總統副總統;1995–2024 區域、原住民立委;2008–2024 不分區立委) +- parse.py:逐資料夾讀候選人、得票、當選(副總統候選人、不分區政黨名單也收) +- link.py:跨屆把同一個人串起來(同名+出生年;沒有出生年才用同名+同縣市,標「比對信心:低」) +- scores.py:五項 0–10 的資歷分數,每項附算法與出處 +- council.py:2022(與 2018、2014)年各議員選區的範圍、席次、候選人與當選門檻 +- build.py:輸出 data/build/people/records.json、records-report.md、data/build/council/<年>.json +""" diff --git a/backend/data/pipeline/src/election_data/records/build.py b/backend/data/pipeline/src/election_data/records/build.py new file mode 100644 index 0000000..b33fca6 --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/build.py @@ -0,0 +1,475 @@ +"""輸出歷屆參選人資料庫(縣市長、議員、總統副總統、立委): + +- data/build/people/records.json:每個人的歷次參選與五項資歷分數(算法、出處、依據) +- data/build/people/records-report.md:各選舉人數、串人結果、對不到的情況、這次新增的中央選舉 +- data/build/council/<年>.json:各議員選區的範圍、席次、候選人、當選門檻(2022、2018、2014) + +只讀本機的 data/raw/cec/votedata.zip(不會下載),檔案不存在就丟出錯誤。 +""" + +from __future__ import annotations + +import json +import logging +from collections import Counter, defaultdict +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any + +from ..cec import VOTEDATA_PATH, CecArchive +from ..config import BUILD_DIR, PROTOCOL_VERSION +from .council import RunKey, build_council_year, run_key, uncovered_villages +from .folders import ( + CHIAYI_2022, + COUNCIL_YEARS, + FOLDERS, + LEGISLATOR, + NATIONWIDE, + PARTY_LIST, + PRESIDENT, + VICE_PRESIDENT, + RaceFolder, + council_folders, +) +from .link import LinkReport, Person, link_runs +from .parse import Run, parse_chiayi_2022, parse_folder +from .scores import SCORE_DEFS, Score, load_finance, peer_averages, score_person + +log = logging.getLogger(__name__) + +PEOPLE_DIR = BUILD_DIR / "people" +COUNCIL_DIR = BUILD_DIR / "council" +FINANCE_DIR = BUILD_DIR / "finance" +PACKS_DIR = BUILD_DIR / "packs" +NOTE = "分數是依公開選舉紀錄計算的遊戲數值,不代表對個人的評價" + + +@dataclass(frozen=True) +class Loaded: + runs: tuple[Run, ...] + #: 定義了、但壓縮檔裡沒有的資料夾 + missing: tuple[str, ...] + #: 姓名空白、沒有收的列 + blank: tuple[Run, ...] = () + + +def _present(archive: CecArchive, rf: RaceFolder) -> bool: + """資料夾在壓縮檔裡(不分區看政黨名單檔,其他看候選人檔;2016 年的檔名有後綴)""" + return archive.has(rf.folder, ("elrepm" if rf.is_party_list else "elcand") + rf.suffix) + + +def load_runs(archive: CecArchive) -> Loaded: + runs: list[Run] = [] + missing: list[str] = [] + for rf in FOLDERS: + if not _present(archive, rf): + missing.append(rf.folder) + continue + runs.extend(parse_folder(archive, rf)) + try: + runs.extend(parse_chiayi_2022(archive)) + except FileNotFoundError: + missing.append(CHIAYI_2022.folder) + # 候選人檔姓名空白的列(2002 縣市議員有一筆)沒辦法串人,不收、列在報告裡 + blank = tuple(r for r in runs if not r.name) + return Loaded(tuple(r for r in runs if r.name), tuple(missing), blank) + + +def run_json(r: Run) -> dict[str, Any]: + return { + "year": r.year, + "date": r.date, + "election": r.election, + "office": r.office, + "indigenous": r.indigenous, + "county": r.county, + "countyCode": r.county_code, + "district": r.district, + "number": r.number, + "party": r.party, + "votes": r.votes, + "share": r.share, + "elected": r.elected, + "incumbent": r.incumbent, + # 中央選舉才有的欄位:有值才輸出(檔案小一點) + **{ + k: v + for k, v in ( + ("runningMate", r.running_mate), + ("listRank", r.list_rank), + ("partyVotes", r.party_votes), + ("partyShare", r.party_share), + ) + if v is not None + }, + } + + +def person_json(p: Person, scores: Sequence[Score]) -> dict[str, Any]: + runs = p.runs + parties: list[str | None] = [] + for r in reversed(runs): + if r.party not in parties: + parties.append(r.party) + return { + "id": p.id, + "name": p.name, + "gender": p.gender, + "birthYear": p.birth_year, + "confidence": p.confidence, + **({"matchNote": p.note} if p.note else {}), + "counties": sorted({r.county_code for r in runs if r.county_code}), + "parties": parties, + "stats": { + "runs": len(runs), + "wins": sum(r.elected for r in runs), + "firstYear": runs[0].year, + "lastYear": runs[-1].year, + "maxVotes": max((r.votes or 0 for r in runs), default=0), + }, + "runs": [run_json(r) for r in runs], + "scores": [{"key": s.key, "value": s.value, "basis": s.basis} for s in scores], + } + + +def _sort_key(p: dict[str, Any]) -> tuple[int, int, str]: + return (-p["stats"]["lastYear"], -p["stats"]["maxVotes"], p["name"]) + + +def _sources(archive: CecArchive) -> list[dict[str, Any]]: + meta_path = archive.path.with_name(archive.path.name + ".meta.json") + meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.is_file() else {} + return [ + { + "title": "中央選舉委員會選舉資料庫", + "url": meta.get("url", "https://data.cec.gov.tw/選舉資料庫/votedata.zip"), + "retrievedAt": meta.get("retrievedAt"), + "sha256": meta.get("sha256"), + "license": "政府資料開放授權條款第 1 版", + }, + { + "title": "監察院政治獻金公開查閱平臺", + "url": "https://ardata.cy.gov.tw", + "note": "只用了 data/build/finance 已整理的 2018、2022 年縣市長收支結算表", + "license": "政府資料開放授權條款第 1 版", + }, + ] + + +def _elections(runs: Sequence[Run]) -> list[dict[str, Any]]: + stats: dict[str, dict[str, Any]] = {} + for r in runs: + e = stats.setdefault( + r.folder, + { + "folder": r.folder, + "year": r.year, + "date": r.date, + # 總統副總統選舉一個資料夾裡有兩種參選人 + "election": "總統副總統" if r.office == "president" else r.election, + "office": r.office, + "indigenous": r.indigenous, + "candidates": 0, + "elected": 0, + "noVotes": 0, + }, + ) + e["candidates"] += 1 + e["elected"] += r.elected + # 不分區立委本來就沒有個人得票,不算「沒有得票數」 + e["noVotes"] += r.votes is None and r.election != PARTY_LIST + return sorted(stats.values(), key=lambda e: (e["date"], e["office"] != "mayor", e["folder"])) + + +def person_index(people: Sequence[Person]) -> dict[RunKey, str]: + """(資料夾, 省市, 縣市, 選區代碼, 號次) → 人物 id(議員選區檔用)""" + return {run_key(r): p.id for p in people for r in p.runs} + + +def build_records( + archive_path: Path = VOTEDATA_PATH, + people_dir: Path = PEOPLE_DIR, + council_dir: Path = COUNCIL_DIR, + finance_dir: Path = FINANCE_DIR, + packs_dir: Path = PACKS_DIR, + council_years: Sequence[int] = COUNCIL_YEARS, +) -> list[Path]: + if not archive_path.is_file(): + raise FileNotFoundError(f"找不到中選會選舉資料庫:{archive_path}(這個指令不會自動下載)") + archive = CecArchive(archive_path) + loaded = load_runs(archive) + people, link_report = link_runs(loaded.runs) + peers = peer_averages(loaded.runs) + finance = load_finance(finance_dir) + entries = sorted((person_json(p, score_person(p, peers, finance)) for p in people), key=_sort_key) + elections = _elections(loaded.runs) + payload = { + "protocolVersion": PROTOCOL_VERSION, + "generatedAt": date.today().isoformat(), + "note": NOTE, + "sources": _sources(archive), + "scoreDefs": [ + {"key": d.key, "label": d.label, "formula": d.formula, "source": d.source} for d in SCORE_DEFS + ], + "elections": elections, + "people": entries, + } + people_dir.mkdir(parents=True, exist_ok=True) + records_path = people_dir / "records.json" + records_path.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + outputs = [records_path] + + ids = person_index(people) + council_dir.mkdir(parents=True, exist_ok=True) + council_summary: list[dict[str, Any]] = [] + for year in council_years: + folders = council_folders(year) + if not folders or any(f.folder in loaded.missing for f in folders): + continue + body, unmatched = build_council_year(archive, folders, loaded.runs, ids, packs_dir) + uncovered = uncovered_villages(body["districts"], packs_dir) + council = { + "protocolVersion": PROTOCOL_VERSION, + "year": year, + "date": folders[0].date, + "source": _sources(archive)[0], + **body, + "unmatchedVillages": unmatched, + "uncoveredVillages": uncovered, + } + path = council_dir / f"{year}.json" + path.write_text(json.dumps(council, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + outputs.append(path) + council_summary.append( + { + "year": year, + "districts": len(body["districts"]), + "unmatched": unmatched, + "uncovered": uncovered, + "seats": sum(d["seats"] for d in body["districts"]), + } + ) + report = people_dir / "records-report.md" + skipped = [f for f in archive.folders() if f.startswith(BY_ELECTION_PREFIX)] + report.write_text( + render_report(loaded, people, link_report, elections, entries, council_summary, skipped), + encoding="utf-8", + ) + outputs.append(report) + return outputs + + +#: 立委補選的資料夾(沒有投票日,沒有收;列在報告裡) +BY_ELECTION_PREFIX = "立委補選/" +CENTRAL_OFFICES = frozenset({"president", "legislator"}) + + +def central_kind(r: Run) -> str: + """報告用的中央選舉類別:總統、副總統、區域立委、平地原住民立委、山地原住民立委、不分區立委""" + if r.election == PARTY_LIST: + return "不分區立委" + if r.office == "legislator": + return f"{r.indigenous}立委" if r.indigenous else "區域立委" + return r.election + + +def _span(runs: Sequence[Run]) -> str: + years = sorted({r.year for r in runs}) + return f"{years[0]}–{years[-1]}({len(years)} 次)" if years else "無" + + +def near_misses(people: Sequence[Person]) -> list[tuple[Person, Person]]: + """同名、出生年只差 1 年、其中一位有總統副總統或立委紀錄的兩個人(照規則不串,列給人工抽查)。 + + 中選會不同年份的檔案偶爾把同一個人的出生年寫得不一樣,但也可能真的是兩個人,所以只列出來。""" + by_name: dict[str, list[Person]] = defaultdict(list) + for p in people: + if p.birth_year is not None: + by_name[p.name].append(p) + out = [] + for group in by_name.values(): + for i, a in enumerate(group): + for b in group[i + 1 :]: + central = any(r.office in CENTRAL_OFFICES for r in (*a.runs, *b.runs)) + gap = abs((a.birth_year or 0) - (b.birth_year or 0)) + if central and gap == 1: + out.append((a, b) if a.runs[0].date <= b.runs[0].date else (b, a)) + return sorted(out, key=lambda ab: (ab[0].name, ab[0].runs[0].date)) + + +def _runs_text(p: Person) -> str: + return "、".join(f"{r.year} {r.county} {r.election}" for r in p.runs) + + +def render_central( + loaded: Loaded, people: Sequence[Person], link: LinkReport, skipped: Sequence[str] +) -> list[str]: + """這次新增的中央選舉(總統副總統、立委):幾筆、幾人、串到既有的人幾位、沒有收的""" + central = [r for r in loaded.runs if r.office in CENTRAL_OFFICES] + kinds = Counter(central_kind(r) for r in central) + order = ["總統", "副總統", "區域立委", "平地原住民立委", "山地原住民立委", "不分區立委"] + touched = [p for p in people if any(r.office in CENTRAL_OFFICES for r in p.runs)] + both = [p for p in touched if any(r.office not in CENTRAL_OFFICES for r in p.runs)] + names = {r.name for r in central} + split = [(n, b, k) for n, b, k in link.splits if n in names] + no_birth = [r for r in central if r.birth_year is None] + misses = near_misses(people) + president = [r for r in central if r.election in (PRESIDENT, VICE_PRESIDENT)] + district = [r for r in central if r.election == LEGISLATOR] + plist = [r for r in central if r.election == PARTY_LIST] + by_elections = "、".join(f.removeprefix(BY_ELECTION_PREFIX) for f in skipped) + lines = [ + "## 這次新增:總統副總統、立法委員", + "", + f"- 新增參選紀錄 {len(central):,} 筆:" + "、".join(f"{k} {kinds[k]:,}" for k in order if kinds[k]), + f"- 年份:總統副總統 {_span(president)};區域與原住民立委 {_span(district)};" + f"不分區立委 {_span(plist)}", + f"- 這些紀錄屬於 {len(touched):,} 人:其中 {len(both):,} 人原本就有縣市長、議員紀錄" + f"(同名+出生年串在一起),{len(touched) - len(both):,} 人只有總統副總統或立委紀錄(新增的人)", + "- 副總統候選人也是一筆參選紀錄(選舉寫「副總統」),得票、得票率、當選跟同一組的總統候選人", + "- 不分區立委沒有個人得票(得票、得票率留空),另記政黨名單排名與所屬政黨的全國政黨票", + f"- 中央選舉紀錄沒有出生年(比對信心會變低):{len(no_birth)} 筆", + *[f" - {r.year} {r.election} {r.name}" for r in no_birth], + f"- 同名同出生年、但同一天參選兩次而拆開的組(含中央選舉的名字):{len(split)} 組", + *[f" - {n}({b} 年生)拆成 {k} 人" for n, b, k in split], + "- 出生年差 1 年、串在一起的(同名、有中央選舉紀錄、同黨或人工確認;比對信心:低):" + f"{len(link.near_merged)} 組", + *[f" - {n}({a}、{b} 年生):{why}" for n, a, b, why in link.near_merged], + f"- 比對不到:同名、但兩個檔案的出生年差 1 年,政黨不同或沒有政黨、沒有串在一起的(可人工抽查):" + f"{len(misses)} 組", + *[ + f" - {a.name}:{a.birth_year} 年生({_runs_text(a)})/{b.birth_year} 年生({_runs_text(b)})" + for a, b in misses + ], + "- 沒有收:", + " - 1995–2004 年的全國不分區、僑選立委:壓縮檔裡沒有這幾屆的政黨名單", + f" - 立委補選({len(skipped)} 個資料夾:{by_elections}):" + "資料裡沒有投票日,一半的資料夾名稱也沒有年份", + " - 「2008 12任總統」和「20080322-總統」內容相同,只收後者;「2016總統立委/old」是舊版,沒有收", + " - 1992 年以前的立委、國大代表(壓縮檔裡沒有,或不在這次範圍)", + "", + ] + return lines + + +def render_report( + loaded: Loaded, + people: Sequence[Person], + link: LinkReport, + elections: Sequence[dict[str, Any]], + entries: Sequence[dict[str, Any]], + council: Sequence[dict[str, Any]], + skipped: Sequence[str] = (), +) -> str: + lines = [ + "# 歷屆參選人資料庫:產出報告", + "", + f"產生日期:{date.today().isoformat()}。資料來源:中央選舉委員會選舉資料庫(data/raw/cec/votedata.zip)。", + f"{NOTE}。", + "", + "## 總數", + "", + f"- 參選紀錄:{len(loaded.runs):,} 筆(含副總統候選人;地方選舉的副手沒有收)", + f" - 縣市長、議員 {sum(r.office not in CENTRAL_OFFICES for r in loaded.runs):,} 筆;" + f"總統副總統、立委 {sum(r.office in CENTRAL_OFFICES for r in loaded.runs):,} 筆", + f"- 串成:{len(people):,} 人;參選兩次以上 {sum(len(p.runs) > 1 for p in people):,} 人;" + f"當選過 {sum(any(r.elected for r in p.runs) for p in people):,} 人", + "- 比對信心低(沒有出生年、用同名+同縣市,或出生年差 1 年串起來的):" + f"{sum(p.confidence == 'low' for p in people)} 人", + "", + *render_central(loaded, people, link, skipped), + "## 各次選舉", + "", + "| 投票日 | 選舉 | 類別 | 資料夾 | 候選人 | 當選 | 沒有得票數 |", + "|---|---|---|---|---:|---:|---:|", + ] + for e in elections: + area = e["indigenous"] or ( + "全國" if e["office"] == "president" else "不分區" if e["election"] == PARTY_LIST else "區域" + ) + lines.append( + f"| {e['date']} | {e['election']} | {area} | {e['folder']} " + f"| {e['candidates']} | {e['elected']} | {e['noVotes']} |" + ) + by_year: dict[int, Counter[str]] = defaultdict(Counter) + for r in loaded.runs: + by_year[r.year][r.office] += 1 + lines += [ + "", + "## 各年(屆)人數", + "", + "| 年 | 首長候選人 | 議員候選人 | 總統副總統候選人 | 立委候選人 |", + "|---|---:|---:|---:|---:|", + ] + for year in sorted(by_year): + y = by_year[year] + lines.append(f"| {year} | {y['mayor']} | {y['councilor']} | {y['president']} | {y['legislator']} |") + no_votes = [r for r in loaded.runs if r.votes is None and r.election != PARTY_LIST] + lines += ["", "## 比對不到的情況", ""] + lines.append(f"- 壓縮檔裡沒有的資料夾:{', '.join(loaded.missing) or '無'}") + lines.append("- 1994 年以前(例如 1993 縣市長、1994 縣市議員)壓縮檔裡沒有,沒有收") + lines.append(f"- 候選人檔姓名空白、沒有收:{len(loaded.blank)} 筆") + lines += [ + ( + f" - {r.year} {r.election} {r.party or '無黨籍'}名單第 {r.list_rank} 名" + if r.list_rank + else f" - {r.year} {r.county}{r.district or ''} {r.election} 號次 {r.number}" + ) + for r in loaded.blank + ] + lines.append(f"- 得票檔找不到總計列(得票、得票率留空):{len(no_votes)} 筆") + lines += [f" - {r.year} {r.county}{r.district or ''} {r.election} {r.name}" for r in no_votes] + lines.append(f"- 同名同出生年、但同一天參選兩次而拆開的組:{len(link.splits)} 組") + lines += [f" - {name}({birth} 年生)拆成 {n} 人" for name, birth, n in link.splits] + lines.append(f"- 沒有出生年、併進同名同縣市的人(比對信心:低):{len(link.low_merged)} 筆") + lines += [f" - {name}({county})" for name, county in link.low_merged] + lines.append(f"- 沒有出生年、自成一筆(比對信心:低):{len(link.low_alone)} 筆") + lines += [f" - {name}({county};同名同縣市 {n} 人)" for name, county, n in link.low_alone] + movers = [ + p for p in people if len({r.county_code or r.county for r in p.runs if r.county != NATIONWIDE}) > 1 + ] + lines.append( + "- 在兩個以上縣市參選、串成同一人的(同名同出生年,可人工抽查;全國性的選舉不算縣市):" + f"{len(movers)} 人" + ) + for p in movers: + runs = "、".join(f"{r.year} {r.county}{r.election}" for r in p.runs) + lines.append(f" - {p.name}({p.birth_year} 年生):{runs}") + with_finance = sum( + 1 for e in entries if any(s["key"] == "finance" and s["value"] is not None for s in e["scores"]) + ) + lines += ["", "## 分數", "", f"- 有政治獻金資料(財力分數)的人:{with_finance}", ""] + for d in SCORE_DEFS: + values = [ + s["value"] for e in entries for s in e["scores"] if s["key"] == d.key and s["value"] is not None + ] + if values: + values.sort() + lines.append( + f"- {d.label}:{len(values):,} 人有分數,中位數 {values[len(values) // 2]},最高 {values[-1]}" + ) + lines += ["", "## 議員選區檔", ""] + for c in council: + reasons = Counter(u["reason"] for u in c["unmatched"]) + lines.append(f"### {c['year']} 年:{c['districts']} 個選區、{c['seats']} 席") + lines.append("") + lines.append(f"- 村里代碼對不上目前資料包:{len(c['unmatched'])} 筆") + lines += [f" - {reason}:{n} 筆" for reason, n in reasons.most_common()] + for u in c["unmatched"][:40]: + lines.append(f" - {u['district']} {u['code']}({u['reason']})") + if len(c["unmatched"]) > 40: + lines.append( + f" - ……其餘 {len(c['unmatched']) - 40} 筆見 council/{c['year']}.json 的 unmatchedVillages" + ) + uncovered = c["uncovered"] + lines.append( + f"- 資料包有、但不在任何區域議員選區內的村里:{sum(len(v) for v in uncovered.values())} 個" + ) + lines += [ + f" - {county}:{', '.join(codes[:20])}{' ……' if len(codes) > 20 else ''}" + for county, codes in uncovered.items() + ] + lines.append("") + return "\n".join(lines) + "\n" diff --git a/backend/data/pipeline/src/election_data/records/council.py b/backend/data/pipeline/src/election_data/records/council.py new file mode 100644 index 0000000..691411b --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/council.py @@ -0,0 +1,197 @@ +"""各議員選區的範圍、席次、候選人與當選門檻(給政治生涯的議員關用)。 + +- 涵蓋的村里:elctks 的村里小計列(鄉鎮、村里都不是 0、投開票所全為 0)。跨村里投開票所的代碼 + (A001 這類,2014 年是 9999)用 elbase 的名稱展開成村里,見 elections._cross_village_map。 +- 應選席次:當選註記的人數(elprof 後段的人數欄位各年順序不同,不用)。 +- 當選門檻:得票最少的當選者的得票率(選區內各候選人得票加總為分母)。 +- 村里代碼和 data/build/packs/<縣市>/villages.json(目前的村里)比對,對不上的列在 unmatchedVillages: + 多半是選後合併、改名的里,或跨村里投開票所只對得到鄉鎮(「鄉鎮代碼+000」)。 +""" + +from __future__ import annotations + +import json +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from functools import cache +from pathlib import Path +from typing import Any + +from ..cec import CecArchive +from ..codes import cec_village_code, county_code, is_town_residual, normalize_name +from ..elections import _cross_village_map +from .folders import RaceFolder +from .parse import Run, is_total + + +@dataclass(frozen=True) +class DistrictCoverage: + towns: tuple[str, ...] + villages: tuple[str, ...] + + +def _is_village_subtotal(row: Sequence[str]) -> bool: + return row[3] != "000" and row[4] != "0000" and row[5].strip("0") == "" + + +def coverage( + elctks: Sequence[Sequence[str]], cross: Mapping[tuple[str, str, str, str], Sequence[str]] +) -> dict[tuple[str, str, str], DistrictCoverage]: + """(省市, 縣市, 選區) → 涵蓋的鄉鎮與村里代碼""" + villages: dict[tuple[str, str, str], set[str]] = defaultdict(set) + towns: dict[tuple[str, str, str], set[str]] = defaultdict(set) + for r in elctks: + if not _is_village_subtotal(r): + continue + key = (r[0], r[1], r[2]) + towns[key].add(f"{r[0]}{r[1]}{r[3]}") + code = cec_village_code(r[0], r[1], r[3], r[4]) + villages[key].update([code] if code else cross.get((r[0], r[1], r[3], r[4]), ())) + return { + k: DistrictCoverage(tuple(sorted(towns[k])), tuple(sorted(villages[k]))) + for k in towns.keys() | villages.keys() + } + + +def electors_and_valid(elprof: Sequence[Sequence[str]]) -> dict[tuple[str, str, str], tuple[int, int]]: + """(省市, 縣市, 選區) → (選舉人數, 有效票數)。elprof 後段的人數欄位各年順序不同,只用前段固定的欄位""" + out = {} + for r in elprof: + if r[2] != "00" and is_total(r) and r[6].isdigit() and r[9].isdigit(): + out[(r[0], r[1], r[2])] = (int(r[9]), int(r[6])) + return out + + +@cache +def _pack(packs_dir: Path, county: str) -> tuple[tuple[str, str, str], ...] | None: + """資料包的村里(目前的村里):(代碼, 名稱, 鄉鎮代碼)。 + + 優先用 packs/<縣市>/,沒有就用最新的 packs/<縣市>-before-*/""" + paths = [ + packs_dir / county / "villages.json", + *sorted(packs_dir.glob(f"{county}-before-*/villages.json"), reverse=True), + ] + for path in paths: + if path.is_file(): + data = json.loads(path.read_text(encoding="utf-8")) + return tuple((v["code"], v["name"], v["townCode"]) for v in data.get("villages", [])) + return None + + +def pack_villages(packs_dir: Path, county: str) -> set[str] | None: + found = _pack(packs_dir, county) + return None if found is None else {code for code, _, _ in found} + + +def pack_village_names(packs_dir: Path, counties: Iterable[str]) -> dict[tuple[str, str], str]: + """(鄉鎮代碼, 村里名稱) → 村里代碼:展開跨村里投開票所用(連江縣的村只出現在跨村里代碼裡)""" + out = {} + for county in counties: + for code, name, town in _pack(packs_dir, county) or (): + out[(town, normalize_name(name))] = code + return out + + +RunKey = tuple[str, str, str, str, int | None] + + +def run_key(r: Run) -> RunKey: + """一次參選在中選會資料裡的位置:(資料夾, 省市, 縣市, 選區, 號次)""" + return (r.folder, *r.area, r.district_code, r.number) + + +def _candidate(r: Run, person_ids: Mapping[RunKey, str]) -> dict[str, Any]: + return { + "number": r.number, + "name": r.name, + "party": r.party, + "votes": r.votes, + "share": r.share, + "elected": r.elected, + "incumbent": r.incumbent, + "personId": person_ids.get(run_key(r)), + } + + +def build_council_year( + archive: CecArchive, + folders: Sequence[RaceFolder], + runs: Sequence[Run], + person_ids: Mapping[RunKey, str], + packs_dir: Path, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """回傳 (選區清單, 對不上的村里)""" + districts: list[dict[str, Any]] = [] + unmatched: list[dict[str, Any]] = [] + by_folder: dict[str, list[Run]] = defaultdict(list) + for r in runs: + by_folder[r.folder].append(r) + for rf in folders: + counties = {r.county_code for r in by_folder[rf.folder] if r.county_code} + cross = _cross_village_map(archive, rf.folder, pack_village_names(packs_dir, counties)) + cover = coverage(list(archive.rows(rf.folder, "elctks")), cross) + totals = electors_and_valid(list(archive.rows(rf.folder, "elprof"))) + groups: dict[tuple[str, str, str], list[Run]] = defaultdict(list) + for r in by_folder[rf.folder]: + groups[(*r.area, r.district_code)].append(r) + for key, cands in sorted(groups.items()): + cands.sort(key=lambda r: (-(r.votes or 0), r.number or 0)) + first = cands[0] + county = first.county_code or county_code(key[0], key[1]) + elected = [c for c in cands if c.elected] + electors, valid = totals.get(key, (None, None)) + last = min(elected, key=lambda c: c.votes or 0, default=None) + cov = cover.get(key, DistrictCoverage((), ())) + district_id = f"{county}-{key[2]}" + known = pack_villages(packs_dir, county) + for code in cov.villages: + if is_town_residual(code): + unmatched.append( + {"district": district_id, "code": code, "reason": "跨村里投開票所只對得到鄉鎮"} + ) + elif known is not None and code not in known: + unmatched.append( + { + "district": district_id, + "code": code, + "reason": "不在目前資料包的村里中(多半是選後合併或改名)", + } + ) + districts.append( + { + "id": district_id, + "countyCode": county, + "countyName": first.county, + "election": rf.election, + "indigenous": rf.indigenous, + "district": first.district, + "districtCode": key[2], + "seats": len(elected), + "electors": electors, + "validVotes": valid, + "towns": list(cov.towns), + "villages": [c for c in cov.villages if not is_town_residual(c)], + "candidates": [_candidate(c, person_ids) for c in cands], + "threshold": ( + None + if last is None + else {"name": last.name, "votes": last.votes, "share": last.share} + ), + } + ) + return {"districts": districts}, unmatched + + +def uncovered_villages(districts: Sequence[Mapping[str, Any]], packs_dir: Path) -> dict[str, list[str]]: + """資料包裡有、但不在任何區域議員選區內的村里(檢查用;多半是選後新設的里)""" + covered: dict[str, set[str]] = defaultdict(set) + for d in districts: + if d["indigenous"] is None: + covered[d["countyCode"]].update(d["villages"]) + out = {} + for county, codes in sorted(covered.items()): + known = pack_villages(packs_dir, county) + if known is not None and (missing := sorted(known - codes)): + out[county] = missing + return out diff --git a/backend/data/pipeline/src/election_data/records/folders.py b/backend/data/pipeline/src/election_data/records/folders.py new file mode 100644 index 0000000..e5c399a --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/folders.py @@ -0,0 +1,186 @@ +"""要讀的中選會資料夾: + +- 地方:1994–2022 年的省長、直轄市長、縣市長與省議員、直轄市議員、縣市議員。 +- 中央:1996–2024 年的總統副總統;1995–2024 年的區域立委、平地/山地原住民立委;2008–2024 年的不分區立委 + (有政黨名單檔 elrepm 的年份;1995–2004 年的全國不分區、僑選立委名單壓縮檔裡沒有)。 + +資料夾名稱以 votedata.zip 的實際內容為準(2022 年 C1 是首長、T1 區域議員、T2 平地原住民議員、 +T3 山地原住民議員;prv 是直轄市、city 是縣市;2016 年的檔名有後綴,例如 elcand_T1.csv)。 +投票日是中選會公告的投票日;同一年可能有兩次(例如 1998 年 1 月縣市議員、12 月北高市長與立委)。 +1994 年以前(例如 1993 縣市長、1994 縣市議員、1992 立委)壓縮檔裡沒有,就沒有收。 +沒有收的中央選舉資料夾:「2008 12任總統」(和「20080322-總統」內容相同)、「2016總統立委/old」(舊版)、 +「立委補選」(資料裡沒有投票日,一半的資料夾名稱也沒有年份)、國大代表。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +Office = Literal["mayor", "councilor", "president", "legislator"] + +#: 選舉種類(顯示用) +GOVERNOR = "臺灣省長" +MUNICIPAL_MAYOR = "直轄市長" +COUNTY_MAYOR = "縣市長" +PROVINCIAL_COUNCILOR = "臺灣省議員" +MUNICIPAL_COUNCILOR = "直轄市議員" +COUNTY_COUNCILOR = "縣市議員" + +PRESIDENT = "總統" +VICE_PRESIDENT = "副總統" +LEGISLATOR = "立法委員" +PARTY_LIST = "不分區立法委員" +#: 總統副總統、原住民立委、不分區立委的選區 +NATIONWIDE = "全國" + +LOWLAND = "平地原住民" +HIGHLAND = "山地原住民" +#: 1994–2006 年北高兩市的原住民議員不分平地、山地 +INDIGENOUS = "原住民" + + +@dataclass(frozen=True) +class RaceFolder: + folder: str + year: int + date: str + election: str + office: Office + #: 原住民選區的類別;區域選舉是 None + indigenous: str | None = None + #: 檔名後綴:2016 年的檔案叫 elcand_T1.csv、elcand_P1.csv(elpaty.csv 沒有後綴) + suffix: str = "" + + @property + def is_party_list(self) -> bool: + return self.election == PARTY_LIST + + +def _local(prefix: str, year: int, date: str) -> tuple[RaceFolder, ...]: + """2014、2018 年的地方公職人員選舉(資料夾名稱相同)""" + return ( + RaceFolder(f"{prefix}/直轄市市長", year, date, MUNICIPAL_MAYOR, "mayor"), + RaceFolder(f"{prefix}/縣市市長", year, date, COUNTY_MAYOR, "mayor"), + RaceFolder(f"{prefix}/直轄市區域議員", year, date, MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder(f"{prefix}/直轄市平原議員", year, date, MUNICIPAL_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{prefix}/直轄市山原議員", year, date, MUNICIPAL_COUNCILOR, "councilor", HIGHLAND), + RaceFolder(f"{prefix}/縣市區域議員", year, date, COUNTY_COUNCILOR, "councilor"), + RaceFolder(f"{prefix}/縣市平原議員", year, date, COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{prefix}/縣市山原議員", year, date, COUNTY_COUNCILOR, "councilor", HIGHLAND), + ) + + +_Y2009 = "20091205-縣市長縣市議員及鄉鎮長" +_Y2010 = "20101127-五都市長議員及里長" +_Y2022 = "2022-111年地方公職人員選舉" + +LOCAL_FOLDERS: tuple[RaceFolder, ...] = ( + RaceFolder("1994台灣省長", 1994, "1994-12-03", GOVERNOR, "mayor"), + RaceFolder("1994台灣省議員/區域", 1994, "1994-12-03", PROVINCIAL_COUNCILOR, "councilor"), + RaceFolder("1994台灣省議員/平原", 1994, "1994-12-03", PROVINCIAL_COUNCILOR, "councilor", LOWLAND), + RaceFolder("1994台灣省議員/平原2", 1994, "1994-12-03", PROVINCIAL_COUNCILOR, "councilor", LOWLAND), + RaceFolder("1994台灣省議員/山原", 1994, "1994-12-03", PROVINCIAL_COUNCILOR, "councilor", HIGHLAND), + RaceFolder("1994直轄市長", 1994, "1994-12-03", MUNICIPAL_MAYOR, "mayor"), + RaceFolder("1994直轄市議員/區域", 1994, "1994-12-03", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder("1994直轄市議員/原住民", 1994, "1994-12-03", MUNICIPAL_COUNCILOR, "councilor", INDIGENOUS), + RaceFolder("1997縣市長", 1997, "1997-11-29", COUNTY_MAYOR, "mayor"), + RaceFolder("1998縣市議員/區域", 1998, "1998-01-24", COUNTY_COUNCILOR, "councilor"), + RaceFolder("1998縣市議員/平原", 1998, "1998-01-24", COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder("1998縣市議員/山原", 1998, "1998-01-24", COUNTY_COUNCILOR, "councilor", HIGHLAND), + RaceFolder("1998直轄市長", 1998, "1998-12-05", MUNICIPAL_MAYOR, "mayor"), + RaceFolder("1998直轄市議員/區域", 1998, "1998-12-05", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder("1998直轄市議員/原住民", 1998, "1998-12-05", MUNICIPAL_COUNCILOR, "councilor", INDIGENOUS), + RaceFolder("2001縣市長", 2001, "2001-12-01", COUNTY_MAYOR, "mayor"), + RaceFolder("2002縣市議員/區域", 2002, "2002-01-26", COUNTY_COUNCILOR, "councilor"), + RaceFolder("2002縣市議員/平原", 2002, "2002-01-26", COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder("2002縣市議員/山原", 2002, "2002-01-26", COUNTY_COUNCILOR, "councilor", HIGHLAND), + RaceFolder("2002直轄市長", 2002, "2002-12-07", MUNICIPAL_MAYOR, "mayor"), + RaceFolder("2002直轄市議員(區域)", 2002, "2002-12-07", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder("2002直轄市議員(原住民)", 2002, "2002-12-07", MUNICIPAL_COUNCILOR, "councilor", INDIGENOUS), + RaceFolder("2005縣市長", 2005, "2005-12-03", COUNTY_MAYOR, "mayor"), + RaceFolder("2005縣市議員/區域", 2005, "2005-12-03", COUNTY_COUNCILOR, "councilor"), + RaceFolder("2005縣市議員/平原", 2005, "2005-12-03", COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder("2005縣市議員/山原", 2005, "2005-12-03", COUNTY_COUNCILOR, "councilor", HIGHLAND), + RaceFolder("2006直轄市長", 2006, "2006-12-09", MUNICIPAL_MAYOR, "mayor"), + RaceFolder("2006直轄市議員(區域)", 2006, "2006-12-09", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder("2006直轄市議員(原住民)", 2006, "2006-12-09", MUNICIPAL_COUNCILOR, "councilor", INDIGENOUS), + RaceFolder(f"{_Y2009}/縣市長", 2009, "2009-12-05", COUNTY_MAYOR, "mayor"), + RaceFolder(f"{_Y2009}/區域議員", 2009, "2009-12-05", COUNTY_COUNCILOR, "councilor"), + RaceFolder(f"{_Y2009}/平地議員", 2009, "2009-12-05", COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{_Y2009}/山地議員", 2009, "2009-12-05", COUNTY_COUNCILOR, "councilor", HIGHLAND), + RaceFolder(f"{_Y2010}/市長", 2010, "2010-11-27", MUNICIPAL_MAYOR, "mayor"), + RaceFolder(f"{_Y2010}/區域議員", 2010, "2010-11-27", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder(f"{_Y2010}/平地議員", 2010, "2010-11-27", MUNICIPAL_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{_Y2010}/山地議員", 2010, "2010-11-27", MUNICIPAL_COUNCILOR, "councilor", HIGHLAND), + *_local("2014-103年地方公職人員選舉", 2014, "2014-11-29"), + *_local("2018-107年地方公職人員選舉", 2018, "2018-11-24"), + RaceFolder(f"{_Y2022}/C1/prv", 2022, "2022-11-26", MUNICIPAL_MAYOR, "mayor"), + RaceFolder(f"{_Y2022}/C1/city", 2022, "2022-11-26", COUNTY_MAYOR, "mayor"), + RaceFolder(f"{_Y2022}/T1/prv", 2022, "2022-11-26", MUNICIPAL_COUNCILOR, "councilor"), + RaceFolder(f"{_Y2022}/T2/prv", 2022, "2022-11-26", MUNICIPAL_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{_Y2022}/T3/prv", 2022, "2022-11-26", MUNICIPAL_COUNCILOR, "councilor", HIGHLAND), + RaceFolder(f"{_Y2022}/T1/city", 2022, "2022-11-26", COUNTY_COUNCILOR, "councilor"), + RaceFolder(f"{_Y2022}/T2/city", 2022, "2022-11-26", COUNTY_COUNCILOR, "councilor", LOWLAND), + RaceFolder(f"{_Y2022}/T3/city", 2022, "2022-11-26", COUNTY_COUNCILOR, "councilor", HIGHLAND), +) + + +def _legislators( + prefix: str, + year: int, + date: str, + names: tuple[str, str, str], + party_list: str | None = None, + suffixes: tuple[str, str, str, str] = ("", "", "", ""), +) -> tuple[RaceFolder, ...]: + """一屆立委:(區域, 平地原住民, 山地原住民) 的資料夾名稱,加上不分區(有政黨名單檔的年份)""" + regional, lowland, highland = names + out = ( + RaceFolder(f"{prefix}/{regional}", year, date, LEGISLATOR, "legislator", suffix=suffixes[0]), + RaceFolder(f"{prefix}/{lowland}", year, date, LEGISLATOR, "legislator", LOWLAND, suffixes[1]), + RaceFolder(f"{prefix}/{highland}", year, date, LEGISLATOR, "legislator", HIGHLAND, suffixes[2]), + ) + if party_list: + out += ( + RaceFolder(f"{prefix}/{party_list}", year, date, PARTY_LIST, "legislator", suffix=suffixes[3]), + ) + return out + + +_OLD_LY = ("區域", "平原", "山原") +_NEW_LY = ("區域立委", "平地立委", "山地立委") +_Y2012_C = "20120114-總統及立委" + +#: 中央選舉:總統副總統、立法委員。投票日:中選會公告(elections.py、races2024.py 用的同一批日期) +NATIONAL_FOLDERS: tuple[RaceFolder, ...] = ( + RaceFolder("9任總統", 1996, "1996-03-23", PRESIDENT, "president"), + RaceFolder("2000年10任總統", 2000, "2000-03-18", PRESIDENT, "president"), + RaceFolder("2004 11任總統", 2004, "2004-03-20", PRESIDENT, "president"), + RaceFolder("20080322-總統", 2008, "2008-03-22", PRESIDENT, "president"), + RaceFolder(f"{_Y2012_C}/總統", 2012, "2012-01-14", PRESIDENT, "president"), + RaceFolder("2016總統立委/總統", 2016, "2016-01-16", PRESIDENT, "president", suffix="_P1"), + RaceFolder("2020總統立委/總統", 2020, "2020-01-11", PRESIDENT, "president"), + RaceFolder("2024總統立委/總統", 2024, "2024-01-13", PRESIDENT, "president"), + *_legislators("3屆立委", 1995, "1995-12-02", _OLD_LY), + *_legislators("4屆立委", 1998, "1998-12-05", _OLD_LY), + *_legislators("5屆立委", 2001, "2001-12-01", _OLD_LY), + *_legislators("2004第6屆立法委員", 2004, "2004-12-11", _OLD_LY), + *_legislators("2008立委", 2008, "2008-01-12", _OLD_LY, "不分區政黨"), + *_legislators(_Y2012_C, 2012, "2012-01-14", _NEW_LY, "不分區政黨"), + *_legislators("2016總統立委", 2016, "2016-01-16", _NEW_LY, "不分區政黨", ("_T1", "_T2", "_T3", "_T4")), + *_legislators("2020總統立委", 2020, "2020-01-11", _NEW_LY, "不分區政黨"), + *_legislators("2024總統立委", 2024, "2024-01-13", _NEW_LY, "不分區政黨"), +) + +FOLDERS: tuple[RaceFolder, ...] = LOCAL_FOLDERS + NATIONAL_FOLDERS + +#: 2022 嘉義市長因候選人過世延到 12 月 18 日重行選舉,檔案格式不同(cand.csv、prof.csv,沒有出生年) +CHIAYI_2022 = RaceFolder("2022年_嘉義市長重行選舉", 2022, "2022-12-18", COUNTY_MAYOR, "mayor") + +#: 議員選區檔(council/<年>.json)用的資料夾:該年的區域與原住民議員 +COUNCIL_YEARS = (2022, 2018, 2014) + + +def council_folders(year: int) -> tuple[RaceFolder, ...]: + return tuple(f for f in FOLDERS if f.year == year and f.office == "councilor") diff --git a/backend/data/pipeline/src/election_data/records/link.py b/backend/data/pipeline/src/election_data/records/link.py new file mode 100644 index 0000000..060f48e --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/link.py @@ -0,0 +1,185 @@ +"""跨屆串人:同一個人在不同年份、不同選舉的參選紀錄串成一筆。 + +- 有出生年:同名+同出生年就是同一個人(比對信心:高)。姓名先正規化(全形半形、空白、間隔號、少數異體字), + 有族名拼音的原住民姓名只比漢字部分(各年寫法不一,例如有沒有附羅馬拼音)。 +- 同一組裡有兩筆是同一天投票的(同一天不可能參選兩次),就是同名同年的不同人:依縣市分開; + 同縣市還撞就各自一筆。 +- 沒有出生年(目前只有 2022 嘉義市長重行選舉):同名、而且有在同一個縣市參選過的人只有一位,就併進去; + 否則自成一筆。這兩種都標「比對信心:低」。 +- 出生年只差 1 年(中選會不同年份的檔案偶爾寫得不一樣):其中一位有總統副總統或立委紀錄、 + 兩邊都掛過同一個政黨、沒有同一天參選的,就串在一起;政黨不同但人工確認是同一人的 + 列在 MANUAL_SAME(附理由)。也標「比對信心:低」,並在 note 寫出原因 + (18 第 54 項,使用者 2026-10-27 同意這條規則)。 +""" + +from __future__ import annotations + +import hashlib +from collections import Counter, defaultdict +from collections.abc import Iterable, Sequence +from dataclasses import dataclass + +from ..people.names import han_key, name_key +from .parse import Run + + +@dataclass(frozen=True) +class Person: + id: str + name: str + gender: str | None + birth_year: int | None + runs: tuple[Run, ...] + #: high:都是同名+出生年對上;low:有一筆以上是沒有出生年、用同名+同縣市對的,或出生年差 1 年串起來的 + confidence: str + #: 比對信心低的原因(給檔案室顯示);沒有特別原因是 None + note: str | None = None + + +@dataclass(frozen=True) +class LinkReport: + #: 同名同出生年、但同一天參選兩次而拆開的組:(姓名, 出生年, 拆成幾人) + splits: tuple[tuple[str, int, int], ...] + #: 沒有出生年、併進既有的人:(姓名, 縣市) + low_merged: tuple[tuple[str, str], ...] + #: 沒有出生年、找不到(或找到不只一位)同名同縣市的人而自成一筆:(姓名, 縣市, 同名同縣市的人數) + low_alone: tuple[tuple[str, str, int], ...] + #: 出生年差 1 年而串在一起的:(姓名, 出生年, 出生年, 理由) + near_merged: tuple[tuple[str, int, int, str], ...] = () + + +def match_key(name: str) -> str: + """比對鍵:有兩個字以上的漢字就只比漢字(族名拼音各年寫法不同),否則比整個正規化後的姓名""" + han = han_key(name) + return han if len(han) >= 2 else name_key(name) + + +def person_id(*parts: object) -> str: + digest = hashlib.sha1("|".join(str(p) for p in parts).encode("utf-8")).hexdigest() + return f"r-{digest[:10]}" + + +def _by_date(runs: Iterable[Run]) -> tuple[Run, ...]: + return tuple(sorted(runs, key=lambda r: (r.date, r.office != "mayor", r.folder))) + + +#: 出生年差 1 年的合併只看有中央選舉(總統副總統、立委)紀錄的人,地方選舉的同名者不動 +NEAR_SCOPE = frozenset({"president", "legislator"}) +#: 出生年差 1 年、政黨不同(規則抓不到)但確定是同一人的:(姓名, 出生年, 出生年, 理由) +MANUAL_SAME: tuple[tuple[str, int, int, str], ...] = ( + ("趙少康", 1949, 1950, "1994 年新黨臺北市長候選人和 2024 年國民黨副總統候選人是同一人"), +) + + +def _make(pid: str, runs: Sequence[Run], confidence: str = "high", note: str | None = None) -> Person: + ordered = _by_date(runs) + latest = ordered[-1] + gender = next((r.gender for r in reversed(ordered) if r.gender), None) + birth = next((r.birth_year for r in reversed(ordered) if r.birth_year), None) + return Person(pid, latest.name, gender, birth, ordered, confidence, note) + + +def _has_same_day(runs: Sequence[Run]) -> bool: + return any(n > 1 for n in Counter(r.date for r in runs).values()) + + +def _split(key: str, birth: int, runs: Sequence[Run]) -> list[Person]: + """同名同出生年、同一天參選兩次:依縣市分開,同縣市還撞就各自一筆""" + by_county: dict[str, list[Run]] = defaultdict(list) + for r in runs: + by_county[r.county_code or r.county].append(r) + out = [] + for county, group in sorted(by_county.items()): + if _has_same_day(group): + out.extend( + _make(person_id(key, birth, county, r.folder, r.district_code, r.number), [r]) for r in group + ) + else: + out.append(_make(person_id(key, birth, county), group)) + return out + + +def _parties(p: Person) -> set[str]: + return {r.party for r in p.runs if r.party} + + +def _merge_near(people: list[Person]) -> tuple[list[Person], list[tuple[str, int, int, str]]]: + """出生年只差 1 年的同名者:有中央選舉紀錄、同黨(或人工確認)、沒有同一天參選,就串成一人""" + manual = {(match_key(n), min(a, b), max(a, b)): why for n, a, b, why in MANUAL_SAME} + by_key: dict[str, list[int]] = defaultdict(list) + for i, p in enumerate(people): + if p.birth_year is not None: + by_key[match_key(p.name)].append(i) + gone: set[int] = set() + merged: list[tuple[str, int, int, str]] = [] + for key, idx in by_key.items(): + for x in idx: + for y in idx: + if x >= y or x in gone or y in gone: + continue + a, b = people[x], people[y] + if a.birth_year is None or b.birth_year is None or abs(a.birth_year - b.birth_year) != 1: + continue + if not any(r.office in NEAR_SCOPE for r in (*a.runs, *b.runs)): + continue + if _has_same_day([*a.runs, *b.runs]): + continue + low, high = sorted((a.birth_year, b.birth_year)) + why = manual.get((key, low, high)) + if why is None: + if not _parties(a) & _parties(b): + continue + why = "同名、同黨、出生年只差 1 年" + note = f"中選會不同年份的資料出生年寫 {low}、{high} 年,{why},所以串在一起;可能有誤。" + keep_x = len(a.runs) >= len(b.runs) + keep, drop = (a, b) if keep_x else (b, a) + people[x if keep_x else y] = _make(keep.id, [*keep.runs, *drop.runs], "low", note) + gone.add(y if keep_x else x) + merged.append((a.name, a.birth_year, b.birth_year, why)) + return [p for i, p in enumerate(people) if i not in gone], merged + + +def link_runs(runs: Iterable[Run]) -> tuple[list[Person], LinkReport]: + groups: dict[tuple[str, int], list[Run]] = defaultdict(list) + no_birth: list[Run] = [] + for r in runs: + if r.birth_year is None: + no_birth.append(r) + else: + groups[(match_key(r.name), r.birth_year)].append(r) + people: list[Person] = [] + splits = [] + for (key, birth), group in groups.items(): + if _has_same_day(group): + parts = _split(key, birth, group) + splits.append((group[0].name, birth, len(parts))) + people.extend(parts) + else: + people.append(_make(person_id(key, birth), group)) + people, near_merged = _merge_near(people) + # 沒有出生年:同名、有在同縣市參選過的人只有一位才併 + by_key: dict[str, list[int]] = defaultdict(list) + for i, p in enumerate(people): + by_key[match_key(p.name)].append(i) + merged: dict[int, list[Run]] = defaultdict(list) + low_merged, low_alone = [], [] + alone: dict[tuple[str, str], list[Run]] = defaultdict(list) + for r in no_birth: + county = r.county_code or r.county + hits = [ + i + for i in by_key.get(match_key(r.name), []) + if any((x.county_code or x.county) == county for x in people[i].runs) + ] + if len(hits) == 1: + merged[hits[0]].append(r) + low_merged.append((r.name, r.county)) + else: + alone[(match_key(r.name), county)].append(r) + low_alone.append((r.name, r.county, len(hits))) + for i, extra in merged.items(): + p = people[i] + people[i] = _make(p.id, [*p.runs, *extra], "low", p.note) + for (key, county), group in alone.items(): + people.append(_make(person_id(key, "none", county), group, "low")) + return people, LinkReport(tuple(splits), tuple(low_merged), tuple(low_alone), tuple(near_merged)) diff --git a/backend/data/pipeline/src/election_data/records/parse.py b/backend/data/pipeline/src/election_data/records/parse.py new file mode 100644 index 0000000..dd6b7b9 --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/parse.py @@ -0,0 +1,349 @@ +"""讀一個中選會資料夾的候選人與得票。 + +elcand 欄位:省市、縣市、選區、鄉鎮、村里、號次、姓名、政黨代碼、性別、出生(2010 年以前是民國出生年 3 碼, +之後是民國出生日期 7 碼;2000、2004 總統是「0310000」這種月日為 0 的寫法)、年齡、出生地、學歷、現任(Y/N)、 +當選註記(見 ELECTED)、副手(Y)。 +elctks 欄位:省市、縣市、選區、鄉鎮、村里、投開票所、號次、得票、得票率、當選註記。 +候選人的總票數取「鄉鎮=000、村里=0000、投開票所全為 0」的總計列。少數舊資料夾的選區代碼兩個檔不一致 +(例如 1994 北高市長:elcand 選區 00、elctks 選區 01;總統、原住民立委:elcand 選區 01、全國總計列選區 00), +這時改用 (省市, 縣市, 號次) 對,只有一列符合才算。 + +總統副總統:副手列(副總統候選人)也收,選舉寫「副總統」,得票、得票率、當選跟同一組的總統候選人 +(副手列的當選註記 2008 年起都是空的)。省市代碼 00 的選區(總統、原住民立委)縣市寫「全國」。 +不分區立委:elrepm 是政黨名單(政黨代碼、排名、姓名、性別、出生日期、年齡、出生地、學歷、現任、當選註記), +沒有個人得票;另外記所屬政黨的全國政黨票(elctks 全國總計列)與得票率。 +""" + +from __future__ import annotations + +import re +from collections import defaultdict +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, replace + +from ..cec import CecArchive +from ..codes import COUNTY_CODE_BY_NAME, normalize_name, roc_to_iso_date +from ..elections import is_independent +from ..people.cec_results import load_chiayi_2022 +from ..people.names import display_name +from .folders import CHIAYI_2022, NATIONWIDE, VICE_PRESIDENT, RaceFolder + +_GENDER = {"1": "M", "2": "F"} +#: 當選註記:* 當選、! 以婦女保障名額當選;- 是票數夠、但名額讓給婦女保障而落選 +ELECTED = frozenset({"*", "!"}) +_DISTRICT = re.compile(r"第(.+?)選(?:舉)?區") +_CN_DIGITS = { + "〇": 0, + "零": 0, + "一": 1, + "二": 2, + "三": 3, + "四": 4, + "五": 5, + "六": 6, + "七": 7, + "八": 8, + "九": 9, +} + + +@dataclass(frozen=True) +class Run: + """一位候選人的一次參選""" + + folder: str + year: int + date: str + election: str + office: str + indigenous: str | None + #: 當年的縣市名稱(臺北縣、臺灣省……) + county: str + #: 對到目前的縣市代碼(臺北縣 → 65000);臺灣省長、省議員的原住民選區是 None + county_code: str | None + #: 選區名稱(第 3 選區);縣市長、整個縣市一個選區時是 None + district: str | None + #: 中選會的 (省市, 縣市) 代碼與選區代碼 2 碼(2014 年以前是中選會自己的流水號) + area: tuple[str, str] + district_code: str + number: int | None + name: str + party: str | None + gender: str | None + birth_year: int | None + votes: int | None + share: float | None + elected: bool + incumbent: bool | None + #: 總統副總統同一組的搭檔 + running_mate: str | None = None + #: 不分區立委:政黨名單排名、所屬政黨的全國政黨票與得票率 + list_rank: int | None = None + party_votes: int | None = None + party_share: float | None = None + + +def chinese_number(text: str) -> int | None: + """「12」「十二」「二十一」「01」→ 整數""" + if text.isdigit(): + return int(text) + if not text or any(ch not in _CN_DIGITS and ch != "十" for ch in text): + return None + if "十" not in text: + return int("".join(str(_CN_DIGITS[ch]) for ch in text)) + tens, _, ones = text.partition("十") + return (_CN_DIGITS[tens] if tens else 1) * 10 + (_CN_DIGITS[ones] if ones else 0) + + +def district_label(name: str | None, code: str) -> str | None: + """elbase 的選區名稱(「臺北縣第十二選區」「第01選舉區」)→「第12選區」。 + + 沒有選區列時:代碼 00 代表整個縣市一個選區(None),其他代碼用代碼本身的數字。""" + if name and (m := _DISTRICT.search(name)) and (n := chinese_number(m.group(1))) is not None: + return f"第{n}選區" + return None if code.strip("0") == "" else f"第{int(code)}選區" + + +def birth_year(raw: str) -> int | None: + """民國出生年(3 碼)或民國出生日期(7 碼)→ 西元年。 + + 2000、2004 總統的出生日期是「0310000」(只有年、月日為 0),日期不合法時取前 3 碼當民國年。""" + raw = raw.strip() + if len(raw) >= 6: + iso = roc_to_iso_date(raw) + if iso: + return int(iso[:4]) + head = raw[:-4] + return int(head) + 1911 if head.isdigit() and int(head) > 0 and raw[-4:] == "0000" else None + if raw.isdigit() and int(raw) > 0: + return int(raw) + 1911 + return None + + +def is_total(row: Sequence[str]) -> bool: + """選區總計列:鄉鎮 000、村里 0000、投開票所全為 0(2018 年以前寫 0,2020 年起寫 0000)""" + return row[3] == "000" and row[4] == "0000" and row[5].strip("0") == "" + + +def county_names(elbase: Iterable[Sequence[str]]) -> dict[tuple[str, str], str]: + """(省市, 縣市) → 縣市名稱。選區 00 的那一列優先;1994 省議員只有選區 01 的縣市列""" + out: dict[tuple[str, str], str] = {} + for prv, city, district, town, village, name in (r[:6] for r in elbase): + if town != "000" or village != "0000" or "選" in name or name == "全國": + continue + if district == "00" or (prv, city) not in out: + out[(prv, city)] = normalize_name(name) + return out + + +def district_names(elbase: Iterable[Sequence[str]]) -> dict[tuple[str, str, str], str]: + return { + (r[0], r[1], r[2]): r[5] + for r in elbase + if r[2] != "00" and r[3] == "000" and r[4] == "0000" and "選" in r[5] + } + + +def candidate_votes(elctks: Iterable[Sequence[str]]) -> dict[tuple[str, str, str, str], int]: + """(省市, 縣市, 選區, 號次) → 選區總票數""" + return {(r[0], r[1], r[2], r[6]): int(r[7]) for r in elctks if is_total(r) and r[7].isdigit()} + + +def _lookup( + totals: dict[tuple[str, str, str, str], int], + loose: dict[tuple[str, str, str], list[int]], + row: Sequence[str], +) -> int | None: + found = totals.get((row[0], row[1], row[2], row[5])) + if found is not None: + return found + candidates = loose.get((row[0], row[1], row[5]), []) + return candidates[0] if len(candidates) == 1 else None + + +def _party_name(parties: dict[str, str], code: str) -> str | None: + party = parties.get(code, code) + return None if not party or is_independent(party) else party + + +def _single_district_counties(rf: RaceFolder, cands: Sequence[Sequence[str]]) -> set[tuple[str, str]]: + """立委:整個縣市只有一個選區的縣市(選區寫 None,只顯示縣市)""" + if rf.office != "legislator": + return set() + codes: dict[tuple[str, str], set[str]] = defaultdict(set) + for r in cands: + codes[(r[0], r[1])].add(r[2]) + return {k for k, v in codes.items() if len(v) == 1} + + +def parse_rows( + rf: RaceFolder, + elbase: Sequence[Sequence[str]], + elpaty: Iterable[Sequence[str]], + elcand: Iterable[Sequence[str]], + elctks: Iterable[Sequence[str]], +) -> list[Run]: + parties = {r[0]: r[1] for r in elpaty} + counties = county_names(elbase) + districts = district_names(elbase) + totals = candidate_votes(elctks) + loose: dict[tuple[str, str, str], list[int]] = defaultdict(list) + for (prv, city, _, number), votes in totals.items(): + loose[(prv, city, number)].append(votes) + rows = list(elcand) + cands = [r for r in rows if r[15] != "Y"] + # 副手只有總統副總統選舉收(地方選舉沒有副手):(省市, 縣市, 選區, 號次) → 副手列 + mates = {(r[0], r[1], r[2], r[5]): r for r in rows if r[15] == "Y"} if rf.office == "president" else {} + votes = {id(r): _lookup(totals, loose, r) for r in cands} + valid: dict[tuple[str, str, str], int] = defaultdict(int) + for r in cands: + valid[(r[0], r[1], r[2])] += votes[id(r)] or 0 + whole_county = _single_district_counties(rf, cands) + out = [] + for r in cands: + # 總統、原住民立委的省市代碼是 00(全國);臺灣省長、省議員原住民選區也是 00,但縣市名稱是「臺灣省」 + nationwide = r[0] == "00" and rf.office in ("president", "legislator") + county = NATIONWIDE if nationwide else counties.get((r[0], r[1]), "") + v = votes[id(r)] + total = valid[(r[0], r[1], r[2])] + mate = mates.get((r[0], r[1], r[2], r[5])) + run = Run( + folder=rf.folder, + year=rf.year, + date=rf.date, + election=rf.election, + office=rf.office, + indigenous=rf.indigenous, + county=county, + county_code=None if nationwide else COUNTY_CODE_BY_NAME.get(county), + district=( + None + if rf.office in ("mayor", "president") or nationwide or (r[0], r[1]) in whole_county + else district_label(districts.get((r[0], r[1], r[2])), r[2]) + ), + area=(r[0], r[1]), + district_code=r[2], + number=int(r[5]) if r[5].isdigit() else None, + name=display_name(r[6]), + party=_party_name(parties, r[7]), + gender=_GENDER.get(r[8]), + birth_year=birth_year(r[9]), + votes=v, + share=round(v / total, 6) if v is not None and total else None, + elected=r[14] in ELECTED, + incumbent={"Y": True, "N": False}.get(r[13]), + running_mate=display_name(mate[6]) if mate else None, + ) + out.append(run) + if mate: + # 副總統:得票、得票率、當選跟同一組的總統候選人 + out.append( + replace( + run, + election=VICE_PRESIDENT, + name=display_name(mate[6]), + party=_party_name(parties, mate[7]), + gender=_GENDER.get(mate[8]), + birth_year=birth_year(mate[9]), + incumbent={"Y": True, "N": False}.get(mate[13]), + running_mate=run.name, + ) + ) + return out + + +def parse_party_list( + rf: RaceFolder, + elpaty: Iterable[Sequence[str]], + elcand: Iterable[Sequence[str]], + elctks: Iterable[Sequence[str]], + elrepm: Iterable[Sequence[str]], +) -> list[Run]: + """不分區立委:政黨名單上的每一位(沒有個人得票),附所屬政黨的全國政黨票""" + parties = {r[0]: r[1] for r in elpaty} + #: 政黨代碼 → 選票上的政黨號次(elcand 的「姓名」欄是政黨名稱) + ballot = {r[7]: r[5] for r in elcand} + #: 政黨號次 → 全國政黨票(省市 00 的總計列) + national = {r[6]: int(r[7]) for r in elctks if r[0] == "00" and is_total(r) and r[7].isdigit()} + valid = sum(national.values()) + out = [] + for r in elrepm: + number = ballot.get(r[0]) + pv = national.get(number) if number else None + out.append( + Run( + folder=rf.folder, + year=rf.year, + date=rf.date, + election=rf.election, + office=rf.office, + indigenous=None, + county=NATIONWIDE, + county_code=None, + district=None, + area=("00", "000"), + district_code="00", + number=int(number) if number and number.isdigit() else None, + name=display_name(r[2]), + party=_party_name(parties, r[0]), + gender=_GENDER.get(r[3]), + birth_year=birth_year(r[4]), + votes=None, + share=None, + elected=r[9] in ELECTED, + incumbent={"Y": True, "N": False}.get(r[8]), + list_rank=int(r[1]) if r[1].isdigit() else None, + party_votes=pv, + party_share=round(pv / valid, 6) if pv is not None and valid else None, + ) + ) + return out + + +def parse_folder(archive: CecArchive, rf: RaceFolder) -> list[Run]: + s = rf.suffix + if rf.is_party_list: + return parse_party_list( + rf, + archive.rows(rf.folder, "elpaty"), + archive.rows(rf.folder, "elcand" + s), + archive.rows(rf.folder, "elctks" + s), + archive.rows(rf.folder, "elrepm" + s), + ) + return parse_rows( + rf, + list(archive.rows(rf.folder, "elbase" + s)), + archive.rows(rf.folder, "elpaty"), + archive.rows(rf.folder, "elcand" + s), + archive.rows(rf.folder, "elctks" + s), + ) + + +def parse_chiayi_2022(archive: CecArchive) -> list[Run]: + """2022 嘉義市長重行選舉:沿用人物資料的讀法(people/cec_results.py),這份資料沒有出生年與性別""" + rf = CHIAYI_2022 + return [ + Run( + folder=rf.folder, + year=rf.year, + date=rf.date, + election=rf.election, + office=rf.office, + indigenous=None, + county=r.county or "嘉義市", + county_code=COUNTY_CODE_BY_NAME.get(r.county or "嘉義市"), + district=None, + area=("10", "020"), + district_code="00", + number=i + 1, + name=r.name, + party=None if not r.party or is_independent(r.party) else r.party, + gender=r.gender, + birth_year=None, + votes=r.votes, + share=r.share, + elected=r.elected, + incumbent=None, + ) + for i, r in enumerate(load_chiayi_2022(archive.path)) + ] diff --git a/backend/data/pipeline/src/election_data/records/scores.py b/backend/data/pipeline/src/election_data/records/scores.py new file mode 100644 index 0000000..7748b9b --- /dev/null +++ b/backend/data/pipeline/src/election_data/records/scores.py @@ -0,0 +1,298 @@ +"""客觀資歷分數:只用公開的選舉紀錄(與政治獻金申報)照固定公式算,0–10 分,不是對個人的評價。 + +總統副總統、立委也套同一套公式(知名度的上限仍是 500 萬票,總統選舉超過的一律 10 分), +例外寫在各項的算法裡:選區實力不比總統副總統(沒有同黨可比)、不分區立委沒有個人得票。 + +每一項都附「算法」(公式文字)與「出處」,每個人另外附「依據」(代入公式的數字),畫面照抄這三段。 +""" + +from __future__ import annotations + +import json +import logging +import math +import re +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path + +from ..codes import normalize_name +from ..people.names import name_key +from .folders import LEGISLATOR, PARTY_LIST, PRESIDENT, VICE_PRESIDENT +from .link import Person +from .parse import Run + +log = logging.getLogger(__name__) + +CEC_SOURCE = "中央選舉委員會選舉資料庫(各次選舉的候選人檔與得票檔)" +FINANCE_SOURCE = ( + "監察院政治獻金公開查閱平臺:擬參選人首次申報收支結算表(目前整理了 2018、2022 年縣市長," + "2020、2024 年總統副總統與區域立委)" +) + +FAME_FLOOR, FAME_CEIL = 1_000, 5_000_000 +FINANCE_FLOOR, FINANCE_CEIL = 100_000, 200_000_000 +WIN_POINTS, REELECT_POINTS = 1.5, 1.0 +YEARS_PER_POINT = 2.5 + + +@dataclass(frozen=True) +class ScoreDef: + key: str + label: str + formula: str + source: str + + +SCORE_DEFS: tuple[ScoreDef, ...] = ( + ScoreDef( + "fame", + "知名度", + "生涯單次最高得票數取對數:分數 = 10 ×(log10(得票) − 3)÷(log10(5,000,000) − 3),夾在 0–10。" + "1,000 票以下是 0,500 萬票是 10;得票差 10 倍,分數差約 2.7。" + "總統副總統選舉的得票是全國的票(正副總統一組,副總統候選人用同一組的票)," + "500 萬票以上一律 10 分,不會超過 10;不分區立委沒有個人得票,那次不算。", + CEC_SOURCE, + ), + ScoreDef( + "organization", + "組織", + "分數 = 1.5 × 當選次數 + 1 × 連任次數,最高 10。連任:這次當選、而且這個人的上一次參選也當選。" + "副總統、不分區立委當選也算一次當選。", + CEC_SOURCE, + ), + ScoreDef( + "seniority", + "資歷", + "第一次當選到最後一次參選相隔的年數 ÷ 2.5,最高 10(相隔 25 年以上是 10);沒有當選紀錄是 0。" + "資料從 1994 年開始,更早的經歷沒有算進去。", + CEC_SOURCE, + ), + ScoreDef( + "strength", + "選區實力", + "每次參選的得票率 ÷ 同年、同一種選舉、同黨(無黨籍算一組)候選人的平均得票率,各次取平均;" + "分數 = 5 × 這個比值,夾在 0–10(和同黨平均一樣是 5)。區域與原住民選區分開比。" + "總統副總統選舉全國只有一場、每黨只有一組,沒有同黨可比,不算;不分區立委沒有個人得票,也不算。", + CEC_SOURCE, + ), + ScoreDef( + "finance", + "財力", + "政治獻金收支結算表的收入合計取對數:分數 = 10 ×(log10(收入) − 5)÷(log10(2 億) − 5),夾在 0–10" + "(10 萬元以下是 0,2 億元是 10);有好幾次申報取最高的一次。" + "總統副總統的申報是正副一組(例如「甲、乙」),算在總統候選人身上。沒有申報資料就是「無資料」。", + FINANCE_SOURCE, + ), +) + + +@dataclass(frozen=True) +class Score: + key: str + #: 0–10,一位小數;沒有資料是 None + value: float | None + #: 代入公式的數字 + basis: str + + +def _clamp(x: float) -> float: + return round(min(10.0, max(0.0, x)), 1) + + +def _log_scale(x: float, floor: float, ceil: float) -> float: + if x <= floor: + return 0.0 + return _clamp(10 * (math.log10(x) - math.log10(floor)) / (math.log10(ceil) - math.log10(floor))) + + +def run_label(r: Run) -> str: + """「2022 臺北市 直轄市長」「2018 新北市第 3 選區 直轄市議員(平地原住民)」「2024 全國 副總統」""" + place = r.county + (r.district or "") + kind = r.election + (f"({r.indigenous})" if r.indigenous else "") + return f"{r.year} {place} {kind}" + + +def peer_key(r: Run) -> tuple[str, str, str, str]: + return (r.date, r.election, r.indigenous or "", r.party or "") + + +def in_strength(r: Run) -> bool: + """選區實力只比有同黨可比的選舉:總統副總統(全國一場、每黨一組)不算;不分區沒有個人得票率""" + return r.office != "president" and r.share is not None + + +def peer_averages(runs: Iterable[Run]) -> dict[tuple[str, str, str, str], float]: + """同年、同一種選舉、同黨候選人的平均得票率""" + sums: dict[tuple[str, str, str, str], list[float]] = defaultdict(list) + for r in runs: + if in_strength(r) and r.share is not None: + sums[peer_key(r)].append(r.share) + return {k: sum(v) / len(v) for k, v in sums.items()} + + +@dataclass(frozen=True) +class FinanceRecord: + year: int + county: str + name: str + election: str + income: int + + +#: (西元年, 選舉種類 mayor/legislator/president, 縣市(總統是空字串), 姓名比對鍵) +FinanceKey = tuple[int, str, str, str] + + +def _finance_year(election: str) -> int | None: + m = re.match(r"(\d+)年", election) + return int(m.group(1)) + 1911 if m else None + + +def _finance_kind(election: str) -> str | None: + """監察院平臺的選舉名稱 → 選舉種類;其他選舉(議員、鄉鎮長……)不收""" + if "市長" in election or "縣(市)長" in election: + return "mayor" + if "總統" in election: + return "president" + if "立法委員" in election: + return "legislator" + return None + + +def load_finance(finance_dir: Path) -> dict[FinanceKey, FinanceRecord]: + """(西元年, 選舉種類, 縣市, 姓名比對鍵) → 縣市長、區域立委、總統候選人的政治獻金收入。 + + 資料夾不存在就是空的。 + + 總統副總統的申報以「正、副」兩人並列(例如「賴清德、蕭美琴」),用正手(總統候選人)的名字對照。""" + out: dict[FinanceKey, FinanceRecord] = {} + if not finance_dir.is_dir(): + return out + for path in sorted(finance_dir.glob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as e: + log.warning("政治獻金檔讀不了,略過:%s(%s)", path.name, e) + continue + election = str(data.get("election", "")) + year = _finance_year(election) + kind = _finance_kind(election) + if year is None or kind is None: + continue + county = "" if kind == "president" else normalize_name(str(data.get("area", ""))) + for c in data.get("candidates", []): + income = c.get("income") + name = str(c.get("name", "")) + if isinstance(income, int): + key = (year, kind, county, name_key(name.split("、")[0])) + out[key] = FinanceRecord(year, county, name, election, income) + return out + + +def finance_key(r: Run) -> FinanceKey | None: + """一次參選對到政治獻金資料的鍵:縣市長、區域立委、總統候選人(副總統、原住民、不分區立委沒有)""" + if r.office == "mayor": + return (r.year, "mayor", normalize_name(r.county), name_key(r.name)) + if r.office == "legislator" and r.election == LEGISLATOR and r.indigenous is None: + return (r.year, "legislator", normalize_name(r.county), name_key(r.name)) + if r.election == PRESIDENT: + return (r.year, "president", "", name_key(r.name)) + return None + + +def fame(runs: Sequence[Run]) -> Score: + best = max((r for r in runs if r.votes is not None), key=lambda r: r.votes or 0, default=None) + if best is None or best.votes is None: + only_list = any(r.election == PARTY_LIST for r in runs) + return Score( + "fame", None, "沒有個人得票紀錄(不分區立委沒有個人得票)" if only_list else "沒有得票紀錄" + ) + ticket = ( + f",和{best.running_mate}同一組的票" if best.election == VICE_PRESIDENT and best.running_mate else "" + ) + return Score( + "fame", + _log_scale(best.votes, FAME_FLOOR, FAME_CEIL), + f"生涯單次最高 {best.votes:,} 票({run_label(best)}{ticket})", + ) + + +def organization(runs: Sequence[Run]) -> Score: + wins = sum(r.elected for r in runs) + reelected = sum(1 for prev, cur in zip(runs, runs[1:], strict=False) if prev.elected and cur.elected) + return Score( + "organization", + _clamp(WIN_POINTS * wins + REELECT_POINTS * reelected), + f"當選 {wins} 次,其中連任 {reelected} 次(共參選 {len(runs)} 次)", + ) + + +def seniority(runs: Sequence[Run]) -> Score: + first_win = next((r for r in runs if r.elected), None) + if first_win is None: + return Score("seniority", 0.0, f"沒有當選紀錄(共參選 {len(runs)} 次)") + last = runs[-1] + years = last.year - first_win.year + return Score( + "seniority", + _clamp(years / YEARS_PER_POINT), + f"{first_win.year} 年第一次當選,最後一次參選是 {last.year} 年,相隔 {years} 年", + ) + + +def strength(runs: Sequence[Run], peers: Mapping[tuple[str, str, str, str], float]) -> Score: + pairs = [ + (r.share, peers[peer_key(r)]) + for r in runs + if in_strength(r) and r.share is not None and peers.get(peer_key(r)) + ] + if not pairs: + national = any(not in_strength(r) for r in runs) + why = "(總統副總統、不分區立委不列入)" if national else "" + return Score("strength", None, f"沒有可以和同黨比較的得票率紀錄{why}") + ratio = sum(s / p for s, p in pairs) / len(pairs) + own = sum(s for s, _ in pairs) / len(pairs) + peer = sum(p for _, p in pairs) / len(pairs) + return Score( + "strength", + _clamp(5 * ratio), + f"平均得票率 {own * 100:.1f}%,同年同選舉同黨平均 {peer * 100:.1f}%" + f"(比值 {ratio:.2f},共 {len(pairs)} 次)", + ) + + +def finance(runs: Sequence[Run], records: Mapping[FinanceKey, FinanceRecord]) -> Score: + found = [ + rec for r in runs if (key := finance_key(r)) is not None and (rec := records.get(key)) is not None + ] + if not found: + return Score( + "finance", + None, + "無資料(目前只有 2018、2022 年縣市長,2020、2024 年總統與區域立委候選人的申報)", + ) + best = max(found, key=lambda rec: rec.income) + where = f"({best.county})" if best.county else "" + who = f",申報人「{best.name}」" if "、" in best.name else "" + return Score( + "finance", + _log_scale(best.income, FINANCE_FLOOR, FINANCE_CEIL), + f"{best.election}{where}收入合計 {best.income:,} 元{who}", + ) + + +def score_person( + person: Person, + peers: Mapping[tuple[str, str, str, str], float], + finance_records: Mapping[FinanceKey, FinanceRecord], +) -> tuple[Score, ...]: + runs = person.runs + return ( + fame(runs), + organization(runs), + seniority(runs), + strength(runs, peers), + finance(runs, finance_records), + ) diff --git a/backend/data/pipeline/src/election_data/report.py b/backend/data/pipeline/src/election_data/report.py new file mode 100644 index 0000000..8e58015 --- /dev/null +++ b/backend/data/pipeline/src/election_data/report.py @@ -0,0 +1,162 @@ +"""資料包的核對報告(report.md):完整度、旗標、與中選會總數的核對、模型參數。""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Sequence +from pathlib import Path + +from .codes import is_town_residual +from .geo import VillageShape + + +def _not_flagged(prefix: str): # noqa: ANN202 - 小工具 + return lambda v: not any(f.startswith(prefix) for f in v["flags"]) + + +# 補值之後所有欄位都有值;這裡列出「實際資料」的比例 +_FIELDS = ( + ("邊界與面積", lambda v: v["attributes"]["areaKm2"] > 0), + ("政黨傾向", _not_flagged("lean_imputed")), + ("基本投票率", _not_flagged("turnout_imputed")), + ("選舉人數", _not_flagged("electors_imputed")), + ("所得", _not_flagged("income_imputed")), + ("6 次選舉都有資料", _not_flagged("missing_elections")), +) + + +def _pct(n: int, total: int) -> str: + return f"{n:,} / {total:,}({n / total:.1%})" if total else "0" + + +def write_report( + out_dir: Path, + manifest: dict, + villages: Sequence[dict], + towns: Sequence[dict], + history: dict, + orphans: Sequence[tuple[str, str, int]], + shapes: Sequence[VillageShape], +) -> None: + n = len(villages) + lines = [ + f"# 資料包核對報告:{manifest['scope']['countyName']}({manifest['packId']})", + "", + f"- 產生時間:{manifest['createdAt']}", + f"- 人口快照:{manifest['snapshot']['population']};" + f"村里界圖版本:{manifest['snapshot']['boundaries']}", + f"- 村里:{n:,};鄉鎮市區:{len(towns):,};有旗標的村里:{manifest['counts']['villagesWithFlags']:,}", + f"- 總人口:{sum(v['population']['total'] for v in villages):,};" + f"20 歲以上:{sum(v['population']['adults'] for v in villages):,}", + "", + "## 欄位完整度", + "", + "所有村里的所有欄位都有值。缺少實際資料的村里,依序以相鄰村里、同鄉鎮、全縣市的加權平均補值,並加上旗標。", + "", + "| 欄位 | 使用實際資料的村里 |", + "|---|---|", + ] + lines += [f"| {label} | {_pct(sum(1 for v in villages if test(v)), n)} |" for label, test in _FIELDS] + + flag_counts = Counter( + "missing_elections" if f.startswith("missing_elections") else f for v in villages for f in v["flags"] + ) + lines += ["", "## 旗標", "", "| 旗標 | 村里數 |", "|---|---|"] + lines += [f"| `{flag}` | {count:,} |" for flag, count in flag_counts.most_common()] or ["| (無) | 0 |"] + missing_detail = Counter( + e + for v in villages + for f in v["flags"] + if f.startswith("missing_elections:") + for e in f.split(":")[1].split(",") + ) + if missing_detail: + lines += [ + "", + "缺少的選舉(村里數):" + "、".join(f"{k} {c}" for k, c in missing_detail.most_common()), + ] + + pack_codes = {v["code"] for v in villages} + extra_shapes = [s for s in shapes if s.code not in pack_codes] + lines += [ + "", + "## 村里界圖與戶政資料的差異", + "", + f"- 界圖有、戶政沒有(不納入資料包):{len(extra_shapes)} 個", + ] + lines += [f" - {s.code} {s.town_name}{s.name}" for s in extra_shapes[:30]] + lines += [f"- 戶政有、界圖沒有:{flag_counts.get('no_boundary', 0)} 個"] + + lines += [ + "", + "## 與中選會總數核對(有效票)", + "", + "資料包加總包含所有對得到代碼的票,包括已合併或改名、目前不存在的舊里(這些票不會出現在現存村里的歷史中)。", + "", + "| 選舉@縣市 | 中選會 | 資料包加總 | 差 |", + "|---|---|---|---|", + ] + for row in history["reconciliation"]: + if row["cecValid"] == 0 and row["packValid"] == 0: + continue + lines.append( + f"| {row['electionId']} | {row['cecValid']:,} | {row['packValid']:,} | {row['diff']:+,} |" + ) + orphan_by_election = Counter() + residual_by_election = Counter() + for election_id, code, valid in orphans: + (residual_by_election if is_town_residual(code) else orphan_by_election)[election_id] += valid + lines += ["", "### 已不存在的舊里(孤兒代碼)", ""] + if orphan_by_election: + lines.append( + "這些票對到合併或改名前的舊里代碼,計入上表的核對,但沒有分配給現存村里;" + "需要舊、新村里的對照表才能分配(docs/13 M0 的里代碼對照表)。" + ) + lines += [""] + [ + f"- {eid}:{len({c for e, c, _ in orphans if e == eid and not is_town_residual(c)})} 個舊代碼," + f"有效票 {v:,}" + for eid, v in orphan_by_election.most_common() + ] + else: + lines.append("無。") + lines += ["", "### 只知道鄉鎮或縣市的票", ""] + if residual_by_election: + lines.append( + "對不到任何現存或 2018 年以後村里的票(多半是 2018 年以前就合併或改名的里," + "或舊資料缺漏的村里列),記在「鄉鎮代碼+000」或「縣市代碼+000000」:" + "計入上表的核對,不分配給任何村里(legacy.py)。" + ) + lines += [""] + [f"- {eid}:有效票 {v:,}" for eid, v in residual_by_election.most_common()] + else: + lines.append("無。") + + adults_total = sum(v["population"]["adults"] for v in villages) or 1 + lines += ["", "## 政黨傾向(以成年人口加權)", "", "| 傾向 | 比例 |", "|---|---|"] + for key in ("a_core", "a_lean", "middle", "b_lean", "b_core", "c_lean"): + share = sum(v["lean"][key] * v["population"]["adults"] for v in villages) / adults_total + lines.append(f"| {key} | {share:.1%} |") + + model = manifest["parameters"]["ageLeanModel"] + leans = list(next(iter(model.values())).keys()) + lines += [ + "", + "## 年齡 × 政黨傾向(生態推論,P(傾向 | 年齡))", + "", + f"以{manifest['parameters']['ageLeanScope']}估計,收斂強度 {manifest['parameters']['ageLeanRidge']}。" + "生態推論在各里年齡結構高度相似時很不穩定,不加收斂會出現不合理的極端值;" + "這組數字只是暫時的保守估計,取得政大選研中心 TEDS 調查資料後要重新校正(docs/10)。", + "", + "| 年齡 | " + " | ".join(leans) + " |", + "|---|" + "---|" * len(leans), + ] + lines += [ + f"| {age} | " + " | ".join(f"{row[lean]:.2f}" for lean in leans) + " |" for age, row in model.items() + ] + lines += [ + "", + "## 參數", + "", + "政黨傾向換算、選舉權重、派系強度都是初始值,M1 以歷史回測校準。見 manifest.json 的 parameters。", + "", + ] + (out_dir / "report.md").write_text("\n".join(lines), encoding="utf-8") diff --git a/backend/data/pipeline/src/election_data/scoring/__init__.py b/backend/data/pipeline/src/election_data/scoring/__init__.py new file mode 100644 index 0000000..78aa65c --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/__init__.py @@ -0,0 +1 @@ +"""人物 AI 評分管線(docs/15):收集證據 → 依公開評分規則打分 → 一致性與偏差檢查 → 人工抽查。""" diff --git a/backend/data/pipeline/src/election_data/scoring/__main__.py b/backend/data/pipeline/src/election_data/scoring/__main__.py new file mode 100644 index 0000000..2a4b790 --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/__main__.py @@ -0,0 +1,72 @@ +"""python -m election_data.scoring [--limit N] [--no-web] [--dry-run] + +--dry-run 不呼叫 API:只產生證據包與提示預覽,並粗估費用。真正執行前請先確認費用。 +""" + +from __future__ import annotations + +import argparse +import json +import logging +from datetime import date +from pathlib import Path + +from ..config import BUILD_DIR +from .evidence import record_evidence, render_packet +from .pipeline import RUNS, ScoringStats, score_person, write_outputs + +log = logging.getLogger(__name__) + +# 粗估用的價格與用量(claude-opus-5-5:輸入 $4、輸出 $20 / 百萬 tokens;網路搜尋 $10 / 千次) +PRICE_IN, PRICE_OUT, PRICE_SEARCH = 4.0, 20.0, 10.0 +EST_RESEARCH_IN, EST_RESEARCH_OUT, EST_SEARCHES = 30_000, 2_500, 5 +EST_SCORE_IN, EST_SCORE_OUT = 4_000, 1_500 + + +def estimate(n: int, use_web: bool) -> str: + research = ( + EST_RESEARCH_IN * PRICE_IN + EST_RESEARCH_OUT * PRICE_OUT + ) / 1e6 + EST_SEARCHES * PRICE_SEARCH / 1000 + scoring = RUNS * (EST_SCORE_IN * PRICE_IN + EST_SCORE_OUT * PRICE_OUT) / 1e6 + per_person = scoring + (research if use_web else 0) + return f"約 {n} 人 × US${per_person:.2f} ≈ US${n * per_person:.0f}(粗估,實際依搜尋結果長度而定)" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="election_data.scoring", description="人物 AI 評分") + parser.add_argument("--people", default=str(BUILD_DIR / "people" / "people.json")) + parser.add_argument("--limit", type=int, default=0, help="只評前 N 人(0 = 全部)") + parser.add_argument("--no-web", action="store_true", help="不做網路研究,只用資料庫紀錄") + parser.add_argument("--effort", default="medium", choices=["low", "medium", "high", "xhigh", "max"]) + parser.add_argument("--dry-run", action="store_true", help="不呼叫 API,只輸出預覽與費用估計") + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") + + people_file = json.loads(Path(args.people).read_text(encoding="utf-8")) + people = people_file["people"][: args.limit or None] + out_dir = BUILD_DIR / "people" + evidence_dir = out_dir / "evidence" + evidence_dir.mkdir(parents=True, exist_ok=True) + use_web = not args.no_web + + if args.dry_run: + preview = out_dir / "scoring_preview.md" + sample = people[:3] + parts = [f"# 評分預覽(不呼叫 API)\n\n費用估計:{estimate(len(people), use_web)}\n"] + parts += [f"## {p['name']}\n\n```\n{render_packet(p, record_evidence(p), 0)}\n```\n" for p in sample] + preview.write_text("\n".join(parts), encoding="utf-8") + log.info("費用估計:%s;預覽:%s", estimate(len(people), use_web), preview) + return 0 + + from .llm import AnthropicBackend # 只有真正執行時才需要憑證 + + backend = AnthropicBackend(effort=args.effort) + stats = ScoringStats() + scored = [score_person(p, backend, stats, evidence_dir, date.today(), use_web) for p in people] + out = write_outputs(out_dir, people_file, scored, stats) + log.info("完成:%s", out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/data/pipeline/src/election_data/scoring/derive.py b/backend/data/pipeline/src/election_data/scoring/derive.py new file mode 100644 index 0000000..a7d1788 --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/derive.py @@ -0,0 +1,67 @@ +"""由公開資料直接計算的屬性(不經 AI):知名度、人脈;體力用預設值。""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from datetime import date + +# 職位層級:用來估計知名度下限(初始值,M1 平衡時調整)。 +# 依序比對、取第一個符合的,所以「副」字頭的職稱要排在正職前面。 +POSITION_LEVELS: tuple[tuple[str, int], ...] = ( + ("副總統", 95), + ("總統", 100), + ("副院長", 85), + ("院長", 92), + ("黨主席", 85), + ("副市長", 65), + ("市長", 85), + ("副縣長", 60), + ("縣長", 80), + ("政務次長", 60), + ("部長", 75), + ("主任委員", 70), + ("主席", 80), + ("立法委員", 60), + ("議員", 45), +) +DEFAULT_STAMINA = 60 + + +def _level(title: str) -> int: + return next((lvl for key, lvl in POSITION_LEVELS if key in title), 40) + + +def _years(start: str | None, end: str | None, today: date) -> float: + if not start: + return 1.0 + begin = date.fromisoformat(start) + finish = date.fromisoformat(end) if end else today + return max(0.0, (finish - begin).days / 365.25) + + +def awareness(person: Mapping) -> tuple[int, list[str]]: + """max(職位層級, 得票換算);得票 100 萬約 60 分、500 萬約 70 分。""" + best, sources = 30, [] + for pos in person.get("positions", []): + lvl = _level(pos["title"]) + if lvl > best: + best, sources = lvl, list(pos["sourceIds"]) + for rec in person.get("electionHistory", []): + votes = rec.get("votes") or 0 + if votes > 0: + score = int(min(95, max(0, 15 * math.log10(votes) - 30))) + if score > best: + best, sources = score, list(rec["sourceIds"]) + return best, sources + + +def network(person: Mapping, today: date) -> tuple[int, list[str]]: + """公職年資與歷任職位數:30 + 每年 3 分 + 每多一個職位 5 分,上限 95。""" + positions = person.get("positions", []) + if not positions: + return 30, [] + years = sum(_years(p.get("from"), p.get("to"), today) for p in positions) + score = int(min(95, 30 + 3 * years + 5 * (len(positions) - 1))) + sources = sorted({s for p in positions for s in p["sourceIds"]}) + return score, sources diff --git a/backend/data/pipeline/src/election_data/scoring/evidence.py b/backend/data/pipeline/src/election_data/scoring/evidence.py new file mode 100644 index 0000000..81a3aaa --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/evidence.py @@ -0,0 +1,58 @@ +"""證據包:每位人物的公開資料條目,給模型引用。 + +- R 開頭:人物資料庫中的結構化紀錄(職位、學歷、選舉紀錄),出處是 people.json 的 sourceIds。 +- W 開頭:研究階段由網路搜尋找到的公開事實,出處是網址。 +""" + +from __future__ import annotations + +import random +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + + +@dataclass(frozen=True) +class EvidenceItem: + id: str + text: str + sources: tuple[str, ...] # 出處 id 或網址 + + +def record_evidence(person: Mapping) -> list[EvidenceItem]: + items: list[EvidenceItem] = [] + + def add(text: str, sources: Sequence[str]) -> None: + items.append(EvidenceItem(f"R{len(items) + 1}", text, tuple(sources))) + + if person.get("party"): + add(f"政黨:{person['party']}", person.get("fieldSources", {}).get("party", [])) + for pos in person.get("positions", []): + span = f"{pos.get('from') or '?'}~{pos.get('to') or '現在'}" + add(f"職位:{pos['org']} {pos['title']}({span})", pos["sourceIds"]) + for edu in person.get("education", []): + add(f"學歷:{edu.get('school') or ''} {edu['degree']}".strip(), edu["sourceIds"]) + for rec in person.get("electionHistory", []): + result = "當選" if rec["elected"] else "未當選" + votes = f",得票 {rec['votes']:,}" if rec.get("votes") is not None else "" + share = f"({rec['share']:.1%})" if rec.get("share") is not None else "" + district = f" {rec['district']}" if rec.get("district") else "" + add(f"選舉:{rec['election']}{district},{result}{votes}{share}", rec["sourceIds"]) + return items + + +def web_evidence(raw_items: Sequence[Mapping]) -> list[EvidenceItem]: + out = [] + for i, item in enumerate(raw_items, 1): + date = f"({item['published']})" if item.get("published") else "" + out.append(EvidenceItem(f"W{i}", f"{item['claim']}{date}", (item["url"],))) + return out + + +def render_packet(person: Mapping, items: Sequence[EvidenceItem], seed: int) -> str: + """證據清單;以 seed 打亂順序,讓三次評分看到不同排列(一致性檢查)。""" + shuffled = list(items) + random.Random(seed).shuffle(shuffled) + header = f"人物:{person['name']}({person['category']})" + lines = [header, "", "證據清單(請以編號引用):"] + lines += [f"[{item.id}] {item.text}" for item in shuffled] + return "\n".join(lines) diff --git a/backend/data/pipeline/src/election_data/scoring/llm.py b/backend/data/pipeline/src/election_data/scoring/llm.py new file mode 100644 index 0000000..4ae10d9 --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/llm.py @@ -0,0 +1,142 @@ +"""呼叫 Claude:研究(網路搜尋找公開事實)與評分(結構化輸出)。 + +- 模型預設 claude-opus-5-5,effort 明確設定(此模型預設 medium)。 +- 開啟伺服器端拒絕回退(fallbacks: "default"),被安全分類器拒絕時由伺服器改用其他模型; + 實際回應的模型記錄在每筆評分的 model 欄位。 +- 憑證由 SDK 自行解析(ANTHROPIC_API_KEY、ANTHROPIC_AUTH_TOKEN 或 `ant auth login` 的設定檔)。 +""" + +from __future__ import annotations + +import json +import logging +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Protocol + +import anthropic + +from .rubric import render_rubric, score_schema + +log = logging.getLogger(__name__) + +MODEL = "claude-opus-5-5" +FALLBACK_BETA = "server-side-fallback-2026-07-01" +MAX_CONTINUATIONS = 5 +STAT_ENUM = ["affinity", "eloquence", "strategy", "online", "image", "wealth"] + +RESEARCH_SYSTEM = ( + "你是台灣政治資料研究員。任務:為指定的公眾人物整理與其公開角色相關、可查證的公開事實," + "供遊戲的屬性評分使用。只收錄公開報導、官方資料、公開民調、公開的社群數據。" + "不收錄私生活、家人、住址、外貌,也不收錄尚未定案的指控。" + "每一條都要附上你實際看過的網址。整理完成後呼叫 submit_evidence 提交。" +) +SUBMIT_EVIDENCE_TOOL = { + "name": "submit_evidence", + "description": "提交整理好的公開事實清單(最多 15 條),每條附網址與相關的屬性。", + "strict": True, + "input_schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "claim": {"type": "string", "description": "一句話的事實陳述,繁體中文"}, + "url": {"type": "string"}, + "published": {"type": "string", "description": "YYYY-MM;不確定時留空字串"}, + "stats": {"type": "array", "items": {"type": "string", "enum": STAT_ENUM}}, + }, + "required": ["claim", "url", "published", "stats"], + "additionalProperties": False, + }, + } + }, + "required": ["items"], + "additionalProperties": False, + }, +} + + +@dataclass(frozen=True) +class LlmResult: + data: Mapping + model: str + input_tokens: int + output_tokens: int + + +class ScoringBackend(Protocol): + def research(self, person_summary: str, max_searches: int) -> LlmResult: ... + + def score(self, packet: str) -> LlmResult: ... + + +class RefusedError(RuntimeError): + pass + + +@dataclass +class AnthropicBackend: + model: str = MODEL + effort: str = "medium" + client: anthropic.Anthropic | None = None + + def __post_init__(self) -> None: + self.client = self.client or anthropic.Anthropic() + + def _create(self, *, output_config: Mapping | None = None, **kwargs: object): # noqa: ANN202 + """回傳 SDK 的 BetaMessage。effort 一律明確設定;其他 output_config 欄位(例如 format)合併進來。""" + assert self.client is not None + return self.client.beta.messages.create( + model=self.model, + max_tokens=16000, + betas=[FALLBACK_BETA], + fallbacks="default", + output_config={"effort": self.effort, **(output_config or {})}, + **kwargs, + ) + + def research(self, person_summary: str, max_searches: int = 6) -> LlmResult: + tools = [ + {"type": "web_search_20260209", "name": "web_search", "max_uses": max_searches}, + SUBMIT_EVIDENCE_TOOL, + ] + user = {"role": "user", "content": f"{person_summary}\n\n請搜尋並整理,完成後呼叫 submit_evidence。"} + messages: list[dict] = [user] + tokens_in = tokens_out = 0 + nudged = False + for _ in range(MAX_CONTINUATIONS + 1): + response = self._create(system=RESEARCH_SYSTEM, tools=tools, messages=messages) + tokens_in += response.usage.input_tokens + tokens_out += response.usage.output_tokens + if response.stop_reason == "refusal": + raise RefusedError(f"研究被拒絕:{getattr(response.stop_details, 'category', None)}") + submit = next( + (b for b in response.content if b.type == "tool_use" and b.name == "submit_evidence"), None + ) + if submit is not None: + return LlmResult(dict(submit.input), response.model, tokens_in, tokens_out) + # 對話只往後附加,不修改先前的內容(保留思考區塊的完整性) + messages = [*messages, {"role": "assistant", "content": response.content}] + if response.stop_reason == "pause_turn": + continue + if nudged: + break + messages.append({"role": "user", "content": "請把整理好的事實以 submit_evidence 提交。"}) + nudged = True + raise RuntimeError("研究階段沒有提交證據") + + def score(self, packet: str) -> LlmResult: + response = self._create( + system=[{"type": "text", "text": render_rubric(), "cache_control": {"type": "ephemeral"}}], + messages=[{"role": "user", "content": f"{packet}\n\n請依評分規則,為六個屬性各給一筆評分。"}], + output_config={"format": {"type": "json_schema", "schema": score_schema()}}, + ) + if response.stop_reason == "refusal": + raise RefusedError(f"評分被拒絕:{getattr(response.stop_details, 'category', None)}") + text = next(b.text for b in response.content if b.type == "text") + return LlmResult( + json.loads(text), response.model, response.usage.input_tokens, response.usage.output_tokens + ) diff --git a/backend/data/pipeline/src/election_data/scoring/pipeline.py b/backend/data/pipeline/src/election_data/scoring/pipeline.py new file mode 100644 index 0000000..e8b9d1a --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/pipeline.py @@ -0,0 +1,257 @@ +"""評分流程:衍生屬性 → 研究 → 三次評分取中位數 → 一致性、偏差檢查 → 人工抽查清單。""" + +from __future__ import annotations + +import csv +import hashlib +import json +import logging +import random +import statistics +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import UTC, date, datetime +from pathlib import Path + +from jsonschema import Draft202012Validator + +from ..validate import validate +from .derive import DEFAULT_STAMINA, awareness, network +from .evidence import EvidenceItem, record_evidence, render_packet, web_evidence +from .llm import RefusedError, ScoringBackend +from .rubric import AI_STATS, RUBRIC_VERSION, score_schema + +log = logging.getLogger(__name__) + +RUNS = 3 +CONSISTENCY_LIMIT = 10 # 三次分數差超過這個值就標記人工複核 +BIAS_LIMIT = 8.0 # 各政黨平均分數差超過這個值就整批複核規則 +MIN_GROUP = 5 +REVIEW_SAMPLE_RATE = 0.05 +DEFAULT_VALUE = 50 +TIER_A_KEYWORDS = ("總統", "院長", "市長", "縣長", "黨主席", "部長") +_RANGE_VALIDATOR = Draft202012Validator( + {"type": "object", "properties": {"value": {"type": ["integer", "null"], "minimum": 0, "maximum": 100}}} +) + + +@dataclass +class ScoringStats: + people: int = 0 + research_failures: list[str] = field(default_factory=list) + refusals: list[str] = field(default_factory=list) + inconsistent: list[tuple[str, str, list[int]]] = field(default_factory=list) + input_tokens: int = 0 + output_tokens: int = 0 + + +def _seed(person_id: str, run: int) -> int: + return int(hashlib.sha256(f"{person_id}:{run}".encode()).hexdigest()[:8], 16) + + +def _record(stat: str, value: int, method: str, rationale: str | None, citations: Sequence[str], + confidence: str, model: str | None, now: str) -> dict: # fmt: skip + return { + "stat": stat, + "value": int(value), + "method": method, + "rationale": rationale, + "citations": list(citations), + "confidence": confidence, + "model": model, + "rubricVersion": RUBRIC_VERSION, + "scoredAt": now, + "reviewed": False, + } + + +def _summary(person: Mapping, items: Sequence[EvidenceItem]) -> str: + known = "\n".join(f"- {item.text}" for item in items[:20]) + return f"人物:{person['name']}\n類別:{person['category']}\n已知公開紀錄:\n{known}" + + +def _aggregate( + stat: str, runs: Sequence[Mapping], valid_ids: set[str] +) -> tuple[int, str, list[str], str, bool]: + """回傳 (分數, 方法, 引用, 理由, 是否不一致)。引用不在證據清單中的分數視為無效(docs/15)。""" + usable = [] + for run in runs: + entry = next((s for s in run["scores"] if s["stat"] == stat), None) + if entry is None or entry["insufficient"] or entry["value"] is None: + continue + cited = [c for c in entry["citations"] if c in valid_ids] + if not cited or list(_RANGE_VALIDATOR.iter_errors(entry)): + continue + usable.append((entry, cited)) + if len(usable) < 2: + return DEFAULT_VALUE, "default", [], "證據不足,使用預設值。", False + values = sorted(e["value"] for e, _ in usable) + median = int(statistics.median(values)) + closest = min(usable, key=lambda pair: abs(pair[0]["value"] - median)) + inconsistent = values[-1] - values[0] > CONSISTENCY_LIMIT + return ( + median, + "ai", + sorted({c for _, cited in usable for c in cited}), + closest[0]["rationale"], + inconsistent, + ) + + +def score_person( + person: Mapping, + backend: ScoringBackend, + stats: ScoringStats, + evidence_dir: Path, + today: date, + use_web: bool, +) -> dict: + now = datetime.now(UTC).isoformat(timespec="seconds") + records: list[dict] = [] + value, sources = awareness(person) + records.append( + _record("awareness", value, "derived", "依最高職位層級與歷屆得票計算。", sources, "high", None, now) + ) + value, sources = network(person, today) + records.append( + _record("network", value, "derived", "依公職年資與歷任職位數計算。", sources, "high", None, now) + ) + records.append( + _record("stamina", DEFAULT_STAMINA, "default", "沒有客觀資料,使用預設值。", [], "low", None, now) + ) + + items = record_evidence(person) + cache = evidence_dir / f"{person['id']}.json" + if use_web: + if cache.exists(): + web_raw = json.loads(cache.read_text(encoding="utf-8"))["items"] + else: + try: + result = backend.research(_summary(person, items), max_searches=6) + web_raw = list(result.data.get("items", [])) + stats.input_tokens += result.input_tokens + stats.output_tokens += result.output_tokens + cache.write_text( + json.dumps({"model": result.model, "items": web_raw}, ensure_ascii=False, indent=1), + encoding="utf-8", + ) + except RefusedError as exc: + stats.refusals.append(f"{person['id']} 研究:{exc}") + web_raw = [] + except Exception as exc: # noqa: BLE001 - 單人失敗不中斷整批 + log.exception("研究失敗:%s", person["id"]) + stats.research_failures.append(f"{person['id']}:{exc}") + web_raw = [] + items = items + web_evidence(web_raw) + valid_ids = {item.id for item in items} + citation_sources = {item.id: item.sources for item in items} + + runs, model = [], None + for run in range(RUNS): + try: + result = backend.score(render_packet(person, items, _seed(person["id"], run))) + except RefusedError as exc: + stats.refusals.append(f"{person['id']} 評分:{exc}") + continue + validate_scores(result.data) + runs.append(result.data) + model = result.model + stats.input_tokens += result.input_tokens + stats.output_tokens += result.output_tokens + + for rubric in AI_STATS: + value, method, cited, rationale, inconsistent = _aggregate(rubric.key, runs, valid_ids) + if inconsistent: + per_run = [ + s["value"] + for r in runs + for s in r["scores"] + if s["stat"] == rubric.key and s["value"] is not None + ] + stats.inconsistent.append((person["id"], rubric.key, per_run)) + expanded = sorted({src for c in cited for src in citation_sources[c]}) + confidence = "low" if method == "default" else ("medium" if inconsistent else "high") + records.append( + _record(rubric.key, value, method, rationale, expanded or cited, confidence, model, now) + ) + + stats.people += 1 + by_stat = {r["stat"]: r["value"] for r in records} + return {**person, "stats": {**person["stats"], **by_stat}, "scoring": records} + + +def validate_scores(data: Mapping) -> None: + errors = list(Draft202012Validator(score_schema()).iter_errors(data)) + if errors: + raise ValueError(f"評分輸出不符合結構:{errors[0].message}") + + +def bias_report(people: Sequence[Mapping]) -> list[str]: + """各政黨的 AI 屬性平均;差距超過門檻的列出來(需要人工判斷是否有客觀原因)。""" + lines = [] + for rubric in AI_STATS: + groups: dict[str, list[int]] = defaultdict(list) + for p in people: + rec = next((r for r in p["scoring"] if r["stat"] == rubric.key and r["method"] == "ai"), None) + if rec: + groups[p.get("party") or "無黨籍"].append(rec["value"]) + means = {party: statistics.mean(v) for party, v in groups.items() if len(v) >= MIN_GROUP} + if len(means) < 2: + continue + spread = max(means.values()) - min(means.values()) + flag = "⚠ 需要複核" if spread > BIAS_LIMIT else "通過" + detail = "、".join(f"{k} {v:.1f}({len(groups[k])} 人)" for k, v in sorted(means.items())) + lines.append(f"| {rubric.name} | {detail} | {spread:.1f} | {flag} |") + return lines + + +def review_sample(people: Sequence[Mapping], seed: int = 2026) -> list[Mapping]: + """全部 A 級人物,加上其餘人物隨機抽 5%。""" + tier_a = [p for p in people if any(k in pos["title"] for pos in p["positions"] for k in TIER_A_KEYWORDS)] + rest = [p for p in people if p not in tier_a] + k = max(1, round(len(rest) * REVIEW_SAMPLE_RATE)) if rest else 0 + return tier_a + random.Random(seed).sample(rest, k) + + +def write_outputs( + out_dir: Path, people_file: Mapping, scored: Sequence[Mapping], stats: ScoringStats +) -> Path: + payload = {**people_file, "people": list(scored)} + validate(payload, "people.schema.json") + out = out_dir / "people_scored.json" + out.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8") + sample = review_sample(scored) + with (out_dir / "review_sample.csv").open("w", encoding="utf-8-sig", newline="") as fh: + writer = csv.writer(fh) + writer.writerow(["id", "姓名", "屬性", "分數", "方法", "信心", "理由", "出處", "複核結果"]) + for p in sample: + for r in p["scoring"]: + writer.writerow([p["id"], p["name"], r["stat"], r["value"], r["method"], r["confidence"], + r["rationale"], " ".join(r["citations"]), ""]) # fmt: skip + lines = [ + f"# AI 評分報告(規則 {RUBRIC_VERSION})", + "", + f"- 評分人數:{stats.people}", + f"- 用量:輸入 {stats.input_tokens:,} tokens,輸出 {stats.output_tokens:,} tokens", + f"- 研究失敗:{len(stats.research_failures)};被拒絕:{len(stats.refusals)}", + f"- 三次評分差距超過 {CONSISTENCY_LIMIT} 分:{len(stats.inconsistent)} 筆" + "(已標記為中信心,需人工複核)", + f"- 人工抽查清單:review_sample.csv({len(sample)} 人)", + "", + "## 政黨偏差檢查", + "", + "| 屬性 | 各政黨平均 | 最大差距 | 結果 |", + "|---|---|---|---|", + *(bias_report(scored) or ["| (人數不足以比較) | | | |"]), + "", + "## 不一致的評分", + "", + *[f"- {pid} {stat}:{vals}" for pid, stat, vals in stats.inconsistent[:50]], + "", + "## 失敗與拒絕", + "", + *[f"- {x}" for x in stats.research_failures + stats.refusals], + ] + (out_dir / "scoring_report.md").write_text("\n".join(lines) + "\n", encoding="utf-8") + return out diff --git a/backend/data/pipeline/src/election_data/scoring/rubric.py b/backend/data/pipeline/src/election_data/scoring/rubric.py new file mode 100644 index 0000000..24ff00f --- /dev/null +++ b/backend/data/pipeline/src/election_data/scoring/rubric.py @@ -0,0 +1,141 @@ +"""公開評分規則 v1。規則改版時 RUBRIC_VERSION 要升版,所有人重新評分(docs/15)。""" + +from __future__ import annotations + +from dataclasses import dataclass + +RUBRIC_VERSION = "v1" + + +@dataclass(frozen=True) +class StatRubric: + key: str + name: str + definition: str + anchors: tuple[tuple[str, str], ...] # (分數段, 描述) + + +AI_STATS: tuple[StatRubric, ...] = ( + StatRubric( + "affinity", + "親和力", + "與一般民眾互動的溫度與接地氣程度,包括基層走訪、服務案件、與選民面對面的互動。", + ( + ("80–100", "長期以基層經營著稱,親民形象被多家媒體反覆報導"), + ("60–79", "有穩定、可查的地方走訪或服務紀錄"), + ("40–59", "一般;公開資料沒有特別突出的正面或負面紀錄"), + ("20–39", "公開報導多描述其距離感,基層互動紀錄少"), + ("0–19", "多次因對待民眾的態度引發廣泛的公開批評"), + ), + ), + StatRubric( + "eloquence", + "口才", + "辯論、質詢、受訪、演講的表達能力與臨場反應。", + ( + ("80–100", "在全國性辯論、質詢或重大記者會中的表現被廣泛報導為出色"), + ("60–79", "公開發言條理清楚,有可查的良好表現紀錄"), + ("40–59", "一般"), + ("20–39", "公開發言常被報導為不清楚或失準"), + ("0–19", "多次重大失言並造成廣泛負面報導"), + ), + ), + StatRubric( + "strategy", + "謀略", + "選戰操盤、議程設定、協商與組織動員的成效。", + ( + ("80–100", "多次在困難選情中勝選,或主導重大政治協商、法案、組織改造成功"), + ("60–79", "有可查的成功選戰或協商紀錄"), + ("40–59", "一般"), + ("20–39", "公開紀錄中策略失誤多於成功"), + ("0–19", "多次重大策略失誤並被廣泛報導"), + ), + ), + StatRubric( + "online", + "網路魅力", + "社群平台的經營成效與網路聲量,以公開的追蹤數與互動情形為主要依據。", + ( + ("80–100", "主要平台追蹤數居全國政治人物前列,經常產生大量互動"), + ("60–79", "追蹤數與互動在同層級公職中屬前段"), + ("40–59", "一般"), + ("20–39", "社群經營有限"), + ("0–19", "幾乎沒有經營社群,或網路聲量以負面為主"), + ), + ), + StatRubric( + "image", + "形象", + "公眾對其清廉、專業、可信度的整體觀感,以公開民調的好感度、信任度為主要依據。", + ( + ("80–100", "公開民調的好感或信任度長期居前段"), + ("60–79", "好感度高於同層級平均"), + ("40–59", "一般或資料不足以判斷高低"), + ("20–39", "好感度明顯低於同層級平均"), + ("0–19", "長期居於各項民調的末段"), + ), + ), + StatRubric( + "wealth", + "財力", + "個人可動用的財務資源,以公開的財產申報與公開報導為依據。", + ( + ("80–100", "公開申報或報導顯示資產規模在政治人物中居前段"), + ("60–79", "高於同層級平均"), + ("40–59", "一般或資料不足"), + ("20–39", "低於同層級平均"), + ("0–19", "公開資料顯示資源非常有限"), + ), + ), +) + +RULES: tuple[str, ...] = ( + "分數以全台灣的政治人物與公眾人物為比較基準,50 分代表一般水準。", + "每個分數都必須引用證據清單中的編號;沒有證據支持時,回報資料不足(insufficient),不要猜。", + "只使用與其公開角色相關的公開資訊。不考慮私生活、家人、外貌。", + "政黨、政治立場不是評分因素;同樣的表現不論政黨都給同樣的分數。", + "爭議中、尚未定案的指控不能作為扣分依據;只有確定判決或官方正式認定的事項可以。", + "理由用繁體中文寫一到兩句,直接說明依據,不超過 120 字。", +) + + +def render_rubric() -> str: + """產生公開版評分規則(docs/rubric-v1.md 與模型的系統提示共用同一份文字)。""" + lines = [f"# 人物評分規則 {RUBRIC_VERSION}", "", "## 共通規則", ""] + lines += [f"{i}. {rule}" for i, rule in enumerate(RULES, 1)] + for stat in AI_STATS: + lines += [ + "", + f"## {stat.name}({stat.key})", + "", + stat.definition, + "", + "| 分數 | 描述 |", + "|---|---|", + ] + lines += [f"| {band} | {desc} |" for band, desc in stat.anchors] + return "\n".join(lines) + "\n" + + +def score_schema() -> dict: + """結構化輸出的 JSON Schema。數值範圍另以 jsonschema 在本地驗證。""" + item = { + "type": "object", + "properties": { + "stat": {"type": "string", "enum": [s.key for s in AI_STATS]}, + "insufficient": {"type": "boolean"}, + "value": {"type": ["integer", "null"]}, + "confidence": {"type": "string", "enum": ["high", "medium", "low"]}, + "rationale": {"type": "string"}, + "citations": {"type": "array", "items": {"type": "string"}}, + }, + "required": ["stat", "insufficient", "value", "confidence", "rationale", "citations"], + "additionalProperties": False, + } + return { + "type": "object", + "properties": {"scores": {"type": "array", "items": item}}, + "required": ["scores"], + "additionalProperties": False, + } diff --git a/backend/data/pipeline/src/election_data/sources.py b/backend/data/pipeline/src/election_data/sources.py new file mode 100644 index 0000000..e81bdaa --- /dev/null +++ b/backend/data/pipeline/src/election_data/sources.py @@ -0,0 +1,135 @@ +"""資料來源登錄:每個資料集的出處、授權、下載網址。 + +輸出的 SourceRef 對應協定的 `SourceRef`(packages/protocol/src/common.ts)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +LICENSE_OGDL = "政府資料開放授權條款第1版" + + +@dataclass(frozen=True) +class SourceSpec: + id: str + title: str + agency: str + page_url: str + license: str + version: str | None = None + note: str | None = None + + +@dataclass(frozen=True) +class SourceRef: + id: str + title: str + agency: str + url: str + license: str + retrieved_at: str + version: str | None = None + note: str | None = None + + def to_json(self) -> dict[str, str]: + out = { + "id": self.id, + "title": self.title, + "agency": self.agency, + "url": self.url, + "license": self.license, + "retrievedAt": self.retrieved_at, + } + if self.version: + out["version"] = self.version + if self.note: + out["note"] = self.note + return out + + +CATALOG: dict[str, SourceSpec] = { + spec.id: spec + for spec in ( + SourceSpec( + "cec-votedata", + "選舉資料庫(含選舉區資料)", + "中央選舉委員會", + "https://data.gov.tw/dataset/13119", + LICENSE_OGDL, + ), + SourceSpec( + "ris-odrp014", + "村里戶數、單一年齡人口(新增區域代碼)", + "內政部戶政司", + "https://data.gov.tw/dataset/77132", + LICENSE_OGDL, + ), + SourceSpec( + "ris-odrp013", + "現住人口數按性別及原住民身分分(新增區域代碼)", + "內政部戶政司", + "https://data.gov.tw/dataset/77145", + LICENSE_OGDL, + ), + SourceSpec( + "nlsc-village", + "村里界圖(TWD97 經緯度)", + "內政部國土測繪中心", + "https://data.gov.tw/dataset/7438", + LICENSE_OGDL, + ), + SourceSpec( + "fia-income", + "綜稅綜合所得總額全國各縣市鄉鎮村里統計分析表", + "財政部財政資訊中心", + "https://data.gov.tw/dataset/103066", + LICENSE_OGDL, + ), + SourceSpec( + "dgbas-census-2020", + "109 年人口及住宅普查縣市別報告統計表", + "行政院主計總處", + "https://www.stat.gov.tw/News_Content.aspx?n=2755&s=230160", + "網站開放資料宣告", + ), + SourceSpec( + "hakka-key-areas", + "客家委員會客家文化重點發展區", + "客家委員會", + "https://data.gov.tw/dataset/162466", + LICENSE_OGDL, + ), + SourceSpec( + "moi-temples", + "全國宗教資訊系統資料-寺廟", + "內政部", + "https://data.gov.tw/dataset/8203", + LICENSE_OGDL, + ), + SourceSpec( + "moi-churches", + "全國宗教資訊系統資料-法人教會", + "內政部", + "https://data.gov.tw/dataset/8204", + LICENSE_OGDL, + ), + ) +} + + +def source_ref( + source_id: str, retrieved_at: str, version: str | None = None, note: str | None = None +) -> SourceRef: + """依登錄資料產生 SourceRef;version、note 以呼叫端提供的為優先。""" + spec = CATALOG[source_id] + return SourceRef( + id=spec.id, + title=spec.title, + agency=spec.agency, + url=spec.page_url, + license=spec.license, + retrieved_at=retrieved_at, + version=version or spec.version, + note=note or spec.note, + ) diff --git a/backend/data/pipeline/src/election_data/validate.py b/backend/data/pipeline/src/election_data/validate.py new file mode 100644 index 0000000..bab5dec --- /dev/null +++ b/backend/data/pipeline/src/election_data/validate.py @@ -0,0 +1,35 @@ +"""用協定產生的 JSON Schema 驗證輸出(packages/protocol/schema)。""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from functools import cache +from typing import Any + +from jsonschema import Draft202012Validator + +from .config import SCHEMA_DIR + + +class SchemaValidationError(ValueError): + pass + + +@cache +def _validator(schema_file: str) -> Draft202012Validator: + path = SCHEMA_DIR / schema_file + if not path.exists(): + raise FileNotFoundError(f"找不到 {path};請先在 backend 執行 `pnpm schema`") + return Draft202012Validator(json.loads(path.read_text(encoding="utf-8"))) + + +def validate(data: Mapping[str, Any], schema_file: str, *, max_errors: int = 5) -> None: + """不符合結構時丟出 SchemaValidationError,列出前幾個錯誤的位置。""" + errors = sorted(_validator(schema_file).iter_errors(data), key=lambda e: list(e.absolute_path)) + if errors: + lines = [ + f"{'/'.join(map(str, e.absolute_path)) or '(root)'}: {e.message}" for e in errors[:max_errors] + ] + more = f"\n…另有 {len(errors) - max_errors} 個錯誤" if len(errors) > max_errors else "" + raise SchemaValidationError(f"{schema_file} 驗證失敗:\n" + "\n".join(lines) + more) diff --git a/backend/data/pipeline/tests/people/__init__.py b/backend/data/pipeline/tests/people/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/data/pipeline/tests/people/conftest.py b/backend/data/pipeline/tests/people/conftest.py new file mode 100644 index 0000000..3e71568 --- /dev/null +++ b/backend/data/pipeline/tests/people/conftest.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +FIXTURES = Path(__file__).parent / "fixtures" + + +@pytest.fixture +def fixtures() -> Path: + return FIXTURES + + +def read_fixture(name: str) -> str: + return (FIXTURES / name).read_text(encoding="utf-8") diff --git a/backend/data/pipeline/tests/people/fixtures/ey_agency_heads_sample.html b/backend/data/pipeline/tests/people/fixtures/ey_agency_heads_sample.html new file mode 100644 index 0000000..2213219 --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/ey_agency_heads_sample.html @@ -0,0 +1,42 @@ +<ul class="grid2 effect" id="grid"> +<li class="member_img hvr-outline-in"> +<div class="member_box"> +<a href="https://www.moi.gov.tw/cp.aspx?n=27" target="_blank" title="內政部劉世芳(另開視窗)" rel="noreferrer noopener"> +<span></span> +<span class="title"><span style="color: #414641;border-bottom: none;">內政部</span><br /><span>劉世芳部長</span></span> +</a> +</div> +</li> +<li class="member_img hvr-outline-in"> +<div class="member_box"> +<a href="https://www.ocac.gov.tw/OCAC/Pages/Detail.aspx?nodeid=555&pid=78817233" target="_blank" title="僑務委員會李姸慧(另開視窗)" rel="noreferrer noopener"> +<span></span> +<span class="title"><span style="color: #414641;border-bottom: none;">僑務委員會</span><br /><span>李姸慧代理委員長</span></span> +</a> +</div> +</li> +<li class="member_img hvr-outline-in"> +<div class="member_box"> +<a href="https://www.cip.gov.tw/zh-tw/menu/data-list/80A47B1EC7BF5A12-info.html?cumid=80A47B1EC7BF5A12" target="_blank" title="原住民族委員會曾智勇(另開視窗)" rel="noreferrer noopener"> +<span></span> +<span class="title"><span style="color: #414641;border-bottom: none;">原住民族委員會</span><br /><span>曾智勇 Ljaucu‧Zingrur 主任委員</span></span> +</a> +</div> +</li> +<li class="member_img hvr-outline-in"> +<div class="member_box"> +<a href="https://www.cbc.gov.tw/tw/cp-326-27196-EF74B-1.html" target="_blank" title="中央銀行楊金龍(另開視窗)" rel="noreferrer noopener"> +<span></span> +<span class="title"><span style="color: #414641;border-bottom: none;">中央銀行</span><br /><span>楊金龍總裁</span></span> +</a> +</div> +</li> +<li class="member_img hvr-outline-in"> +<div class="member_box"> +<a href="https://www.ftc.gov.tw/internet/main/doc/docDetail.aspx?uid=1948&docid=17978" target="_blank" title="公平交易委員會陳志民(另開視窗)" rel="noreferrer noopener"> +<span></span> +<span class="title"><span style="color: #414641;border-bottom: none;">公平交易委員會</span><br /><span>陳志民代理主任委員</span></span> +</a> +</div> +</li> +</ul> diff --git a/backend/data/pipeline/tests/people/fixtures/ey_premier_sample.html b/backend/data/pipeline/tests/people/fixtures/ey_premier_sample.html new file mode 100644 index 0000000..764dc9b --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/ey_premier_sample.html @@ -0,0 +1,26 @@ +<html><head><title> + 行政院全球資訊網-院長 +
+ + 行政院卓榮泰院長 + +
+
+ + +
+
+ + + 學 歷
  • 民國68年09月-73年06月 中興大學法律系畢業
+ + 經 歷
  • 民國78年-87年 臺北市議員
  • 民國88年-93年 立法委員
  • 民國93年-94年 總統府副秘書長
  • 民國94年-95年 行政院秘書長
  • 民國95年-96年 總統府副秘書長
  • 民國96年-97年 民進黨秘書長
  • 民國106年04月-106年09月 民進黨副秘書長
  • 民國106年-107年 行政院秘書長
  • 民國108年-109年 民進黨主席
  • 民國113年5月20日- 行政院院長
+ + +
+
+
+

+

以上內容之著作權均屬行政院或原著作權人所有,除有合理使用情形外,應取得著作權人之同意或授權後,方得利用。 diff --git a/backend/data/pipeline/tests/people/fixtures/ly_id9_sample.json b/backend/data/pipeline/tests/people/fixtures/ly_id9_sample.json new file mode 100644 index 0000000..c1d1200 --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/ly_id9_sample.json @@ -0,0 +1,76 @@ + + +{ + "dataList": [ + { + "term": "11", + "name": "丁學忠", + "sex": "男", + "party": "中國國民黨", + "partyGroup": "中國國民黨", + "areaName": "雲林縣第1選舉區", + "committee": "第11屆第1會期:內政委員會;第11屆第2會期:內政委員會;第11屆第3會期:內政委員會;第11屆第4會期:內政委員會;第11屆第5會期:內政委員會;第11屆第6會期:內政委員會;", + "onboardDate": "2024/02/01", + "degree": "國立虎尾科技大學碩士學位", + "leaveFlag": "否", + "leaveDate": "", + "leaveReason": "" + }, + { + "term": "11", + "name": "伍麗華Saidhai‧Tahovecahe", + "sex": "女", + "party": "民主進步黨", + "partyGroup": "民主進步黨", + "areaName": "山地原住民選舉區", + "committee": "第11屆第1會期:財政委員會;第11屆第2會期:財政委員會;第11屆第3會期:教育及文化委員會;第11屆第3會期:修憲委員會;第11屆第4會期:教育及文化委員會;第11屆第5會期:教育及文化委員會;第11屆第5會期:修憲委員會;第11屆第6會期:教育及文化委員會;", + "onboardDate": "2024/02/01", + "degree": "國立屏東大學教育行政研究所博士;屏東師範學院國民教育硏究所碩士(85年-87年);屏東師範學院(80年-84年);屏東師專(73年-78年)", + "leaveFlag": "否", + "leaveDate": "", + "leaveReason": "" + }, + { + "term": "11", + "name": "吳春城", + "sex": "男", + "party": "台灣民眾黨", + "partyGroup": "台灣民眾黨", + "areaName": "全國不分區及僑居國外國民", + "committee": "第11屆第1會期:教育及文化委員會;第11屆第2會期:教育及文化委員會;", + "onboardDate": "2024/02/01", + "degree": "復旦大學管理學博士;中山大學法學碩士;中央大學文學士", + "leaveFlag": "是", + "leaveDate": "2025/02/27", + "leaveReason": "辭職" + }, + { + "term": "11", + "name": "高金素梅", + "sex": "女", + "party": "無黨籍", + "partyGroup": "中國國民黨", + "areaName": "山地原住民選舉區", + "committee": "第11屆第1會期:內政委員會;第11屆第2會期:內政委員會;第11屆第3會期:內政委員會;第11屆第4會期:內政委員會;第11屆第5會期:內政委員會;第11屆第6會期:內政委員會;", + "onboardDate": "2024/02/01", + "degree": "臺中市青年高級中學", + "leaveFlag": "否", + "leaveDate": "", + "leaveReason": "" + }, + { + "term": "11", + "name": "陳俊宇", + "sex": "男", + "party": "民主進步黨", + "partyGroup": "民主進步黨", + "areaName": "宜蘭縣選舉區", + "committee": "第11屆第1會期:司法及法制委員會;第11屆第2會期:司法及法制委員會;第11屆第3會期:外交及國防委員會;第11屆第4會期:外交及國防委員會;第11屆第5會期:外交及國防委員會;第11屆第6會期:外交及國防委員會;", + "onboardDate": "2024/02/01", + "degree": "佛光大學公共事務學系碩士;蘭陽技術學院國際貿易科;宜蘭高商資料處理科;復興國中;大湖國小", + "leaveFlag": "否", + "leaveDate": "", + "leaveReason": "" + } + ] +} \ No newline at end of file diff --git a/backend/data/pipeline/tests/people/fixtures/moi_detail_sample.html b/backend/data/pipeline/tests/people/fixtures/moi_detail_sample.html new file mode 100644 index 0000000..b232de4 --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/moi_detail_sample.html @@ -0,0 +1,56 @@ +

+
+ + + +
+ +
+
+
新竹市政府
+ 高虹安 +
+
+ +
+
黨籍
+
+
    +
  • 台灣民眾黨
+
+
+ +
+
選舉屆次
+
+
    +
  • 111年度縣市長選舉
+
+
+ +
+
學歷
+
+
    +
  • 美國辛辛那提大學機械工程博士 +國立台灣大學資訊工程碩士 +國立臺灣師範大學資訊教育學士 +台北市立第一女子高級中學
  • +
+
+
+ +
+
簡歷
+
+
    +
  • 第十屆立法委員 +台灣民眾黨立法院黨團副總召 +財團法人郭台銘文教基金會董事 +財團法人消防發展基金會董事 +鴻海科技集團副總經理
  • +
+
+
+ +
辦公地址
diff --git a/backend/data/pipeline/tests/people/fixtures/moi_list_sample.html b/backend/data/pipeline/tests/people/fixtures/moi_list_sample.html new file mode 100644 index 0000000..9552408 --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/moi_list_sample.html @@ -0,0 +1,74 @@ +
+
+
+
+ + +
+
+
+ 高虹安
+
+ 新竹市
+
+ 新竹市政府市長
+
+ 台灣民眾黨 +
+
+ +
+ +
+
+
+
+
+
+ + +
+
+
+ 陳福海
+
+ 金門縣
+
+ 金門縣政府縣長
+
+ 無 +
+
+ +
+ +
+
+
+
+
+
+ + +
+
+
+ 王忠銘
+
+ 連江縣
+
+ 連江縣政府縣長
+
+ 中國國民黨 +
+
+ +
+ +
+
+
+
diff --git a/backend/data/pipeline/tests/people/fixtures/wikidata_sample.json b/backend/data/pipeline/tests/people/fixtures/wikidata_sample.json new file mode 100644 index 0000000..b199dcb --- /dev/null +++ b/backend/data/pipeline/tests/people/fixtures/wikidata_sample.json @@ -0,0 +1,784 @@ +{ + "results": { + "bindings": [ + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q21055059" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1959-01-17T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "桃園市議員|桃園市議員|桃園市議員" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q21055059" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1959-01-17T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "桃園市議員|桃園市議員|桃園市議員" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q21055059" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1959-01-17T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "桃園市議員|桃園市議員|桃園市議員" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨|民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q121904956" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "丁學忠" + }, + "births": { + "type": "literal", + "value": "1970-06-28T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q121904956" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "丁學忠" + }, + "births": { + "type": "literal", + "value": "1970-06-28T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q121904956" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "丁學忠" + }, + "births": { + "type": "literal", + "value": "1970-06-28T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q124293468" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1971-09-27T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q124293468" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1971-09-27T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "中國國民黨|中國國民黨|中國國民黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q7198343" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1972-11-15T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "立法委員|立法委員|立法委員" + }, + "parties": { + "type": "literal", + "value": "民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q7198343" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1972-11-15T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "立法委員|立法委員|立法委員" + }, + "parties": { + "type": "literal", + "value": "民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q7198343" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1972-11-15T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "立法委員|立法委員|立法委員" + }, + "parties": { + "type": "literal", + "value": "民主進步黨|民主進步黨|民主進步黨" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q116894056" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "王興煥" + }, + "births": { + "type": "literal", + "value": "1973-01-01T00:00:00Z/9" + }, + "positions": { + "type": "literal", + "value": "台灣基進秘書長|台湾基进秘书长|台湾基进党主席" + }, + "parties": { + "type": "literal", + "value": "台灣基進|台灣基進|台灣基進" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q116894056" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "王興煥" + }, + "births": { + "type": "literal", + "value": "1973-01-01T00:00:00Z/9" + }, + "positions": { + "type": "literal", + "value": "台灣基進秘書長|台湾基进秘书长|台湾基进党主席" + }, + "parties": { + "type": "literal", + "value": "台灣基進|台灣基進|台灣基進" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q697458" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1962-09-26T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q697458" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1962-09-26T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q697458" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1962-09-26T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q9369618" + }, + "name": { + "xml:lang": "zh-tw", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1976-10-16T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q9369618" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1976-10-16T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q9369618" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1976-10-16T00:00:00Z/11" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45405003" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q7462" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45405003" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q7462" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45584156" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45584156" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45608712" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45608712" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45657305" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45657305" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q9903" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45696507" + }, + "name": { + "xml:lang": "zh-hant", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1899-01-01T00:00:00Z/9" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q13426199" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q45696507" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "陳瑩" + }, + "births": { + "type": "literal", + "value": "1899-01-01T00:00:00Z/9" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q13426199" + } + }, + { + "item": { + "type": "uri", + "value": "http://www.wikidata.org/entity/Q47689971" + }, + "name": { + "xml:lang": "zh", + "type": "literal", + "value": "吳宗憲" + }, + "births": { + "type": "literal", + "value": "1961-01-01T00:00:00Z/9" + }, + "positions": { + "type": "literal", + "value": "" + }, + "parties": { + "type": "literal", + "value": "" + }, + "countries": { + "type": "literal", + "value": "Q865" + } + } + ] + } +} \ No newline at end of file diff --git a/backend/data/pipeline/tests/people/test_people_elections.py b/backend/data/pipeline/tests/people/test_people_elections.py new file mode 100644 index 0000000..2483e49 --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_elections.py @@ -0,0 +1,246 @@ +"""2026 候選人名單與中選會選舉結果的解析。""" + +from __future__ import annotations + +import json +from collections.abc import Iterator + +import pytest + +from election_data.people.candidates import ( + COUNTY, + MUNICIPAL, + article_html, + parse_elcand, + parse_press_release, + to_claim, +) +from election_data.people.cec_results import ElectionSpec, candidate_totals, load_at_large, load_election + +pytestmark = pytest.mark.unit + +PRESS_BODY = ( + "

中央選舉委員會今(16)日舉行委員會議…

" + "

一、直轄市長候選人部分:受理登記計3人,均符合規定:

" + "

(一)臺北市3人:郭璽、沈伯洋、蔣萬安。

" + "

二、縣(市)長候選人部分:受理登記計4人,均符合規定:

" + "

(一)新竹縣2人:鄭朝方、徐欣瑩。

" + "

(二)嘉義市2人:黃宏成台灣阿成世界偉人財神總統、張啓楷。

" + "

三、直轄市議員候選人部分:受理登記計610人…

" + "

(一)臺北市不符合規定者計1人:某某…

" +) + + +def _api(body: str) -> dict: + content = json.dumps({"content": [{"blockType": "Text", "content": body}]}, ensure_ascii=False) + return {"code": 0, "data": {"content": content, "beginTime": "20261016"}} + + +def test_parse_press_release() -> None: + body, date = article_html(_api(PRESS_BODY)) + entries = parse_press_release(body, "cec") + assert date == "2026-10-16" + assert [(e.county, e.name, e.office) for e in entries][:2] == [ + ("臺北市", "郭璽", MUNICIPAL), + ("臺北市", "沈伯洋", MUNICIPAL), + ] + assert sum(e.office == COUNTY for e in entries) == 4 + assert "某某" not in {e.name for e in entries} # 議員段落不算 + + +def test_parse_press_release_count_mismatch_raises() -> None: + with pytest.raises(ValueError, match="應有 3 人"): + parse_press_release(PRESS_BODY.replace("郭璽、", ""), "cec") + + +def test_parse_press_release_total_mismatch_raises() -> None: + with pytest.raises(ValueError, match="候選人應有"): + parse_press_release(PRESS_BODY.replace("受理登記計4人", "受理登記計5人"), "cec") + + +def test_parse_elcand_and_claim() -> None: + elbase = [["63", "000", "00", "000", "0000", "臺北市"]] + elpaty = [["1", "中國國民黨"], ["999", "無黨籍及未經政黨推薦"]] + elcand = [ + [ + "63", + "000", + "00", + "000", + "0000", + "1", + "甲某", + "999", + "2", + "0650515", + "61", + "臺北市", + "博士", + "N", + "", + "", + ], + [ + "63", + "000", + "00", + "000", + "0000", + "2", + "乙某", + "1", + "1", + "0671226", + "47", + "臺北市", + "博士", + "Y", + "", + "", + ], + [ + "63", + "000", + "00", + "000", + "0000", + "2", + "副手某", + "1", + "1", + "0600101", + "66", + "臺北市", + "碩士", + "N", + "", + "Y", + ], + ] + entries = parse_elcand(elcand, elbase, elpaty, MUNICIPAL, "elcand") + assert [e.name for e in entries] == ["甲某", "乙某"] + first, second = entries + assert (first.party, first.party_known, first.gender, first.birth_date) == (None, True, "F", "1976-05-15") + assert (second.number, second.party) == (2, "中國國民黨") + claim = to_claim(second, "2026-11-12") + assert claim.positions[0].title == "臺北市長候選人(號次 2)" + assert claim.party and claim.party.value == "中國國民黨" + assert claim.birth_date and claim.birth_date.value == "1978-12-26" + + +def test_parse_elcand_unknown_county_raises() -> None: + row = ["99", "999", "00", "000", "0000", "1", "某", "1", "1", "0650515", "61", "", "", "N", "", ""] + with pytest.raises(ValueError): + parse_elcand([row], [], [], COUNTY, "x") + + +def _ctks( + prv: str, city: str, area: str, town: str, vil: str, station: str, no: str, votes: int +) -> list[str]: + return [prv, city, area, town, vil, station, no, str(votes), "0", ""] + + +def test_candidate_totals_district_level_and_verification() -> None: + rows = [ + _ctks("63", "000", "01", "000", "0000", "0000", "1", 30), + _ctks("63", "000", "01", "010", "0000", "0000", "1", 30), # 鄉鎮層級,不採用 + _ctks("63", "000", "01", "010", "0001", "0001", "1", 10), + _ctks("63", "000", "01", "010", "0002", "0002", "1", 20), + ] + assert candidate_totals(rows, national=False) == {("63", "000", "01", "1"): 30} + bad = [*rows[:-1], _ctks("63", "000", "01", "010", "0002", "0002", "1", 21)] + with pytest.raises(ValueError, match="不一致"): + candidate_totals(bad, national=False) + + +def test_candidate_totals_national() -> None: + rows = [ + _ctks("00", "000", "00", "000", "0000", "0000", "1", 15), + _ctks("63", "000", "00", "000", "0000", "0000", "1", 15), + _ctks("63", "000", "01", "010", "0001", "0001", "1", 5), + _ctks("64", "000", "01", "010", "0001", "0002", "1", 10), + ] + assert candidate_totals(rows, national=True) == {("00", "000", "00", "1"): 15} + + +class FakeArchive: + def __init__(self, tables: dict[str, list[list[str]]]) -> None: + self.tables = tables + + def rows(self, folder: str, kind: str) -> Iterator[list[str]]: + yield from self.tables[kind] + + +def test_load_election_shares_and_district_labels() -> None: + archive = FakeArchive( + { + "elpaty": [["1", "中國國民黨"], ["16", "民主進步黨"]], + "elbase": [["10", "002", "00", "000", "0000", "宜蘭縣"]], + "elcand": [ + [ + "10", + "002", + "01", + "000", + "0000", + "1", + "甲", + "1", + "1", + "0600101", + "", + "", + "大學", + "N", + "", + "", + ], + [ + "10", + "002", + "01", + "000", + "0000", + "2", + "乙", + "16", + "2", + "0700101", + "", + "", + "碩士", + "Y", + "*", + "", + ], + ], + "elctks": [ + _ctks("10", "002", "01", "000", "0000", "0000", "1", 40), + _ctks("10", "002", "01", "000", "0000", "0000", "2", 60), + _ctks("10", "002", "01", "010", "0001", "0001", "1", 40), + _ctks("10", "002", "01", "010", "0001", "0001", "2", 60), + ], + } + ) + spec = ElectionSpec("x", "2024 立法委員選舉(區域)", "legislator_district", None) + a, b = load_election(archive, spec) # type: ignore[arg-type] + assert (a.district, a.county, a.votes, a.share, a.elected) == ("宜蘭縣選舉區", "宜蘭縣", 40, 0.4, False) + assert (b.party, b.gender, b.birth_date, b.elected) == ("民主進步黨", "F", "1981-01-01", True) + + +def test_load_at_large_from_elrepm() -> None: + archive = FakeArchive( + { + "elpaty": [["1", "中國國民黨"]], + "elrepm": [["1", "1", "韓國瑜", "1", "0460617", "66", "新北市", "碩士", "N", "*"]], + } + ) + (r,) = load_at_large(archive) # type: ignore[arg-type] + assert (r.name, r.party, r.gender, r.birth_date, r.votes, r.elected) == ( + "韓國瑜", + "中國國民黨", + "M", + "1957-06-17", + None, + True, + ) diff --git a/backend/data/pipeline/tests/people/test_people_matching.py b/backend/data/pipeline/tests/people/test_people_matching.py new file mode 100644 index 0000000..0fdecdf --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_matching.py @@ -0,0 +1,141 @@ +"""合併、選舉紀錄比對、更正的規則。""" + +from __future__ import annotations + +from dataclasses import replace + +import pytest + +from election_data.people.cec_results import CecResult +from election_data.people.enrich import CEC_SOURCE_ID, attach_name_only, attach_strong, index_results +from election_data.people.manual import Override +from election_data.people.merge import apply_overrides, merge_claims +from election_data.people.model import PersonClaim, PersonDraft, PositionRec, Sourced + +pytestmark = pytest.mark.unit + + +def claim(name: str, role: str, county: str | None = None, **kw: object) -> PersonClaim: + category = "official" if role == "official" else "politician" + pos = PositionRec(role, "org", None, None, (role,)) + return PersonClaim( + name=name, role=role, category=category, name_source=role, county=county, positions=(pos,), **kw + ) # type: ignore[arg-type] + + +def result( + name: str, election: str, district: str, county: str | None, birth: str | None = None +) -> CecResult: + kind = "president" if district == "全國" else "mayor" + return CecResult(election, kind, district, county, name, "某黨", "M", birth, "碩士", 100, 0.5, True) + + +def test_candidate_merges_with_legislator_in_same_county() -> None: + persons, notes = merge_claims( + [ + claim("張嘉郡", "legislator", "雲林縣", district="雲林縣第1選舉區"), + claim("張嘉郡", "candidate_2026", "雲林縣"), + ] + ) + assert len(persons) == 1 + assert persons[0].roles == {"legislator", "candidate_2026"} + assert any(n.kind == "merged" for n in notes) + + +def test_same_name_in_different_counties_is_not_merged() -> None: + persons, notes = merge_claims( + [claim("王某", "mayor", "臺北市"), claim("王某", "candidate_2026", "高雄市")] + ) + assert len(persons) == 2 + assert [n.kind for n in notes] == ["not_merged"] + + +def test_two_current_legislators_with_same_name_stay_separate() -> None: + persons, _ = merge_claims([claim("林某", "legislator"), claim("林某", "legislator")]) + assert len(persons) == 2 + + +def test_departed_legislator_attaches_only_to_existing_person() -> None: + departed = replace(claim("洪某", "legislator"), current=False, gender=Sourced("M", ("ly",))) + persons, notes = merge_claims( + [claim("洪某", "official"), departed, replace(claim("黃某", "legislator"), current=False)] + ) + assert len(persons) == 1 + assert persons[0].gender and persons[0].gender.value == "M" + assert persons[0].roles == {"official"} + assert {n.kind for n in notes} == {"departed_attached", "departed_dropped"} + + +def test_party_conflict_is_reported_and_priority_kept() -> None: + persons, notes = merge_claims( + [ + claim("甲", "mayor", "臺北市", party=Sourced("A黨", ("moi",))), + claim("甲", "party_chair", party=Sourced("B黨", ("yaml",))), + ] + ) + assert persons[0].party == Sourced("A黨", ("moi",)) + assert any(n.kind == "conflict" for n in notes) + + +def test_apply_overrides() -> None: + persons, _ = merge_claims([claim("鍾某", "mayor", "苗栗縣", party=Sourced(None, ("moi",)))]) + out, notes = apply_overrides(persons, [Override("鍾某", "party", "中國國民黨", "恢復黨籍", ("news",))]) + assert out[0].party == Sourced("中國國民黨", ("news",)) + missing, notes2 = apply_overrides(persons, [Override("不存在", "party", None, "", ("x",))]) + assert missing == persons and notes2[0].kind == "override_missing" + + +def draft(name: str, counties: set[str] | None = None, birth: Sourced | None = None) -> PersonDraft: + return PersonDraft( + name=name, + category="politician", + roles=frozenset({"mayor"}), + name_sources=("x",), + counties=frozenset(counties or set()), + birth_date=birth, + ) + + +def test_strong_match_by_county_adds_record_and_official_birth() -> None: + index = index_results([result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")]) + persons, notes, done = attach_strong([draft("蔣某", {"臺北市"})], index) + p = persons[0] + assert p.elections[0].election == "2022 直轄市長選舉" and p.elections[0].source_ids == (CEC_SOURCE_ID,) + assert p.birth_date == Sourced("1978-12-26", (CEC_SOURCE_ID,)) + assert done[0] == {"2022 直轄市長選舉"} and notes[0].kind == "strong" + + +def test_strong_match_ambiguous_when_two_same_name_in_county() -> None: + rs = [ + result("許某", "2024 立法委員選舉(區域)", "臺北市第1選舉區", "臺北市"), + result("許某", "2024 立法委員選舉(區域)", "臺北市第5選舉區", "臺北市"), + ] + persons, notes, _ = attach_strong([draft("許某", {"臺北市"})], index_results(rs)) + assert persons[0].elections == () and notes[0].kind == "ambiguous" + + +def test_strong_match_rejected_on_birth_conflict() -> None: + rs = [result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")] + person = draft("蔣某", {"臺北市"}, Sourced("1980-01-01", ("cec-other",))) + persons, notes, _ = attach_strong([person], index_results(rs)) + assert persons[0].elections == () and notes[0].kind == "conflict" + + +def test_name_only_requires_matching_birth() -> None: + rs = [result("賴某", "2024 總統副總統選舉", "全國", None, "1959-10-06")] + index = index_results(rs) + same, notes = attach_name_only([draft("賴某", birth=Sourced("1959-10-06", ("wikidata",)))], index, {}) + assert same[0].elections and notes[0].kind == "name_only" + assert same[0].birth_date == Sourced("1959-10-06", (CEC_SOURCE_ID,)) # 官方資料取代 Wikidata + + other, notes = attach_name_only([draft("賴某", birth=Sourced("1960-01-01", ("wikidata",)))], index, {}) + assert other[0].elections == () and notes[0].kind == "different_birth" + + unknown, notes = attach_name_only([draft("賴某")], index, {}) + assert unknown[0].elections == () and notes[0].kind == "unverified" + + +def test_name_only_skips_elections_already_matched() -> None: + rs = [result("蔣某", "2022 直轄市長選舉", "臺北市", "臺北市", "1978-12-26")] + persons, notes = attach_name_only([draft("蔣某")], index_results(rs), {0: {"2022 直轄市長選舉"}}) + assert persons[0].elections == () and notes == [] diff --git a/backend/data/pipeline/tests/people/test_people_names_education.py b/backend/data/pipeline/tests/people/test_people_names_education.py new file mode 100644 index 0000000..48e1501 --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_names_education.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import pytest + +from election_data.people.education import UNSPECIFIED, parse_education +from election_data.people.names import han_key, name_key, slug_name, wikidata_label_variants + +pytestmark = pytest.mark.unit + + +def test_name_key_ignores_spacing_dots_and_case() -> None: + assert name_key("伍麗華 Saidhai.Tahovecahe") == name_key("伍麗華Saidhai‧Tahovecahe") + assert name_key("鄭天財 Sra‧Kacaw") == name_key("鄭天財Sra Kacaw") == "鄭天財srakacaw" + + +def test_name_key_folds_known_variants_but_slug_keeps_them() -> None: + assert name_key("張啓楷") == name_key("張啟楷") + assert name_key("李姸慧") == name_key("李妍慧") + assert slug_name("李姸慧") == "李姸慧" + + +def test_name_key_keeps_tai_characters_in_person_names() -> None: + assert "台灣" in name_key("黃宏成台灣阿成世界偉人財神總統") + + +def test_han_key_drops_romanized_indigenous_names() -> None: + assert han_key("伍麗華Saidhai‧Tahovecahe") == "伍麗華" + assert han_key("曾智勇 Ljaucu‧Zingrur") == "曾智勇" + + +def test_wikidata_label_variants_include_han_only_and_folded() -> None: + assert wikidata_label_variants("伍麗華Saidhai‧Tahovecahe") == ("伍麗華Saidhai‧Tahovecahe", "伍麗華") + assert wikidata_label_variants("李姸慧") == ("李姸慧", "李妍慧") + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("國立政治大學外交學系學士", [("學士", "國立政治大學外交學系")]), + ("國立虎尾科技大學碩士學位", [("碩士", "國立虎尾科技大學")]), + ("中興大學法律系畢業", [("學士", "中興大學法律系")]), + ( + "法國巴黎第十大學政治、經濟、社會哲學博士候選人", + [("博士候選人", "法國巴黎第十大學政治、經濟、社會哲學")], + ), + ("屏東師範學院國民教育硏究所碩士(85年-87年)", [("碩士", "屏東師範學院國民教育硏究所")]), + ("國立臺灣大學EMBA碩士班", [("碩士", "國立臺灣大學EMBA")]), + ("國立政治大學新聞學系", [(UNSPECIFIED, "國立政治大學新聞學系")]), + ( + "龜山國小、大有國中、武陵高中", + [("國小", "龜山國小"), ("國中", "大有國中"), ("高中職", "武陵高中")], + ), + ("嘉義大學管理碩士、", [("碩士", "嘉義大學管理")]), + ("臺北縣立頂溪國小畢業", [("國小", "臺北縣立頂溪國小")]), + ("屏東師專(73年-78年)", [("專科", "屏東師專")]), + ("臺灣會計師高考及格", []), + ("國立清華大學\t博士後研究", []), + ], +) +def test_parse_education(text: str, expected: list[tuple[str, str | None]]) -> None: + assert parse_education(text) == expected + + +def test_parse_education_splits_semicolons_and_dedupes() -> None: + text = "東海大學社會工作學系學士;東海大學社會工作學系碩士;東海大學社會工作學系學士" + assert parse_education(text) == [("學士", "東海大學社會工作學系"), ("碩士", "東海大學社會工作學系")] diff --git a/backend/data/pipeline/tests/people/test_people_network.py b/backend/data/pipeline/tests/people/test_people_network.py new file mode 100644 index 0000000..f7df9b3 --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_network.py @@ -0,0 +1,39 @@ +"""連網測試:確認官方來源的格式沒有改變(預設不執行:pytest -m network)。""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from election_data.people.cabinet import parse_members +from election_data.people.candidates import CEC_ARTICLE_API, article_html, parse_press_release +from election_data.people.catalog import EY_AGENCY_HEADS +from election_data.people.downloads import fetch +from election_data.people.legislators import LY_ID9_URL, load_ly_json, parse_legislators +from election_data.people.mayors import MOI_BASE, parse_list + +pytestmark = pytest.mark.network + + +def test_ly_id9_live(tmp_path: Path) -> None: + result = fetch(LY_ID9_URL, tmp_path / "id9.json") + claims = parse_legislators(load_ly_json(result.path), "ly") + assert sum(c.current for c in claims) >= 100 + + +def test_moi_county_mayors_live(tmp_path: Path) -> None: + result = fetch(MOI_BASE + "LocalOfficial.aspx?n=579&TYP=KND0005&PageSize=50", tmp_path / "moi.html") + assert len(parse_list(result.path.read_text(encoding="utf-8"))) == 16 + + +def test_ey_agency_heads_live(tmp_path: Path) -> None: + result = fetch(EY_AGENCY_HEADS.url, tmp_path / "ey.html") + assert len(parse_members(result.path.read_text(encoding="utf-8"))) >= 20 + + +def test_cec_candidates_live(tmp_path: Path) -> None: + result = fetch(CEC_ARTICLE_API, tmp_path / "cec.json") + body, _ = article_html(json.loads(result.path.read_text(encoding="utf-8"))) + assert len(parse_press_release(body, "cec")) == 81 diff --git a/backend/data/pipeline/tests/people/test_people_sources.py b/backend/data/pipeline/tests/people/test_people_sources.py new file mode 100644 index 0000000..a9463b8 --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_sources.py @@ -0,0 +1,132 @@ +"""官方頁面解析:立法院 ID9、內政部地方公職人員、行政院內閣(使用存下來的小型頁面片段)。""" + +from __future__ import annotations + +import pytest + +from election_data.people.cabinet import parse_leader, parse_members, roc_day, split_name_title +from election_data.people.legislators import ( + AT_LARGE, + MOUNTAIN, + committees_in_session, + latest_session, + load_ly_json, + ly_date, + parse_district, + parse_legislators, +) +from election_data.people.mayors import parse_detail, parse_list, to_claim + +from .conftest import FIXTURES, read_fixture + +pytestmark = pytest.mark.unit + + +@pytest.mark.parametrize( + ("area", "label", "county"), + [ + ("雲林縣第1選舉區", "雲林縣第1選舉區", "雲林縣"), + ("台北市第10選舉區", "臺北市第10選舉區", "臺北市"), + ("宜蘭縣選舉區", "宜蘭縣選舉區", "宜蘭縣"), + ("全國不分區及僑居國外國民", AT_LARGE, None), + ("山地原住民選舉區", MOUNTAIN, None), + ], +) +def test_parse_district(area: str, label: str, county: str | None) -> None: + district = parse_district(area) + assert (district.label, district.county) == (label, county) + + +def test_parse_district_rejects_unknown() -> None: + with pytest.raises(ValueError): + parse_district("火星第1選舉區") + + +def test_ly_date() -> None: + assert ly_date("2024/02/01") == "2024-02-01" + assert ly_date("") is None + + +def test_committees_only_from_requested_session() -> None: + text = "第11屆第5會期:財政委員會;第11屆第6會期:內政委員會;第11屆第6會期:程序委員會;" + assert committees_in_session(text, 6) == ["內政委員會", "程序委員會"] + assert latest_session([{"committee": text}]) == 6 + + +def test_parse_legislators_fixture() -> None: + claims = {c.name: c for c in parse_legislators(load_ly_json(FIXTURES / "ly_id9_sample.json"), "ly")} + ding = claims["丁學忠"] + assert ding.current and ding.gender and ding.gender.value == "M" + assert ding.county == "雲林縣" and ding.district == "雲林縣第1選舉區" + assert ding.party and ding.party.value == "中國國民黨" + assert ding.positions[0].start == "2024-02-01" and ding.positions[0].end is None + assert any(p.title.startswith("內政委員會委員") for p in ding.positions) + assert ding.education[0].degree == "碩士" + + wu = claims["吳春城"] + assert not wu.current + assert wu.district == AT_LARGE and wu.county is None + assert wu.positions == wu.positions[:1] # 離職者不收委員會 + assert wu.positions[0].end == "2025-02-27" + + assert claims["伍麗華Saidhai‧Tahovecahe"].district == MOUNTAIN + assert claims["陳俊宇"].district == "宜蘭縣選舉區" + + +def test_moi_list_and_detail_fixture() -> None: + entries = parse_list(read_fixture("moi_list_sample.html")) + assert [e.name for e in entries] == ["高虹安", "陳福海", "王忠銘"] + kao, chen = entries[0], entries[1] + assert (kao.county, kao.org, kao.title, kao.party) == ("新竹市", "新竹市政府", "市長", "台灣民眾黨") + assert chen.party is None # 「無」= 無黨籍 + assert kao.detail_url.startswith("https://www.moi.gov.tw/LocalOfficial_Content.aspx?") + + detail = parse_detail(read_fixture("moi_detail_sample.html")) + assert detail.party == "台灣民眾黨" and detail.term == "111年度縣市長選舉" + assert detail.education[0] == "美國辛辛那提大學機械工程博士" + + claim = to_claim(kao, detail, "moi") + assert claim.positions[0].title == "市長" and claim.positions[0].source_ids == ("moi",) + assert [e.degree for e in claim.education] == ["博士", "碩士", "學士", "高中職"] + chen_claim = to_claim(chen, None, "moi") + assert chen_claim.party and chen_claim.party.value is None and chen_claim.party.source_ids == ("moi",) + + +@pytest.mark.parametrize( + ("text", "name", "title"), + [ + ("劉世芳部長", "劉世芳", "部長"), + ("葉俊顯主任委員", "葉俊顯", "主任委員"), + ("陳志民代理主任委員", "陳志民", "代理主任委員"), + ("李姸慧代理委員長", "李姸慧", "代理委員長"), + ("曾智勇 Ljaucu‧Zingrur 主任委員", "曾智勇 Ljaucu‧Zingrur", "主任委員"), + ("陳淑姿主計長", "陳淑姿", "主計長"), + ("張惇涵秘書長", "張惇涵", "秘書長"), + ], +) +def test_split_name_title(text: str, name: str, title: str) -> None: + assert split_name_title(text) == (name, title) + + +def test_split_name_title_rejects_unknown_title() -> None: + with pytest.raises(ValueError): + split_name_title("某某顧問") + + +def test_parse_members_fixture() -> None: + members = parse_members(read_fixture("ey_agency_heads_sample.html")) + pairs = {(m.org, m.name, m.title) for m in members} + assert ("內政部", "劉世芳", "部長") in pairs + assert ("公平交易委員會", "陳志民", "代理主任委員") in pairs + assert ("中央銀行", "楊金龍", "總裁") in pairs + + +def test_parse_leader_fixture_skips_title_tag() -> None: + leader = parse_leader(read_fixture("ey_premier_sample.html")) + assert (leader.name, leader.title, leader.start) == ("卓榮泰", "院長", "2024-05-20") + assert leader.education == ("中興大學法律系畢業",) + + +def test_roc_day() -> None: + assert roc_day("民國113年5月20日-") == "2024-05-20" + assert roc_day("民國78年-87年") is None diff --git a/backend/data/pipeline/tests/people/test_people_wikidata_output.py b/backend/data/pipeline/tests/people/test_people_wikidata_output.py new file mode 100644 index 0000000..fb793a7 --- /dev/null +++ b/backend/data/pipeline/tests/people/test_people_wikidata_output.py @@ -0,0 +1,198 @@ +"""Wikidata 比對、id 與輸出格式、手動 YAML。""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from election_data.config import CONFIG_DIR, PROTOCOL_VERSION +from election_data.people.manual import ManualDataError, load_manual, parse_party_chairs +from election_data.people.model import PersonDraft, PositionRec, Sourced +from election_data.people.output import assign_ids, people_file, referenced_source_ids +from election_data.people.wd_match import match_one, match_wikidata +from election_data.people.wikidata import WdItem, build_query, parse_bindings +from election_data.validate import validate + +from .conftest import FIXTURES + +pytestmark = pytest.mark.unit + + +def items() -> list[WdItem]: + return parse_bindings(json.loads((FIXTURES / "wikidata_sample.json").read_text(encoding="utf-8"))) + + +def person(name: str, roles: set[str], **kw: object) -> PersonDraft: + category = "official" if roles <= {"official"} else "politician" + return PersonDraft(name=name, category=category, roles=frozenset(roles), name_sources=("x",), **kw) # type: ignore[arg-type] + + +def test_parse_bindings_merges_rows_per_qid_and_keeps_precision() -> None: + by_qid = {it.qid: it for it in items()} + assert {"Q124293468", "Q21055059", "Q697458"} <= by_qid.keys() # 多位吳宗憲 + assert by_qid["Q116894056"].births == (("1973-01-01", 9),) # 王興煥只有年份 + assert by_qid["Q116894056"].day_births() == frozenset() + assert "Q865" in by_qid["Q121904956"].countries + + +def test_match_uses_official_birth_to_pick_among_namesakes() -> None: + wu = person( + "吳宗憲", + {"legislator"}, + districts=frozenset({"全國不分區及僑居國外國民"}), + party=Sourced("中國國民黨", ("ly",)), + birth_date=Sourced("1971-09-27", ("cec-votedata",)), + ) + note = match_one(wu, [it for it in items() if "吳宗憲" in it.label_keys]) + assert (note.kind, note.qid) == ("matched", "Q124293468") + + +def test_match_ambiguous_without_birth() -> None: + wu = person("吳宗憲", {"legislator"}, party=Sourced("中國國民黨", ("ly",))) + note = match_one(wu, [it for it in items() if "吳宗憲" in it.label_keys]) + assert note.kind == "ambiguous" and note.qid is None + + +def test_birth_conflict_excludes_item() -> None: + p = person( + "丁學忠", + {"legislator"}, + party=Sourced("中國國民黨", ("ly",)), + birth_date=Sourced("1999-01-01", ("cec",)), + ) + note = match_one(p, [it for it in items() if "丁學忠" in it.label_keys]) + assert note.kind == "unmatched" and "出生日期不符" in note.detail + + +def test_medium_rule_for_officials() -> None: + item = WdItem( + "Q1", frozenset({"某官員"}), (("1960-01-01", 11),), ("衛生福利部部長",), (), frozenset({"Q865"}) + ) + official = person( + "某官員", {"official"}, positions=(PositionRec("政務委員", "行政院", None, None, ("ey",)),) + ) + assert match_one(official, [item]).kind == "matched_medium" + candidate = person("某官員", {"candidate_2026"}, counties=frozenset({"臺北市"})) + assert match_one(candidate, [item]).kind == "unmatched" + + +def test_duplicate_qid_is_dropped_and_wikidata_birth_filled() -> None: + item = WdItem("Q9", frozenset({"同名"}), (("1970-05-05", 11),), ("立法委員",), (), frozenset({"Q865"})) + a = person("同名", {"legislator"}, districts=frozenset({"臺北市第1選舉區"})) + out, notes = match_wikidata([a], [item]) + assert out[0].wikidata_id == Sourced("Q9", ("wikidata",)) + assert out[0].birth_date == Sourced("1970-05-05", ("wikidata",)) + _, notes = match_wikidata([a, a], [item]) + assert [n.kind for n in notes] == ["duplicate_qid", "duplicate_qid"] + + +def test_build_query_includes_label_variants_and_escapes() -> None: + q = build_query(["伍麗華Saidhai‧Tahovecahe", 'a"b']) + assert '"伍麗華"@zh-tw' in q and '"a\\"b"@zh' in q + + +def _draft(name: str, birth: str | None = None, qid: str | None = None) -> PersonDraft: + return PersonDraft( + name=name, + category="politician", + roles=frozenset({"candidate_2026"}), + name_sources=("cec",), + birth_date=Sourced(birth, ("cec",)) if birth else None, + wikidata_id=Sourced(qid, ("wikidata",)) if qid else None, + party=Sourced(None, ("moi",)), + positions=(PositionRec("臺北市長候選人", "115年直轄市長選舉", "2026-10-16", None, ("cec",)),), + ) + + +def test_assign_ids_qid_slug_and_deterministic_suffix() -> None: + a, b, c = _draft("王 某", "1970-01-01"), _draft("王某", "1970-02-02"), _draft("李某", qid="Q42") + ids = assign_ids([a, b, c]) + assert ids[2] == "Q42" + assert sorted(ids[:2]) == ["tw-politician-王某-1970", "tw-politician-王某-1970-2"] + assert assign_ids([b, a, c]) == [ids[1], ids[0], ids[2]] + assert assign_ids([_draft("李某")]) == ["tw-politician-李某-x"] + + +def test_people_file_validates_against_protocol_schema() -> None: + persons = [_draft("王某", "1970-01-01"), _draft("李某", qid="Q42")] + doc = people_file(persons, assign_ids(persons), PROTOCOL_VERSION, "2026-10-25") + validate(doc, "people.schema.json") + first = doc["people"][0] + assert first["stats"] == dict.fromkeys(first["stats"]) and first["scoring"] == [] + assert first["fieldSources"]["party"] == ["moi"] # 已查證為無黨籍 + assert referenced_source_ids(doc) == {"cec", "moi", "wikidata"} + + +def test_load_manual_config_files() -> None: + data = load_manual(CONFIG_DIR / "people") + chairs = [c for c in data.claims if c.role == "party_chair"] + assert {c.party.value for c in chairs if c.party} >= { + "民主進步黨", + "中國國民黨", + "台灣民眾黨", + "時代力量", + "台灣基進", + } + assert all(c.positions and c.positions[0].source_ids for c in data.claims) + assert {o.field for o in data.overrides} == {"party"} + assert all(s.retrieved_at and s.url.startswith("https://") for s in data.sources) + assert len({s.id for s in data.sources}) == len(data.sources) + + +@pytest.mark.parametrize( + "entry", + [ + {"name": "某", "party": "某黨", "sources": []}, + { + "name": "某", + "party": "某黨", + "sources": [ + { + "id": "x", + "title": "t", + "agency": "a", + "url": "http://x", + "license": "l", + "retrievedAt": "2026-10-25", + } + ], + }, + { + "name": "某", + "party": "某黨", + "sources": [ + { + "id": "x", + "title": "t", + "agency": "a", + "url": "https://x", + "license": "l", + "retrievedAt": "2026/10/25", + } + ], + }, + { + "party": "某黨", + "sources": [ + { + "id": "x", + "title": "t", + "agency": "a", + "url": "https://x", + "license": "l", + "retrievedAt": "2026-10-25", + } + ], + }, + ], +) +def test_party_chair_yaml_validation(entry: dict) -> None: + with pytest.raises(ManualDataError): + parse_party_chairs({"chairs": [entry]}) + + +def test_missing_config_dir_is_empty(tmp_path: Path) -> None: + data = load_manual(tmp_path) + assert data.claims == () and data.overrides == () and data.sources == () diff --git a/backend/data/pipeline/tests/records/__init__.py b/backend/data/pipeline/tests/records/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/data/pipeline/tests/records/helpers.py b/backend/data/pipeline/tests/records/helpers.py new file mode 100644 index 0000000..aa30db7 --- /dev/null +++ b/backend/data/pipeline/tests/records/helpers.py @@ -0,0 +1,63 @@ +"""測試用的合成資料:中選會各檔的列與參選紀錄。""" + +from __future__ import annotations + +from dataclasses import replace + +from election_data.records.parse import Run + +BASE = Run( + folder="2022/T1", + year=2022, + date="2022-11-26", + election="直轄市議員", + office="councilor", + indigenous=None, + county="臺北市", + county_code="63000", + district="第1選區", + area=("63", "000"), + district_code="01", + number=1, + name="王小明", + party="甲黨", + gender="M", + birth_year=1970, + votes=10_000, + share=0.1, + elected=True, + incumbent=False, +) + + +def run(**changes: object) -> Run: + return replace(BASE, **changes) # type: ignore[arg-type] + + +def cand( + prv: str, city: str, district: str, number: str, name: str, party: str, birth: str, elected: str = "" +) -> list[str]: + """elcand 的一列(16 欄)""" + return [ + prv, + city, + district, + "000", + "0000", + number, + name, + party, + "1", + birth, + "50", + "", + "", + "N", + elected, + "", + ] + + +def total(prv: str, city: str, district: str, number: str, votes: int, station: str = "0000") -> list[str]: + """elctks 的選區總計列""" + return [prv, city, district, "000", "0000", station, number, str(votes), "", ""] diff --git a/backend/data/pipeline/tests/records/test_build_integration.py b/backend/data/pipeline/tests/records/test_build_integration.py new file mode 100644 index 0000000..ba2279d --- /dev/null +++ b/backend/data/pipeline/tests/records/test_build_integration.py @@ -0,0 +1,45 @@ +"""用本機的 votedata.zip 實際產出一次(檔案不在就略過;不會下載)。""" + +from pathlib import Path + +import pytest + +from election_data.cec import VOTEDATA_PATH +from election_data.records.build import FINANCE_DIR, PACKS_DIR, build_records + +pytestmark = pytest.mark.integration + + +@pytest.mark.skipif(not VOTEDATA_PATH.is_file(), reason="沒有 data/raw/cec/votedata.zip") +def test_build_records(tmp_path: Path) -> None: + import json + + outputs = build_records( + people_dir=tmp_path / "people", + council_dir=tmp_path / "council", + finance_dir=FINANCE_DIR, + packs_dir=PACKS_DIR, + council_years=(2022,), + ) + assert {p.name for p in outputs} == {"records.json", "2022.json", "records-report.md"} + records = json.loads((tmp_path / "people" / "records.json").read_text(encoding="utf-8")) + years = {r["year"] for p in records["people"] for r in p["runs"]} + assert {1994, 1997, 1998, 2001, 2002, 2005, 2006, 2009, 2010, 2014, 2018, 2022} <= years + # 總統副總統 1996–2024、立委 1995–2024 + assert {1995, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024} <= years + assert all(len(p["scores"]) == 5 for p in records["people"]) + elections = records["elections"] + # 每次總統選舉當選一組(總統+副總統) + assert [e["elected"] for e in elections if e["office"] == "president"] == [2] * 8 + # 2008 年起:區域立委 73 席、不分區 34 席 + regional = {e["year"]: e["elected"] for e in elections if e["folder"].endswith(("/區域", "/區域立委"))} + assert all(regional[y] == 73 for y in (2008, 2012, 2016, 2020, 2024)) + plist = [e["elected"] for e in elections if e["election"] == "不分區立法委員"] + assert plist == [34] * 5 + vice = [r for p in records["people"] for r in p["runs"] if r["election"] == "副總統"] + assert len(vice) == 25 and all(r["runningMate"] and r["votes"] for r in vice) + council = json.loads((tmp_path / "council" / "2022.json").read_text(encoding="utf-8")) + # 2022 年直轄市議員 + 縣市議員共 910 席(含原住民選區) + assert sum(d["seats"] for d in council["districts"]) == 910 + assert all(d["threshold"] for d in council["districts"]) + assert all(c["personId"] for d in council["districts"] for c in d["candidates"]) diff --git a/backend/data/pipeline/tests/records/test_council.py b/backend/data/pipeline/tests/records/test_council.py new file mode 100644 index 0000000..c411d63 --- /dev/null +++ b/backend/data/pipeline/tests/records/test_council.py @@ -0,0 +1,48 @@ +"""議員選區檔:涵蓋的村里、跨村里投開票所、資料包比對。""" + +import json +from pathlib import Path + +import pytest + +from election_data.records.council import coverage, electors_and_valid, pack_village_names, pack_villages + +pytestmark = pytest.mark.unit + + +def test_coverage_uses_village_subtotals_and_cross_codes() -> None: + elctks = [ + ["63", "000", "01", "000", "0000", "0000", "1", "300", "", ""], # 選區總計 + ["63", "000", "01", "010", "0000", "0000", "1", "300", "", ""], # 鄉鎮小計 + ["63", "000", "01", "010", "0001", "0000", "1", "100", "", ""], # 村里小計 + ["63", "000", "01", "010", "0001", "0001", "1", "100", "", ""], # 投開票所 + ["63", "000", "01", "010", "A001", "0000", "1", "200", "", ""], # 跨村里 + ["63", "000", "02", "020", "0003", "0", "1", "50", "", ""], # 2018 年以前投開票所寫 0 + ] + cross = {("63", "000", "010", "A001"): ["63000010002", "63000010003"]} + cov = coverage(elctks, cross) + assert cov[("63", "000", "01")].villages == ("63000010001", "63000010002", "63000010003") + assert cov[("63", "000", "01")].towns == ("63000010",) + assert cov[("63", "000", "02")].villages == ("63000020003",) + + +def test_electors_and_valid_reads_district_totals() -> None: + elprof = [ + ["63", "000", "00", "000", "0000", "0000", "999", "1", "1000", "2000", "3000"], + ["63", "000", "01", "000", "0000", "0000", "275279", "5986", "281265", "413790", "499756"], + ["63", "000", "01", "010", "0001", "0000", "1", "1", "1", "1", "1"], + ] + assert electors_and_valid(elprof) == {("63", "000", "01"): (413790, 275279)} + + +def test_pack_villages_prefers_plain_pack(tmp_path: Path) -> None: + def write(folder: str, codes: list[str]) -> None: + (tmp_path / folder).mkdir() + villages = [{"code": c, "name": f"{c[-1]}里", "townCode": c[:8]} for c in codes] + (tmp_path / folder / "villages.json").write_text(json.dumps({"villages": villages}), encoding="utf-8") + + write("10020-before-2018-11-24", ["10020010001"]) + write("10020-before-2022-11-26", ["10020010002"]) + assert pack_villages(tmp_path, "10020") == {"10020010002"} + assert pack_village_names(tmp_path, ["10020"]) == {("10020010", "2里"): "10020010002"} + assert pack_villages(tmp_path, "99999") is None diff --git a/backend/data/pipeline/tests/records/test_link.py b/backend/data/pipeline/tests/records/test_link.py new file mode 100644 index 0000000..7bd717a --- /dev/null +++ b/backend/data/pipeline/tests/records/test_link.py @@ -0,0 +1,100 @@ +"""跨屆串人:同名+出生年、族名寫法不同、同名同年不同人、沒有出生年。""" + +import pytest + +from election_data.records.link import link_runs, match_key + +from .helpers import run + +pytestmark = pytest.mark.unit + + +def test_same_name_and_birth_year_is_one_person() -> None: + people, report = link_runs( + [ + run(year=2018, date="2018-11-24", folder="2018"), + run(year=2022, date="2022-11-26", folder="2022"), + run(name="王小明", birth_year=1980), # 同名不同年:另一個人 + ] + ) + assert sorted(len(p.runs) for p in people) == [1, 2] + two = next(p for p in people if len(p.runs) == 2) + assert [r.year for r in two.runs] == [2018, 2022] + assert two.confidence == "high" + assert report.splits == () + + +def test_indigenous_names_match_on_han_part() -> None: + assert match_key("伊凡諾幹 Iban Nokan") == match_key("伊凡諾幹") + assert match_key("柔夏.布待Rosya.Butay") == match_key("柔夏‧布待") + people, _ = link_runs([run(name="伊凡諾幹", date="2010-11-27"), run(name="伊凡諾幹 Iban Nokan")]) + assert len(people) == 1 + assert people[0].name == "伊凡諾幹 Iban Nokan" # 用最近一次的寫法 + + +def test_same_day_runs_are_different_people() -> None: + people, report = link_runs( + [ + run(county="臺北市", county_code="63000"), + run(county="新北市", county_code="65000"), + run(county="新北市", county_code="65000", date="2018-11-24", year=2018), + ] + ) + assert sorted(len(p.runs) for p in people) == [1, 2] + assert report.splits == (("王小明", 1970, 2),) + assert len({p.id for p in people}) == 2 + + +def test_no_birth_year_merges_by_name_and_county() -> None: + people, report = link_runs( + [ + run(county="嘉義市", county_code="10020", date="2018-11-24", year=2018), + run(county="嘉義市", county_code="10020", date="2022-12-18", birth_year=None), + run(name="陳某", county="嘉義市", county_code="10020", birth_year=None), + ] + ) + merged = next(p for p in people if p.name == "王小明") + assert len(merged.runs) == 2 and merged.confidence == "low" and merged.birth_year == 1970 + alone = next(p for p in people if p.name == "陳某") + assert alone.confidence == "low" and alone.birth_year is None + assert report.low_merged == (("王小明", "嘉義市"),) + assert report.low_alone == (("陳某", "嘉義市", 0),) + + +def test_ids_are_stable() -> None: + a, _ = link_runs([run()]) + b, _ = link_runs([run()]) + assert a[0].id == b[0].id and a[0].id.startswith("r-") + + +def test_birth_year_off_by_one_merges_only_same_party_with_central_run() -> None: + people, report = link_runs( + [ + # 同黨、其中一筆是立委:串在一起(比對信心低,寫原因) + run(name="張大同", birth_year=1937, party="民主進步黨", date="1994-12-03", year=1994), + run(name="張大同", birth_year=1938, party="民主進步黨", office="legislator", date="1995-12-02", year=1995), + # 政黨不同:不串 + run(name="李小華", birth_year=1952, party="中國國民黨", date="1998-01-24", year=1998), + run(name="李小華", birth_year=1951, party="喜樂島聯盟", office="legislator", date="2020-01-11", year=2020), + # 都是地方選舉:不動 + run(name="陳某某", birth_year=1960, party="中國國民黨", date="2014-11-29", year=2014), + run(name="陳某某", birth_year=1961, party="中國國民黨", date="2018-11-24", year=2018), + ] + ) + zhang = [p for p in people if p.name == "張大同"] + assert len(zhang) == 1 and len(zhang[0].runs) == 2 + assert zhang[0].confidence == "low" and zhang[0].note and "1937、1938" in zhang[0].note + assert len([p for p in people if p.name == "李小華"]) == 2 + assert len([p for p in people if p.name == "陳某某"]) == 2 + assert report.near_merged == (("張大同", 1937, 1938, "同名、同黨、出生年只差 1 年"),) + + +def test_manual_same_person_list_merges_across_parties() -> None: + people, report = link_runs( + [ + run(name="趙少康", birth_year=1949, party="新黨", date="1994-12-03", year=1994), + run(name="趙少康", birth_year=1950, party="中國國民黨", office="president", date="2024-01-13", year=2024), + ] + ) + assert len(people) == 1 and len(people[0].runs) == 2 + assert report.near_merged[0][0] == "趙少康" diff --git a/backend/data/pipeline/tests/records/test_parse.py b/backend/data/pipeline/tests/records/test_parse.py new file mode 100644 index 0000000..5b65b77 --- /dev/null +++ b/backend/data/pipeline/tests/records/test_parse.py @@ -0,0 +1,219 @@ +"""中選會資料夾的讀法:選區名稱、出生年、得票對照、當選註記。""" + +import pytest + +from election_data.records.folders import FOLDERS, RaceFolder +from election_data.records.parse import ( + birth_year, + chinese_number, + district_label, + parse_party_list, + parse_rows, +) + +from .helpers import cand, total + +pytestmark = pytest.mark.unit + +COUNCIL = RaceFolder("2022/T1", 2022, "2022-11-26", "直轄市議員", "councilor") +MAYOR = RaceFolder("1994直轄市長", 1994, "1994-12-03", "直轄市長", "mayor") + + +@pytest.mark.parametrize( + ("text", "expected"), + [("12", 12), ("01", 1), ("十二", 12), ("二十一", 21), ("十", 10), ("三", 3), ("甲", None), ("", None)], +) +def test_chinese_number(text: str, expected: int | None) -> None: + assert chinese_number(text) == expected + + +def test_district_label() -> None: + assert district_label("臺北縣第十二選區", "12") == "第12選區" + assert district_label("第01選舉區", "01") == "第1選區" + # 沒有選區列:00 是整個縣市一個選區,其他代碼用數字 + assert district_label(None, "00") is None + assert district_label(None, "02") == "第2選區" + + +def test_birth_year() -> None: + assert birth_year("042") == 1953 # 2010 年以前:民國出生年 + assert birth_year("0620404") == 1973 # 之後:民國出生日期 + assert birth_year("000") is None + assert birth_year("") is None + + +def test_parse_council_district() -> None: + elbase = [ + ["00", "000", "00", "000", "0000", "全國"], + ["63", "000", "00", "000", "0000", "臺北市"], + ["63", "000", "01", "000", "0000", "第01選舉區"], + ] + elpaty = [["1", "甲黨"], ["999", "無黨籍及未經政黨推薦"]] + elcand = [ + cand("63", "000", "01", "1", "王小明", "1", "0590101", "*"), + cand("63", "000", "01", "2", "李小華", "999", "0700101", "!"), # 婦女保障名額當選 + cand("63", "000", "01", "3", "張大同", "1", "0650101", "-"), # 名額讓給婦女保障而落選 + ] + elctks = [ + total("63", "000", "01", "1", 500), + total("63", "000", "01", "2", 200), + total("63", "000", "01", "3", 300), + ["63", "000", "01", "010", "0001", "0000", "1", "100", "", ""], # 村里小計,不是總計 + ] + runs = parse_rows(COUNCIL, elbase, elpaty, elcand, elctks) + by_name = {r.name: r for r in runs} + assert [r.name for r in runs] == ["王小明", "李小華", "張大同"] + ming = by_name["王小明"] + assert (ming.county, ming.county_code, ming.district, ming.birth_year) == ( + "臺北市", + "63000", + "第1選區", + 1970, + ) + assert (ming.votes, ming.share, ming.elected, ming.party) == (500, 0.5, True, "甲黨") + assert by_name["李小華"].elected and by_name["李小華"].party is None + assert not by_name["張大同"].elected + + +def test_parse_mismatched_district_codes_and_old_county() -> None: + """1994 北高市長:elcand 選區 00、elctks 選區 01,改用 (省市, 縣市, 號次) 對""" + elbase = [["00", "000", "00", "000", "0000", "全國"], ["02", "000", "00", "000", "0000", "高雄市"]] + elcand = [ + cand("02", "000", "00", "1", "甲", "99", "039"), + cand("02", "000", "00", "2", "乙", "1", "040", "*"), + ] + elctks = [total("02", "000", "01", "1", 30, "0"), total("02", "000", "01", "2", 70, "0")] + runs = parse_rows(MAYOR, elbase, [["1", "甲黨"], ["99", "無"]], elcand, elctks) + assert [(r.votes, r.share, r.district, r.county_code) for r in runs] == [ + (30, 0.3, None, "64000"), + (70, 0.7, None, "64000"), + ] + assert runs[0].party is None # 「無」是無黨籍 + + +def test_running_mates_are_skipped() -> None: + row = cand("63", "000", "00", "1", "副手", "1", "0590101") + row[15] = "Y" + assert parse_rows(MAYOR, [], [], [row], []) == [] + + +def test_folders_are_unique_and_dated() -> None: + assert len({f.folder for f in FOLDERS}) == len(FOLDERS) + assert all(f.date.startswith(str(f.year)) for f in FOLDERS) + + +# ── 中央選舉:總統副總統、立委 ── + +PRESIDENT = RaceFolder("2024總統立委/總統", 2024, "2024-01-13", "總統", "president") +LEGISLATOR = RaceFolder("2024總統立委/區域立委", 2024, "2024-01-13", "立法委員", "legislator") +LIST = RaceFolder("2024總統立委/不分區政黨", 2024, "2024-01-13", "不分區立法委員", "legislator") +NATION = [["00", "000", "00", "000", "0000", "全國"]] + + +def test_birth_year_with_zero_month_day() -> None: + """2000、2004 總統的出生日期只有年(月日為 0)""" + assert birth_year("0310000") == 1942 + assert birth_year("0000000") is None + + +def test_parse_president_ticket_includes_vice_president() -> None: + top = cand("00", "000", "01", "1", "甲", "1", "0450101", "*") + vice = cand("00", "000", "01", "1", "乙", "1", "0500101") # 副手列:2008 年起當選註記是空的 + vice[15] = "Y" + other = cand("00", "000", "01", "2", "丙", "2", "0400101") + # 全國總計列的選區是 00、候選人檔是 01:用 (省市, 縣市, 號次) 對 + elctks = [total("00", "000", "00", "1", 600), total("00", "000", "00", "2", 400)] + runs = parse_rows(PRESIDENT, NATION, [["1", "甲黨"], ["2", "乙黨"]], [top, vice, other], elctks) + by_name = {r.name: r for r in runs} + assert [r.name for r in runs] == ["甲", "乙", "丙"] + a, b = by_name["甲"], by_name["乙"] + assert (a.election, a.county, a.county_code, a.district, a.running_mate) == ( + "總統", + "全國", + None, + None, + "乙", + ) + assert (b.election, b.votes, b.share, b.elected, b.running_mate) == ("副總統", 600, 0.6, True, "甲") + assert (b.birth_year, b.party, b.number) == (1961, "甲黨", 1) + assert not by_name["丙"].elected and by_name["丙"].running_mate is None + + +def test_running_mates_only_for_president() -> None: + row = cand("00", "000", "01", "1", "副手", "1", "0590101") + row[15] = "Y" + assert parse_rows(LEGISLATOR, NATION, [], [row], []) == [] + + +def test_parse_legislators_single_district_county_has_no_district() -> None: + elbase = [ + ["63", "000", "00", "000", "0000", "臺北市"], + ["10", "017", "00", "000", "0000", "基隆市"], + ] + elcand = [ + cand("63", "000", "01", "1", "甲", "1", "0500101", "*"), + cand("63", "000", "02", "1", "乙", "1", "0500101", "*"), + cand("10", "017", "01", "1", "丙", "1", "0500101", "*"), + ] + elctks = [ + total("63", "000", "01", "1", 10), + total("63", "000", "02", "1", 10), + total("10", "017", "01", "1", 10), + ] + runs = parse_rows(LEGISLATOR, elbase, [["1", "甲黨"]], elcand, elctks) + assert [(r.county, r.county_code, r.district) for r in runs] == [ + ("臺北市", "63000", "第1選區"), + ("臺北市", "63000", "第2選區"), + ("基隆市", "10017", None), # 全縣一區 + ] + + +def test_parse_indigenous_legislators_are_nationwide() -> None: + rf = RaceFolder("2024總統立委/山地立委", 2024, "2024-01-13", "立法委員", "legislator", "山地原住民") + elcand = [cand("00", "000", "01", "1", "甲", "1", "0500101", "*")] + runs = parse_rows(rf, NATION, [["1", "甲黨"]], elcand, [total("00", "000", "00", "1", 30)]) + assert [(r.county, r.county_code, r.district, r.votes, r.indigenous) for r in runs] == [ + ("全國", None, None, 30, "山地原住民") + ] + + +def test_province_wide_race_keeps_province_name() -> None: + """1994 臺灣省長:省市代碼也是 00,但縣市名稱是臺灣省(不是「全國」)""" + rf = RaceFolder("1994台灣省長", 1994, "1994-12-03", "臺灣省長", "mayor") + elbase = [["00", "000", "00", "000", "0000", "臺灣省"]] + runs = parse_rows(rf, elbase, [["1", "甲黨"]], [cand("00", "000", "00", "1", "甲", "1", "030", "*")], []) + assert runs[0].county == "臺灣省" + + +def test_parse_party_list_members() -> None: + elpaty = [["1", "甲黨"], ["16", "乙黨"]] + elcand = [cand("00", "000", "01", "1", "乙黨", "16", "0"), cand("00", "000", "01", "2", "甲黨", "1", "0")] + elctks = [ + total("00", "000", "00", "1", 300), + total("00", "000", "00", "2", 700), + total("63", "000", "00", "1", 99), # 縣市列不算 + ] + elrepm = [ + ["1", "1", "王小明", "1", "0460617", "66", "", "", "N", "*"], + ["1", "2", "李小華", "2", "0510429", "61", "", "", "Y", "!"], + ["16", "1", "張大同", "1", "0600101", "50", "", "", "N", ""], + ] + runs = parse_party_list(LIST, elpaty, elcand, elctks, elrepm) + assert [(r.name, r.party, r.number, r.list_rank, r.elected) for r in runs] == [ + ("王小明", "甲黨", 2, 1, True), + ("李小華", "甲黨", 2, 2, True), + ("張大同", "乙黨", 1, 1, False), + ] + first = runs[0] + assert (first.votes, first.share, first.party_votes, first.party_share) == (None, None, 700, 0.7) + assert (first.county, first.county_code, first.birth_year, first.incumbent) == ("全國", None, 1957, False) + + +def test_national_folders() -> None: + presidents = {f.year for f in FOLDERS if f.office == "president"} + assert presidents == {1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024} + lists = {f.year for f in FOLDERS if f.is_party_list} + assert lists == {2008, 2012, 2016, 2020, 2024} + legislators = {f.year for f in FOLDERS if f.office == "legislator" and not f.is_party_list} + assert legislators == {1995, 1998, 2001, 2004, 2008, 2012, 2016, 2020, 2024} + assert all(f.suffix for f in FOLDERS if f.folder.startswith("2016總統立委")) diff --git a/backend/data/pipeline/tests/records/test_scores.py b/backend/data/pipeline/tests/records/test_scores.py new file mode 100644 index 0000000..debcdf8 --- /dev/null +++ b/backend/data/pipeline/tests/records/test_scores.py @@ -0,0 +1,174 @@ +"""資歷分數:固定公式、夾在 0–10、依據文字。""" + +import json +from pathlib import Path + +import pytest + +from election_data.records.link import link_runs +from election_data.records.scores import ( + SCORE_DEFS, + fame, + finance, + load_finance, + organization, + peer_averages, + score_person, + seniority, + strength, +) + +from .helpers import run + +pytestmark = pytest.mark.unit + + +def test_every_score_has_formula_and_source() -> None: + assert [d.key for d in SCORE_DEFS] == ["fame", "organization", "seniority", "strength", "finance"] + assert all(d.formula and d.source for d in SCORE_DEFS) + + +def test_fame_is_log_scaled() -> None: + assert fame([run(votes=1_000)]).value == 0.0 + assert fame([run(votes=5_000_000)]).value == 10.0 + assert fame([run(votes=900)]).value == 0.0 + mid = fame([run(votes=10_000), run(votes=100_000)]) + assert mid.value == pytest.approx(5.4, abs=0.05) + assert "100,000 票" in mid.basis + assert fame([run(votes=None)]).value is None + + +def test_organization_counts_wins_and_reelections() -> None: + runs = [run(elected=True), run(elected=True), run(elected=False), run(elected=True)] + score = organization(runs) + assert score.value == 1.5 * 3 + 1 + assert "當選 3 次,其中連任 1 次" in score.basis + assert organization([run(elected=True)] * 6).value == 10.0 + + +def test_seniority_from_first_win_to_last_run() -> None: + runs = [run(year=1998, elected=False), run(year=2002, elected=True), run(year=2022, elected=False)] + assert seniority(runs).value == 8.0 + assert seniority([run(elected=False)]).value == 0.0 + assert seniority([run(year=1994), run(year=2022)]).value == 10.0 + + +def test_strength_compares_with_same_party_peers() -> None: + a = run(share=0.2) + b = run(share=0.1, name="乙") + c = run(share=0.3, party="乙黨", name="丙") + peers = peer_averages([a, b, c]) + assert strength([a], peers).value == pytest.approx(5 * 0.2 / 0.15, abs=0.05) + assert strength([c], peers).value == 5.0 # 同黨只有自己:等於平均 + assert strength([run(share=None)], peers).value is None + + +def test_finance_matches_mayor_runs(tmp_path: Path) -> None: + (tmp_path / "111年直轄市市長選舉-臺北市.json").write_text( + json.dumps( + { + "election": "111年直轄市市長選舉", + "area": "臺北市", + "candidates": [{"name": "王小明", "income": 10_000_000}], + } + ), + encoding="utf-8", + ) + (tmp_path / "壞掉.json").write_text("{", encoding="utf-8") + records = load_finance(tmp_path) + mayor = run(office="mayor", election="直轄市長", district=None) + score = finance([mayor], records) + assert score.value == pytest.approx(10 * 2 / (8.30103 - 5), abs=0.05) + assert "10,000,000 元" in score.basis + assert finance([run()], records).value is None # 議員沒有申報資料 + assert load_finance(tmp_path / "沒有這個資料夾") == {} + + +def test_score_person_returns_all_keys() -> None: + people, _ = link_runs([run()]) + scores = score_person(people[0], peer_averages(people[0].runs), {}) + assert [s.key for s in scores] == [d.key for d in SCORE_DEFS] + assert all(s.value is None or 0 <= s.value <= 10 for s in scores) + + +# ── 總統副總統、立委 ── + + +def _national(**changes: object): + base = { + "folder": "2024總統立委/總統", + "year": 2024, + "date": "2024-01-13", + "election": "總統", + "office": "president", + "county": "全國", + "county_code": None, + "district": None, + } + return run(**{**base, **changes}) + + +def test_fame_caps_nationwide_votes_and_names_the_ticket() -> None: + vice = _national(election="副總統", votes=8_000_000, running_mate="甲") + score = fame([run(votes=50_000), vice]) + assert score.value == 10.0 # 500 萬票以上一律 10,不會超過 + assert "8,000,000 票" in score.basis and "副總統" in score.basis and "和甲同一組的票" in score.basis + # 不分區沒有個人得票:不算進知名度 + listed = _national(election="不分區立法委員", office="legislator", votes=None, share=None, list_rank=1) + assert fame([listed]).value is None + assert "不分區" in fame([listed]).basis + assert fame([listed, run(votes=10_000)]).value == pytest.approx(2.7, abs=0.05) + + +def test_strength_skips_president_runs() -> None: + top = _national(share=0.4) + local = run(share=0.2) + peers = peer_averages([top, local, run(share=0.1, name="乙")]) + assert strength([top], peers).value is None + assert "總統副總統" in strength([top], peers).basis + assert strength([top, local], peers).value == pytest.approx(5 * 0.2 / 0.15, abs=0.05) + + +def test_wins_as_vice_president_or_party_list_count() -> None: + runs = [ + run(year=2016, elected=True), + _national(election="不分區立法委員", office="legislator", year=2020, votes=None, share=None), + _national(election="副總統", year=2024), + ] + assert organization(runs).value == 1.5 * 3 + 1 * 2 + assert seniority(runs).value == pytest.approx(8 / 2.5, abs=0.05) + + +def test_finance_for_president_and_legislators(tmp_path: Path) -> None: + (tmp_path / "113年總統、副總統選舉-.json").write_text( + json.dumps( + { + "election": "113年總統、副總統選舉", + "area": "", + "candidates": [{"name": "王小明、李小華", "income": 300_000_000}], + } + ), + encoding="utf-8", + ) + (tmp_path / "113年立法委員選舉-臺北市.json").write_text( + json.dumps( + { + "election": "113年立法委員選舉", + "area": "臺北市", + "candidates": [{"name": "張大同", "income": 1_000_000}], + } + ), + encoding="utf-8", + ) + records = load_finance(tmp_path) + top = _national(name="王小明") + score = finance([top], records) + assert score.value == 10.0 and "王小明、李小華" in score.basis + # 副總統不算(申報是正副一組,算在總統候選人) + assert finance([_national(name="李小華", election="副總統")], records).value is None + legislator = run( + year=2024, date="2024-01-13", election="立法委員", office="legislator", name="張大同", county="臺北市" + ) + assert finance([legislator], records).value == pytest.approx(10 * 1 / (8.30103 - 5), abs=0.05) + # 同名的議員不會對到立委的申報 + assert finance([run(year=2024, name="張大同")], records).value is None diff --git a/backend/data/pipeline/tests/scoring/test_scoring.py b/backend/data/pipeline/tests/scoring/test_scoring.py new file mode 100644 index 0000000..99ca3fd --- /dev/null +++ b/backend/data/pipeline/tests/scoring/test_scoring.py @@ -0,0 +1,206 @@ +from datetime import date +from pathlib import Path + +import pytest + +from election_data.scoring.derive import awareness, network +from election_data.scoring.evidence import record_evidence, render_packet, web_evidence +from election_data.scoring.llm import LlmResult, RefusedError +from election_data.scoring.pipeline import ( + ScoringStats, + _aggregate, + bias_report, + score_person, + validate_scores, + write_outputs, +) +from election_data.scoring.rubric import AI_STATS, render_rubric + +pytestmark = pytest.mark.unit + +NULL_STATS = dict.fromkeys( + ["awareness", "network", "affinity", "eloquence", "strategy", "online", "image", "wealth", "stamina"] +) + + +def person(pid: str = "tw-politician-甲-1970", party: str = "某黨", title: str = "立法委員") -> dict: + return { + "id": pid, + "kind": "real", + "category": "politician", + "name": "甲", + "gender": "F", + "birthDate": "1970-01-01", + "party": party, + "wikidataId": None, + "positions": [ + {"title": title, "org": "立法院", "from": "2020-02-01", "to": None, "sourceIds": ["ly-id9"]} + ], + "education": [{"degree": "碩士", "school": "某大學", "sourceIds": ["ly-id9"]}], + "electionHistory": [ + { + "election": "2024 區域立委", + "district": "某選區", + "party": party, + "votes": 120_000, + "share": 0.52, + "elected": True, + "sourceIds": ["cec-votedata"], + } + ], + "stats": dict(NULL_STATS), + "scoring": [], + "fieldSources": {"name": ["ly-id9"], "party": ["ly-id9"]}, + "asOf": "2026-10-25", + } + + +def scores(value: int | None, cite: str = "R1", insufficient: bool = False) -> dict: + return { + "scores": [ + { + "stat": s.key, + "insufficient": insufficient, + "value": value, + "confidence": "medium", + "rationale": "測試", + "citations": [cite], + } + for s in AI_STATS + ] + } + + +class FakeBackend: + def __init__(self, values: list[int], research_items: list[dict] | None = None, cite: str = "W1") -> None: + self.values = list(values) + self.research_items = research_items or [ + { + "claim": "曾於全國辯論中表現受肯定", + "url": "https://example.org/a", + "published": "2024-01", + "stats": [], + } + ] + self.cite = cite + self.research_calls = 0 + + def research(self, person_summary: str, max_searches: int) -> LlmResult: + self.research_calls += 1 + return LlmResult({"items": self.research_items}, "fake-model", 100, 50) + + def score(self, packet: str) -> LlmResult: + assert "[R1]" in packet + return LlmResult(scores(self.values.pop(0), self.cite), "fake-model", 10, 5) + + +class TestDerive: + def test_vice_president_is_not_president(self) -> None: + vp = person(title="副總統") + p = person(title="總統") + assert awareness(vp)[0] == 95 + assert awareness(p)[0] == 100 + + def test_votes_raise_awareness(self) -> None: + low = person(title="助理") + low["electionHistory"][0]["votes"] = 5_000_000 + assert awareness(low)[0] == 70 + + def test_network_grows_with_tenure(self) -> None: + score, sources = network(person(), date(2026, 2, 1)) + assert score == 30 + 18 # 6 年 × 3 + assert sources == ["ly-id9"] + + +class TestEvidence: + def test_record_ids_and_sources(self) -> None: + items = record_evidence(person()) + assert [i.id for i in items] == ["R1", "R2", "R3", "R4"] + assert items[-1].sources == ("cec-votedata",) + + def test_packet_order_depends_on_seed(self) -> None: + items = record_evidence(person()) + web_evidence( + [{"claim": "x", "url": "https://e/1", "published": ""}] + ) + assert render_packet(person(), items, 1) != render_packet(person(), items, 2) + + +class TestAggregate: + def test_median_of_cited_runs(self) -> None: + runs = [scores(60), scores(70), scores(64)] + value, method, cited, _, inconsistent = _aggregate("eloquence", runs, {"R1"}) + assert (value, method, cited, inconsistent) == (64, "ai", ["R1"], False) + + def test_uncited_scores_are_discarded(self) -> None: + runs = [scores(90, cite="X9"), scores(90, cite="X9"), scores(60)] + value, method, *_ = _aggregate("eloquence", runs, {"R1"}) + assert (value, method) == (50, "default") + + def test_insufficient_falls_back_to_default(self) -> None: + runs = [scores(None, insufficient=True)] * 3 + assert _aggregate("image", runs, {"R1"})[:2] == (50, "default") + + def test_spread_flags_inconsistency(self) -> None: + runs = [scores(40), scores(55), scores(70)] + assert _aggregate("image", runs, {"R1"})[4] is True + + def test_out_of_range_rejected(self) -> None: + runs = [scores(150), scores(140), scores(60)] + assert _aggregate("image", runs, {"R1"})[1] == "default" + + +def test_rubric_mentions_every_stat() -> None: + text = render_rubric() + assert all(s.name in text for s in AI_STATS) + + +def test_validate_scores_rejects_bad_shape() -> None: + with pytest.raises(ValueError): + validate_scores({"scores": [{"stat": "eloquence"}]}) + + +def test_score_person_end_to_end(tmp_path: Path) -> None: + backend = FakeBackend([60, 62, 75]) + stats = ScoringStats() + out = score_person(person(), backend, stats, tmp_path, date(2026, 10, 25), use_web=True) + by_stat = {r["stat"]: r for r in out["scoring"]} + assert out["stats"]["eloquence"] == 62 + assert by_stat["eloquence"]["citations"] == ["https://example.org/a"] # 引用展開成實際出處 + assert by_stat["eloquence"]["confidence"] == "medium" # 60–75 差 15 分 → 不一致 + assert by_stat["awareness"]["method"] == "derived" + assert by_stat["stamina"]["method"] == "default" + assert (tmp_path / f"{person()['id']}.json").exists() # 研究結果有快取 + score_person(person(), FakeBackend([60, 60, 60]), stats, tmp_path, date(2026, 10, 25), use_web=True) + assert stats.people == 2 + + +def test_refusal_is_recorded_not_raised(tmp_path: Path) -> None: + class Refusing(FakeBackend): + def score(self, packet: str) -> LlmResult: + raise RefusedError("cyber") + + stats = ScoringStats() + out = score_person(person(), Refusing([]), stats, tmp_path, date(2026, 10, 25), use_web=False) + assert all(r["method"] != "ai" for r in out["scoring"]) + assert len(stats.refusals) == 3 + + +def test_bias_report_flags_party_gap() -> None: + people = [] + for i in range(6): + for party, value in (("甲黨", 70), ("乙黨", 50)): + p = person(pid=f"{party}-{i}", party=party) + p["scoring"] = [{"stat": s.key, "value": value, "method": "ai"} for s in AI_STATS] + people.append(p) + lines = bias_report(people) + assert lines and all("需要複核" in line for line in lines) + + +def test_write_outputs_validates_against_protocol(tmp_path: Path) -> None: + backend = FakeBackend([60, 61, 62]) + stats = ScoringStats() + scored = [score_person(person(), backend, stats, tmp_path, date(2026, 10, 25), use_web=True)] + out = write_outputs(tmp_path, {"protocolVersion": "1.0.0", "asOf": "2026-10-25"}, scored, stats) + assert out.exists() + assert (tmp_path / "review_sample.csv").exists() + assert "AI 評分報告" in (tmp_path / "scoring_report.md").read_text(encoding="utf-8") diff --git a/backend/data/pipeline/tests/test_cells_and_lean.py b/backend/data/pipeline/tests/test_cells_and_lean.py new file mode 100644 index 0000000..4b6344d --- /dev/null +++ b/backend/data/pipeline/tests/test_cells_and_lean.py @@ -0,0 +1,118 @@ +import numpy as np +import pytest + +from election_data.cells import AgeLeanModel, fit_age_lean, ipf, village_cells +from election_data.elections import PARTY_A, PARTY_B, PARTY_C +from election_data.lean import LEAN_KEYS, LeanParams, Observation, base_turnout, lean_shares + +pytestmark = pytest.mark.unit + +AGES = ("20-29", "30-39", "40-49", "50-64", "65+") + + +def obs(a: int, b: int, c: int, other: int = 0, weight: float = 1.0, contested=None) -> Observation: + valid = a + b + c + other + return Observation( + weight=weight, + valid=valid, + ballots=valid, + electors=int(valid / 0.7), + votes={PARTY_A: a, PARTY_B: b, PARTY_C: c, "其他": other}, + contested=frozenset(contested or {PARTY_A, PARTY_B, PARTY_C}), + ) + + +class TestLean: + def test_shares_sum_to_one(self) -> None: + shares = lean_shares([obs(400, 350, 200, 50), obs(450, 400, 100, 50)]) + assert shares is not None + assert set(shares) == set(LEAN_KEYS) + assert sum(shares.values()) == pytest.approx(1.0) + + def test_core_never_exceeds_mean(self) -> None: + shares = lean_shares([obs(500, 300, 200)]) + assert shares is not None + assert shares["a_core"] <= 0.5 + 1e-9 + assert shares["a_core"] + shares["a_lean"] < 0.5 + + def test_volatility_lowers_core(self) -> None: + steady = lean_shares([obs(500, 400, 100), obs(500, 400, 100)]) + swingy = lean_shares([obs(700, 200, 100), obs(300, 600, 100)]) + assert steady is not None and swingy is not None + assert swingy["a_core"] < steady["a_core"] + + def test_uncontested_party_is_ignored(self) -> None: + # 第三勢力只在第二次選舉參選:平均只看那一次(0.2),而不是兩次平均(0.1)。 + # 甲、乙平均各 0.45,三者合計 1.1 > 1,所以等比例縮放成 0.2 / 1.1。 + shares = lean_shares( + [obs(500, 500, 0, contested={PARTY_A, PARTY_B}), obs(400, 400, 200)], + LeanParams(third_to_middle=0.0), + ) + assert shares is not None + assert shares["c_lean"] == pytest.approx(0.2 / 1.1, abs=1e-6) + + def test_no_valid_votes(self) -> None: + assert lean_shares([Observation(1.0, 0, 0, 0, {}, frozenset())]) is None + + def test_base_turnout_weighted(self) -> None: + o1 = Observation(3.0, 70, 70, 100, {}, frozenset()) + o2 = Observation(1.0, 50, 50, 100, {}, frozenset()) + assert base_turnout([o1, o2]) == pytest.approx(0.65) + + +class TestIpf: + def test_matches_marginals(self) -> None: + seed = np.ones((2, 3)) + rows = np.array([30.0, 70.0]) + cols = np.array([20.0, 50.0, 30.0]) + fitted = ipf(seed, rows, cols) + assert fitted.sum(axis=1) == pytest.approx(rows) + assert fitted.sum(axis=0) == pytest.approx(cols) + + def test_rejects_inconsistent_targets(self) -> None: + with pytest.raises(ValueError): + ipf(np.ones((2, 2)), np.array([1.0, 1.0]), np.array([1.0, 2.0])) + + +class TestEcologicalRegression: + def test_recovers_known_association(self) -> None: + rng = np.random.default_rng(7) + leans = LEAN_KEYS + truth = rng.dirichlet(np.ones(len(leans)) * 3, size=len(AGES)) + ages, lean_rows = [], [] + for _ in range(400): + counts = rng.integers(50, 500, size=len(AGES)).astype(float) + share = counts / counts.sum() + lean = share @ truth + ages.append(dict(zip(AGES, counts, strict=True))) + lean_rows.append(dict(zip(leans, lean, strict=True))) + model = fit_age_lean(ages, lean_rows, AGES, leans) + assert np.abs(model.matrix - truth).max() < 0.02 + assert model.matrix.sum(axis=1) == pytest.approx(np.ones(len(AGES))) + + def test_ridge_shrinks_toward_overall_mean(self) -> None: + rng = np.random.default_rng(3) + leans = LEAN_KEYS + ages, lean_rows = [], [] + for _ in range(200): + counts = rng.integers(50, 500, size=len(AGES)).astype(float) + lean = rng.dirichlet(np.ones(len(leans)) * 5) + ages.append(dict(zip(AGES, counts, strict=True))) + lean_rows.append(dict(zip(leans, lean, strict=True))) + loose = fit_age_lean(ages, lean_rows, AGES, leans, ridge=0.0) + tight = fit_age_lean(ages, lean_rows, AGES, leans, ridge=1e6) + spread = lambda m: (m.matrix.max(axis=0) - m.matrix.min(axis=0)).max() # noqa: E731 + assert spread(tight) < 0.01 + assert spread(tight) < spread(loose) + + def test_village_cells_respect_marginals(self) -> None: + model = AgeLeanModel(AGES, LEAN_KEYS, np.full((5, 6), 1 / 6)) + ages = dict(zip(AGES, [100, 200, 150, 250, 300], strict=True)) + lean = dict(zip(LEAN_KEYS, [0.2, 0.1, 0.25, 0.1, 0.25, 0.1], strict=True)) + cells = np.array(village_cells(model, ages, lean)).reshape(5, 6) + assert cells.sum(axis=1) == pytest.approx(list(ages.values()), abs=0.05) + assert cells.sum(axis=0) == pytest.approx([x * 1000 for x in lean.values()], abs=0.05) + + def test_empty_village(self) -> None: + model = AgeLeanModel(AGES, LEAN_KEYS, np.full((5, 6), 1 / 6)) + assert village_cells(model, dict.fromkeys(AGES, 0), dict.fromkeys(LEAN_KEYS, 1 / 6)) == [0.0] * 30 diff --git a/backend/data/pipeline/tests/test_codes.py b/backend/data/pipeline/tests/test_codes.py new file mode 100644 index 0000000..b0df664 --- /dev/null +++ b/backend/data/pipeline/tests/test_codes.py @@ -0,0 +1,42 @@ +import pytest + +from election_data.codes import cec_village_code, county_code, normalize_name, roc_to_iso_date, town_code + +pytestmark = pytest.mark.unit + + +def test_cec_village_code_matches_villcode() -> None: + # 文件中的例子:63/000/010/0002 → 63000010002 + assert cec_village_code("63", "000", "010", "0002") == "63000010002" + + +def test_cec_village_code_rejects_cross_village_and_aggregates() -> None: + assert cec_village_code("68", "000", "010", "A001") is None + assert cec_village_code("68", "000", "010", "0000") is None + assert cec_village_code("68", "000", "000", "0000") is None + + +def test_cec_village_code_rejects_four_digit_village() -> None: + with pytest.raises(ValueError): + cec_village_code("68", "000", "010", "1001") + + +def test_county_and_town_codes() -> None: + assert county_code("68", "000") == "68000" + assert town_code("68", "000", "010") == "68000010" + + +@pytest.mark.parametrize( + ("raw", "expected"), + [("台北市", "臺北市"), (" 桃園區 ", "桃園區"), ("AB里", "AB里")], +) +def test_normalize_name(raw: str, expected: str) -> None: + assert normalize_name(raw) == expected + + +@pytest.mark.parametrize( + ("raw", "expected"), + [("0481006", "1959-10-06"), ("481006", "1959-10-06"), ("113/01/13", "2024-01-13"), ("abc", None)], +) +def test_roc_to_iso_date(raw: str, expected: str | None) -> None: + assert roc_to_iso_date(raw) == expected diff --git a/backend/data/pipeline/tests/test_donations.py b/backend/data/pipeline/tests/test_donations.py new file mode 100644 index 0000000..0577e3b --- /dev/null +++ b/backend/data/pipeline/tests/test_donations.py @@ -0,0 +1,28 @@ +from election_data.donations import download_url, parse_summary + +HEADER = ( + "序號,擬參選人,選舉名稱,申報序號,個人捐贈收入,營利事業捐贈收入,政黨捐贈收入,人民團體捐贈收入," + "匿名捐贈收入,其他收入,收入小計,人事費用支出,宣傳支出,租用宣傳車輛支出,租用競選辦事處支出,集會支出," + "交通旅運支出,雜支支出,返還捐贈支出,繳庫支出,公共關係費用支出,支出小計\n" +) + + +def test_parse_summary_reads_totals_and_breakdown() -> None: + row = ( + "1,王小明,111年測試市長選舉,首次申報,100.00,200.00,0.00,0.00,1.00,0.00,301.00," + "10,250,0,20,5,0,0,0,0,0,285.00\n" + ) + [c] = parse_summary(HEADER + row) + assert c.name == "王小明" + assert c.income == 301 + assert c.spending == 285 + assert c.incomeBreakdown["business"] == 200 + assert c.spendingBreakdown["advertising"] == 250 + assert c.spendingBreakdown["offices"] == 20 + + +def test_download_url_encodes_chinese_names() -> None: + url = download_url("111年直轄市市長選舉", "桃園市") + assert url.startswith("https://ardata.cy.gov.tw/api/v1/Search/download?") + assert "ElectionArea=%E6%A1%83%E5%9C%92%E5%B8%82" in url + assert "DownloadType=3" in url diff --git a/backend/data/pipeline/tests/test_elections.py b/backend/data/pipeline/tests/test_elections.py new file mode 100644 index 0000000..698aa2a --- /dev/null +++ b/backend/data/pipeline/tests/test_elections.py @@ -0,0 +1,34 @@ +import pytest + +from election_data.elections import INDEPENDENT, OTHER, PARTY_A, apportion, party_group + +pytestmark = pytest.mark.unit + + +class TestApportion: + def test_total_is_preserved(self) -> None: + parts = apportion(101, [1.0, 1.0, 1.0]) + assert sum(parts) == 101 + assert sorted(parts) == [33, 34, 34] + + def test_follows_weights(self) -> None: + assert apportion(100, [3.0, 1.0]) == [75, 25] + + def test_zero_weights_split_evenly(self) -> None: + assert apportion(10, [0.0, 0.0]) == [5, 5] + + def test_empty(self) -> None: + assert apportion(10, []) == [] + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + (PARTY_A, PARTY_A), + ("無黨籍及未經政黨推薦", INDEPENDENT), + ("無黨團結聯盟", OTHER), # 這是政黨名稱,不是無黨籍 + ("小民參政歐巴桑聯盟", OTHER), + ], +) +def test_party_group(raw: str, expected: str) -> None: + assert party_group(raw) == expected diff --git a/backend/data/pipeline/tests/test_elections_archive.py b/backend/data/pipeline/tests/test_elections_archive.py new file mode 100644 index 0000000..976569c --- /dev/null +++ b/backend/data/pipeline/tests/test_elections_archive.py @@ -0,0 +1,113 @@ +"""用合成的 votedata.zip 測試中選會資料的讀取、跨村里分配與總數核對。""" + +import zipfile +from pathlib import Path + +import pytest + +from election_data.cec import CecArchive +from election_data.elections import PARTY_A, PARTY_B, ElectionDef, load_election + +pytestmark = pytest.mark.unit + +ROOT = "votedata/votedata/voteData/" + + +def csv(rows: list[list[str]]) -> str: + return "\n".join(",".join(f'"{c}"' for c in row) for row in rows) + "\n" + + +def write_folder( + zf: zipfile.ZipFile, folder: str, county: tuple[str, str], cross: bool, national: str +) -> None: + prv, city = county + elbase = [ + [prv, city, "00", "000", "0000", "某市"], + [prv, city, "00", "010", "0000", "某區"], + [prv, city, "00", "010", "0001", "一里"], + [prv, city, "00", "010", "0002", "二里"], + ] + if cross: + elbase.append([prv, city, "00", "010", "A001", "一里、二里"]) + elpaty = [["16", PARTY_A], ["1", PARTY_B], ["999", "無黨籍及未經政黨推薦"]] + elcand = [ + [prv, city, "00", "000", "0000", "1", "候選人甲", "16", "1", "0600101", "66", "", "", "N", "", ""], + [prv, city, "00", "000", "0000", "2", "候選人乙", "1", "1", "0600101", "66", "", "", "N", "", ""], + ] + elctks = [ + [prv, city, "00", "000", "0000", "0000", "1", "70", "", ""], # 縣市總計列 + [prv, city, "00", "010", "0001", "0000", "1", "30", "", ""], + [prv, city, "00", "010", "0001", "0000", "2", "10", "", ""], + [prv, city, "00", "010", "0002", "0000", "1", "20", "", ""], + [prv, city, "00", "010", "0002", "0001", "1", "20", "", ""], # 投開票所列,不重複計算 + ] + elprof = [ + [ + "00", + "000", + "00", + "000", + "0000", + "0000", + national, + "0", + national, + "1", + ], # 每個資料夾各有一列「全國」 + [prv, city, "00", "000", "0000", "0000", "100" if cross else "60", "0", "100", "150"], + [prv, city, "00", "010", "0001", "0000", "40", "1", "41", "60"], + [prv, city, "00", "010", "0002", "0000", "20", "0", "20", "30"], + ] + if cross: + elctks.append([prv, city, "00", "010", "A001", "0000", "2", "40", "", ""]) + elprof.append([prv, city, "00", "010", "A001", "0000", "40", "0", "40", "60"]) + for kind, rows in { + "elbase": elbase, + "elpaty": elpaty, + "elcand": elcand, + "elctks": elctks, + "elprof": elprof, + }.items(): + zf.writestr(f"{ROOT}{folder}/{kind}.csv", csv(rows)) + + +@pytest.fixture +def archive(tmp_path: Path) -> CecArchive: + path = tmp_path / "votedata.zip" + with zipfile.ZipFile(path, "w") as zf: + write_folder(zf, "X/prv", ("68", "000"), cross=True, national="100") + write_folder(zf, "X/city", ("10", "002"), cross=False, national="60") + return CecArchive(path) + + +ELECTION = ElectionDef("t", "測試", "2024-01-13", "mayor", ("X/prv", "X/city"), 1.0) + + +def test_folders_listed(archive: CecArchive) -> None: + assert archive.folders() == ["X/city", "X/prv"] + + +def test_village_subtotals_and_parties(archive: CecArchive) -> None: + data = load_election(archive, ELECTION, county="10002") + village = data.by_village["10002010001"] + assert dict(village.votes) == {PARTY_A: 30, PARTY_B: 10} + assert (village.electors, village.ballots, village.valid) == (60, 41, 40) + assert data.by_village["10002010002"].votes == {PARTY_A: 20} # 投開票所列沒有被重複加總 + + +def test_cross_village_allocated_by_weight(archive: CecArchive) -> None: + weights = {"68000010001": 3.0, "68000010002": 1.0} + data = load_election(archive, ELECTION, county="68000", weights=weights) + one, two = data.by_village["68000010001"], data.by_village["68000010002"] + assert one.votes[PARTY_B] == 10 + 30 and two.votes.get(PARTY_B) == 10 + assert one.allocated and two.allocated + assert one.electors == 60 + 45 and two.electors == 30 + 15 + assert data.skipped_rows == 0 + + +def test_county_and_national_totals(archive: CecArchive) -> None: + data = load_election(archive, ELECTION) + assert data.cec_valid_by_county["68000"] == 100 + assert data.cec_valid_by_county["10002"] == 60 + assert data.cec_valid_by_county["00000"] == 160 # 兩個資料夾的全國列相加 + assert data.party_totals_by_county["10002"] == {PARTY_A: 50, PARTY_B: 10} diff --git a/backend/data/pipeline/tests/test_fetch.py b/backend/data/pipeline/tests/test_fetch.py new file mode 100644 index 0000000..c2eac26 --- /dev/null +++ b/backend/data/pipeline/tests/test_fetch.py @@ -0,0 +1,51 @@ +import json +import ssl +from pathlib import Path + +import pytest + +from election_data import fetch + +pytestmark = pytest.mark.unit + + +@pytest.fixture(autouse=True) +def no_sleep(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(fetch.time, "sleep", lambda _s: None) + + +def test_download_writes_meta_and_uses_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[bool] = [] + + def fake_stream(url: str, tmp: Path, verify: bool, timeout: float) -> None: + calls.append(verify) + tmp.write_bytes(b'{"ok": true}') + + monkeypatch.setattr(fetch, "_stream_to", fake_stream) + dest = tmp_path / "a" / "x.json" + first = fetch.download("https://example.org/x.json", dest) + assert not first.from_cache and first.tls_verified + meta = json.loads((tmp_path / "a" / "x.json.meta.json").read_text(encoding="utf-8")) + assert meta["sha256"] == first.sha256 and meta["bytes"] == 12 + data, second = fetch.fetch_json("https://example.org/x.json", dest) + assert data == {"ok": True} and second.from_cache + assert calls == [True] + + +def test_tls_fallback_only_for_allowed_hosts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def fake_stream(url: str, tmp: Path, verify: bool, timeout: float) -> None: + if verify: + raise ssl.SSLError("CERTIFICATE_VERIFY_FAILED") + tmp.write_bytes(b"data") + + monkeypatch.setattr(fetch, "_stream_to", fake_stream) + ok = fetch.download("https://ws.dgbas.gov.tw/a.xlsx", tmp_path / "a.xlsx") + assert ok.tls_verified is False + with pytest.raises(RuntimeError): + fetch.download("https://example.org/b.xlsx", tmp_path / "b.xlsx", retries=2) + + +def test_ssl_context_keeps_verification() -> None: + ctx = fetch._ssl_context() + assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.check_hostname + assert not ctx.verify_flags & ssl.VERIFY_X509_STRICT diff --git a/backend/data/pipeline/tests/test_geo_impute.py b/backend/data/pipeline/tests/test_geo_impute.py new file mode 100644 index 0000000..9af0ea5 --- /dev/null +++ b/backend/data/pipeline/tests/test_geo_impute.py @@ -0,0 +1,67 @@ +import io +import zipfile +from pathlib import Path + +import numpy as np +import pytest +import shapefile + +from election_data.geo import _SHP_STEM, area_km2, count_points_in, load_villages +from election_data.impute import NeighborIndex, impute + +pytestmark = pytest.mark.unit + +# 三個 0.01 度見方的格子:A、B 相鄰(同鄉鎮),C 在遠處(另一個鄉鎮) +SQUARES = { + "68000010001": (121.00, 25.00, "68000010", "桃園區", "甲里"), + "68000010002": (121.01, 25.00, "68000010", "桃園區", "乙里"), + "68000020001": (121.20, 25.00, "68000020", "中壢區", "丙里"), +} + + +def make_zip(tmp_path: Path) -> Path: + shp, shx, dbf = io.BytesIO(), io.BytesIO(), io.BytesIO() + writer = shapefile.Writer(shp=shp, shx=shx, dbf=dbf, shapeType=shapefile.POLYGON, encoding="utf-8") + for name in ("VILLCODE", "COUNTYNAME", "TOWNNAME", "VILLNAME", "COUNTYCODE", "TOWNCODE"): + writer.field(name, "C", 40) + for code, (x, y, town_code, town, name) in SQUARES.items(): + writer.poly([[[x, y], [x, y + 0.01], [x + 0.01, y + 0.01], [x + 0.01, y], [x, y]]]) + writer.record(code, "桃園市", town, name, "68000", town_code) + writer.close() + path = tmp_path / "v.zip" + with zipfile.ZipFile(path, "w") as zf: + zf.writestr(f"{_SHP_STEM}.shp", shp.getvalue()) + zf.writestr(f"{_SHP_STEM}.shx", shx.getvalue()) + zf.writestr(f"{_SHP_STEM}.dbf", dbf.getvalue()) + return path + + +def test_load_filter_area_and_points(tmp_path: Path) -> None: + villages = load_villages(make_zip(tmp_path), "68000") + assert [v.code for v in villages] == sorted(SQUARES) + assert villages[0].town_name == "桃園區" + # 0.01 度見方在北緯 25 度約 1.009 × 1.106 平方公里 + assert area_km2(villages[0].geometry) == pytest.approx(1.116, rel=0.01) + counts = count_points_in( + villages, [(121.005, 25.005), (121.015, 25.005), (121.015, 25.006), (130.0, 25.0)] + ) + assert counts == {"68000010001": 1, "68000010002": 2, "68000020001": 0} + assert load_villages(make_zip(tmp_path), "99999") == [] + + +def test_impute_prefers_neighbors_then_town_then_county(tmp_path: Path) -> None: + villages = load_villages(make_zip(tmp_path), None) + index = NeighborIndex(villages) + assert index.neighbors("68000010001") == ["68000010002"] + weights = dict.fromkeys(SQUARES, 1.0) + town = lambda code: [c for c in SQUARES if c[:8] == code[:8]] # noqa: E731 + county = list(SQUARES) + + known = {"68000010002": np.array([0.4]), "68000020001": np.array([0.9])} + found = impute("68000010001", known, weights, index, town, county) + assert found is not None and found.source == "neighbors" and found.value[0] == pytest.approx(0.4) + + found = impute("68000020001", {"68000010001": np.array([0.2])}, weights, index, town, county) + assert found is not None and found.source == "county" + + assert impute("68000010001", {}, weights, index, town, county) is None diff --git a/backend/data/pipeline/tests/test_historic.py b/backend/data/pipeline/tests/test_historic.py new file mode 100644 index 0000000..11082aa --- /dev/null +++ b/backend/data/pipeline/tests/test_historic.py @@ -0,0 +1,192 @@ +"""經典之戰:2014 縣市長與 1996–2016 總統的人口基準、命令列與產出。""" + +import json +from pathlib import Path + +import pytest + +from election_data import cli +from election_data.codes import cec_village_code +from election_data.config import BUILD_DIR +from election_data.local2022 import LOCAL_RACES +from election_data.population import parse_county_population, parse_year_end_population +from election_data.races2024 import NATIONAL_RACES + +SCENARIOS = BUILD_DIR / "scenarios" + + +@pytest.mark.unit +def test_2014_cross_village_code_is_not_a_village() -> None: + # 2014 年的跨村里投開票所寫成 9999,不能當成村里代碼 + assert cec_village_code("66", "000", "060", "9999") is None + + +@pytest.mark.unit +def test_parse_monthly_county_table() -> None: + rows = [ + ["戶數、人口數、性別比例及人口密度統計表(續)", None, None], + [None, "中 華 民 國 103 年 5 月 底", None], + ["區 域 別", "戶 數", "人  口  數"], + ["總 計", 10, 100], + ["臺灣省", 9, 60], + ["臺北市", 3, 40], + ["桃園縣", 2, 35], # 升格前的名稱對到 68000 + ["金門縣", 1, 25], + ["東沙群島", 0, 0], + ] + assert parse_county_population(rows, "10305") == {"00000": 100, "63000": 40, "68000": 35, "09020": 25} + with pytest.raises(ValueError, match="年月"): + parse_county_population(rows, "10306") + + +@pytest.mark.unit +def test_monthly_table_merges_old_counties_and_checks_total() -> None: + rows = [ + [None, "96年9月底", None], + ["區域別", "戶數", "人口數"], + ["總  計", 0, 30], + ["臺中縣 ", 0, 20], + ["臺中市 ", 0, 10], + ] + assert parse_county_population(rows, "09609") == {"00000": 30, "66000": 30} + rows[2][2] = 31 + with pytest.raises(ValueError, match="不符"): + parse_county_population(rows, "09609") + + +@pytest.mark.unit +def test_parse_year_end_table() -> None: + rows = [ + ["表一 各縣市人口數按性別及五歲年齡組分", None, None], + ["中 華 民 國 84 年 底", None, None], + ["區 域 別", "性別", "總 計"], + [None, "計", 50], + ["總  計", "男", 26], + [None, "女", 24], + [None, "計", 30], + ["臺 北 縣", "男", 16], + [None, "女", 14], + [None, "計", 20], + ["高 雄 市", "男", 10], + [None, "女", 10], + ] + assert parse_year_end_population(rows, 84) == {"00000": 50, "65000": 30, "64000": 20} + + +def _mock_pack(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> list[tuple]: + called: list[tuple] = [] + + def fake(county: str, exclude: tuple = (), name: str | None = None, older: bool = False, **extra) -> Path: + called.append((county, set(exclude), name, extra)) + return tmp_path + + monkeypatch.setattr(cli, "build_pack", fake) + return called + + +@pytest.mark.unit +def test_cli_historic_window(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + called = _mock_pack(monkeypatch, tmp_path) + args = ["pack", "--county", "00000", "--historic", "--since", "2012-01-01", "--before", "2016-01-16"] + assert cli.main([*args, "--past-only"]) == 0 + county, exclude, name, extra = called[0] + assert name == "00000-before-2016-01-16" + assert extra == {"historic": True, "since": "2012-01-01", "until": "2016-01-16"} + assert exclude == set() # 之後的選舉根本不讀,不用排除 + assert cli.main(args) == 0 + _, exclude, _, extra = called[1] + assert "until" not in extra + assert {"2016-president", "2024-president"} <= exclude and "2014-mayor" not in exclude + + +@pytest.mark.unit +def test_cli_past_only_needs_before(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + _mock_pack(monkeypatch, tmp_path) + with pytest.raises(SystemExit): + cli.main(["pack", "--county", "00000", "--historic", "--past-only"]) + + +@pytest.mark.unit +def test_race_definitions() -> None: + assert LOCAL_RACES[2014].cap_month == "10305" + # 投票月前第六個月的月底;1996 年那個月沒有月報,載入時改用年底(population.load_county_population) + assert {y: NATIONAL_RACES[y].cap_month for y in (1996, 2000, 2004, 2008, 2012, 2016)} == { + 1996: "08409", + 2000: "08809", + 2004: "09209", + 2008: "09609", + 2012: "10007", + 2016: "10407", + } + assert all(NATIONAL_RACES[y].folder is None for y in (1996, 2000, 2004, 2008, 2012, 2016)) + + +@pytest.mark.skipif( + not (SCENARIOS / "2014-local" / "63000.json").exists(), reason="需要先執行 local --year 2014" +) +def test_2014_local_caps_and_totals() -> None: + # 中選會 2014 年公告的六都競選經費上限 + published = { + "65000": 105_384_000, + "63000": 87_690_000, + "66000": 87_900_000, + "67000": 76_361_000, + "64000": 88_884_000, + "68000": 78_670_000, + } + files = sorted((SCENARIOS / "2014-local").glob("[0-9]*.json")) + assert len(files) == 22 + for path in files: + data = json.loads(path.read_text(encoding="utf-8")) + total = sum(sum(v["votes"].values()) for v in data["byVillage"].values()) + assert total == data["cecValid"], path.name + assert all(c["finance"] is None for c in data["candidates"]) + if data["countyCode"] in published: + assert data["spendingCap"] == published[data["countyCode"]], path.name + + +@pytest.mark.skipif(not (SCENARIOS / "1996-president" / "00000.json").exists(), reason="需要先執行 races") +def test_historic_presidents() -> None: + first = json.loads((SCENARIOS / "1996-president" / "00000.json").read_text(encoding="utf-8")) + assert [(c["name"], c["runningMate"]) for c in first["candidates"]] == [ + ("陳履安", "王清峰"), + ("李登輝", "連戰"), + ("彭明敏", "謝長廷"), + ("林洋港", "郝柏村"), + ] + assert first["candidates"][0]["party"] is None # 舊資料的「連署」是無黨籍 + for year in (1996, 2000, 2004, 2008, 2012, 2016): + data = json.loads((SCENARIOS / f"{year}-president" / "00000.json").read_text(encoding="utf-8")) + counties = {code[:5] for code in data["byVillage"]} + assert len(counties) == 22, year # 舊縣市都併進現在的 22 縣市 + total = sum(sum(v["votes"].values()) for v in data["byVillage"].values()) + # 2004 年中選會檔案有約 50 個里的得票列與投票概況對不上,加總多 1,851 票(萬分之 1.4) + tolerance = data["cecValid"] * 2e-4 if year == 2004 else 0 + assert abs(total - data["cecValid"]) <= tolerance, year + assert all(c["runningMate"] for c in data["candidates"]), year + + +@pytest.mark.unit +def test_blocs_only_change_lean_inputs() -> None: + from election_data.elections import ( + INDEPENDENT, + PARTY_A, + PARTY_B, + ElectionData, + ElectionDef, + VillageResult, + ) + from election_data.pack import _observations + + election = ElectionDef("x", "測試", "2000-03-18", "president", (), 0.25, blocs=((INDEPENDENT, PARTY_B),)) + votes = {PARTY_A: 40, PARTY_B: 20, INDEPENDENT: 35} + data = ElectionData( + election, + {"63000010001": VillageResult(100, 96, 95, votes)}, + {"63000": 95}, + {"63000": {PARTY_A: 40, PARTY_B: 20, INDEPENDENT: 35}}, + ) + [obs] = _observations("63000010001", [data]) + assert obs.votes == {PARTY_A: 40, PARTY_B: 55} + assert obs.contested == {PARTY_A, PARTY_B} + assert data.by_village["63000010001"].votes[INDEPENDENT] == 35 # history.json 仍是原本的分法 diff --git a/backend/data/pipeline/tests/test_legacy.py b/backend/data/pipeline/tests/test_legacy.py new file mode 100644 index 0000000..25d7cbe --- /dev/null +++ b/backend/data/pipeline/tests/test_legacy.py @@ -0,0 +1,188 @@ +"""2014 年以前的中選會資料(流水號代碼)用名稱對照到目前的村里代碼。""" + +import zipfile +from pathlib import Path + +import pytest + +from election_data.cec import CecArchive +from election_data.codes import county_residual_code, is_town_residual, town_residual_code +from election_data.elections import PARTY_A, PARTY_B, ElectionDef, candidate_party, load_election +from election_data.legacy import Gazetteer, legacy_places, stem +from election_data.population import VillagePopulation + +pytestmark = pytest.mark.unit + +ROOT = "votedata/votedata/voteData/" +AGES = tuple([0] * 101) + + +def village(code: str, site: str, name: str) -> VillagePopulation: + return VillagePopulation(code, site, name, 0, AGES) + + +#: 目前的戶政資料:新北市板橋區、臺中市(中區與豐原區)、臺南市中西區 +CURRENT = [ + village("65000010001", "新北市板橋區", "留侯里"), + village("65000010002", "新北市板橋區", "公舘里"), + village("65000010003", "新北市板橋區", "\U000fffb5寮里"), + village("66000010001", "臺中市中區", "大墩里"), + village("66000140001", "臺中市豐原區", "南田里"), + village("67000370001", "臺南市中西區", "赤嵌里"), + village("64000050001", "高雄市三民區", "民族里"), + village("64000380001", "高雄市那瑪夏區", "南沙魯里"), +] +#: 2018 年還在、後來合併掉的里 +OLD = [village("65000010099", "新北市板橋區", "舊里")] + + +@pytest.fixture +def gazetteer() -> Gazetteer: + return Gazetteer.from_snapshots([OLD, CURRENT]) + + +class TestGazetteer: + def test_stem_drops_level_and_folds_variants(self) -> None: + assert stem("板橋市", "市鎮鄉區") == stem("板橋區", "市鎮鄉區") == "板橋" + assert stem("三芝村", "村里") == "三芝" + assert stem("公館里", "村里") == stem("公舘里", "村里") + # 只去掉最後一個字:前鎮區不會變成「前」 + assert stem("前鎮區", "市鎮鄉區") == "前鎮" + + def test_towns_by_name_including_old_counties(self, gazetteer: Gazetteer) -> None: + assert gazetteer.town("65000", "板橋市") == "65000010" + assert gazetteer.town("66000", "豐原市") == "66000140" + # 舊臺南市的西區併進中西區;臺中市的中區還在 + assert gazetteer.town("67000", "西區", "臺南市") == "67000370" + assert gazetteer.town("66000", "中區", "臺中市") == "66000010" + # 高雄縣三民鄉是現在的那瑪夏區,不是高雄市三民區 + assert gazetteer.town("64000", "三民鄉", "高雄縣") == "64000380" + assert gazetteer.town("64000", "三民區", "高雄市") == "64000050" + assert gazetteer.town("65000", "不存在鄉") is None + + def test_villages_current_old_and_private_use(self, gazetteer: Gazetteer) -> None: + assert gazetteer.village("65000010", "留侯里") == "65000010001" + assert gazetteer.village("65000010", "公館里") == "65000010002" # 異體字 + assert gazetteer.village("65000010", "獇寮里") == "65000010003" # 私用區字元當萬用字元 + assert gazetteer.village("65000010", "舊里") == "65000010099" # 2018 年以後合併的舊代碼 + assert gazetteer.village("65000010", "沒有這里") is None + + +def csv(rows: list[list[str]]) -> str: + return "\n".join(",".join(f'"{c}"' for c in row) for row in rows) + "\n" + + +@pytest.fixture +def archive(tmp_path: Path) -> CecArchive: + """2008 年格式:臺北縣 03/001、臺中縣 03/006、臺中市 03/019,鄉鎮與村里都是流水號""" + elbase = [ + ["00", "000", "00", "000", "0000", "全國"], + ["03", "001", "00", "000", "0000", "臺北縣"], + ["03", "001", "00", "001", "0000", "板橋市"], + ["03", "001", "00", "001", "0001", "留侯里"], + ["03", "001", "00", "001", "0002", "公館里、獇寮里"], # 數字代碼但涵蓋兩個里 + ["03", "001", "00", "001", "0003", "已消失里"], # 2018 年以前就合併掉 + ["03", "006", "00", "000", "0000", "臺中縣"], + ["03", "006", "00", "001", "0000", "豐原市"], + ["03", "006", "00", "001", "0004", "南田里"], + ["03", "019", "00", "000", "0000", "臺中市"], + ["03", "019", "00", "001", "0000", "中區"], + ["03", "019", "00", "001", "0005", "大墩里"], + ] + elpaty = [["2", PARTY_A], ["1", PARTY_B]] + elcand = [ + ["00", "000", "01", "000", "0000", "1", "甲", "2", "1", "", "", "", "", "N", "", ""], + ["00", "000", "01", "000", "0000", "1", "甲副", "2", "1", "", "", "", "", "N", "", "Y"], + ["00", "000", "01", "000", "0000", "2", "乙", "1", "1", "", "", "", "", "N", "", ""], + ] + + def ctks(cc: tuple[str, str], town: str, vill: str, a: int, b: int) -> list[list[str]]: + return [ + [*cc, "01", town, vill, "0", "1", str(a), "", ""], + [*cc, "01", town, vill, "0", "2", str(b), "", ""], + ] + + def prof(cc: tuple[str, str], town: str, vill: str, valid: int) -> list[str]: + return [*cc, "01", town, vill, "0", str(valid), "0", str(valid), str(valid * 2)] + + tp, tc, tcc = ("03", "001"), ("03", "006"), ("03", "019") + rows_ctks = [ + *ctks(tp, "000", "0000", 75, 45), # 臺北縣總計:選區欄是 00 以外的寫法也要對得到候選人 + *ctks(tp, "001", "0001", 30, 10), + *ctks(tp, "001", "0002", 20, 20), + *ctks(tp, "001", "0003", 10, 5), + *ctks(tp, "001", "0009", 15, 10), # elbase 沒列的里:只知道鄉鎮 + *ctks(tc, "000", "0000", 10, 30), + *ctks(tc, "001", "0004", 10, 30), + *ctks(tcc, "000", "0000", 50, 50), + *ctks(tcc, "001", "0005", 20, 20), # 另有 20:20 的票只在縣市總計(村里列缺漏) + ] + rows_prof = [ + ["00", "000", "00", "000", "0000", "0", "300", "0", "300", "600"], + [*tp, "00", "000", "0000", "0", "120", "0", "120", "240"], + prof(tp, "001", "0001", 40), + prof(tp, "001", "0002", 40), + prof(tp, "001", "0003", 15), + prof(tp, "001", "0009", 25), + [*tc, "00", "000", "0000", "0", "40", "0", "40", "80"], + prof(tc, "001", "0004", 40), + [*tcc, "00", "000", "0000", "0", "100", "0", "100", "200"], + prof(tcc, "001", "0005", 40), + prof(tcc, "001", "0006", 60), # 有投票概況、沒有得票列的里 + ] + path = tmp_path / "votedata.zip" + with zipfile.ZipFile(path, "w") as zf: + for kind, rows in { + "elbase": elbase, + "elpaty": elpaty, + "elcand": elcand, + "elctks": rows_ctks, + "elprof": rows_prof, + }.items(): + zf.writestr(f"{ROOT}OLD/{kind}.csv", csv(rows)) + return CecArchive(path) + + +LEGACY = ElectionDef("2008-x", "測試", "2008-03-22", "president", ("OLD",), 1.0, legacy_codes=True) + + +def test_places_map_old_counties_towns_and_villages(archive: CecArchive, gazetteer: Gazetteer) -> None: + places = legacy_places(archive, "OLD", gazetteer) + assert places.counties[("03", "006")] == places.counties[("03", "019")] == "66000" + assert places.villages[("03", "001", "001", "0002")] == ("65000010002", "65000010003") + assert places.villages[("03", "001", "001", "0003")] == (town_residual_code("65000010"),) + assert places.town_only == 1 + + +def test_legacy_load_reconciles_with_county_totals(archive: CecArchive, gazetteer: Gazetteer) -> None: + data = load_election(archive, LEGACY, gazetteer=gazetteer) + by = data.by_village + assert by["65000010001"].votes == {PARTY_A: 30, PARTY_B: 10} + # 跨兩個里的列平均分配(沒有權重) + assert by["65000010002"].votes[PARTY_A] + by["65000010003"].votes[PARTY_A] == 20 + assert by["65000010002"].allocated + # 對不到的里與 elbase 沒列的里記在鄉鎮層級 + residual = by[town_residual_code("65000010")] + assert residual.votes == {PARTY_A: 25, PARTY_B: 15} and residual.valid == 40 + # 臺中縣+臺中市併成 66000;村里列缺漏的票記在縣市層級 + county = by[county_residual_code("66000")] + assert county.votes == {PARTY_A: 30, PARTY_B: 30} and county.valid == 60 + assert data.cec_valid_by_county["66000"] == 140 == sum(r.valid for c, r in by.items() if c[:5] == "66000") + for cc in ("65000", "66000"): + votes = sum(sum(r.votes.values()) for c, r in by.items() if c[:5] == cc) + assert votes == data.cec_valid_by_county[cc] + assert data.cec_valid_by_county["00000"] == 300 + assert is_town_residual(county_residual_code("66000")) + + +def test_legacy_requires_gazetteer(archive: CecArchive) -> None: + with pytest.raises(ValueError, match="gazetteer"): + load_election(archive, LEGACY) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [("民主進步黨", "民主進步黨"), ("無黨籍及未經政黨推薦", None), ("無", None), ("連署", None), ("", None)], +) +def test_candidate_party(raw: str, expected: str | None) -> None: + assert candidate_party(raw) == expected diff --git a/backend/data/pipeline/tests/test_local2022.py b/backend/data/pipeline/tests/test_local2022.py new file mode 100644 index 0000000..74df818 --- /dev/null +++ b/backend/data/pipeline/tests/test_local2022.py @@ -0,0 +1,48 @@ +import json + +import pytest + +from election_data.local2022 import OUT_DIR, clean_name, office_of, spending_cap + + +def test_spending_cap_formula_matches_cec() -> None: + # 中選會公告:2022 桃園市長 81,679,000(2022-05-31 人口 2,262,765) + assert spending_cap("68000", 2_262_765) == 81_679_000 + # 縣市長固定金額 3,000 萬 + assert spending_cap("10016", 105_000) == 31_470_000 + + +def test_office_and_names() -> None: + assert office_of("63000") == "市長" + assert office_of("10018") == "市長" + assert office_of("10002") == "縣長" + assert office_of("09020") == "縣長" + assert clean_name("江淵") == "江聰淵" + + +@pytest.mark.skipif(not (OUT_DIR / "65000.json").exists(), reason="需要先執行 election-data local2022") +def test_built_caps_match_published_figures() -> None: + # 中央社 2022-07-15 報導的中選會公告數字 + published = { + "65000": 105_620_000, + "66000": 89_191_000, + "64000": 88_138_000, + "10007": 47_468_000, + "10013": 41_217_000, + "10009": 39_330_000, + "68000": 81_679_000, + } + for county, cap in published.items(): + data = json.loads((OUT_DIR / f"{county}.json").read_text(encoding="utf-8")) + assert data["spendingCap"] == cap, county + + +@pytest.mark.skipif(not (OUT_DIR / "68000.json").exists(), reason="需要先執行 election-data local2022") +def test_candidate_votes_sum_to_cec_totals() -> None: + for path in OUT_DIR.glob("[0-9]*.json"): + data = json.loads(path.read_text(encoding="utf-8")) + total = sum(sum(v["votes"].values()) for v in data["byVillage"].values()) + assert total == data["cecValid"], path.name + numbers = {f"#{c['number']}" for c in data["candidates"]} + for v in data["byVillage"].values(): + assert set(v["votes"]) <= numbers diff --git a/backend/data/pipeline/tests/test_pack_integration.py b/backend/data/pipeline/tests/test_pack_integration.py new file mode 100644 index 0000000..7e72aae --- /dev/null +++ b/backend/data/pipeline/tests/test_pack_integration.py @@ -0,0 +1,74 @@ +"""整合測試:用已下載的真實資料完整產生桃園市資料包。 + +需要 data/raw 中的快取(第一次執行 election-data pack 時下載);沒有快取就略過。 +""" + +import json +from pathlib import Path + +import pytest + +from election_data import cli +from election_data.config import RAW_DIR +from election_data.pack import build_pack + +pytestmark = pytest.mark.integration + +needs_data = pytest.mark.skipif( + not (RAW_DIR / "cec" / "votedata.zip").exists() or not (RAW_DIR / "census2020" / "68000").exists(), + reason="沒有下載過的原始資料", +) + + +@needs_data +def test_taoyuan_pack(tmp_path: Path) -> None: + out = build_pack("68000", out_root=tmp_path) + manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8")) + villages = json.loads((out / "villages.json").read_text(encoding="utf-8"))["villages"] + history = json.loads((out / "history.json").read_text(encoding="utf-8"))["history"] + assert manifest["counts"]["villages"] == len(villages) > 500 + assert all(v["lean"] and v["baseTurnout"] for v in villages) + assert [r for r in history["reconciliation"] if r["diff"] != 0] == [] + report = (out / "report.md").read_text(encoding="utf-8") + assert "與中選會總數核對" in report and "孤兒代碼" in report + + +def test_cli_dispatches_to_build_pack(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + called: list[str] = [] + monkeypatch.setattr( + cli, + "build_pack", + lambda county, exclude=(), name=None, older=False: called.append((county, exclude, name)) or tmp_path, + ) + assert cli.main(["pack", "--county", "68000", "--exclude", "2022-mayor"]) == 0 + assert called == [("68000", ("2022-mayor",), None)] + + +def test_cli_before_excludes_later_elections(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + called: list[tuple] = [] + monkeypatch.setattr( + cli, + "build_pack", + lambda county, exclude=(), name=None, older=False: called.append((county, exclude, name)) or tmp_path, + ) + assert cli.main(["pack", "--county", "68000", "--before", "2022-11-26"]) == 0 + county, exclude, name = called[0] + assert name == "68000-before-2022-11-26" + assert set(exclude) == {"2022-mayor", "2022-councilor", "2024-president", "2024-party-list"} + + +def test_cli_older_before_2020_uses_2016_and_2018(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + called: list[tuple] = [] + monkeypatch.setattr( + cli, + "build_pack", + lambda county, exclude=(), name=None, older=False: ( + called.append((county, exclude, name, older)) or tmp_path + ), + ) + assert cli.main(["pack", "--county", "63000,00000", "--before", "2020-01-11", "--older"]) == 0 + assert [c[0] for c in called] == ["63000", "00000"] + county, exclude, name, older = called[0] + assert name == "63000-before-2020-01-11" and older + # 2020 年以後的都排除,2016、2018 年的留著 + assert "2020-president" in exclude and "2018-mayor" not in exclude and "2016-president" not in exclude diff --git a/backend/data/pipeline/tests/test_population_attributes.py b/backend/data/pipeline/tests/test_population_attributes.py new file mode 100644 index 0000000..1d246c5 --- /dev/null +++ b/backend/data/pipeline/tests/test_population_attributes.py @@ -0,0 +1,87 @@ +from pathlib import Path + +import openpyxl +import pytest + +from election_data.attributes import _coordinates, _town_rows, parse_hakka, parse_income +from election_data.population import parse_indigenous, parse_population + +pytestmark = pytest.mark.unit + + +def population_row( + code: str = "68000010001", ages: dict[int, int] | None = None, total: int | None = None +) -> dict: + ages = ages or {} + row = {"district_code": code, "site_id": "桃園市桃園區", "village": "示例里"} + for a in range(100): + row[f"people_age_{a:03d}_m"] = str(ages.get(a, 0)) + row[f"people_age_{a:03d}_f"] = "0" + row["people_age_100up_m"] = str(ages.get(100, 0)) + row["people_age_100up_f"] = "0" + row["people_total"] = str(total if total is not None else sum(ages.values())) + return row + + +class TestPopulation: + def test_bands_and_adults(self) -> None: + [p] = parse_population([population_row(ages={5: 10, 20: 3, 29: 2, 64: 4, 65: 1, 100: 2})]) + assert p.band_counts() == {"20-29": 5, "30-39": 0, "40-49": 0, "50-64": 4, "65+": 3} + assert p.adults == 12 + assert p.total == 22 + + def test_mismatched_total_is_logged(self, caplog: pytest.LogCaptureFixture) -> None: + parse_population([population_row(ages={30: 5}, total=9)]) + assert "不符" in caplog.text + + def test_indigenous(self) -> None: + row = { + "district_code": "68000130001", + "indigenous_plain_total_m": "3", + "indigenous_plain_total_f": "4", + "indigenous_mountain_total_m": "10", + "indigenous_mountain_total_f": "", + } + [i] = parse_indigenous([row]) + assert (i.lowland, i.highland) == (7, 10) + + +def test_parse_income_normalizes_and_skips_totals() -> None: + text = ( + '"縣市別","村里","納稅單位(戶)","綜合所得總額","平均數","中位數"\n' + '"台北市松山區","中崙里","1464","2745453","1875","857"\n' + '"臺北市松山區","合計","9","9","9","9"\n' + '"臺北市松山區","壞資料","x","1","1","1"\n' + ) + [row] = parse_income(text) + assert (row.site, row.village, row.households, row.median) == ("臺北市松山區", "中崙里", 1464, 857.0) + + +def test_parse_hakka() -> None: + text = "area_name,AreaCode,Ratio\n68000 ,68000040 ,0.71 \nbad,123,0.5\n" + assert parse_hakka(text) == {"68000040": 0.71} + + +def test_town_rows_reads_two_space_rows(tmp_path: Path) -> None: + wb = openpyxl.Workbook() + ws = wb.active + ws.append(["表1 常住人口"]) + ws.append([" 桃園市", 100]) + ws.append(["  桃園區", 10, 5]) + ws.append(["  Taoyuan Dist"]) + path = tmp_path / "t.xlsx" + wb.save(path) + assert _town_rows(path) == {"桃園區": [10, 5]} + + +def test_coordinates_filters_bad_points(tmp_path: Path) -> None: + xml = tmp_path / "t.xml" + xml.write_text( + "" + "<負責人>某人121.324.9" + "" + "00" + "", + encoding="utf-8", + ) + assert list(_coordinates(xml)) == [(121.3, 24.9)] diff --git a/backend/data/pipeline/tests/test_races2024.py b/backend/data/pipeline/tests/test_races2024.py new file mode 100644 index 0000000..773755a --- /dev/null +++ b/backend/data/pipeline/tests/test_races2024.py @@ -0,0 +1,127 @@ +import json + +import pytest + +from election_data.races2024 import ( + OUT_LEGISLATOR, + OUT_PRESIDENT, + district_towns, + legislator_cap, + president_cap, +) + + +def test_president_cap_matches_published_2020_figure() -> None: + # 2019-07-31 人口 23,592,598 → 中選會公告 2020 總統選舉上限 430,297,000 + assert president_cap(23_592_598) == 430_297_000 + + +def test_legislator_cap_formula() -> None: + assert legislator_cap(14_005) == 10_295_000 + + +@pytest.mark.skipif(not (OUT_PRESIDENT / "00000.json").exists(), reason="需要先執行 election-data races2024") +def test_president_totals_match_cec() -> None: + data = json.loads((OUT_PRESIDENT / "00000.json").read_text(encoding="utf-8")) + total = sum(sum(v["votes"].values()) for v in data["byVillage"].values()) + assert total == data["cecValid"] == 13_947_506 + assert [c["name"] for c in data["candidates"]] == ["柯文哲", "賴清德", "侯友宜"] + assert all(c["finance"] for c in data["candidates"]) + + +@pytest.mark.skipif(not OUT_LEGISLATOR.exists(), reason="需要先執行 election-data races2024") +def test_legislator_districts() -> None: + # calibration.json 是校準結果,不是選區 + files = sorted(OUT_LEGISLATOR.glob("[0-9]*-[0-9]*.json")) + assert len(files) == 73 + seen: set[str] = set() + for path in files: + data = json.loads(path.read_text(encoding="utf-8")) + villages = set(data["byVillage"]) + assert not villages & seen, path.name # 每個里只屬於一個選區 + seen |= villages + numbers = {f"#{c['number']}" for c in data["candidates"]} + for v in data["byVillage"].values(): + assert set(v["votes"]) <= numbers + + +def test_district_towns_marks_partial_towns() -> None: + sites = { + "63000110001": "臺北市士林區", + "63000110002": "臺北市士林區", + "63000120001": "臺北市北投區", + } + towns = district_towns({"63000110001", "63000120001"}, sites, "臺北市") + assert towns == [ + {"code": "63000110", "name": "士林區", "partial": True}, + {"code": "63000120", "name": "北投區", "partial": False}, + ] + + +@pytest.mark.skipif( + not (OUT_LEGISLATOR / "63000-01.json").exists(), reason="需要先執行 election-data races2024" +) +def test_taipei_first_district_towns() -> None: + data = json.loads((OUT_LEGISLATOR / "63000-01.json").read_text(encoding="utf-8")) + assert [(t["name"], t["partial"]) for t in data["towns"]] == [("士林區", True), ("北投區", False)] + + +class _FakeIndex: + def __init__(self, edges: dict[str, list[str]]) -> None: + self._edges = edges + + def neighbors(self, code: str) -> list[str]: + return self._edges.get(code, []) + + +def _shape(code: str): + from types import SimpleNamespace + + return SimpleNamespace(code=code, county_code=code[:5]) + + +def test_assign_orphans_prefers_same_town_and_spreads_outward() -> None: + from election_data.races2024 import assign_orphans + + district_of = {"63000110001": "A", "63000120001": "B", "63000120002": "B"} + edges = { + # 新里 003 同時鄰接士林(A)與北投(B),同區的鄰居優先 + "63000120003": ["63000110001", "63000120001"], + # 新里 004 只鄰接另一個新里,要等 003 先分好 + "63000120004": ["63000120003"], + } + shapes = [_shape(c) for c in [*district_of, "63000120003", "63000120004"]] + assert assign_orphans(district_of, shapes, _FakeIndex(edges)) == { + "63000120003": "B", + "63000120004": "B", + } + + +@pytest.mark.skipif(not OUT_LEGISLATOR.exists(), reason="需要先執行 election-data races2024") +def test_every_pack_village_is_in_a_district() -> None: + by_county: dict[str, set[str]] = {} + for path in OUT_LEGISLATOR.glob("[0-9]*-[0-9]*.json"): + data = json.loads(path.read_text(encoding="utf-8")) + by_county.setdefault(data["countyCode"], set()).update(data["byVillage"]) + packs = OUT_LEGISLATOR.parent.parent / "packs" + for county, villages in by_county.items(): + pack = packs / f"{county}-before-2024-01-13" / "villages.json" + if not pack.exists(): + continue + codes = {v["code"] for v in json.loads(pack.read_text(encoding="utf-8"))["villages"]} + assert codes <= villages, (county, sorted(codes - villages)[:5]) + + +def test_remap_population_matches_renamed_offices_by_village_name() -> None: + from election_data.population import VillagePopulation + from election_data.races2024 import remap_population + + def vp(code: str, site: str, village: str, total: int) -> VillagePopulation: + return VillagePopulation(code, site, village, total, (0,) * 101) + + old = [ + vp("64000051001", "高雄市三民一", "鼎金里", 100), # 2019 年三民區分兩個戶政所 + vp("64000010001", "高雄市鹽埕區", "藍橋里", 50), + ] + now = [vp("64000050007", "高雄市三民區", "鼎金里", 0), vp("64000010001", "高雄市鹽埕區", "藍橋里", 0)] + assert remap_population(old, now) == {"64000050007": 100, "64000010001": 50} diff --git a/backend/docs/03-voter-model.md b/backend/docs/03-voter-model.md new file mode 100644 index 0000000..19ce3b5 --- /dev/null +++ b/backend/docs/03-voter-model.md @@ -0,0 +1,111 @@ +# 03 選民模型 + +用真實資料估出每個村里的選民結構,再算每位候選人的預期得票。程式在 `packages/engine/src/voter.ts`(公式)與 +`packages/engine/src/params.ts`(參數);選民群人數由資料管線 `data/pipeline/src/election_data/cells.py` 估計。 + +現在用到它的地方: + +- **選戰卡牌開局**(`packages/rogue/src/setup.ts`、`local.ts`):用模型算出各區、各里的預期得票,當成雙方的底盤。開局之後的變化都是牌面上的數字,規則不再碰模型。 +- **校準與回測**(`apps/sim`):舊的十週引擎讓 AI 對打,調整每位候選人的魅力值與投票率倍率,讓全縣市得票接近真實結果,寫進 `calibration.json`(見下面「校準」)。 + +## 地理層級 + +| 層級 | 用途 | +|---|---| +| 村里 | 模擬的最小單位,每個村里 30 個選民群 | +| 鄉鎮市區(區) | 縣市長、立委選舉的地圖單位;樁腳強度以區為單位 | +| 縣市 | 總統選舉的地圖單位(資料包以 `regionLevel: "county"` 建立,把縣市當成區) | + +## 選民群 + +每個村里的成年人切成 5 個年齡層 × 6 個政黨傾向 = 30 個選民群(`protocol/src/area.ts` 的 `AGE_BANDS`、`LEANS`): + +| 維度 | 分類 | +|---|---| +| 年齡層 | 20–29、30–39、40–49、50–64、65 以上 | +| 政黨傾向 | 甲黨核心、甲黨傾向、中間、乙黨傾向、乙黨核心、第三勢力傾向 | + +甲、乙、第三勢力是模型裡的槽位(`a`、`b`、`c`,其他政黨是 `other`),由劇本對應到當年的真實政黨。 + +### 人數怎麼估 + +1. 年齡:戶政的村里年齡人口。 +2. 政黨傾向:該里歷屆選舉的得票比例。 +3. 生態推論:用所有村里的年齡結構與政黨傾向做加權最小平方(加 ridge 收斂),估出各年齡層的傾向分布 P(傾向 | 年齡)。不需要調查資料。 +4. 疊代比例調整(IPF):以 P(傾向 | 年齡) × 年齡人數當種子,調到同時符合該里的年齡人數與傾向比例。 + +村里另外帶有屬性(每千人宮廟數、人口密度、客家人口比例等),卡牌模式用來判斷地區特色(年輕人多、長輩多、宮廟多、客家庄…)。 + +## 狀態 + +| 狀態 | 單位 | 意義 | 每週衰退 | +|---|---|---|---| +| 知名度 A | 選民群 × 候選人 | 知不知道這個人(0–1) | 2% | +| 好感度 F | 選民群 × 候選人 | 喜不喜歡(−1–1) | 往基準回歸 10% | +| 熱度 M | 選民群 × 候選人 | 支持者有多想去投票(0–1) | 15% | +| 樁腳 K | 區 × 候選人 | 地方組織 | 5% | +| 聲勢 S | 候選人 | 整體氣勢 | 25% | +| 全國風向 | 政黨槽位 | 全國氣氛 | — | + +## 投票公式(`computeVoteModel`) + +選民群 g 對候選人 c 的偏好: + +``` +U(g,c) = βp · 政黨契合[c 的槽位][g 的傾向] + + βf · F(g,c) + + βk · K(g 所在的區, c) + + βs · S(c) + + βmood · 全國風向(c 的槽位) + + 魅力(c) // 劇本裡的 appeal,由校準決定 + − 2.5(候選人已退選) +``` + +考慮集合:知名度太低的人大多不會被考慮,`w(g,c) = sigmoid((A − a0) / s)`。 + +選擇機率: + +``` +誠實票 P(g,c) ∝ w · exp(U / τ) +策略票 P'(g,c) ∝ w · exp((U + βv · ln V(c)) / τ) // V = 被認知的勝選機率(最近一次公開民調) +實際 (1 − σ) · P + σ · P' // σ = 這個傾向的策略性選民比例(棄保) +``` + +沒有民調時(例如卡牌開局)不計棄保。 + +投票率: + +``` +T(g) = 該里歷史投票率 × 劇本投票率倍率 × 年齡層係數 × (1 + κ · (熱度 − 熱度基準)) × 天氣係數 +``` + +夾在 15%–97% 之間。年齡層係數以村里平均正規化成 1,保留該里的歷史投票率。 + +預期得票 = Σ 選民群人數 × T × P(`aggregate`)。舊引擎的投票日(`engine/src/election.ts`)再依這個期望值抽樣,分到各村里。 + +## 參數(`DEFAULT_PARAMS`) + +| 參數 | 值 | 說明 | +|---|---|---| +| βp | 2.0 | 政黨契合 | +| βf | 1.5 | 好感度 | +| βk | 0.6 | 樁腳 | +| βs | 0.4 | 聲勢 | +| βmood | 1.0 | 全國風向 | +| βv | 0.5 | 棄保 | +| τ | 1.0 | 選擇溫度 | +| a0, s | 0.3, 0.08 | 考慮集合的門檻與斜率 | +| σ | 核心 0.05、傾向 0.25、中間與第三勢力 0.35 | 策略性選民比例 | +| κ | 0.25 | 熱度對投票率的影響(熱度基準 0.3) | +| 年齡層投票率 | 0.82、0.88、0.98、1.08、1.06 | 20 歲起五個年齡層 | +| 廢票率 | 1.5% | | + +政黨契合是槽位 × 傾向的表(例如甲黨對甲黨核心 1.0、對乙黨核心 −1.0、對中間 0),完整數字見 `params.ts`。 + +## 校準 + +`node apps/sim/src/calibrate-local.ts --set <劇本組>`:讓舊引擎的 AI 對打,反覆調整每位候選人的魅力值(`appeal`)與全縣市投票率倍率(`turnoutScale`), +直到全縣市得票與投票率接近真實結果;「勢均力敵」劇本另外算一組 `evenAppeal`。各區、各里的誤差只當驗證,寫進 `data/build/scenarios/<劇本組>/calibration.json` +與報告。`packages/scenarios` 讀這個檔把校準值放進劇本,卡牌模式開局時用。 + +回測:`pnpm --filter @election2026/sim backtest`,拿區、里層級的結果和真實開票比較。 diff --git a/backend/docs/10-data-sources.md b/backend/docs/10-data-sources.md new file mode 100644 index 0000000..9e7c3ea --- /dev/null +++ b/backend/docs/10-data-sources.md @@ -0,0 +1,290 @@ +# 10 資料來源與資料管線 + +> **2026-10-28 現況:** 管線(`data/pipeline`)實際下載與使用的是選舉(中選會)、人口(戶政)、宗教(內政部宮廟教會)、 +> 地理(村里界)、社會經濟(主計、財政、客委會)、競選財務(監察院政治獻金)、人物(中選會、立法院、Wikidata)。 +> 本文件的「氣象」「媒體使用」「政治態度(TEDS)」三節只是研究,管線沒有用到;選民群的年齡與傾向關聯用的是方案 B(生態推論)。 +> 人物資料庫(`people.json`)與 AI 評分的產出目前沒有接進遊戲,遊戲用的是 `records.json` 的客觀資歷分數(docs/23)。 + +> 本文件的資料集與法規已於 **2026-10-25** 逐一查證(實際下載或開啟官方頁面)。 +> 「授權 1」指「政府資料開放授權條款第 1 版」。狀態欄:**確認**=已實際取得;**部分**=只取得部分或需要申請。 + +## 管線總覽 + +``` +下載原始資料(data/raw) + → 清理與代碼統一(以村里代碼 VILLCODE 為主鍵) + → 合併為里層級的寬表 + → 估計選民群人數(IPF) + → 產出資料包(全國、各縣市、各選舉規格)(data/build) + → 回測與檢查 +``` + +全國一次處理,各選舉再從全國資料包切出需要的範圍。 + +## 選舉資料 + +| 資料集 | 機關 | 粒度 | 格式 | 更新 | 授權 | 用途 | 狀態 | +|---|---|---|---|---|---|---|---| +| 選舉資料庫(含選舉區資料) | 中選會 | 投開票所,附村里小計 | 單一 ZIP(約 110 MB),內含各次選舉的 CSV | 選後 7 日內 | 授權 1 | 歷屆得票、投票率、底盤、回測 | 確認 | +| 投開票所地址 | 中選會 | 投開票所 | CSV(2024 年 17,794 所;無座標) | 不定期 | — | 開票夜回報、地圖點位 | 部分(2022、2026 未找到全國檔) | +| 議員選舉區劃分 | 中選會 | 區,切開的選區附里清單 | 2026 公告 PDF | 每屆 | — | 議員選區定義 | 確認 | +| 立委選舉區範圍 | 中選會 | 區、里(文字描述) | CSV | 每屆 | — | 立委選區定義 | 確認 | + +- 資料庫涵蓋 1994–2024 年,包含 2018、2022 地方選舉,2024 總統、區域、原住民、不分區。 +- 每次選舉的 CSV:`elbase`(地名與選區對照)、`elcand`(候選人)、`elctks`(各候選人得票)、`elprof`(投票概況)、`elpaty`(政黨)、`elretks`(政黨票)。 +- `elbase` 本身就有村里對應選區的代碼,可以直接用來建立選區。 +- 連結:https://data.gov.tw/dataset/13119 、https://db.cec.gov.tw/ 、https://data.cec.gov.tw/ +- 2026 年選舉的結果會在選後 7 日內併入同一個資料庫,屆時可以做 2030 劇本。 + +## 人口 + +| 資料集 | 機關 | 粒度 | 格式 | 更新 | 授權 | 用途 | 狀態 | +|---|---|---|---|---|---|---|---| +| 村里戶數、單一年齡人口(新增區域代碼) | 內政部戶政司 | 村里,0–99 歲加 100 歲以上,分性別 | JSON API(分頁) | 每月(2018 起) | 授權 1 | 年齡結構、選舉人數估計、經費上限計算 | 確認 | +| 現住人口數按性別及原住民身分分 | 戶政司 | 村里 | API(ODRP013) | 每月 | 授權 1 | 平地、山地原住民人口;原住民選區 | 確認 | +| 現住原住民人口按性別、年齡 | 戶政司 | 村里 | API(ODRP015) | 每月 | 授權 1 | 原住民選民群年齡結構 | 確認 | +| 現住原住民人口按族別 | 戶政司 | 村里 | API(ODRP018) | 每月 | 授權 1 | 族別地緣 | 確認 | +| 外籍配偶與大陸港澳配偶人數 | 內政部統計處 | **縣市** | 統計查詢網 | 每月 | 授權 1 | 新住民比例 | 部分(無全國鄉鎮層級) | + +- 年齡人口 API:`https://www.ris.gov.tw/rs-opendata/api/v1/datastore/ODRP014/{民國年月}`(例如 `11509`),2026 年 9 月共 7,781 個村里。 +- 連結:https://data.gov.tw/dataset/77132 、77145、77129、77052、13503 + +## 社會經濟 + +| 資料集 | 機關 | 粒度 | 格式 | 更新 | 授權 | 用途 | 狀態 | +|---|---|---|---|---|---|---|---| +| 綜稅綜合所得總額全國各縣市鄉鎮村里統計分析表 | 財政部財政資訊中心 | 村里 | CSV(101–112 年度) | 每年 8 月 | 授權 1 | 所得(平均、中位數、四分位數) | 確認;**沒有代碼,只能用地名串接** | +| 109 年人口及住宅普查 縣市別報告統計表 | 主計總處 | 鄉鎮市區 | XLSX、ODS | 十年一次 | 網站開放宣告 | 常住人口(表 1)、教育(表 10–11)、職業(表 13)、**家庭使用語言(表 6)** | 確認;未找到鄉鎮層級的行業別 | +| 社會經濟資料服務平台(SEGIS) | 內政部 | 村里、最小統計區 | CSV、SHP、JSON、XML、網路服務 | 依資料 | 免費資料採開放授權;部分需申請 | 15 歲以上教育程度、婚姻、5 歲與 10 歲年齡組 | 確認 | +| 客家人口基礎資料調查(110 年) | 客委會 | 鄉鎮(只在報告 PDF) | PDF | 不定期 | — | 客家比例 | 部分;未找到更新的版本 | +| 客家文化重點發展區 | 客委會 | 鄉鎮(70 個,代碼 TOWNCODE) | CSV、JSON、XML | 不定期 | 授權 1 | 客家比例(≥ 1/3 的鄉鎮)、腔調 | 確認 | + +- 普查連結:https://www.stat.gov.tw/News_Content.aspx?n=2755&s=230160 +- SEGIS:https://segis.moi.gov.tw/STATCloud/Catalog +- 所得:https://data.gov.tw/dataset/103066 ;客家重點區:https://data.gov.tw/dataset/162466 + +## 地理 + +| 資料集 | 機關 | 內容 | 格式與座標 | 授權 | 狀態 | +|---|---|---|---|---|---| +| 村里界圖(TWD97 經緯度) | 國土測繪中心 | 版本 1150817,7,986 個多邊形;欄位 VILLCODE、TOWNCODE、COUNTYCODE | SHP,TWD97[2020] 經緯度 | 授權 1 | 確認 | +| 鄉鎮市區界線 | 國土測繪中心 | | SHP | 授權 1 | 確認 | +| 直轄市、縣市界線 | 國土測繪中心 | | SHP、GML | 授權 1 | 確認 | +| 最小統計區圖 | 國土測繪中心 | | TWD97 TM2(本島 121 分帶、離島 119 分帶) | 授權 1 | 確認 | + +- data.gov.tw 資料集編號:7438(村里)、7441(鄉鎮)、7442(縣市)、25128(最小統計區)。 +- 遊戲使用時轉成 TopoJSON 並簡化,依層級各產生一份。 + +## 宗教 + +| 資料集 | 機關 | 內容 | 格式 | 授權 | 狀態 | +|---|---|---|---|---|---| +| 全國宗教資訊系統:寺廟 | 內政部 | 12,425 間,名稱、主祀神、地址;11,925 間有 WGS84 座標 | XML | 授權 1 | 確認 | +| 全國宗教資訊系統:教會 | 內政部 | 同上 | XML | 授權 1 | 確認 | + +- https://religion.moi.gov.tw/Report/temple.xml (資料集 8203)、`church.xml`(8204) +- 以座標做點落多邊形,算出每個里的宮廟與教會密度。**只用密度,不在遊戲中顯示具名宮廟**(14)。 + +## 氣象 + +| 資料 | 來源 | 用途 | +|---|---|---| +| 各測站月平均(C-B0027-001) | 中央氣象署開放資料 API(免費金鑰) | 11 月(地方選舉)、1 月(總統選舉)的天氣分布 | +| 每日雨量(C-B0025-001) | 同上 | 雨天機率 | +| 測站清單(C-B0074) | 同上 | 測站對應到區 | +| 颱風警報與路徑(W-C0034-001、005) | 同上 | 即時;劇本用 | +| 測站長期日資料 | CODiS(網頁下載) | 歷年同期的雨天機率 | +| 颱風資料庫 | https://rdc28.cwa.gov.tw/TDB/ | 發布警報的颱風清單;最佳路徑需研究帳號 | + +## 媒體使用 + +| 資料 | 來源 | 狀態 | +|---|---|---| +| 2025 台灣網路報告 | TWNIC | 確認:報告 PDF+**受訪者層級 XLSX**(2,142 人、約 220 個變數,含出生年與年齡組)。報告以外的用途需要申請授權 | + +- https://report.twnic.tw/2025/ +- 用途:各年齡層對各媒體管道的觸及率。電視、報紙、廣播的使用率需要其他來源補足,或作為設計值。 + +## 政治態度 + +| 資料 | 來源 | 狀態 | +|---|---|---| +| 重要政治態度分佈趨勢 | 政大選舉研究中心 | 部分:全國層級,1992 年至 2026 年 6 月;圖表數值的 Excel 需要簽署申請書 | +| TEDS 台灣選舉與民主化調查 | 政大 | 部分:年齡別交叉表需要微觀資料;免費註冊會員並提出申請,限非營利使用 | + +- https://esc.nccu.edu.tw/PageDoc/Detail?fid=7806&id=6965 、https://teds.nccu.edu.tw/data/super_pages.php?ID=data1 +- **授權注意:** TEDS 限非營利使用。若遊戲有營利,需要另外確認,或改用下方的生態推論做法。 + +## 競選財務 + +| 資料 | 來源 | 用途 | 狀態 | +|---|---|---|---| +| 政治獻金會計報告書 | 監察院政治獻金公開查閱平臺 | 2018、2022 候選人的收支規模與支出類別,用來校準預算與價格 | 確認:每位候選人一個 CSV 壓縮檔(需通過驗證碼與同意條款) | +| 政治獻金賸餘報告 | data.gov.tw(例如 174254) | 參考 | 確認 | + +- https://ardata.cy.gov.tw/ + +## 人物資料 + +| 資料 | 來源 | 內容 | 格式 | 狀態 | +|---|---|---|---|---| +| 候選人 | 中選會選舉資料庫 `elcand` | 姓名、政黨代碼、性別、出生日期(民國)、學歷程度、是否現任、是否當選 | CSV | 確認(2022 年的候選人檔只有選區、姓名、號次) | +| 經歷 | 選舉公報 | 學歷、經歷、政見 | **只有 PDF**(2024 年約 276 MB) | 確認;需要人工或 OCR 整理 | +| 2026 候選人名單 | 中選會公告 | | | 直轄市長於 11/12 公告、其餘於 11/17 公告;號次已於 10/23 抽籤 | +| 立法委員 | 立法院開放資料 ID9(現任)、ID16(歷屆,1,657 筆,每日更新) | 屆別、姓名、性別、政黨、黨團、選區、委員會、學歷、經歷、照片網址、離職 | JSON、CSV、XML、XLS、TXT | 確認 | +| 地方公職人員 | 內政部地方公職人員資訊專區 | 縣市長、議員、**村里長**,含政黨與任期 | ODS 匯出 | 確認 | +| 行政院內閣 | 行政院網站 | 首長名單 | 只有 HTML | 確認;需要人工維護 | +| 結構化人物資料 | Wikidata(SPARQL) | 職位、政黨、出生日期 | **CC0** | 確認:立委 1,037 人(994 人有出生日期、725 人有政黨);**議員資料稀疏** | +| 財產申報 | 監察院(廉政專刊) | 申報內容 | PDF 或電子書;未刊登的需要線上申請並臨櫃查閱 | 部分;**不是機器可讀** | + +- 立法院 API 範例:`https://data.ly.gov.tw/odw/ID9Action.action?term=11&fileType=json` +- 地方公職人員:https://www.moi.gov.tw/LocalOfficial.aspx?n=574&TYP=KND0002 +- Wikidata:https://query.wikidata.org/sparql + +### 對人物系統的影響 + +- **財力屬性:** 財產申報不是機器可讀,第一版先不使用,或只對少數重要人物人工整理成級距。 +- **照片:** 總統府與立法院網站的資料開放宣告採授權 1,但**只處理著作權,不涵蓋肖像權與個資**,而且排除機關另外標示需要同意的圖片。這再次確認頭像一律用捏臉繪製、不用照片的決定(14、15)。 +- **維基百科文字** 不直接複製;結構化資料用 Wikidata(CC0)。 + +### 非政治人物與機構(待查證) + +人物資料需要以下來源。**這一節尚未逐一查證**,M1 開始前要比照上面的方式確認。 + +| 對象 | 可能的來源 | 備註 | +|---|---|---| +| 企業家 | 經濟部商工登記公示資料(公司負責人、董監事);Wikidata | 只取與公開職務相關的資料 | +| 藝人、名嘴、網紅 | Wikidata;公開社群帳號的追蹤數(人工記錄) | 社群平台的使用條款可能限制自動擷取 | +| 電視台、廣播 | 國家通訊傳播委員會公告的事業與頻道名單 | | +| 民調機構 | 歷屆公開民調的發布者;各機構官網 | 機構效應需要歷屆民調數字,來源與授權要個別確認 | +| 村里長 | 內政部地方公職人員資訊專區(已確認,見上表) | | + +### AI 評分的輸入資料 + +| 資料 | 來源 | 使用方式 | +|---|---|---| +| 結構化經歷 | 上述人物資料 | 直接使用 | +| 立法院質詢、發言紀錄 | 立法院開放資料 | 評估口才、議題 | +| 公開新聞報導 | 各媒體網站 | 只作為評分依據;遊戲內只顯示出處連結與摘要,不轉載全文(14)。擷取前確認各網站的使用條款 | +| 社群公開數據 | 追蹤數、互動數(人工或官方 API) | 評估網路魅力 | + +## 代碼與串接 + +| 來源 | 代碼 | 轉換到主鍵 VILLCODE | +|---|---|---| +| 戶政司 API | `district_code`(11 碼) | 直接相同。例:65000010001 是新北市板橋區留侯里 | +| 國土測繪中心村里界 | `VILLCODE` | 主鍵 | +| 中選會 | 5 段代碼:省市 2 + 縣市 3 + 鄉鎮 3 + 村里 4 | 前三段相接,加上村里段的後 3 碼。例:63/000/010/0002 → 63000010002 | +| 客委會重點區 | `TOWNCODE`(8 碼) | 鄉鎮層級,對應到轄下所有里 | +| 綜稅所得 | **無代碼** | 以「縣市+鄉鎮+村里」名稱串接;需統一「台/臺」等異體字,並處理同名 | +| 普查 | 鄉鎮名稱 | 以名稱對到 TOWNCODE | + +### 已知的串接問題 + +| 問題 | 處理 | +|---|---| +| **跨村里投開票所**:部分投開票所服務多個里,村里代碼以字母開頭(如 A001、0A01),票數無法拆到里。2024 總統選舉 17,795 列中有 22 列 | 每次選舉有跨村里對照表(.ods)。依各里選舉人數比例分配,並在資料中標註為估計值 | +| **邊界 7,986 個多邊形 vs 戶政 7,781 個有人口的里** | 待比對:可能是無人口的里、海域或離島多邊形、行政區調整 | +| **歷屆之間的里合併與改名** | 建立里代碼對照表;以最新里界為準,舊資料依對照表重新分配 | +| **普查日(2020-11-08)與戶籍資料的時間點** | 戶籍與常住的差距,用同月份的戶政資料比較 | + +## 選民群估計 + +目標:每個里 30 個選民群(5 個年齡層 × 6 個政黨傾向)的人數(03)。 + +1. **年齡邊際:** 戶政單一年齡人口,取 20 歲以上,分成 5 層。 +2. **政黨傾向邊際:** 該里歷屆得票(2018、2020、2022、2024,近期權重較高)轉換成 6 類傾向。 +3. **年齡與傾向的關聯:** + - 方案 A:TEDS 的年齡別政黨認同交叉表(需申請,限非營利)。 + - 方案 B:**生態推論**。用全國約 7,700 個里的「年齡結構」與「得票率」做跨里迴歸,估計各年齡層的政黨傾向。不需要調查資料,也沒有授權問題。 + - 建議先做方案 B,拿到 TEDS 後用方案 A 校正。 +4. **疊代比例調整(IPF):** 以第 3 步的關聯為種子矩陣,調整到同時符合第 1、2 步的邊際分布。 + +## 單位屬性對照 + +| 遊戲屬性(03) | 資料來源 | 粒度 | 備註 | +|---|---|---|---| +| 族群與語言 | 普查表 6「家庭使用語言」;客委會重點區;戶政原住民人口 | 鄉鎮、里 | 官方統計沒有「外省」身分,改用語言使用作為代理 | +| 新住民 | 統計處外籍配偶人數 | 縣市 | 以人口比例分配到區,或只當縣市層級屬性 | +| 教育程度 | SEGIS 15 歲以上教育程度 | 里 | | +| 所得 | 綜稅所得 | 里 | | +| 職業 | 普查表 13 | 鄉鎮 | 無行業別 | +| 宮廟密度、宗教 | 宗教資訊系統座標 | 里 | | +| 都市化 | 人口 ÷ 里面積 | 里 | | +| 戶籍外流比例 | 普查常住人口 vs 戶籍人口 | 鄉鎮 | | +| 媒體習慣 | TWNIC 依年齡層 | 全國 | 依各里年齡結構推算 | +| 基本投票率 | 中選會 `elprof` | 里 | | +| 地方派系強度 | **沒有開放資料** | 縣市 | 設計值;可參考地方議員連任率等代理指標 | + +## 經費上限的計算 + +依選罷法第 41 條,以戶政人口計算(選前第 6 個月的戶籍人口): + +| 選舉 | 公式 | +|---|---| +| 直轄市長 | 人口 × 70% × 20 元 + 5,000 萬元 | +| 縣市長 | 人口 × 70% × 20 元 + 3,000 萬元 | +| 直轄市議員 | 人口 × 70% ÷ 應選名額 × 30 元 + 1,000 萬元 | +| 縣市議員 | 人口 × 70% ÷ 應選名額 × 30 元 + 600 萬元 | + +2026 年公告例:新北市長 106,551,000 元、臺北市長 83,986,000 元。管線依此公式自動算出每個選舉規格的上限。 + +## 已查證的法規 + +供其他文件引用。**選罷法在 2026 年 1 月 21 日與 7 月 1 日都有修正,正式上線前要再核對一次法規資料庫。** + +| 項目 | 內容 | 依據 | 狀態 | +|---|---|---|---| +| 2026 投票日 | 2026-11-28(星期六)08:00–16:00;選舉人約 1,965 萬 | 中選會公告(2026-08-20) | 確認 | +| 民調封關 | 投票日前 10 日起至投票截止,不得發布、報導、引述民調 | 選罷法第 53 條第 3 項 | 確認 | +| 不得撤回登記 | 經登記為候選人者,不得撤回登記;政黨只能在登記截止前撤回推薦 | 選罷法第 31 條第 1 項 | 確認 | +| 競選經費補助 | 每票 30 元,以經費上限為限。單一席次:得票達當選票數 1/3;多席次:達最低當選票數 1/2 | 選罷法第 43 條 | 確認 | +| 經費上限 | 見上一節 | 選罷法第 41 條 | 確認 | +| 參選年齡 | 一般 23 歲;直轄市長、縣市長 30 歲;總統副總統 40 歲 | 選罷法第 24 條;總統副總統選罷法第 20 條 | 確認 | +| 總統連署 | 45 日內達上次總統選舉選舉人總數 1.5%;連署保證金 100 萬元(未達半數不退) | 總統副總統選罷法第 23 條 | 確認 | +| 總統政黨推薦 | 上次總統或立委選舉得票達 5% 的政黨 | 總統副總統選罷法第 22 條 | 確認 | +| 總統保證金 | 1,500 萬元;得票未達選舉人總數 5% 不退 | 總統副總統選罷法第 31 條 | 確認 | +| 議員婦女保障 | **2026 年仍適用**:每 4 席 1 名婦女,之後每增加 4 席再加 1 名(12 席 → 3 名) | 地方制度法第 33 條第 5 項;計算方式見選罷法第 68 條 | 確認 | +| 議員婦女保障(新制) | 2025-12-03 修法改為「任一性別 1/3」,**自 2030-12-25 就職的議員起適用** | 地方制度法第 33 條末項 | 確認 | +| 原住民議員 | 平地或山地原住民人口達 2,000 人(直轄市)、1,500 人(縣市)時應有原住民議員 | 地方制度法第 33 條第 2、3 項;選罷法第 36 條 | 確認 | +| 立委不分區 | 政黨得票達 5%;最大餘數法;各政黨當選名單婦女不得低於 1/2 | 選罷法第 67 條 | 確認 | +| 不在籍投票 | **2026 年沒有**;草案在 2025-12 送協商,2026-04 仍未完成。2026-01 修正只讓原住民可使用另設的投票所 | 選罷法第 57 條第 3 項 | 部分 | +| 2028 總統選舉日 | 尚未公告;依法須在任期屆滿(2028-05-19)前 30 日完成投票,並於 120 日前公告 | 總統副總統選罷法第 34、35 條 | 未公告 | + +### 檢舉賄選獎金上限 + +法務部「鼓勵檢舉妨害選舉要點」(找到的最新版本為 2023-08-22),用於 06 的「檢舉獎金誘因」: + +| 選舉 | 上限 | +|---|---| +| 總統 | 1,500 萬元 | +| 立委、直轄市長 | 1,000 萬元 | +| 直轄市議員、縣市長 | 500 萬元 | +| 縣市議員、鄉鎮市長 | 200 萬元 | +| 候選人親屬、競選辦事處負責人等 | 100 萬元 | +| 其他(含村里長) | 50 萬元 | + +預備犯減半。另有境外勢力介入(100 萬至 2,000 萬元)與賭盤(5 萬至 500 萬元)的檢舉獎金。 + +## 產出的資料包 + +格式見 `packages/protocol/src/area.ts`(`DataPackManifest`、`VillagesFile` 等)。另外產出: + +- `people.json`:人物資料庫,每個欄位附出處與擷取日期 +- `sources.json`:所有資料集的名稱、機關、版本、擷取日期、授權,給製作名單與遊戲內的資料來源頁使用 + +## 更新排程 + +| 資料 | 頻率 | +|---|---| +| 戶政人口 | 每月(但每個劇本固定一個快照) | +| 選舉結果 | 每次選舉後(選後 7 日內入庫) | +| 所得 | 每年 8 月 | +| 人物職位 | 每月,加上重大異動時手動觸發 | +| 普查、客家調查 | 有新版時 | + +## 授權與標示 + +- 授權 1 的資料需要標示來源。`sources.json` 自動產生製作名單。 +- TEDS、TWNIC 微觀資料需要申請,且有使用限制(TEDS 限非營利)。只在管線中使用其彙總結果,不重新散布原始資料。 +- Wikidata 為 CC0;Wikimedia Commons 上的照片各有授權,不使用。 diff --git a/backend/docs/14-legal-and-ethics.md b/backend/docs/14-legal-and-ethics.md new file mode 100644 index 0000000..5f24c56 --- /dev/null +++ b/backend/docs/14-legal-and-ethics.md @@ -0,0 +1,111 @@ +# 14 法律、中立與倫理 + +> 本文件是設計上的自我約束清單,不是法律意見。公開上線前請熟悉台灣選舉法與人格權的律師審閱, +> 特別是在真實選舉期間上線「真實候選人劇本」的情況。條號以 [10](10-data-sources.md) 的查證結果為準。 + +## 真實人物 + +遊戲裡的候選人是**真實的歷屆參選人**,能力分數用客觀資歷計算(docs/23「歷屆參選人與客觀資歷分數」);里長、議員對手、部長、幕僚、路人等是虛構角色。真實人物是本作最大的法律風險來源,以下是降低風險的設計。 + +### 主要風險 + +| 風險 | 相關規範(待律師確認) | 本作最容易踩到的地方 | +|---|---|---| +| 名譽權、誹謗 | 刑法誹謗罪(第 310 條)、民法人格權 | 真實人物在遊戲中被描繪成買票、發黑函、被起訴;AI 給出偏低的形象分數 | +| 選舉期間散布不實 | 公職人員選舉罷免法、總統副總統選舉罷免法中「意圖使人當選或不當選而散布不實」的條文 | 選舉期間的「真實候選人劇本」產生的模擬新聞被截圖外流,脫離遊戲脈絡 | +| 深度偽造 | 近年選罷法已針對候選人的深偽影音加重規範(條文待查證) | 用 AI 生成真人寫實肖像或聲音 | +| 姓名權、肖像權 | 民法人格權相關規定 | 寫實頭像、商業推廣中使用真人姓名或形象 | +| 照片著作權 | 著作權法 | 描摹單一新聞照片或官方照片 | +| 非政治人物 | 同上,且公眾人物程度較低,保護較強 | 企業家、藝人、村里長被捲入買票、站台、醜聞事件 | +| 冒用媒體與民調機構名義 | 名譽、商標、公平交易相關規範 | 遊戲內「某真實電視台民調」的數字被截圖當成真的民調 | + +### 設計上的界線 + +| 項目 | 做法 | +|---|---| +| 頭像 | 卡通化的向量頭像(部件目錄,docs/24);不使用照片、不描摹單一照片;不用 AI 生成真人肖像 | +| 聲音 | 不合成真人聲音 | +| 客觀資料 | 只收錄可查證的公開資料,每個欄位附出處與擷取日期 | +| 能力分數 | 用客觀資歷(歷次參選、得票、任職)計算,每項附算法與出處(docs/23)。資料管線另有一套 AI 評分(rubric-v1.md),目前沒有接進遊戲 | +| 負面事實 | 只收錄有確定判決或官方正式認定的事項 | +| 黑色行動 | 是**玩家的選擇**,不是對真人的描述。AI 控制的真實人物不使用奧步;栽贓、檢舉類新聞不點名真人犯罪 | +| 模擬新聞與民調 | 新聞台用諧音惡搞的台名(中夭、三粒、鄉民直播台),不用真實媒體的台標與商標。畫面上不標「遊戲模擬」(使用者 2026-10-26 決定,docs/18 第 41 項);只在首頁底部寫資料來源、分享圖卡角落寫「選舉小鎮・選戰遊戲」 | +| 引述 | 不捏造真實人物的發言當成真實引述。角色台詞以遊戲角色的口吻呈現,並與真實新聞明顯區隔 | +| 表態事件 | 事件都是虛構的一般情境,不寫真人說過的話。AI 控制的真實人物隨機表態只影響數字、**不上新聞**,避免替真人捏造立場;玩家自己操作的角色表態才會出現在模擬新聞 | +| AI 生成插圖 | 只用在一般場景(市場、宮廟、記者會…)與不具名的小人;不生成真人肖像、不出現政黨標誌與文字 | +| 推廣素材 | 商業推廣、廣告、商品不使用真人姓名或形象 | +| 更正與下架 | 設置更正管道與處理時限;接到當事人合理要求時可以調整評分、調整或移除特定內容 | +| 免責聲明 | 開場與人物頁說明:本作為政治模擬與諷刺遊戲,遊戲內事件、行為與評分不代表真實人物 | + +### 非政治人物的額外措施 + +- 企業家、藝人、名嘴、網紅只出現在與其公開角色相符的情境(站台、募款、推薦、媒體邀約)。 +- 非政治人物**不會成為黑色行動的執行者**,也不會被系統指派為隨機醜聞事件的當事人。玩家仍可對其送禮、邀請站台,由規則判定是否接受。 +- 村里長出現在挖樁腳、買票情境時,只以職稱與所屬里呈現在列表中;具名資料只在人物頁顯示。是否在這類情境顯示姓名,上線前再評估。 +- 媒體與民調機構的「機構效應」(民調偏差)由歷史公開資料計算並附出處,不憑印象設定。 + +### 選舉期間 + +- 真實選舉投票日前(例如 2026 年 11 月 28 日之前)是風險最高的時段。建議: + - 「真實候選人劇本」在投票日之後才公開上線,或在選舉期間只開放私人房間。 + - 選舉期間的公開房間預設使用自由劇本或自創角色。 +- 選舉封關期間(投票前 10 天),真實候選人劇本中的遊戲內民調一律不顯示真實媒體與民調機構名稱。 +- 不提供「真實候選人勝率預測」功能。 +- 社群平台推廣在選舉期間可能被歸類為政治或社會議題廣告,需要額外驗證。 + +## 政黨 + +- 使用真實政黨名稱。模型內的政黨槽位由劇本對應到當時的真實政黨(docs/03)。 +- 使用真實政黨的代表色與黨旗(使用者決定,2026-10-25)。黨旗以向量自行重繪(`web/src/game/PartyFlag.tsx`),不使用官方圖檔;民進黨旗中的台灣輪廓由內政部村里界線簡化而成。 +- 黨徽、黨旗可能有商標登記,**公開上線前**逐一確認使用條件。台灣民眾黨的黨旗尚未確認細節,目前用黨色暫代。 + +## 政治中立 + +真實人物加上真實政黨,讓中立變得更重要: + +| 檢查項目 | 做法 | +|---|---| +| 機制對稱 | 所有陣營可用的行動、黑色行動、事件機率完全相同;沒有任何政黨內建的負面特質 | +| 評分對稱 | 資歷分數的算法對所有人一致,不看政黨 | +| 事件庫審查 | 醜聞與爭議事件以抽象情境寫成,不綁定任何真實政黨或真實人物的特定事件 | +| 政見中立 | 政見只描述立場,不評論對錯;每個政見都有支持與反對的族群 | +| 預設劇本 | 首頁推薦的劇本在各政黨之間輪替 | +| 內部審查 | 每次新增內容時,由不同政治立場的人各看一次 | + +## 黑暗面的呈現 + +- 定位是諷刺與模擬,呈現台灣選舉文化中真實存在的現象及其代價。 +- 行動以抽象參數描述(規模、對象、價格),不提供任何現實中可操作的方法。 +- 奧步都有代價(例如沒有把柄就爆料會反傷自己,`packages/rogue/src/cards.ts`)。 +- 不提供真錢的選舉賭盤或投注功能。遊戲內的「地下賽馬」只是資訊來源,不能下注。 +- 原作的「假槍擊」改為「苦肉計」,避免影射特定的真實事件。 + +## 原作的版權 + +- 《臺灣模擬選戰》是軟體世界(智冠科技)的作品。 +- 不使用原作的名稱、美術、音樂、動畫、文字內容。原作頭像只解讀來做風格研究,不放進遊戲或公開頁面。 +- 玩法概念(行動種類、週行事曆、人口結構)可以參考,這是致敬,不是重製。 +- [appendix-1994-original.md](appendix-1994-original.md) 是研究紀錄,不會進入遊戲內容。 + +## 資料授權 + +- 政府開放資料多半採用「政府資料開放授權條款」,需要標示來源。製作名單中列出每個資料集與提供機關。 +- 個別資料集可能有不同條款,例如學術調查資料可能禁止重新散布原始資料,只能使用彙總結果。 + 維基百科的文字是姓名標示-相同方式分享授權,不直接複製其文字;結構化資料優先使用授權較寬的來源。 + 每個資料集的授權標註在 [10](10-data-sources.md)。 +- AI 評分的輸入資料(新聞報導)只作為評分依據,遊戲內只顯示出處連結與摘要,不轉載全文。 +- 地圖邊界資料同樣要標示來源。 + +## 遊戲分級 + +- 台灣的遊戲軟體需要依分級規定標示級別。 +- 本作涉及賄選、選舉暴力事件、政治諷刺,需要在上線前自評級別。 +- 若有未成年玩家,聊天功能需要相應的保護設計。 + +## 隱私與個資 + +- 帳號只收必要資料(暱稱、登入方式)。 +- 聊天紀錄只保存處理檢舉所需的時間。 +- 比賽紀錄(指令與結果)不含玩家個資,可以用於戰報與平衡分析。 +- 真實人物資料只收錄與其公開角色相關的公開資訊,不收錄家人、住址、私生活。 +- 遵守個人資料保護法。 diff --git a/backend/docs/18-feedback-backlog.md b/backend/docs/18-feedback-backlog.md new file mode 100644 index 0000000..c3877cf --- /dev/null +++ b/backend/docs/18-feedback-backlog.md @@ -0,0 +1,110 @@ +# 18 使用者回饋待辦(改版) + +使用者試玩後提出的所有要求,一條都不能漏。做完一項就打勾並寫上完成日期。 +排序是目前的工作順序;新的要求加在最後,再依重要性調整順序。 + +## 已完成 + +- [x] 全台縣市長/立委/總統、2018/2020 年份、捏人物、立體桌遊盤、出牌、幕僚方針、表態事件(2026-10-25) +- [x] 研究模擬選舉遊戲怎麼玩,做提案頁(2026-10-25) +- [x] 美術方向「桌遊+選戰文宣」第一版:新色票、字體、貼紙按鈕、主視覺(2026-10-25) +- [x] 補 49 個行動(設計總覽 92 個行動中遊戲原本只做 30 個)(2026-10-25) +- [x] 首頁地圖:嘉義市等小縣市加圓形熱區與縣市清單(2026-10-25) +- [x] 事件不隨機、條件不合理(總統候選人還有黨內大老站台):加條件、事件庫擴充到 49 張(2026-10-25) +- [x] 拜票做成副本(每次遭遇不同)、具名宮廟、街訪(2026-10-25;瀏覽器實測還沒做,見下方) +- [x] 小候選人平衡:免費草根牌(徒步掃街、臉書直播、志工電話,錢少時保證發兩張)、募款保底、黑馬加成(知名度低曝光效果最多 1.5 倍)、個人目標(雖敗猶榮)、公平起跑選項(2026-10-26) + +## 進行中/待做(依序) + +1. [x] (2026-10-26 完成:記者堵麥 engine/press.ts+content/press.ts,選情快報+幕僚建議可加入手牌)**新聞與戰報要有用、可以選擇**:跟你有關的新聞附 2–3 個回應選項(澄清、反擊、冷處理、乘勝追擊、搶議題),各有代價與效果;戰報改成「本週戰果+下週建議」,建議可以一鍵放進手牌。 +2. [x] (2026-10-26 完成:news/NewsRoom.tsx 取代晨報,52 中夭、54 三粒、鄉民直播台,名嘴與推文評論)**電視台播新聞的感覺**:模仿台灣新聞台的節目樣式(跑馬燈、獨家、名嘴座談、雙台不同立場報導同一件事),台名用諧音惡搞(使用者提議「中夭」「三粒」),不用真實台標,畫面標「遊戲模擬」。 +3. [x] (2026-10-26 完成:plan/TownCard.tsx 區情卡,手牌可直接打在該區)**地圖區塊點下去要有作用**:點區開「區情卡」——誰領先、年齡與政黨傾向、地方議題、宮廟、本週機會(廟會、市集)、你在這區的狀況,以及可以直接在這區打的牌、設服務處、派幕僚駐點。 +4. [~] (2026-10-26 部分完成:候選人卡片五項能力條、總統顯示副手、可換四種虛構副手類型;自創角色已有 #/create。待做:真實人物不畫肖像,Q 版頭像只給自創角色與虛構副手)**選人畫面要看得到候選人素質**:每位候選人的能力值(知名度、口才、策略、財力、人脈、魅力),總統要有正副手資訊;可以自己選搭檔、自由組隊、自己造一個角色;Q 版頭像(像動物森友會那樣捏,不用照片、不用 AI 生成真人)。 +5. [x] (2026-10-26 完成第一輪:306 個 CC0/OFL 素材在 web/public/assets(LICENSES.md 逐檔記錄);首頁改成會動的 3D 選戰小鎮 start/hero3d.ts;粉圓+凍蒜圓體(源泉圓體子集,依 OFL 改名);桌遊盤真木紋、棋子換 Q 版小人;住宅綠屋頂換磚紅避免政黨色聯想)**美術全面改版(首頁到遊玩畫面都要好玩)**:用網路上免費、不用標示作者的素材(CC0、OFL 字型,含 GitHub 上的開源素材),整理授權清單 web/public/assets/LICENSES.md。 +6. [x] (2026-10-26 完成第一輪:audio/music.ts 背景音樂交叉淡入、audio/sfx.ts 改用 CC0 音檔;首頁進行曲、規劃配樂、新聞片頭、開票夜緊張配樂、當選號角+派對音樂;發牌飛入、週轉場蓋章、首頁標題落下動畫;設定可關音樂)**動畫與音樂**(像人選之人造浪者):首頁最重要;出牌飛入、週轉場、開票夜;音樂可在設定關掉。 +7. [x] (2026-10-26 完成:改用本機 grok 補齊,見第 21 項)**卡牌插圖補齊**:codex 用量重置後背景補生(art/regen-later.sh),新加的 4 張草根/街訪牌也要生。 +8. [x](2026-10-26 部分完成:1996–2024 歷屆總統、2014 縣市長可玩;1990 年代縣市長等見 docs/19-classic-battles.md) **經典之戰**:從台灣有選舉紀錄開始到現在的歷史資料(先 2010 縣市合併後,再處理 1990 年代舊縣市代碼,例如 1994/1998 臺北市長、2000 總統)。 +9. [x] (2026-10-26 完成:開始畫面「自己組隊」,content/lineup.ts,客串的人知名度與組織打折)**自己組隊參選、虛構對決**:候選人組合不一定要真實。 +10. [x] (2026-10-26 完成:開始畫面「規則設定」,content/rules.ts)**規則不要訂太死**:週數、資金倍率、AI 難度、事件多寡、黑暗面開關、公平起跑。 +11. [x] (2026-10-26 完成:Playwright 整場試玩無錯誤;修正副本花費讓資金變負數的 bug)瀏覽器實測副本、新行動、免費草根牌、本場目標顯示。 +12. [x] (2026-10-26 完成:13-roadmap.md 加上「改版:選戰卡牌」一節,記憶檔已更新)更新 13-roadmap.md、記憶檔,最後向使用者報告(附資料來源連結)。 + +## 第三輪回饋(2026-10-26 凌晨) + +13. [x](2026-10-26 完成:頂部電視按鈕、跑馬燈「看電視」) **電視要能隨時打開**:遊戲中任何時候都能開電視看本週新聞、回應堵麥、看選情快報。 +14. [x](2026-10-26 完成:所有候選人都有 Q 版頭像,可換頭像) **候選人看板要有頭像**:像截圖裡的號次看板(王育敏)只有字很無趣;每位候選人都要有 Q 版頭像(卡通、不照真人長相畫),玩家可以自己改頭像。 +15. [x](2026-10-26 完成:board3d/town.ts 各區依密度長出店面住家樹;board3d/effects.ts 出牌演出、鏡頭拉近) **遊戲畫面也要像首頁的 3D 選戰小鎮**:地圖上的每一區要有房子、樹、人;出牌時在地圖上演出(宣傳車開過去、群眾聚集、彩帶、金幣),候選人是會動的小人。 +16. [x](2026-10-26 完成:點小人、宣傳車、舞台有反應;15 秒拜票挑戰) **首頁要更有趣味性**:小鎮可以互動(點小人會跳、點宣傳車會喊凍蒜、點舞台放煙火、小小拜票遊戲),選候選人像遊戲的選角畫面。 + +17. [x](2026-10-26 完成:歷屆總統資料補齊後卡庫自動涵蓋 1996–2024) (2026-10-26 部分完成:同一人各時期的版本卡、人物卡庫、亂數組合、歷屆總統大亂鬥入口;歷屆資料等經典之戰補齊)**人物卡庫**:開一場總統選戰時,可以從歷屆所有總統候選人挑人、亂數排列組合或捏新人;同一個人有不同時期的版本(例如韓國瑜 2018 高雄市長版、2020 總統版)。 +18. [x](2026-10-26 第一輪完成:新漫畫肖像系統(臉型、眼鏡款式等),40 位政治人物照公開肖像設定特徵,#/faces 對照頁;待補:更多髮型、細框眼鏡) **紙娃娃系統要更好看、要像本人**:找開源頭像系統(候選:DiceBear 的各種風格,授權各不同),卡通但一看就知道是哪位政治人物(髮型、眼鏡、髮色、臉型等招牌特徵的預設)。 +19. [x](2026-10-26 完成:文宣品產生器;134 位候選人的真實標語附出處,docs/20-campaign-slogans.md;查不到的 68 位印「請支持 N 號」) **每年的競選標語與文宣品**:每位候選人當年的真實競選標語(附出處,查不到就不寫,不捏造);遊戲裡的文宣品都要做出來(看板、旗幟、傳單、宣傳車看板、背心、帽子、面紙包、扇子等),印上號次、名字、標語、頭像。 + +20. [x] (2026-10-26 完成)**電視要像真的播報**:自動一則一則播、有進度條、播完切到堵麥;三台版面完全不同(中夭聳動快訊、三粒名嘴座談、鄉民台直播加推文)。 +21. [x] (2026-10-26 完成:本機 grok CLI 補齊 38 張卡牌插圖,art/gen-card-grokcli.sh)**用 grok 生圖**。 + +## 第四輪回饋(2026-10-26 早上) + +22. [x] (2026-10-26 完成:拿掉舊的「晚間新聞」,每週只開一次電視;主播語音被打斷時不再連續跳下一則)**每週跳出兩個新聞、一個主播在講話卻不能選、很快跳過像壞掉**:原因是舊版晚間新聞(設定裡的「每週播晚間新聞」)和新版電視連續播;晚間新聞的語音被打斷時會誤判成念完,一則不到一秒就跳過。 +23. [x] (2026-10-26 完成;晚上再跑一次舊玩法整場 11 週無錯誤。原註:拿掉「幕僚方針」,幕僚每週各帶一張專長牌,沒派到的時間跟著玩家打牌的區跑;新增組合拳、打對台、推薦區;平衡模擬:勢均力敵的桃園,懂戰術打法勝率 55–80%、一般打法 15–20%。尚未整場瀏覽器實測)**出牌和幕僚自動做事重複,要整合,而且要好玩一點,現在很無聊**。 +24. [x] (2026-10-26:改造計劃 https://claude.ai/artifact/UdMUGSaWTcp8jNZQS9w55B 使用者同意照建議做;第一階段見 docs/21;晚上完成第 2–4 階段,見 docs/22-rogue-v2.md;只剩線上排行榜要另外評估)**遊戲看起來不夠精緻、可玩性不夠,請以現有基底改成更有趣、可玩性更多、機制更猛、讓玩家會一直黏著的遊戲**:先列改善計劃給使用者看(不先動工),計劃確認後再分階段做。 + +## 第五輪回饋(2026-10-26 晚上) + +25. [x] (2026-10-26 完成,見 docs/22-rogue-v2.md:下一站七種、牌升級與關鍵字、能力牌、狀態牌、插旗翻轉、隔壁區擴散、32 位幕僚、對手性格與大型造勢預告、記者堵麥、電視辯論、民調、匿名黑函、選前之夜、逆風 0–10、22 個成就與圖鑑、每日一戰、政治生涯、朋友挑戰連結、結果圖卡、開票夜、新手教學、手機直式、存檔)**選戰卡牌趣味性變多了:繼續把該做的都做完,也要更多有趣的遊戲機制**:照改造計劃做第 2–4 階段(精緻度、手機直式、出牌動畫、新手教學、開票夜、電視與堵麥接進新玩法;更多牌與幕僚、對手性格、電視辯論、黑函危機、逆風難度、成就圖鑑、全台縣市長/立委/總統;結果圖卡、每日一戰、政治生涯),並加新機制(路線選擇、牌升級、插旗與翻轉、記者追問牌等),設計寫在 docs/22-rogue-v2.md。 +26. [x] (2026-10-26 完成)使用者提供遊戲開發工具清單(github.com/gamedev-skills/awesome-gamedev-agent-skills):讀過 card-game、game-feel、game-ui-ux、save-systems、roguelike;大多是 Godot/Unity/Unreal 專用,不安裝,套用其中的原則(存檔加版本、效果用資料描述、回饋分輕中重三級、可關閉畫面震動)。 +27. [x] (2026-10-26 完成:rogue/src/data.ts INTENT_LABELS、content.ts、scenes.ts)對手是真實人物時,對手的行動不能寫成「抹黑」「爆料」:改成「批評你的政見」「到你的票倉拉票」;黑函一律是「匿名黑函」,不算在任何候選人頭上。 + +## 第六輪回饋(2026-10-26 晚上) + +28. [x] (2026-10-26 完成,見 docs/22「首頁」:3D 小鎮+示範手牌、主按鈕依進度、大廳、怎麼玩、真實資料、經典模式搬到 #/classic;另外開票夜加地圖、內容擴充、拆分下載)**選戰卡牌就是主要玩法;繼續做;首頁重新想**:首頁改成以選戰卡牌為主(3D 選戰小鎮保留),一進來就能繼續上一局、玩教學、每日一戰、自由選戰、政治生涯;舊的十週行程版移到「經典模式」。 + +## 第七輪回饋(2026-10-26 深夜) + +29. [x] (2026-10-26 完成:新牌放在抽牌堆最上面,下週一定抽到;政治生涯帶過來的牌第一週就抽到)**從一些地方拿到的牌好像都沒出現在手牌**:原因是新牌放進棄牌堆,要等抽牌堆用完洗牌才回來(第 1 週拿的牌第 2 週 200 局都抽不到)。 +30. [x] (2026-10-26 完成:前端經典模式畫面、伺服器 /api/matches 等 API 刪除;刪前打包在 archive/classic-mode-*.tar.gz;選民模型、資料包、劇本、引擎保留,新玩法的開局底盤在用)**經典模式都刪除**:只留選戰卡牌(使用者:「現在這樣很讚」)。刪除前先打包備份。 +31. [x] (2026-10-26 完成:週末結算加「本週戰果」—拉到、被拉走、擋下、全市差距變化;打對台、澄清、事實查核擋下的票逐條列出;狀態列顯示本週已拉到;出牌爆分也顯示擋下幾票)**攻守的效果要更明顯、加分項目好像不見了、做什麼都被扣分**:週末結算只列對手的扣分,出牌加的票沒算進去;擋下的票也要看得到。 +32. [x] (2026-10-26 完成,見 docs/23:論點連擊辯論、三個選戰小遊戲(下一站)、政策工坊(對象×做法×財源,自己取名)、政策島 12 棟建築與政績點)**更好玩的玩法、選戰小遊戲、真的可以寫政策、政策島,增加黏著度與多樣性**(參考遊戲開發工具清單):計劃 https://claude.ai/artifact/RxqGeu3Lsi67HizemA8aGS,等使用者確認。 +33. [x] (2026-10-26 完成,見 docs/23:里長→議員→立委→縣市長→總統五關,可跳過前兩關;里長用真實的里、議員用 2022 議員選區與最後一席;每次當選做任期小遊戲(陳情、質詢、審預算、講解法條、搶主席台鬧劇版、預算與颱風);五項能力 0–5 級)**完整的政治生涯與歷練**:例如到立法院講解法條、打架:先列計劃確認。 +34. [x] (2026-10-26 完成方案 A,見 docs/23:1994–2022 縣市長、議員 14,004 筆參選紀錄串成 7,588 人,#/people 個人頁五項客觀資歷分數附公式與出處;玩真實候選人時依之前的紀錄給溫和的開局能力。方案 B(AI 整理生平政績)使用者沒有選,沒做)**歷屆縣市長與議員全部寫清楚,抓生平政績,幫每個候選人評分**:牽涉真實人物評價與 API 費用,先列計劃確認。 + +35. [ ] (2026-10-26 討論過、給了三個方向和大富翁/2077 樣品;使用者決定風格先維持原本的,暫緩)**風格很不華麗、像無聊的網頁、非常 AI**:改完這一輪所有程式之後,先跟使用者討論問題出在哪、可以怎麼修正(附例子),討論後再動手。 +36. [x] (2026-10-26 完成:開局記下選區名稱,狀態列、開場、開票夜、結果圖卡都寫「高雄市第 4 選舉區立委」;新增 /api/rogue/runs/:id/area,立委選區的地圖只畫選區內的村里、放大到選區,選區外淡化;總統關改用縣市為單位畫地圖;開票夜改成各區同時一點一點開、顯示開票進度百分比,票數和百分比同步,開票三成後才提示換人領先)**開票怪怪的、選高雄居然只有幾區**:生涯第一關是立委,選高雄會分到一個立委選區(例如第 4 選區只有林園、大寮、仁武、鳥松 4 區),資料沒錯;但畫面只寫「高雄市立法委員」、地圖畫整個高雄,選區縮在角落;開票一次開完一整區,只跳幾下,票數還是 0 時百分比就先出現。 + +## 第八輪回饋(2026-10-26 深夜) + +37. [x] (2026-10-26 完成:原因是對手越後面越強(行動 2→4 個、每週 +7–9%、第 7 週大型造勢 ×2.4),你的力量不變,加上開票日聲勢高的一方帶出比較多未表態的票(看不到);調緩對手成長(每週 +3.5%/後發制人 +5%、起始強一點)、行動到最後一週才 4 個、大型造勢 ×2;狀態列加「今天開票預估(含聲勢帶出的未表態)」,第 5 週起快報提醒後期要佈樁、打對台。模擬:隨手玩後期只小幅下滑,勝率 36–43% → 48–59%,打得好仍 100%,逆風 10 級打得好約 50%)**為什麼前面領先、後來節節敗退?是操作問題嗎**:使用者 15 局有 13 局第 4–5 週領先、第 6 週後一路掉。 +38. [x] (2026-10-26 完成,見 docs/23「每週流程整合」:快報變跑馬燈、堵麥變手牌裡的事件牌、民調自動、黑函和堵麥結果用提示、全市牌點兩下打出、結算和下一站同一個面板、門上直接攤開內容一鍵拿;一般週出牌以外 7–9 下 → 2–4 下)**流程整合、操作越簡略越好,但必要的功能要留**:一週的視窗與點擊太多(快報、劇情、結果、結算、下一站、站內選擇)。 +39. [x] (2026-10-26 使用者看過兩種大廳樣品 https://claude.ai/artifact/PUwM86knNyP8JNojyzWMdN 後決定:「風格先維持原本的」,不改風格;第 35 項一併暫緩)**風格:喜歡《電馭叛客 2077》或《大富翁》的風格;先改大廳(大廳風格很重要),進到遊戲裡也要;卡圖可以重畫;參考大富翁、電馭叛客 2077**:只參考手感與視覺語言,不用對方的商標、角色、字型。先給兩個方向的大廳樣品讓使用者選。 +40. [x] (2026-10-26 完成:首頁只留三層——3D 小鎮+一個主按鈕、四種玩法、一排小連結;拿掉「一週怎麼玩」「真實資料」「牌與幕僚預覽」和重複的連結(圖鑑原本出現三次、政策島與歷屆參選人兩次、政治生涯兩次),玩法卡說明縮成一行,手機版玩法排兩欄;電腦版一個畫面看完)**首頁排版太混亂了,簡單一點**。 +41. [x] (2026-10-26 完成:拿掉畫面上所有「遊戲模擬」「不代表真實選情」「(虛構)」「(虛構人物)」:電視快報、辯論與堵麥標題、黑函、民調、開票夜、結果頁、說明、大廳、生涯頁、任期遊戲、對手介紹;只剩首頁最底下一行資料來源,和分享圖卡角落「選舉小鎮・選戰遊戲」(第 48 項改名前是「凍蒜 2026」)(圖會離開遊戲、上面有真實人物);不捏造真人引述、真實人物不用奧步照舊)**把那些模擬、虛擬的字眼全部拿掉,看起來不有趣**。 +42. [x] (2026-10-26 完成,見 docs/23「政策落地」:每種政策對象在島上有一棟家,家每級 +10%;工坊的政策卡下面列小島加成;小島建築名牌掛政策條、說明列出落在這裡的政策)**小島建設跟政策工坊有啥關聯**:原本只有政策研究院決定帶幾份,其他加成看不到。使用者同意先做「把加成寫出來」再做「政策在島上落地」。 +43. [x] (2026-10-26 完成:圖鑑改成全螢幕卡冊〔雙頁、索引貼、沒收錄的灰卡寫怎麼拿到〕、捏人物改成競選總部更衣間〔化妝鏡舞台、七個分頁、衣櫃〕、歷屆參選人改成選舉檔案室、政策島與政治生涯都用同一個全螢幕場景外框〔ui/GameScene.tsx〕,選戰畫面加換週橫幅和「地圖放大」;第一步:首頁=遊戲標題畫面——全螢幕 3D 小鎮、不捲動,左邊大選單〔繼續/開始選戰、自由選戰、每日一戰、政治生涯、新手教學〕,下面一排圓形圖示〔圖鑑、政策島、參選人、捏人物、小遊戲〕,自由選戰在畫面上跳出設定,#/rogue 選戰大廳也用這個畫面;手機版小鎮在標題和選單中間。其他畫面的計劃等使用者確認)**首頁跟進去的每一組東西都要更遊戲一點,看起來很網頁,一點都不沉浸式**:風格(顏色、字型、3D 素材)維持原本的,改骨架。 + +## 第九輪回饋(2026-10-26 深夜) + +44. [x] (2026-10-26 完成,見 docs/23「練等」:careerRules.ts 等級 1/3/5/8/12 開關卡、經驗表、落選也有經驗、逆風加成、技能點加點與重新分配;任期前有任務簡報與一二三步說明;圖鑑卡冊沒收錄的灰色顯示並寫怎麼拿到;Playwright 實測選角→出發→打完回來戰報→挑帶走的東西→上任→任期→回地圖升級)**政治生涯要像練等,可以重複選、拿經驗升級、點技能;任期要說明怎麼玩;圖鑑沒拿到的也要看得到(灰色)**。 +45. [x] (2026-10-26 完成,見 docs/23「收集卡」:玩過的參選人彩色、沒玩過灰色但都看得到;檔案裡一年一張參選證;右上角「收集 N/7,588」,另有「收集冊」分頁只列玩過的人)**參選人要像收集卡片**:用過的候選人有顏色,沒用過的灰灰的,但一樣看得到說明和他當年度的證件(那一年的參選登記:選舉、選區、號次、政黨、得票)。 +46. [x] (2026-10-26 完成:start/hero3d.ts 板子加深、馬路內縮,後排房子依實際尺寸排在馬路外側、不超過板子;樹改種在四個角和兩側草地;連拍 6 張確認宣傳車一圈都沒被擋)**首頁的動畫壞掉:宣傳車在繞,房子跟樹擋在車上**:原因是後排房子太深、壓到馬路,前面和兩側的樹種在馬路上。 +47. [x] (2026-10-26 完成,見 docs/23「生涯畫面」:選角畫面的角色卡右上角可以丟掉〔遊戲內確認視窗〕,「換人物」改用遊戲內確認、不再用瀏覽器 confirm();路線圖換成和首頁同一套的 3D 桌遊棋盤〔五關五棟建築、沒解鎖灰色土路、選上插旗、點哪關宣傳車開過去〕;角色卡、出征卡、選角三步驟、戰報蓋章都重做;手機用分頁切換、整頁不捲)**政治生涯的人物不能刪除;裡面不精緻;路線圖很醜**。 + +## 第十輪回饋(2026-10-26 深夜) + +48. [x] (2026-10-27 完成:網頁分頁標題、首頁標題〔選舉小鎮,英文小字 ELECTION TOWN〕、3D 舞台看板、分享圖卡〔選舉小鎮・選戰卡牌、選舉小鎮・選戰遊戲〕、存圖檔名 election-town-result.png、說明文件標題都改掉;宣傳車看板改「請支持!」。遊戲裡的競選口號「凍蒜」〔當選的台語〕保留:小遊戲「造勢喊凍蒜」、當選標題「某某凍蒜!」、成就「凍蒜!」。存檔的內部代號〔tongsuan.*〕不改,改了玩家的進度會不見)**整個遊戲名稱改成「選舉小鎮」**:不要「凍蒜」,也不要加年份。 +49. [x] (2026-10-27 完成:伺服器沒寫類型的劇本當作縣市長,桃園兩份劇本也補上 kind;里長關的選舉人數改成「現在的戶籍 20 歲以上人口 × 0.9987」〔2024 總統大選全國選舉人數 ÷ 2023 年 12 月 20 歲以上人口,桃園逐里 0.987–1.013〕,和現在的里界一致;2022 年後新設的里〔桃園 13 個〕也能選議員、地圖畫得出來)**選桃園時選里長就出錯;確認資料是正確的**:原因是桃園 2022 是早期手做的劇本,沒寫選舉類型,伺服器開里長關的檢查判定「不是縣市長劇本」。另外核對發現:里長關用的選舉人數是 2020 年總統大選、2020 年的里界,但里的名單是 2026 年的(桃園這幾年重劃過,41 個里差超過一成五)。 +50. [x] (2026-10-27 完成第一階段與畫風,見 docs/24:部件目錄〔protocol/data/avatar-catalog.json,舊代號沿用、看不懂的換預設〕、新部位〔帽子、口罩、背心外套、彩帶、胸前、手持物、外框〕、第一批 27 件原創向量部件、服裝店 #/shop〔試穿、小鎮幣、每週輪替 6 件〕、小鎮幣〔每局發、分免費與付費兩本、無期限〕、Q 版大頭/復刻像素/平面貼紙三種畫風〔全遊戲設定+每個角色可選,真實政治人物也能用〕、#/avatar-check 部件檢查頁;帳號與真錢照決定沒做。使用者「就按照你的建議」:小鎮幣、第一批 24 件照清單、真實政治人物只開正式類、畫風先做 Q 版大頭+復刻像素〔貼紙風順手〕、每週輪替 6 件但一年內會再上架;帳號與真錢〔第三階段〕先不做。進行中。方案:https://claude.ai/artifact/WrMJfdNEgGPggv9vbhGXcb 第二部分;完整方案 docs/24-avatar-shop-plan.md)**紙娃娃系統要更豐富;以後要賣商城、可以隨時加新東西;也許加某種卡通樣式**:先想怎麼做、列方案給使用者確認。 +51. [ ] (2026-10-27 查過:捏人物名字欄、政治生涯快速捏人物、檔案室搜尋、政策工坊取名,在 Chromium〔含模擬注音組字〕和 iPhone 的 WebKit 都打得進去,重現不出來。先把捏人物講台上寫「你的名字」的名牌改成按鈕〔點了跳到名字欄、游標放好〕,因為它看起來像輸入框、原本點了沒反應;等使用者說是哪個畫面、哪台裝置)**輸入名字的地方無法輸入**。 +52. [x] (2026-10-27 完成:pipeline 新增 `election-data parties`,從中選會選舉資料庫 1994–2024 找出真的推過候選人的 142 個政黨〔排除無黨籍、連署、2005 年國代「某某等 N 人聯盟」〕,產生 protocol/parties.ts;伺服器依清單驗證;捏人物列出三大黨+最近還有推人的 6 個黨+無黨籍,「更多政黨」可以搜尋全部、看推出幾人當選幾人;政治生涯快速捏人物有下拉選單;劇本裡有同黨候選人就取代。三大黨以外沒有查證過的政黨色,用灰色、不畫黨旗;選民基本盤和無黨籍一樣)**政黨太少,台灣出現過的政黨都要有**。 +53. [x] (2026-10-27 完成,見 docs/23「出身與黨的資源」:使用者「就按照你的建議」——做法 B 有得有失、小黨與無黨籍政治生涯經驗 ×1.2、自由選戰也套用出身能力和黨的資源但選民基本盤照真實;10 張出身專屬牌、黨中央風波、黨部動員掃街;模擬調平衡後打得好的玩家各黨 96–98%。方案:https://claude.ai/artifact/WrMJfdNEgGPggv9vbhGXcb 第一部分,推薦 B「有得有失」)**能力是不是按出身可以不同;按照政黨有加成(不能點,但就是多一些:加入大黨能力好、小黨比較爛),還是覺得有平衡?**:牽涉玩法,先列方案給使用者確認(現況:出身已經有不同加成、政黨影響開局資金和樁腳,但畫面上沒寫出來)。 +54. [x] (2026-10-27 完成,見 docs/23:加入 1996–2024 總統副總統、1995–2024 區域與原住民立委、2008–2024 不分區立委,共 4,160 筆;參選紀錄 18,163 筆、9,361 人〔874 人和原本的縣市長、議員紀錄串在一起〕;檔案室分頁「全部/總統/立委/首長/議員」+收集冊;參選證寫搭檔、不分區寫名單排名和政黨票。沒收:立委補選〔原始檔沒有投票日〕、1995–2004 不分區與僑選〔沒有名單〕;出生年差 1 年的 10 組同名〔例如趙少康〕沒有自動合併,列在 records-report.md;2026-10-27 使用者同意照「同名、同黨、出生年只差 1 年」合併:合併張俊雄、葉宜津、蔣乃辛,趙少康〔1994 新黨、2024 國民黨,政黨不同〕列入人工確認名單 MANUAL_SAME 一起合併;都標比對信心低、檔案裡寫原因;其他 6 組政黨不同或沒有政黨,看起來是不同人,不合併)**歷屆參選人沒有總統嗎?**:檔案室目前只有 1994–2022 縣市長、議員。 +55. [x] (2026-10-27 完成,見 docs/23「里長關」:使用者 5 局都在大溪區僑愛里開局落後約 12 個百分點;政黨強弱對里長開局的影響改成最多 ±3 個百分點,同一個里民進黨開局變成 42.5% 對 44.5%;模擬隨手玩 75%、打得好 96%。另外「落後很多也要有大絕招翻盤」見第 57 項)**里長是不是差太多了,根本打不贏?** +56. [x] (2026-10-27 完成:出征卡上先挑區再挑里,附現在的選舉人數;不挑就隨機;換里後議員選區跟著換)**里長都選同一里,應該要可以自己選要選哪一里**。 +57. [x] (2026-10-27 完成,見 docs/23「大絕招與真實開局差距」:選戰畫面「結束這週」上面有大絕招集氣鈕,集滿挑三招之一玩小遊戲;三招強度一致;政治生涯縣市長、立委、總統照真實底盤、最多落後 10 點〔試過 15 點太難〕;模擬:落後 10 點時打得好的人翻盤勝率 10%→48%。使用者「把它做完,都按照你推薦的」:落後越多集越快、基本 1 次+落後超過 8 點第 6 週再一次、里長維持縮小的差距、縣市長/立委/總統保留真實差距;三招接三個小遊戲。規則、伺服器、選戰畫面、模擬都做好〔見 docs/23「大絕招與真實開局差距」〕;縣市長、立委、總統照真實底盤、最多落後 10 點。已用瀏覽器實際玩過一次放出大絕招)**差很多也可以(像沈伯洋跟蔣萬安現在一樣),但要有大絕招可以放,不然很硬;有什麼遊戲可以玩,玩得好有機會翻盤**:新玩法,先列方案給使用者確認。 +58. [x] (2026-10-27 完成,見 docs/23「選戰小遊戲」:小遊戲大廳、三級難度與星等、最佳紀錄、全螢幕、示範、倒數、暫停、結束畫面;掃街握手 20 秒、加里長伯與拿相機的記者;造勢喊凍蒜 8 小節、亂按扣分;看板卡位修好提示字重疊、手機點兩下放置;選戰的小遊戲站也改成全螢幕)**小遊戲看起來不完整,請完整做完**。 + +## 約束(每一項都適用) + +- 真人肖像不用照片、不用 AI 生成真人寫實肖像。 +- (2026-10-26 使用者決定)畫面上不再標「遊戲模擬」「虛構」,只在首頁底部和分享圖卡寫是遊戲;不捏造真人引述;栽贓、檢舉類新聞不點名真人犯罪;AI 控制的真實人物不使用奧步。 +- 宮廟只用名稱、主祀神祇、鄉鎮。 +- 素材只用 CC0/公眾領域/OFL 或明確允許免標示商用的授權,逐一記錄出處。 diff --git a/backend/docs/19-classic-battles.md b/backend/docs/19-classic-battles.md new file mode 100644 index 0000000..f8856a1 --- /dev/null +++ b/backend/docs/19-classic-battles.md @@ -0,0 +1,87 @@ +# 19 經典之戰:歷史選舉劇本 + +> 2026-10-26。使用者要「從最早的選舉紀錄一路到現在」。本文件記錄已經做好的部分。 +> 2010 年以前的地方選舉(舊縣市代碼、1994/1998 臺北市長等)還沒做。 + +## 已經可以玩 + +| 劇本組 | 場數 | 資料包 | 政黨傾向用的選舉 | +|---|---:|---|---| +| 2014 縣市長(`2014-local`) | 22 | `<縣市>-before-2014-11-29` | 2012 總統、2012 政黨票、2010 五都市長+2009 縣市長、同年議員 | +| 2016 總統 | 1 | `00000-before-2016-01-16` | 2014 縣市長、2014 議員、2012 總統、2012 政黨票 | +| 2012 總統 | 1 | `00000-before-2012-01-14` | 2010/2009 縣市長與議員、2008 總統、2008 政黨票 | +| 2008 總統 | 1 | `00000-before-2008-03-22` | 2006 北高市長+2005 縣市長、2004 總統、2008 政黨票 | +| 2004 總統 | 1 | `00000-before-2004-03-20` | 2001 立委(區域)、2000 總統 | +| 2000 總統 | 1 | `00000-before-2000-03-18` | 1998 立委(區域)、1996 總統 | +| 1996 總統 | 1 | `00000-before-1996-03-23` | 1995 立委(區域) | + +校準(`apps/sim/out/calibrate-<組>.md`;誤差是各候選人得票率與真實結果的平均絕對誤差,百分點): + +| 劇本組 | 場數 | 全區誤差 | 各區誤差 | 各里誤差 | 各里最差 | +|---|---:|---:|---:|---:|---| +| 2014 縣市長 | 22 | 0.38 | 2.59 | 2.95 | 南投縣 4.53 | +| 2016 總統 | 1 | 0.15 | 3.75(縣市) | 3.37 | | +| 2012 總統 | 1 | 0.24 | 2.99(縣市) | 2.81 | | +| 2008 總統 | 1 | 0.41 | 3.26(縣市) | 3.17 | | +| 2004 總統 | 1 | 0.34 | 5.48(縣市) | 5.41 | | +| 2000 總統 | 1 | 0.22 | 4.58(縣市) | 4.16 | | +| 1996 總統 | 1 | 0.35 | 5.18(縣市) | 5.49 | | + +- 2014 連江縣兩位候選人都登記國民黨,同一個槽位,預設 7 輪收斂不了(3.53),用 `--only 09007 --rounds 14` 補跑到 1.04。 +- 2004 年連戰、宋楚瑜搭檔(中選會候選人檔),但資料包只看國民黨的票,2000 年宋楚瑜(無黨籍)與 2001 年親民黨的票算成中間選民, + 縣市誤差 7.77。`ElectionDef.blocs` 讓這兩場在**算政黨傾向時**把那些票算在國民黨一側(history.json 不變),誤差降到 5.48。 + 只用中選會資料本身能佐證的合併(同一組搭檔),沒有另外判斷政黨陣營。 +- 1996、2000 年仍比近年差(約 5 個百分點):1996 只有 1995 立委一場可以算傾向;2000 年宋楚瑜以無黨籍拿到 37%,之前沒有他的得票可以參考。 +- 2014 臺北市柯文哲以無黨籍登記,用「其他」槽位,各里誤差仍只有 0.94。 + +加上原本的 2018、2022 縣市長與 2020、2024 總統,總統選舉從第一次直選到現在八屆都有, +「虛構對決」的「歷屆總統候選人」分頁自動收進每一屆的候選人(含副手)。 + +建置指令(`data/pipeline`): + +``` +election-data local --year 2014 +election-data races --year 2016 # 2012、2008、2004、2000、1996 同樣;這些年份只做總統 +election-data pack --county all --historic --since 2010-01-01 --before 2014-11-29 --past-only +election-data pack --county 00000 --historic --since 2012-01-01 --before 2016-01-16 --past-only +# 其餘總統:--since 2008-01-01/2004-01-01/2000-01-01/1996-01-01/1995-01-01,--before 該屆投票日 +node apps/sim/src/calibrate-local.ts --set 2014-local # 其他組同樣 +``` + +- `--historic` 加入 1995–2014 年的選舉;`--since` 只讀「上一輪」;`--past-only` 不把之後的開票結果放進資料包。 +- 2016 年以前的經費上限人口用戶政司的縣市統計表(`population.load_county_population`): + 97 年起用月報,87–96 年用每年一份、每月一張工作表的村里鄰戶數表,84 年只有年底數字(1996 總統用 1995 年底)。 + 下載頁要先拿 CSRF token(`fetch.download_form`)。107 年 5 月和村里資料逐縣市核對一致。 +- 2014 六都的上限和中選會公告逐一一致。1996–2008 總統用現行公式推估,**當年的法條與公告數字還沒核對**。 +- 監察院平臺沒有 2018 年以前候選人的政治獻金申報,這些劇本所有候選人都用最低資金,備註有寫。 +- 2012、2016 年的區域立委沒做:2018 年以前沒有村里的月人口,算不出選區的經費上限;2012 年的選區也和現在不同。 + +### 舊代碼怎麼對 + +2014 年以前的資料夾不是內政部代碼,而是中選會自己的流水號(2012 年新北市是 `02/000`、2008 年臺北縣是 `03/001`), +所以用名稱對照(`legacy.py`): + +1. 縣市名稱 → 目前的縣市代碼(臺北縣→新北市、臺中縣+臺中市→臺中市、臺南縣+臺南市→臺南市、高雄縣+高雄市→高雄市、桃園縣→桃園市)。 +2. 鄉鎮去掉最後一個字比對(板橋市→板橋區)。例外表 `TOWN_ALIASES`:舊臺南市中區、西區→中西區;**高雄縣三民鄉→那瑪夏區**(不能對到高雄市三民區)。 +3. 村里去掉「村」「里」比對,異體字(舘/館、脚/腳、槺/糠、壳/殼、峯/峰)先統一;目前名稱裡的私用區字元當萬用字元。 +4. 目前的名稱優先,再找 2018 年以後各時點的戶政名稱(之後合併的里會對到舊代碼,列為孤兒代碼)。 +5. 對不到的里記在「鄉鎮代碼+000」;檔案本身缺漏的(得票列或投票概況少於縣市總計)記在「縣市代碼+000000」。 + 這兩種代碼不會撞到真的村里,只算進總數,所以**每個縣市的總數都和中選會一致**(2004 總統例外,見下)。 + +涵蓋率(有效票對到現存村里的比例):2012 總統 98%、2008 總統 98%、2004 總統 97%、2000 總統 97%、1996 總統 96%; +只對到鄉鎮的 0.5–2.4%,其餘是 2018 年以後才合併的里。臺南市在 2018 年以後有村里整併,約 11% 的票只對到已不存在的舊代碼; +嘉義市 2008–2010 年有 19% 的票所在的里後來重劃,只對到鄉鎮。 + +總統劇本的地圖一個縣市一區,所以村里層級的缺口不影響開票對照;它只影響資料包的政黨傾向(對不到的里用鄰里補值)。 + +### 已知的資料問題 + +| 選舉 | 問題 | 處理 | +|---|---|---| +| 2004 總統 | 約 50 個里的得票列與投票概況對不上(例如臺北縣:投票概況把鄉鎮最後一個里記到下一個鄉鎮;有的里得票列重複) | 村里段是全縣市流水號,用號碼找回;得票加總仍比中選會多 1,851 票(萬分之 1.4),測試放寬 | +| 2004 總統 | 桃園縣的鄉鎮小計列錯置 | 不用鄉鎮小計,只用村里列與縣市總計 | +| 2008 總統 | 3 個里在得票檔有、地名檔沒有 | 記在鄉鎮層級 | +| 2001 立委 | 臺北縣總計比各里加總多 2,096 票 | 差額記在縣市層級 | +| 2014 地方 | 跨村里投開票所寫成村里段 9999 | 當成跨村里代碼 | +| 舊 elpaty | 無黨籍寫成「無」,總統連署參選寫成「連署」 | 都當無黨籍 | +| 2008 | `2008 12任總統` 與 `20080322-總統` 兩份,前者選區欄是 00 | 用後者 | diff --git a/backend/docs/20-campaign-slogans.md b/backend/docs/20-campaign-slogans.md new file mode 100644 index 0000000..eb18e5b --- /dev/null +++ b/backend/docs/20-campaign-slogans.md @@ -0,0 +1,183 @@ +# 20 — 真實競選標語(看板、旗幟、文宣用) + +> 一句話:範圍內 202 位候選人,**134 位找到有出處的真實標語**(high 84、medium 50),另外 68 位查不到可靠出處,**沒有收、也沒有自己編**,列在文末。 + +資料檔:`backend/data/build/people/slogans.json`(UTF-8,依年份新到舊、再依選舉排序)。 + +## 每一筆長什麼樣子 + +| 欄位 | 說明 | +|---|---| +| `name` | 候選人姓名,照選票寫法(例:`谷辣斯.尤達卡 Kolas Yotaka`) | +| `year`、`race` | 選舉年份;`總統`、`臺北市長`、`宜蘭縣長`……地名用「臺」 | +| `party` | 選票上的推薦政黨;無黨籍為 `null` | +| `runningMate` | 只有總統選舉有:副總統候選人 | +| `slogans` | 1–3 句標語,**第一句是主標語**,看板預設用它;其餘是後期或次要標語 | +| `joinedWithComma` | `true` 表示原文是兩行或用空白隔開,我們用全形「,」接起來(共 9 筆) | +| `confidence` | `high` 或 `medium`,判定方式見下 | +| `color` | 只有報導明確寫出主視覺顏色時才有(共 10 筆,例:陳其邁 2022「桃紅色」) | +| `note` | 寫法差異、換過標語、哪句是後期用的等補充 | +| `sources` | 出處清單(網址、標題、媒體、日期) | + +2018、2022 地方選舉和 2020、2024 總統選舉的姓名與政黨,都已和遊戲情境裡的中選會資料逐筆比對,全部一致(2022 嘉義市長不在情境資料裡,改用中選會選舉公報確認)。 + +## 涵蓋範圍 + +| 年份 | 選舉 | 範圍內候選人 | 有標語 | high | medium | 未查證 | +|---|---|---:|---:|---:|---:|---:| +| 2024 | 總統 | 3 | 3 | 3 | 0 | 0 | +| 2022 | 直轄市長 | 14 | 13 | 10 | 3 | 1 | +| 2022 | 市長(基隆、新竹、嘉義) | 7 | 4 | 3 | 1 | 3 | +| 2022 | 縣長 | 30 | 22 | 18 | 4 | 8 | +| 2020 | 總統 | 3 | 3 | 2 | 1 | 0 | +| 2018 | 直轄市長 | 14 | 13 | 9 | 4 | 1 | +| 2018 | 市長(基隆、新竹、嘉義) | 8 | 3 | 3 | 0 | 5 | +| 2018 | 縣長 | 31 | 17 | 13 | 4 | 14 | +| 2016 | 總統 | 3 | 3 | 2 | 1 | 0 | +| 2014 | 直轄市長 | 12 | 10 | 3 | 7 | 2 | +| 2014 | 市長(基隆、新竹、嘉義) | 8 | 7 | 0 | 7 | 1 | +| 2014 | 縣長 | 27 | 14 | 7 | 7 | 13 | +| 2012 | 總統 | 3 | 3 | 2 | 1 | 0 | +| 2010 | 臺北/高雄市長 | 5 | 3 | 2 | 1 | 2 | +| 2008 | 總統 | 2 | 1 | 0 | 1 | 1 | +| 2006 | 臺北/高雄市長 | 5 | 3 | 0 | 3 | 2 | +| 2004 | 總統 | 2 | 2 | 2 | 0 | 0 | +| 2002 | 臺北/高雄市長 | 4 | 0 | 0 | 0 | 4 | +| 2000 | 總統 | 5 | 2 | 1 | 1 | 3 | +| 1998 | 臺北/高雄市長 | 6 | 1 | 1 | 0 | 5 | +| 1996 | 總統 | 4 | 4 | 2 | 2 | 0 | +| 1994 | 臺北/高雄市長 | 6 | 3 | 1 | 2 | 3 | +| **合計** | | **202** | **134** | **84** | **50** | **68** | + +- 總統:1996–2024 共 25 組,21 組有標語。 +- 地方:2014/2018/2022 縣市長,收民進黨、國民黨、民眾黨候選人,加上得票 10% 以上的無黨籍與小黨候選人(如 2018 徐欣瑩、2014 蔡仁堅)。 +- 臺北、高雄市長 1994–2010:選做項目,年代越早,網路資料越少,缺最多。 +- 立委:依需求未做。 + +### 總統選舉一覽 + +| 年份 | 候選人(副手) | 政黨 | 標語(第一句為主標語) | 信心 | +|---|---|---|---|---| +| 2024 | 侯友宜(趙少康) | 中國國民黨 | 台灣再出發 | high | +| 2024 | 柯文哲(吳欣盈) | 台灣民眾黨 | Keep Promise / 相信美好台灣 | high | +| 2024 | 賴清德(蕭美琴) | 民主進步黨 | 選對的人,走對的路 / 信賴台灣 | high | +| 2020 | 宋楚瑜(余湘) | 親民黨 | 藍綠推兩邊、人民擺中間 | medium | +| 2020 | 蔡英文(賴清德) | 民主進步黨 | 2020台灣要贏! | high | +| 2020 | 韓國瑜(張善政) | 中國國民黨 | 台灣安全、人民有錢 / 藍天再現,台灣UP | high | +| 2016 | 宋楚瑜(徐欣瑩) | 親民黨 | 一起找出路 | medium | +| 2016 | 朱立倫(王如玄) | 中國國民黨 | ONE TAIWAN / 台灣就是力量 | high | +| 2016 | 蔡英文(陳建仁) | 民主進步黨 | 點亮台灣 | high | +| 2012 | 宋楚瑜(林瑞雄) | 親民黨 | 拋開藍綠、致力民生、掌握關鍵四年 | medium | +| 2012 | 蔡英文(蘇嘉全) | 民主進步黨 | Taiwan Next / 現在決定未來 | high | +| 2012 | 馬英九(吳敦義) | 中國國民黨 | 台灣加油讚 | high | +| 2008 | 馬英九(蕭萬長) | 中國國民黨 | 台灣向前行,台灣一定贏 | medium | +| 2004 | 連戰(宋楚瑜) | 中國國民黨 | 換總統,救台灣 | high | +| 2004 | 陳水扁(呂秀蓮) | 民主進步黨 | 相信台灣、堅持改革 | high | +| 2000 | 連戰(蕭萬長) | 中國國民黨 | 心手相連,台灣起飛 | medium | +| 2000 | 陳水扁(呂秀蓮) | 民主進步黨 | 年輕台灣,活力政府 / 和平新世紀、安定大賺錢 | high | +| 1996 | 彭明敏(謝長廷) | 民主進步黨 | 和平尊嚴・台灣總統 | high | +| 1996 | 李登輝(連戰) | 中國國民黨 | 尊嚴、活力、大建設 | high | +| 1996 | 林洋港(郝柏村) | 無黨籍 | 新領導・新秩序・新希望 / 總統選林郝,明天會更好 | medium | +| 1996 | 陳履安(王清峰) | 無黨籍 | 和平,救台灣 / 樂觀進取,互助合作 | medium | + +## 怎麼查的 + +1. 依年份和選舉分成 9 組平行查證,每組都是「先找候選人陣營自己發表的(競總成立、主視覺記者會、政黨新聞稿、選舉公報),再找媒體報導交叉比對」。 +2. 用到的來源:中央社、公視、自由時報、聯合報、中國時報、ETtoday、TVBS、NOWnews、新頭殼、風傳媒、鏡週刊、三立、民報、金門日報等新聞;民進黨、國民黨官方新聞稿;中選會選舉公報;**國家文化記憶庫/文化部典藏網裡國立臺灣歷史博物館收藏的真實競選文宣、旗子、看板照片**(老選舉幾乎全靠這批)。 +3. 維基百科只當線索:維基寫了但沒附出處、或出處已失效的,一律不收。 +4. 這輪查證的網路搜尋額度中途用完,後半段改成直接翻各媒體的選舉專題列表、新聞稿列表、館藏條目和維基引用的原始文章(中途有幾組用過自由時報、聯合報和文化部館藏網站的站內搜尋,之後停用;沒有用 Google 等通用搜尋引擎)。每一筆收進來的出處都是實際打開核對過的文章或館藏頁。因此「查無來源」不等於當年沒有標語,只是這次沒查到可靠出處。 + +## 信心怎麼判定 + +- **high**:陣營自己的官方來源(政黨新聞稿、官網、選舉公報;館藏陣營文宣且目錄說明或另一個文字來源寫出同一句),**或**兩家以上互相獨立的媒體都寫了同一句。 +- **medium**:只有一家可靠媒體(同一家媒體寫好幾篇也只算一家),或只能從館藏文宣照片判讀字樣、沒有任何文字來源。 +- 統整時用同一套標準複查,改了 8 筆 high → medium:7 筆 2014 條目其實只有自由時報一家來源(朱立倫、吳志揚、胡志強、賴清德、林右昌、蔡仁堅、許明財),1996 林洋港主標語只能從照片判讀;都在 `note` 註明。 +- 不收的:一次性的演講或喊話、站台者帶喊的口號、活動名稱、政見標題、對手或媒體取的綽號、只出現在維基百科沒有出處的句子、各來源寫法互相矛盾又無法判斷的句子。 + +## 寫法規則 + +- 字照原文,不改寫、不翻譯、不補字。台/臺照陣營印的(例:2004 陳水扁「相信台灣、堅持改革」)。 +- 標點照所引來源;不同媒體標點不一樣時,在 `note` 記下其他寫法。 +- 字串裡中文之間沒有空白、沒有換行;原文是兩行或空白分隔的,用全形「,」接起來並標 `joinedWithComma`。 +- 英文標語保留英文字之間的空格(例:`Keep it Real, Keep it Possible`、`ONE TAIWAN`),因為拿掉就改了原文。 +- 中間點:來源印得出確切符號時照用(.或 ‧);只能從照片看、分不出是哪種點時,統一用「・」,並在 `note` 說明。 + +## 使用時要注意 + +- **有些標語中途換過**:例如 2022 張善政依序是「拚!桃園善好」→「未來,從桃園開始」→「挺善良」,其中「挺善良」也是國民黨全黨的後期口號。看板若想用選前最後的標語,要看 `note`。 +- **有些標語很長**:例如 2018 黃偉哲、2012 宋楚瑜(「拋開藍綠、致力民生、掌握關鍵四年」),看板排版要能換行或縮字。 +- **2022 嘉義市長**(12/18 重行選舉)目前不在遊戲情境資料裡;民進黨候選人是**李俊俋**(研究清單一開始寫成李進勇,已更正)。 +- 真實人物只收標語與公開的競選事實,沒有收個人資料、評論或其他引述。 + +## 未查證名單(沒有收進 slogans.json) + +| 年份 | 選舉 | 候選人 | 政黨 | 為什麼沒收 | +|---|---|---|---|---| +| 2022 | 新北市長 | 侯友宜 | 中國國民黨 | 選舉公報標題是「新北市做大市」+直排 HOU+「做大事」,無法確定成一句;他自稱主軸「好好做事」,但沒找到印在文宣上的來源。 | +| 2022 | 基隆市長 | 謝國樑 | 中國國民黨 | 選舉公報只有政見標題,沒找到標語。 | +| 2022 | 嘉義市長 | 李俊俋 | 民主進步黨 | 只見活動名稱「為嘉投票、翻轉嘉義」「翻轉嘉義 迎向勝利」,無法確認是主標語。(研究清單原誤寫為李進勇,已更正) | +| 2022 | 嘉義市長 | 黃敏惠 | 中國國民黨 | 公報第一項「打造幸福進行式、嘉義未來市」比較像政見,沒找到標語。(12/18 重行選舉,遊戲情境資料目前沒有這一場) | +| 2022 | 宜蘭縣長 | 陳琬惠 | 台灣民眾黨 | 只有一款館藏文宣印著「宜蘭6起來」等字,沒有文字報導可以佐證。 | +| 2022 | 新竹縣長 | 周江杰 | 民主進步黨 | 「城鄉共好 新新竹」各來源都稱為願景或政見,沒有稱為標語。 | +| 2022 | 苗栗縣長 | 謝福弘 | 中國國民黨 | 文宣標誌約為「苗栗下一棒 幸福弘不讓」,但字體太花,無法確定用字,也沒有報導佐證。 | +| 2022 | 澎湖縣長 | 葉竹林 | 無黨籍 | 只找到「1126澎湖換新衫(3)」「選人不選黨」等喊話,沒有被稱為標語。 | +| 2022 | 澎湖縣長 | 賴峰偉 | 中國國民黨 | 只找到抽籤時喊「連任成功」,沒有標語。 | +| 2022 | 澎湖縣長 | 陳光復 | 民主進步黨 | 只找到「去投票,澎湖就會贏」等喊話,沒有標語。 | +| 2022 | 連江縣長 | 曹爾元 | 中國國民黨 | 查無來源。 | +| 2022 | 連江縣長 | 王忠銘 | 中國國民黨 | 只有當選感言「我將無我.無負鄉親」,不是競選標語。 | +| 2018 | 臺南市長 | 陳永和 | 無黨籍 | 只有「公民城市」的政策主張。 | +| 2018 | 基隆市長 | 林右昌 | 民主進步黨 | 維基百科的「我愛基隆」沒附出處(那是 2014 年的標語);2018 年只找到演講語句。 | +| 2018 | 基隆市長 | 謝立功 | 中國國民黨 | 維基百科寫法的出處已失效;只找到文宣標題與登記喊話。 | +| 2018 | 新竹市長 | 許明財 | 中國國民黨 | 「一帶二心三連結」是政見,「新竹第一、市民至上」是承諾,都沒有被稱為標語。 | +| 2018 | 嘉義市長 | 涂醒哲 | 民主進步黨 | 維基百科「信任、幸福、新嘉義」沒附出處;只找到登記當天的一次性標語牌。 | +| 2018 | 嘉義市長 | 蕭淑麗 | 無黨籍 | 只找到造勢喊話與「世代交替」的主張。 | +| 2018 | 宜蘭縣長 | 林信華 | 無黨籍 | 維基百科寫法沒附出處;自由時報抽籤報導反而寫他「未有口號」。 | +| 2018 | 苗栗縣長 | 徐定禎 | 無黨籍 | 只找到「苗栗動起來」一類喊話,各來源寫法不一。 | +| 2018 | 南投縣長 | 林明溱 | 中國國民黨 | 只找到拜票說法;維基百科寫法沒附出處。 | +| 2018 | 嘉義縣長 | 吳育仁 | 中國國民黨 | 只找到政見會的四項訴求;抽籤時他自稱沒有特別的口號。 | +| 2018 | 屏東縣長 | 蘇清泉 | 中國國民黨 | 只找到抽籤時幕僚喊的「清新執政,泉力以赴,屏東大勝利」,單一場合。 | +| 2018 | 花蓮縣長 | 徐榛蔚 | 中國國民黨 | 只找到政見會喊「花蓮第一」與縣黨部遊行名稱。 | +| 2018 | 澎湖縣長 | 賴峰偉 | 中國國民黨 | 維基百科「卓越領航,重返榮耀」沒附出處。 | +| 2018 | 澎湖縣長 | 陳光復 | 民主進步黨 | 只找到蔡英文稱他帶領澎湖「看見幸福」,沒有說是標語。 | +| 2018 | 澎湖縣長 | 陳大松 | 無黨籍 | 只找到「大思維、大方向、大建設及大未來」四大主軸;維基百科寫法沒附出處。 | +| 2018 | 金門縣長 | 楊鎮浯 | 中國國民黨 | 只找到站台者帶喊「翻轉金門」,單一場合。 | +| 2018 | 金門縣長 | 陳福海 | 無黨籍 | 查無來源(只有抽籤時台下喊話)。 | +| 2018 | 連江縣長 | 劉增應 | 中國國民黨 | 查無來源。 | +| 2018 | 連江縣長 | 朱秀珍 | 無黨籍 | 查無來源。 | +| 2018 | 連江縣長 | 蘇柏豪 | 樹黨 | 只找到「公民參政」理念與政見。 | +| 2014 | 桃園市長 | 鄭文燦 | 民主進步黨 | 維基百科「有輪替,才有改變」沒附出處;只找到演講中的「輪替」說法。 | +| 2014 | 高雄市長 | 陳菊 | 民主進步黨 | 「再創高峰」只見蘇貞昌、蔡英文等人喊,沒看到印在她的文宣;維基百科長版沒附出處。 | +| 2014 | 基隆市長 | 黃景泰 | 無黨籍 | 維基百科「行動新基隆」沒附出處。 | +| 2014 | 宜蘭縣長 | 邱淑媞 | 中國國民黨 | 只找到登記喊話與公報政見標題。 | +| 2014 | 新竹縣長 | 鄭永金 | 無黨籍 | 維基百科寫法沒附出處。 | +| 2014 | 苗栗縣長 | 吳宜臻 | 民主進步黨 | 維基百科「打破黑金,迎向光明」沒附出處;民進黨新聞稿記群眾喊「創新苗栗,一起前進」,兩者不一致。 | +| 2014 | 苗栗縣長 | 康世儒 | 無黨籍 | 維基百科寫法沒附出處。 | +| 2014 | 彰化縣長 | 魏明谷 | 民主進步黨 | 官網標誌、電視廣告、布條各有一句(如「相信魏明谷.彰化更富足」),無法判斷哪句是主標語。 | +| 2014 | 南投縣長 | 李文忠 | 民主進步黨 | 只找到喊話與看板「換黨換人做」;維基百科寫法沒附出處。 | +| 2014 | 南投縣長 | 林明溱 | 中國國民黨 | 維基百科寫法沒附出處,而且像政見。 | +| 2014 | 雲林縣長 | 李進勇 | 民主進步黨 | 維基百科寫法沒附出處;造勢活動用的是全黨共同口號。 | +| 2014 | 屏東縣長 | 簡太郎 | 中國國民黨 | 只找到喊話「屏東一定翻轉」;維基百科寫法沒附出處。 | +| 2014 | 臺東縣長 | 黃健庭 | 中國國民黨 | 維基百科寫法像是 2009 年的標語;2014 年公報標題是過渡說法,無法確定。 | +| 2014 | 花蓮縣長 | 傅崐萁 | 無黨籍 | 維基百科「責任.承擔」沒附出處。 | +| 2014 | 花蓮縣長 | 蔡啟塔 | 中國國民黨 | 維基百科寫法沒附出處。 | +| 2014 | 金門縣長 | 陳福海 | 無黨籍 | 只找到訴求與「十大願景」,沒有主標語。 | +| 2010 | 高雄市長 | 楊秋興 | 無黨籍 | 只有官網稱號「五顆星南方小巨人」與政見手冊標題。 | +| 2010 | 高雄市長 | 黃昭順 | 中國國民黨 | 維基百科與她的官網寫法不同(「拼經濟,高雄乎順啦」/『拼經濟、救高雄』~高雄乎順啦!!),無法確認看板用字。 | +| 2008 | 總統 | 謝長廷 | 民主進步黨 | 只找到呼口號「護台灣、救民主」與政見名稱「台灣維新」等,無法確認主標語。 | +| 2006 | 臺北市長 | 謝長廷 | 民主進步黨 | 維基百科「2020奧運在台北」沒附出處,而且像政見。 | +| 2006 | 臺北市長 | 郝龍斌 | 中國國民黨 | 維基百科「城市競爭,台北看郝」沒附出處;館藏文宣只有棄保呼籲。 | +| 2002 | 臺北市長 | 李應元 | 民主進步黨 | 查無直接寫出標語的來源。 | +| 2002 | 臺北市長 | 馬英九 | 中國國民黨 | 查無直接寫出標語的來源。 | +| 2002 | 高雄市長 | 謝長廷 | 民主進步黨 | 查無來源。 | +| 2002 | 高雄市長 | 黃俊英 | 中國國民黨 | 查無來源。 | +| 2000 | 總統 | 宋楚瑜 | 無黨籍 | 查無來源,博物館館藏中也沒找到。 | +| 2000 | 總統 | 李敖 | 新黨 | 只有選舉公報的自我介紹文字,不是標語。 | +| 2000 | 總統 | 許信良 | 無黨籍 | 查無來源。 | +| 1998 | 臺北市長 | 王建煊 | 新黨 | 查無來源。 | +| 1998 | 臺北市長 | 馬英九 | 中國國民黨 | 只找到英文 "Taiwan First, Taipei First"(紐約時報),找不到中文原句,不自行翻譯。 | +| 1998 | 高雄市長 | 吳建國 | 新黨 | 查無來源(得票率 0.81%)。 | +| 1998 | 高雄市長 | 吳敦義 | 中國國民黨 | 查無來源。 | +| 1998 | 高雄市長 | 謝長廷 | 民主進步黨 | 查無來源。 | +| 1994 | 高雄市長 | 吳敦義 | 中國國民黨 | 查無來源。 | +| 1994 | 高雄市長 | 張俊雄 | 民主進步黨 | 查無來源。 | +| 1994 | 高雄市長 | 湯阿根 | 新黨 | 查無來源(得票率 3.45%)。 | diff --git a/backend/docs/22-rogue-v2.md b/backend/docs/22-rogue-v2.md new file mode 100644 index 0000000..2705133 --- /dev/null +++ b/backend/docs/22-rogue-v2.md @@ -0,0 +1,141 @@ +# 22 選戰卡牌第二版:更多機制、精緻度、重玩性、政治生涯 + +2026-10-26 使用者試玩第一版後說「趣味性確實變多了,請繼續把該做的東西都做完,也要更多有趣的遊戲機制」。 +這一版照改造計劃(https://claude.ai/artifact/UdMUGSaWTcp8jNZQS9w55B)做完第 2–4 階段(線上排行榜除外),另外加了幾個新機制。 +參考了使用者提供的遊戲開發工具清單(gamedev-skills/awesome-gamedev-agent-skills)裡 card-game、game-feel、game-ui-ux、save-systems 的原則: +效果用資料描述、回饋分輕重兩級、畫面震動可以關、存檔加版本號。清單裡大多是 Godot/Unity/Unreal 專用,沒有安裝。 + +## 玩法入口(#/rogue) + +| 模式 | 內容 | +|---|---| +| 新手教學 | 虛構的「幸福里里長選舉」,3 個里、3 週、固定牌組,畫面上一步一步提示(隨手玩約九成會贏) | +| 每日一戰 | 每天從縣市長劇本挑一場、挑一位候選人,逆風 3 級、勢均力敵,同一天同一個種子;成績記在瀏覽器 | +| 自由選戰 | 全台縣市長(2014/2018/2022)、區域立委(2020/2024)、總統(1996–2024),可選任何候選人;「勢均力敵」開關(關掉就是照當年底盤);逆風 0 到已解鎖的等級 | +| 政治生涯 | 自創角色從里長一路選到總統(#/rogue/career);現行規則見 docs/23「完整的政治生涯」 | +| 朋友挑戰 | 結果畫面「挑戰朋友」複製連結:同一場選舉、同一個種子、同樣的逆風,朋友打開就能比(伺服器要在同一個網路或上線後才連得到) | +| 圖鑑與成就 | 牌、幕僚、事件看過才會亮;22 個成就;統計局數、勝場、逆風解鎖(#/rogue/collection) | + +## 首頁(2026-10-26,18 第 28 項) + +使用者確認「主要遊戲機制就是要變這樣」,首頁改成以選戰卡牌為主(web/src/game/home): + +- 上面保留會動的 3D 選戰小鎮,標語改成「出牌拉票 一區一區翻過來」。右下角有一手示範牌,點一張就打進小鎮(牌飛過去、造勢放煙火、宣傳車加速、群眾跳起來、跳出票數),一進首頁就摸得到核心動作。 +- 主按鈕看進度:有沒打完的局就「繼續選戰」,第一次玩就「開始選戰(先玩 5 分鐘新手教學)」,其他時候往下捲到大廳;旁邊是「政治生涯」。 +- 下面依序是:選戰卡牌大廳(和 #/rogue 同一個元件:教學、每日一戰、自由選戰、政治生涯、圖鑑與成就、朋友的挑戰)、一週怎麼玩、真實資料(22 縣市、368 鄉鎮市區、7,781 村里、65 場縣市長、146 區立委、8 屆總統)、牌與幕僚預覽、捏人物。 +- 捏人物多一個「存起來,去政治生涯」。(舊的十週行程版在 2026-10-26 依使用者要求刪除。) +- 捏人物、圖鑑、資料檢視器等改成用到才下載,首頁的程式從 1.4 MB 降到 1.08 MB。 + +開票夜同時加上地圖:還沒開的區是灰的,開出來的區塗上贏家的顏色(贏越多越深),剛開的那一區框起來並跳出差距。 +堵麥題目擴充到 24 題、地方抉擇 22 個、每週事件 16 種。 + +## 一局的節奏(8 週) + +| 週 | 開場 | 特色 | +|---|---|---| +| 每週 | 電視快報(鄉民直播台,七秒) | 上週戰果、全市支持度、本週事件、對手動向 | +| 1 | — | 打底盤,對手不批評 | +| 2、5、7 | 記者堵麥 | 依上週發生的事出題(被批評、造勢、翻轉、颱風、錢多錢少…),2–3 個回應 | +| 3 | 電視辯論 | 論點連擊辯論(見 docs/23「論點連擊辯論」,取代原本的三回合猜拳) | +| 4 | 民調公布 | 領先:西瓜效應聲勢 +1;落後:手上多一張「悲情催票」 | +| 5 | — | 對手預告第 7 週的大型造勢(地圖上標出來) | +| 6 | 匿名黑函危機 | 提告(250 萬,損失剩三成)/冷處理(一半機率剩四成,否則更慘)/悲情反擊(剩七成、聲勢 +2)/公開資料自清(體力 −1、沒有損失) | +| 7 | 記者堵麥 | 對手的大型造勢(預告值 ×2.4) | +| 8 | 選前之夜 | 體力 +1,造勢牌 ×1.3,可以下跪 | +| 開票 | 開票夜 | 小區先開、大區最後,最後三區放慢;領先換人時閃一下 | + +每週結束選**下一站**(三選一,第 2、4、6 週一定有招募幕僚;逆風 4 級起只有兩個選項),或回總部休息拿 150 萬: + +- 拜會地方:三選一新牌(普通 3:稀有 1) +- 招募幕僚:三選一幕僚(最多 5 位) +- 黨部研習:升級一張牌 +- 整頓行程:從牌組拿掉一張牌(牌組 8 張以下不會出現) +- 競選物資行:3 張牌(普通 120 萬、稀有 220 萬)、1 位幕僚(300 萬)、刪牌服務(100 萬),可以買好幾樣 +- 深入基層:拜票副本(沿用 content/encounters.ts 的虛構路人),三個人的應對分數(−6 到 +6)決定那區加多少票,總分 4 分以上聲勢 +1 +- 地方抉擇:12 種有代價的選擇(企業主捐款附帶人情包袱、網紅業配、廟方邀請、颱風清淤、老牌操盤手…) + +## 機制 + +- **牌(44 張可抽到的牌+6 張開局牌+6 張劇情與狀態牌)**:地面、組織、空戰、攻防、資金五派,稀有牌有金框。 +- **關鍵字**:消耗(這局用一次就沒了)、保留(週末留在手上)、虛無(週末還在手上就消失)、不能打。 +- **升級(+版)**:數字 ×1.35;有些改成少 1 點體力、多一點效果(造勢+聲勢 +3、打探+一定拿到把柄)。 +- **能力牌**:媒體訓練(之後媒體牌 +25%)、蹲點研究(之後地面牌 +15%),打出後整局有效。 +- **狀態牌**:記者追問(對手批評你沒擋下、黑函會塞進來;花 1 點體力回應就移除,留著過週末全市掉票)、人情包袱(不能打,要整頓行程才拿得掉)、疲勞(不能打,週末消失)。 +- **插旗與翻轉**:已表態的票裡領先 8 個百分點就插旗。每面旗每週 20 萬小額捐款;把對手插過旗的區拿過來(中間掉成沒人插旗也算),聲勢 +1;被翻走,對手聲勢 +1。 +- **隔壁區**:造勢、宣傳車、宣傳車隊長會擴散到相鄰的區。相鄰由地圖拓撲算(共用邊界的區),總統選舉用縣市。 +- **幕僚(32 位)**:地區型(客家事務主任、農會總幹事…)、牌型(宮廟通、造勢天王…)、規則型(開場哥:每週第一張牌 +50%;夜貓子:用掉最後一點體力的牌 +50%;行程秘書:體力 +1 但少抽一張;鐵票部隊:插旗的區對手行動減半…)。都是虛構職位,頭像用漫畫產生器。 +- **對手性格**:組織戰(佈樁盾 ×1.4)、空戰(廣告 ×1.2)、後發制人(前期 ×0.92、每週成長 9%),依劇本的 AI 風格決定。 +- **逆風 0–10**:贏了第 n 級開第 n+1 級。1 對手 +12%、2 起始資金 −40%、3 每週收入 −40%、4 選項只剩 2 個、5 開局多一張人情包袱、6 對手第 4 週起多一個行動、7 對手開局聲勢 2、8 你的牌 −8%、9 黑函加倍且壞事件變多、10 開局落後 3 個百分點。 +- **成就(22 個)**:凍蒜、壓倒性勝利、驚險過關、逆轉勝、以小搏大、全區插旗、乾淨選戰、辯論三戰全勝、黑函零損失、四連拳、翻轉王、一張定江山、精實牌組、財源滾滾、滿編團隊、物資行常客、逆風高手、逆風傳說、每日一戰、國會新科、地方首長、登上大位。 +- **當選判斷**:要贏過對手,也要贏過「其他候選人」裡最強的那一位(不是其他人的票加起來)。 + +## 手感與畫面(第 2 階段) + +- 卡牌重做:稀有度外框、類型色條與圖示、大數字、關鍵字、+版發光(web/src/game/rogue/cards.tsx)。 +- 出牌:牌飛向地圖、爆分(加成一個一個跳出來、音越來越高、總票數蹦出來)、翻轉時畫面震動。設定裡可以關「畫面震動」;系統「減少動態效果」時不飛牌、不震動。 +- 手機直式:地圖和「各區・對手」用分頁切換,狀態列三行,手牌固定在下面;按鈕至少 40px。 +- 開票夜、結果畫面、分享結果圖卡(canvas 畫 1080×1350 PNG,標「遊戲模擬」,真實人物只畫號次章)。 + +## 真實人物的約束(docs/14、18 第 27 項) + +- 對手的行動名稱一律中性:批評你的政見、到你的票倉拉票,不寫抹黑、爆料。 +- 黑函一律是「匿名黑函」,畫面寫「內容沒有根據、來源不明」,不算在任何候選人頭上。 +- 堵麥題目寫「有人質疑」,不捏造真人的話;玩家的爆料只寫「對手支持者動搖」,不寫具體指控。 +- 政治生涯讓自創角色和真實候選人同場,畫面標「假設情境,不代表真實選情」。 + +## 數字從哪來 + +- 開局底盤:選民模型(人口、年齡、政黨傾向、歷史投票率)算各區預期得票;30% 還沒表態。地區特色和全縣市平均比(`packages/rogue/src/setup.ts`)。 +- 牌面與對手行動以「全市 100 萬人投票」為準,乘上比例尺(全市投票人數/100 萬);區的大小係數 (人數/平均)^0.3,夾在 0.6–1.4。 +- 其他都是遊戲數字,寫在 backend/packages/rogue/src/data.ts、advisors.ts、content.ts、rival.ts。 + +## 平衡(apps/sim rogue-balance,2022 桃園勢均力敵) + +標準難度,每種玩家 200 局: + +| 玩家 | 玩張善政:差距/勝率 | 玩鄭運鵬:差距/勝率 | +|---|---|---| +| 什麼都不做 | −11.4/0% | −12.0/0% | +| 亂出牌 | −5.5/1% | −6.2/0% | +| 都打在人最多的區、不理對手 | −1.6/24% | −2.3/14% | +| 隨手玩(照順序出、打推薦第一名) | +0.2/54% | −0.5/39% | +| 看預估挑最划算的 | +7.9/100% | +7.6/100% | +| +只拿地面/空戰/攻防牌 | +8.5/+6.7/+6.6 | +8.2/+6.4/+6.0 | + +逆風階梯(每種 120 局,隨手玩/打得好的勝率): + +| 逆風 | 張善政 | 鄭運鵬 | +|---|---|---| +| 0 | 53%/100% | 38%/100% | +| 3 | 38%/98% | 25%/100% | +| 6 | 5%/85% | 4%/77% | +| 10 | 0%/31% | 1%/17% | + +- 技術有差:打得好比隨手玩多約 8 個百分點,比亂打多 13 個百分點。 +- 沒有一招通吃:只拿某一派牌的差距在 2.3 個百分點以內。 +- 新手教學:隨手玩 96%、亂出牌 75%、什麼都不做 0%。 +- 逆風階梯是修正審查問題之前跑的;修正後標準難度重跑,差距只變動 0.2 個百分點以內。 + +## 審查後修正(2026-10-26) + +另一個助手逐行審查並跑了約 780 局隨機測試,找到並已修正: +- 打出去的牌在效果結算、抽完牌之後才進棄牌堆(原本「志工大隊+」可以把自己抽回來無限循環);「志工大隊+」改成抽 3 張、不再是 0 體力;「熬夜跑行程」每週只能打一次;手牌上限 10 張。 +- 一次打好幾區的牌(志工電話催票、電話拜票中心、全面動員令)也算打過那幾區,重複打不再有組合拳。 +- 預估:第二次佈樁只算還沒擋住的威脅;有公關高手、鐵票部隊時,打對台和澄清的預估跟著打折。 +- 夜貓子看實際花的體力(網路小編免費的那張不算)。 +- 爆分顯示伺服器實際結算的加成(例如爆紅、失言),不是預估。 +- 請求失敗後畫面自動重新拿一次這局的狀態。 +- 存檔:同一局同時有好幾個請求從檔案讀時共用同一次讀檔,不會互相覆蓋。 +- 政治生涯:結果畫面不再出現「挑戰逆風」(自創角色的局不能直接重開);贏了之後重新整理,挑幕僚和牌的畫面還在。 + +## 程式位置 + +- 規則:backend/packages/rogue/src(state 型別與常數、data 牌、advisors 幕僚、content 堵麥/抉擇/辯論、cards 出牌、rival 對手、scenes 開場劇情、route 下一站、rules 每週流程與開票、feats 成就、view 畫面資料、setup 開局與相鄰區、tutorial 新手教學、bots 模擬玩家)。 +- 存檔:apps/server/src/run-store.ts,每局一個 JSON(backend/data/runs/,可用 ROGUE_SAVE_DIR 改),版本號 SAVE_VERSION=2,舊版存檔不讀;先寫暫存檔再改名。伺服器重開也能繼續玩。 +- API:POST /api/rogue/runs(scenarioId、candidateId、seed、ascension、even、daily、custom、career、carry)、/api/rogue/tutorial、GET /api/rogue/catalog、/runs/:id、/play、/end-week、/choose。 +- 畫面:web/src/game/rogue(RogueStart 開始、RogueScreen 主畫面、flow 劇情與下一站、finale 開票夜與結果、Career 政治生涯、Collection 圖鑑、brief 電視快報、coach 教學提示、juice 手感、progress 瀏覽器裡的進度)。 + +## 還沒做 + +- 線上排行榜、跨裝置的每日一戰排名:要把伺服器放上網路並處理防作弊,另外評估。 +- 真機(手機實機)試玩:目前用 Playwright 模擬 390×844 手機畫面。 diff --git a/backend/docs/23-career-and-meta.md b/backend/docs/23-career-and-meta.md new file mode 100644 index 0000000..a12dca3 --- /dev/null +++ b/backend/docs/23-career-and-meta.md @@ -0,0 +1,172 @@ +# 23 選戰小遊戲、政策工坊與政策島、完整的政治生涯、歷屆參選人 + +2026-10-26 深夜,使用者看過計劃頁(https://claude.ai/artifact/RxqGeu3Lsi67HizemA8aGS)後全部選建議選項: +評分用方案 A(免費的客觀資歷分數)、立法院打架做鬧劇版(虛構人物,黨團只寫執政/在野)、政治生涯里長起跳五關(可跳過前兩關)、四塊全部做。 +對應 18-feedback-backlog 第 32–34 項。同一輪也修了第 36 項(開票、選區地圖),見最後一節。 + +## 論點連擊辯論(取代猜拳辯論) + +第 3 週的電視辯論改成三回合「論點連擊」(rogue/src/scenes.ts): + +- 對手每回合丟出一種質疑:質疑數字預算、談感受與在地心聲、翻紀錄與立場。對手是真實人物時只寫中性描述(「對手要你說清楚交通建設政見的預算從哪裡來」),不寫成引述。 +- 你手上有 5 張論點(口才 3 級起 6 張):拿數據、講故事、反問對手,三種至少各一張,其餘照你牌組的組成加權(政策、記者會類的牌多就多數據;地面牌多就多故事;媒體、攻擊牌多就多反問)。用掉就沒了。 +- 對上最好的論點:說服觀眾(全市加票、聲勢 +1);普通的:平手;答非所問:對手佔上風。連續答對 ×1、×1.5、×2,三連擊全勝多一張「辯論金句」。 +- 財源扎實的自寫政策變成一張「用你的政策說明」論點(×1.3);舉債的政策第二回合一定被追問「錢從哪裡來」。 +- 辯論教練、口才 5 級:畫面標出最好的那張論點。 + +## 選戰小遊戲(下一站「選戰小遊戲」) + +2026-10-27 完整版(18 第 58 項):#/minigames 改成小遊戲大廳(GameScene、三張遊戲卡、三級難度新手/老手/選戰老將,前一級 2 星解鎖下一級,最佳紀錄存 tongsuan.minigames.v1);每個遊戲全螢幕、示範動畫、三步規則、3-2-1 倒數、暫停、連擊、結束畫面星等(40/70/90 分 1/2/3 星)與新紀錄;三個遊戲的分數意義一致(隨手玩約 40–60、玩得好 80–95)。開發用的種子與難度拉桿搬到 #/minigames?dev。 + +web/src/game/minigames,試玩頁 #/minigames。每個 10–40 秒,玩完回報 0–100 分,伺服器換成效果(rogue/src/route.ts MINIGAME): + +| 小遊戲 | 玩法 | 效果(70 分算玩得不錯) | +|---|---|---| +| 掃街握手 | 騎樓下有人舉手,10 秒內點越多越好,點到記者扣分 | 選情最接近的那區加票(2,300 × 分數 ÷ 70,照區的大小與聲勢);90 分以上聲勢 +1 | +| 造勢喊凍蒜 | 跟著鼓點按「凍蒜!」,16 拍,越準連擊越高 | 40、80 分各聲勢 +1,全市加一點票 | +| 看板卡位 | 6×6 街區放看板佔人流(像推箱子),不能把路堵死 | 那區之後每週多票(據點 250 + 6 × 分數) | + +小遊戲站不在新手教學出現,出現機率和「深入基層」差不多。分數由瀏覽器回報(單機遊戲,不防作弊)。 + +## 政策工坊與政策島(跨局成長) + +web/src/game/island,#/island、#/island/workshop。進度存在玩家的瀏覽器(tongsuan.island.v1),開局時帶給伺服器,伺服器檢查範圍再套用(rogue/src/meta.ts)。 + +- **政績點**:打完一局當選 +3、落選 +1、S 評價 +2、第一次拿到的成就每個 +1;政治生涯每做完一任另外給(任期分數換算 2–10 點)。同一局只算一次。每日一戰、朋友挑戰不帶政策島(大家條件一樣)。 +- **12 棟建築**(每棟 3 級,3/6/10 點,競選學院、競選總部 4/8/12 點):交通樞紐(前幾週體力 +1)、長照中心、托育園(長輩、年輕人多的區 +8%/級)、科技園區(網路牌)、觀光夜市(市場夜市牌、開局資金)、宮廟廣場、媒體中心、志工之家(第 1 週多抽)、競選學院(開局牌升級)、競選金庫(開局資金)、競選總部(開局聲勢)、政策研究院(多帶政策、3 級政策牌 +15%)。 +- **政策工坊**:對象(長輩、年輕人、上班族、農漁民、客家鄉親、信眾、育兒家庭)× 做法(補助、蓋建設、修法、減稅)× 財源(加稅、舉債、刪別的預算、招商),自己取名字(20 字以內)。每份政策變成一張專屬牌,第 1 週就在手上。 + - 財源的代價:加稅花費少一半但每次打出多一張記者追問;舉債不花錢但效果 −10%、辯論會被追問;刪預算效果 +15% 但全市流失一點票;招商每次資金 +100 萬但效果 −10%。 + - 每局基本帶 1 份,政策研究院 1、2 級各多 1 份(最多 3 份)。 + +### 政策落地:政策和小島的關係(18 第 42 項) + +使用者問「小島建設跟政策工坊有啥關聯」:原本只有政策研究院(可帶幾份)和幾個看不到的間接加成。改成: + +- 每種政策對象在島上有一棟「家」(rogue/src/meta.ts POLICY_HOME):長輩→長照中心、年輕人→科技園區、上班族→交通樞紐、農漁民→觀光夜市、客家鄉親與信眾→宮廟廣場、育兒家庭→托育園。家每蓋一級,這份政策的牌 +10%(出牌時加成說明寫「長照中心落地 ×1.2」)。 +- 政策工坊:政策卡下面列「小島加成」——落地、長照中心/托育園對長輩/年輕人多的區、媒體中心(修法、減稅算媒體牌)、政策研究院 3 級;已經生效的是綠色,還沒蓋的寫「蓋了每級 +N%」;我的政策每張寫落在哪一棟、現在多幾 %。 +- 小島:建築名牌下面多一條紅色政策條(落在這裡的政策名);點建築的說明多「政策落地」一塊,列出落在這裡的政策、有沒有帶進下一局,沒有的話提示去工坊寫哪種對象的政策。 + +## 完整的政治生涯(里長 → 議員 → 立委 → 縣市長 → 總統) + +web/src/game/rogue/Career.tsx(進度 tongsuan.rogue.career.v3;v1、v2 的進度自動換過來)。逆風依序 0/1/2/3/5。開局可以選「跳過里長、議員」直接從立委開始(Lv 5、送 4 個技能點)。 + +- **里長**(rogue/src/local.ts villageSetup):家鄉縣市裡依人口隨機挑一個里(真實的里名、選舉人數、人口結構、宮廟密度),里裡分成三塊(廟口、老街、新社區…依特色取名,地名是虛構的)。對手是虛構的現任里長。5 週。投票數只有幾百到幾千,牌面數字是個位數(真實的里長選舉規模)。 +- **議員**(councilSetup):那個里所在的 2022 年議員選區(中選會資料:席次、最後一席的得票率)。選區有三個以上的區就一區一塊;不到三區就把村里依代碼順序分成 3–6 群,用最大那個里叫「XX里一帶」,地圖照村里分群畫。多席次:贏過最後一席(虛構的現任議員,起點略高於真實的最後一席得票率)就當選,評分用你和最後一席之間的差距。6 週。 +- **立委**:優先挑你住的那個區所在的立委選區(也可以自己換)。**縣市長、總統**:照真實的選舉,自創角色取代同黨的候選人。 +- **任期**(web/src/game/career/term,試玩頁 #/term):每次當選先做一段任期(虛構情境;開始前有任務簡報和一二三步說明): + - 里長:里民陳情 ×2(8 小時、2 個人情,挑處理方式) + - 議員:質詢虛構部長(聽到破綻打出證據卡)+審預算(刪浮編) + - 立委:講解法條(拼條文、選白話說明讓過半委員接受)+質詢+搶主席台(鬧劇版,沒有人受傷;黨團只寫我方/對方) + - 縣市長:分配預算(四個虛構分區的滿意度)+颱風救災 + - 任期結果:五項能力經驗(每 4 點升一級,最高 5 級)、政績點、下一場開局聲勢 0–2、資金 0–300 萬,以及虛構的任期回顧標題。可以跳過任期(沒有加成)。 +- **五項能力**(0–5 級,開局照捏人物的點數換算):口才(記者會、座談類的牌每級 +4%;3 級起辯論多一張論點;5 級看得出最好的論點)、組織(樁腳每級 +10%、地面牌每級 +3%)、媒體(媒體牌每級 +5%、爆紅機率每級 +3%)、財務(開局資金每級 +80 萬、每週收入每級 +15 萬)、清廉(黑函損失每級 −12%、記者追問掉票每級 −15%)。 + +### 練等(18 第 44 項,規則在 web/src/game/rogue/careerRules.ts) + +- 每一關都可以重複選。往上一關要:上一關選上過一次,而且等級夠(議員 Lv 3、立委 Lv 5、縣市長 Lv 8、總統 Lv 12)。 +- 經驗:每關基本 40/60/90/130/200;落選 ×0.4;每多加一級逆風 ×1.15(同一關用前一級逆風選上才解鎖下一級,最多 +3);評等 S ×1.5、A ×1.25;回去選比較低的關 ×0.6。任期另外給經驗(第 1–4 關 30/50/75/110 × 平均分)。 +- 升級要的經驗 = 40 + 30 ×(等級 − 1)。每升一級拿 1 個技能點,自己加在五項能力上(每項最高 5 級),可以重新分配。 +- 當選後挑 2 位幕僚、3 張牌帶到下一場;資金依總當選次數 × 150 萬(最多 1,000 萬)。 + +### 生涯畫面(18 第 47 項) + +- **生涯棋盤**(rogue/careerBoard3d.ts、CareerBoard.tsx):和首頁同一套紙板桌遊、木頭桌面、CC0 模型。一條馬路串起五關的廣場和建築(里辦公處、議會、立法院、縣市政府、總統府);還沒解鎖的建築是灰階、馬路是土路,解鎖到哪柏油路鋪到哪;選上過的廣場是黃色、插旗;點哪一關宣傳車就開過去,支持者站在角色目前最高的那一關。名牌是 HTML 按鈕(可以用鍵盤、讀螢幕),每一格依 3D 位置對齊建築。畫面不夠寬(手機)就從側面看,五關由下往上排。沒有 WebGL 改成一排五張關卡牌。 +- **角色卡**(CareerSheet.tsx):頭像名牌(政黨色)、等級徽章、經驗條、技能點提示、五項能力(圖示、5 格能力條、效果、+)。最下面「重新分配」和「換人物(結束這段生涯)」,都用遊戲裡的確認視窗(ui/ConfirmDialog.tsx),不用瀏覽器的 confirm()。 +- **出征卡**(CareerStage.tsx):關卡徽章、紀錄、在哪裡選(立委可換選區)、再加逆風(火焰格)、當選/落選拿多少經驗、帶著出發的東西、出發參選。沒解鎖的關列出條件(打勾的已經達成)和等級進度。 +- **選角**(CareerSetup.tsx):三步——選角色(衣櫃裡的角色卡片,右上角 × 可以丟掉,要確認;也可以快速捏一個或到更衣間)、家鄉(直轄市、其他縣市兩組)、起點(從里長開始或直接選立委)。 +- **戰報**:當選/落選/任滿蓋章、得票和評等、經驗條、升級提示;當選後挑帶走的幕僚和牌,再上任。 +- 手機:棋盤+出征卡一頁,角色卡另一頁,用最下面的分頁切換(有技能點時分頁上有紅點數字);整頁不捲。 + +### 出身與黨的資源(18 第 53 項,做法 B「有得有失」) + +規則表在 backend/packages/protocol/src/origins.ts(前後端共用),只套在自創角色上(真實候選人照真實的資源)。 + +- **出身**:起始能力 +1(醫師、社運→清廉;律師、教授→口才;前藝人、網紅→媒體;政二代、基層里長→組織;企業家、前官員→財務),再加一張專屬起始牌,第一週就在手上,不會出現在獎勵裡(巡迴義診、法律諮詢站、公共政策講座、粉絲見面會、直播開箱、家族老樁腳、里民大會、企業募款餐會、施政成績單、街頭連署)。 +- **黨的資源**(不能自己點): + - 大黨(民進黨、國民黨):開局資金多、組織 +1、開局一張「黨部動員掃街」;包袱是第 3 或第 4 週的「黨中央風波」(手上一張,那週沒回應全市掉票,週末就消失)。 + - 民眾黨:資金中等、媒體 +1。 + - 其他政黨、無黨籍:資金少;開局得票多 0.2 個百分點、記者追問掉的票少一成五,政治生涯經驗 ×1.2。 +- 起始能力=捏人物點數換算(0–2 級)+出身 +1+黨的資源 +1。政治生涯的舊存檔讀取時換成新規則(自己加的點保留);自由選戰的自創角色也套用同一套能力。 +- 平衡(apps/sim/src/party-balance.ts,2026-10-27):勢均力敵開局、逆風 2,打得好的玩家大黨 98%、民眾黨 96%、小黨與無黨籍 98%;隨手玩 23%/32%/35%。 +- 畫面:捏人物的「出身」格子寫加成、「政黨」下面寫黨的資源與代價;政治生涯角色卡也列出來。 + +### 里長關(18 第 55、56 項) + +- **自己挑里**:出征卡上先挑區、再挑里(每個里寫現在的選舉人數,API `/api/rogue/villages/:scenarioId`);不挑就照人口隨機抽。換里之後,議員選區跟著新的里。 +- **開局差距**:原本是「0.45 × 你的政黨在這個里的強弱(0.7–1.4)」,對手陣營很強的里(例如大溪區僑愛里,民進黨)一開局就落後 12 個百分點、5 週追不回來。改成政黨強弱最多影響 ±3 個百分點(里長選舉看人脈、和政黨關係不大),加上隨機差異最多約 ±1.5。模擬(apps/sim/src/village-balance.ts):隨手玩 75%、打得好 96%。 + +### 大絕招與真實開局差距(18 第 57 項) + +規則在 backend/packages/rogue/src/ultimate.ts,畫面在 web/src/game/rogue/Ultimate.tsx。使用者說「差很多也可以,但要有大絕招可以放,玩得好有機會翻盤」,照推薦做: + +- **集氣**:每週結算時,落後 1 個百分點集 8%(落後 10 點一週集八成);領先或平手每週只集 2%;這週翻轉一區再 +10%。 +- **次數**:基本 1 次;倒數第 3 週(8 週選戰的第 6 週)開始時,如果放過了、還落後超過 8 個百分點,直接再集滿一次。新手教學沒有。 +- **三招**(各接一個小遊戲,0–100 分):選前之夜大造勢(造勢喊凍蒜:全市加票、70 分以上聲勢 +2)、掃街馬拉松(掃街握手:自己挑的 3 個區加票)、看板大作戰(看板卡位:對手插旗、差距最小的 3 個區加票,之後每週還有據點票)。 +- **威力**=分數 × 落後倍率(1 + 落後幾個百分點 ÷ 10,最多 ×2.5)。中途不玩不算用掉。API:`POST /api/rogue/runs/:id/ultimate`。三招調成一樣強:臺中市長關落後 11 點、90 分時,三招都馬上追回約 4.4 個百分點(造勢另外聲勢 +2、看板另外每週據點票);50 分只追回約 1.5 點;0 分沒有效果(ULT.city 15,000、ULT.town 5,500)。 +- **小遊戲**(web/src/game/minigames,18 第 58 項):大絕招和選戰的小遊戲站都是全螢幕,開始畫面寫這一招的獎勵與倍率,結束只有一顆「放出大絕招!」/「回到選戰」(不能重玩)。 +- **真實開局差距**:政治生涯的區域立委、縣市長、總統改照真實的選民底盤(原本一律勢均力敵),但最多落後 10 個百分點(`buildSetup` 的 maxGap);里長、議員照原本各自的算法(里長的政黨影響最多 ±3 點,見上面)。上限試過 15 點:打得好的玩家(立委關 Lv 5 的能力)勝率只有 35–40%;10 點時 55–64%(apps/sim/src/party-balance.ts,REAL=1 GAP=0.10 POINTS=4)。 +- **平衡**(apps/sim/src/ultimate-balance.ts,打得好的機器人小遊戲 75–95 分、隨手玩 40–70 分):開局落後 10 點時,打得好的人勝率從 10% 變成 48%;落後 5 點從 63% 變 85%;落後 15 點從 0% 變 13%;沒落後時沒有影響。隨手玩的機器人本來就很弱(不落後也只有 10%),落後時大絕招幫不太上。 + +## 歷屆參選人與客觀資歷分數(方案 A) + +資料(pipeline `election-data records`,只讀本機的中選會 votedata.zip,不下載): + +- data/build/people/records.json:18,163 筆參選紀錄,串成 9,361 人。 + - 縣市長、議員(1994–2022)14,003 筆。 + - 總統副總統(1996、2000、2004、2008、2012、2016、2020、2024)50 筆:總統、副總統候選人各 25 筆。副總統候選人也是一筆參選紀錄,選舉寫「副總統」,得票、得票率、當選跟同一組的總統候選人(中選會副手列 2008 年起沒有當選註記),runningMate 記搭檔。 + - 立法委員 4,110 筆:區域立委(1995、1998、2001、2004、2008、2012、2016、2020、2024)3,121 筆,平地原住民 80 筆、山地原住民 83 筆,不分區 826 筆(2008–2024;1995–2004 的全國不分區、僑選名單壓縮檔裡沒有)。不分區立委沒有個人得票(votes、share 是 null),記政黨名單排名 listRank 與所屬政黨的全國政黨票 partyVotes、partyShare。 + - 總統副總統、原住民立委、不分區立委的縣市寫「全國」、countyCode 是 null;整個縣市只有一個立委選區的,選區是 null(只顯示縣市)。 + - 這次新增的 4,160 筆屬於 2,647 人:874 人原本就有縣市長、議員紀錄(同名+出生年串在一起,例如韓國瑜:1995、1998 臺北縣立委、2018 高雄市長、2020 總統、2024 不分區立委),1,773 人是新增的人。串人規則沒變(同名+出生年;沒有出生年才用同名+同縣市並標比對信心低)。 + - 沒有收:立委補選(19 個資料夾,資料裡沒有投票日)、「2008 12任總統」(和「20080322-總統」重複)、「2016總統立委/old」(舊版)。 +- data/build/people/records-report.md:各次選舉人數、這次新增幾筆幾人、比對不到的(含 10 組「同名、兩個檔案的出生年差 1 年」照規則沒有串的,給人工抽查)。 +- data/build/council/2014/2018/2022.json:議員選區、席次、村里、最後一席(這次沒有變)。 +- #/people:分類標籤「全部/總統/立委/首長/議員」+收集冊;縣市、年份、名字搜尋。總統分頁含副總統候選人;立委分頁含區域、原住民、不分區。選了縣市時,全國性的選舉(總統副總統、原住民與不分區立委)不會出現。 +- 五項分數:每個分數都附公式、代入的數字和出處,寫明「是遊戲數值,不是評價」。總統副總統、立委套同一套公式,例外寫在各項的算法裡: + - 知名度:單次最高得票取對數(1,000 票 0 分、500 萬票 10 分)。總統選舉是全國的票,500 萬票以上一律 10 分,不會超過;副總統用同一組的票;不分區沒有個人得票,那次不算。 + - 組織:1.5 × 當選次數 + 連任次數(副總統、不分區當選也算)。 + - 資歷:第一次當選到最後一次參選的年數 ÷ 2.5。 + - 選區實力:得票率 ÷ 同年同選舉同黨平均。總統副總統全國只有一場、每黨一組,沒有同黨可比,不算;不分區沒有個人得票率,也不算。 + - 財力:監察院政治獻金收入(2018、2022 縣市長,2020、2024 總統與區域立委;總統副總統是正副一組申報,算在總統候選人身上)。 +- **收集卡**(18 第 45 項,web/src/game/people):檔案室像收集卡冊——玩過的真實參選人是彩色檔案夾(標「玩過 N 次・最佳評等」),沒玩過的是灰色,但名字、政黨、說明、分數都看得到。打開檔案有「歷年參選證」:一次參選一張(年份、投票日、號次、選舉、選區、政黨、得票與得票率、當選與否、現任),可以左右翻。總統副總統的參選證選區寫「全國」、多一行「搭檔」,副總統註明「正副總統同一組的票」;不分區的參選證左邊大字是名單排名,得票欄寫政黨票。玩過誰記在 rogue/progress.ts 的 played(依名字;舊存檔第一次進來時從記錄過的局補算),自創角色不算。 +- **玩真實候選人的開局能力**(apps/server/src/people-routes.ts recordAbilities):只看那場選舉之前的紀錄,溫和換算成 0–2 級:媒體看單次最高得票(3 萬票 1 級、30 萬票 2 級)、組織看當選次數(1 次 1 級、3 次 2 級)、口才看第一次當選到最近一次參選的年數(4 年 1 級、12 年 2 級);財務、清廉沒有客觀依據一律 0。開場快報會寫出依據。每日一戰不套用。 + - 加了總統副總統、立委以後門檻不變:總統選舉的全國票數只會讓媒體停在 2 級(和大縣市的縣市長一樣),副總統用同一組的票;不分區立委沒有個人得票,不算進媒體,當選和其他選舉一樣算一次。 + - 認人:同名、比對信心不是低、有在這個縣市參選過(總統選舉不限縣市)。資料多了以後同名的人變多,所以同名有好幾位時,改成「有這場選舉本身紀錄的那位」優先(同一天投票、同一個縣市;總統選舉看總統副總統紀錄)。這一場的紀錄只拿來認人,不算進能力;還是認不出來或比對信心低就不給。 + - 用現有的劇本試算(舊資料+舊規則 → 新資料+新規則):拿到能力的真實候選人變多(2024 立委 127 → 187 位、2020 立委 141 → 207 位),因為很多立委以前在資料庫裡沒有紀錄;拿到能力的人三項加總的平均:立委劇本約 2.2 → 2.4–2.5 級,縣市長劇本約 1.8–2.0 → 2.5–2.6 級(以前很多人的立委資歷沒算到),2020、2024 總統候選人 3.3、4.0 → 4.7 級(上限還是 6)。也修掉一個認錯人的情況(2020 臺中市立委候選人以前會對到同名的另一位議員候選人)。 + +## 開票夜與選區地圖(18 第 36 項) + +- 開局記下選區名稱(RogueView.area),狀態列、開場快報、開票夜、結果圖卡都寫「高雄市第 4 選舉區立委」「高雄市第11選區議員」「大寮區潮寮里里長」。 +- GET /api/rogue/runs/:id/area:立委選區回傳選區內的村里,地圖只畫選區、放大到選區,選區外淡淡地畫在旁邊;議員選區另外回傳村里分群。總統關的地圖改用縣市為單位。 +- 開票夜改成像電視開票:各區同時一點一點開(每區自己的開始、開完時間,早開的票稍微偏向某一邊),顯示「開票 63%・開完 2 / 4 區」;票數和百分比一起跳;開票三成以後才提示換人領先。開票進度是遊戲演出,不是真實的投開票所。 + +## 每週流程整合(18 第 38 項) + +使用者要「操作流程越簡略越好,但必要的功能要留」。每週只剩三步:看對手 → 出牌 → 拿獎勵。 + +| 以前 | 現在 | +|---|---| +| 每週一開始跳出電視「選情快報」 | 地圖上方的新聞跑馬燈(brief.tsx NewsTicker),點一下才看電視;只有第一週開場自動播 | +| 記者堵麥擋在出牌前,選完再跳結果視窗 | 手牌最左邊一張紅色「事件牌」,這週內回答(伺服器:堵麥時 phase 是 plan,endWeek 會要求先回答);結果用提示和地圖跳字 | +| 民調公布要按繼續 | 第 4 週自動公布(RunState.poll),跑馬燈和提示顯示 | +| 黑函選完再跳結果視窗 | 選完直接用提示和跳字顯示 | +| 全市牌要按「打出這張牌」 | 再點一次那張牌就打出(按鈕也還在) | +| 結束這週 → 結算視窗一條一條播 → 按繼續 → 三扇門 → 進門 → 選 → 結果視窗 | 結算在地圖上跳字,右邊(手機在下面)同一個面板:本週戰果+三扇門;拜會地方、招募幕僚、地方抉擇的內容直接攤開,點一下就拿到(choose 的 option,伺服器在 prepareRoute 先備好門裡的內容);物資行、深入基層、升級、拿掉牌、小遊戲點了再進去 | + +一般的一週,出牌以外只要點 2–4 下(結束這週、選獎勵,有記者時多 1–2 下);以前要 7–9 下、跳 6–7 個視窗。牌、幕僚、劇情、辯論、黑函、小遊戲都留著。 + +## 後期節節敗退(18 第 37 項) + +對手每週變強的幅度調小(每週 +3.5%,後發制人 +5%;整體起始稍強)、行動數到最後一週才 4 個、大型造勢 ×2;狀態列加「今天開票預估(含聲勢帶出的未表態)」;第 5 週起快報提醒後期要佈樁、打對台。 + +## 平衡(模擬玩家) + +- 桃園勢均力敵(新辯論、小遊戲加入後):打得好 100%/100%,隨手玩 53%/32%(之前 46%/41%)。 +- 政治生涯地方選舉(apps/sim/src/career-balance.ts;臺北、高雄、彰化、花蓮 × 民進黨、國民黨、無黨籍): + - 里長(逆風 0):隨手玩 56–81%,打得好 85–100%(第一關刻意簡單)。 + - 議員(逆風 1):隨手玩 23–41%,打得好 84–100%。 + +## 測試 + +- rogue:48 項(新增 test/meta.test.ts:建築、能力、政策、小遊戲;辯論三項)。 +- server:25 項(帶政策島開局、每日一戰不帶、地方選舉、資料庫、依紀錄換算能力)。 +- web:12 項;Playwright 整局(自由選戰含小遊戲站、生涯里長關、任期→議員關、政策島、歷屆參選人,桌機與手機)都沒有錯誤。 diff --git a/backend/docs/24-avatar-shop-plan.md b/backend/docs/24-avatar-shop-plan.md new file mode 100644 index 0000000..e564914 --- /dev/null +++ b/backend/docs/24-avatar-shop-plan.md @@ -0,0 +1,172 @@ +# 24 紙娃娃與服裝店 + +> 第一階段與畫風已完成(2026-10-27):部件目錄、圖層畫法、第一批部件、解鎖、服裝店與小鎮幣、四種畫風。 +> 帳號、真錢、伺服器記帳、寵物、背景圖、表情包、由伺服器提供目錄都還沒做。對應 docs/18 第 50 項。 + +## 已完成:實際做法(2026-10-27) + +### 1a 目錄化(舊存檔一個字都不用改) + +| 東西 | 位置 | +|---|---| +| 目錄原始檔(JSON,46 件舊部件+27 件新部件、16 個部位、4 種畫風、色盤) | `backend/packages/protocol/data/avatar-catalog.json` | +| 目錄格式(Zod)+目錄規則檢查 `lintCatalog` | `backend/packages/protocol/src/avatar/schema.ts` | +| `checkAvatar`/`cleanAvatar`/`parseAvatarLoose`(讀壞存檔用)/`stampAvatarVersion`、每週上架 `shopShelf` | `backend/packages/protocol/src/avatar/catalog.ts`(`protocol/src/index.ts` 加了一行 export) | +| 產生的目錄與部件圖(不要手改) | `backend/packages/protocol/src/avatar/catalog.generated.ts`、`art.generated.ts`(前端用 `@election2026/protocol/avatar-art` 讀) | +| `AvatarSpecSchema`:髮型、服裝、眼鏡、五官從寫死的選項改成「代號格式」(英數+連字號、40 字內);加選填 `v`、`style`、`wear`(最多 12 件)、`tint`(最多 24 色) | `backend/packages/protocol/src/game.ts` | +| 伺服器開局清洗:看不懂的代號換預設、記一筆 log、不擋開局 | `backend/packages/content/src/custom.ts`、`backend/apps/server/src/app.ts`(`customWorld`) | +| 前端讀存檔清洗(自創角色;真人頭像用 `realPerson: true`) | `web/src/game/creator/characters.ts`、`web/src/game/art/candidateAvatar.ts` | +| 捏人物選項改讀目錄(名字也在目錄裡) | `web/src/game/creator/options.ts`、`LooksTabs.tsx` | + +- **部件代號永不刪除、永不改名。** 不賣了改 `status: "retired"`(舊存檔照樣能穿);畫錯了換圖,代號不變。目錄每次更新 `catalogVersion` +1,新部件記 `since`。測試會檢查所有舊代號都還在。 +- 舊部件代號只在同一個部位裡唯一(`round` 同時是臉型、眼睛、眼鏡);新部件代號全目錄唯一、用部位開頭(`hat-…`)。 +- 前端遇到不認得的代號:那一層不畫、不報錯。 +- 第一階段伺服器**不檢查「這件你有沒有買」**(沒有帳號)。 + +### 1b 圖層畫法 + +| 東西 | 位置 | +|---|---| +| 主元件(畫風判斷、貼紙濾鏡、像素轉換、背景) | `web/src/game/art/Avatar.tsx`(原本的 export 都保留:`Avatar`、`avatarFromSeed`、`AvatarSpec`、`HairStyle`) | +| 幾何、錨點(`headTop` 跟頭寬縮放、`face` 跟臉寬臉長)、Q 版頭身變形 | `web/src/game/art/avatar/geometry.ts` | +| 舊部件的程式畫法(從原本的 Avatar.tsx 搬過來,外觀不變) | `web/src/game/art/avatar/builtin.tsx` | +| 新部件畫法(魔術色換色、印號次名字) | `web/src/game/art/avatar/parts.tsx` | +| 照目錄一層一層疊(部位的 `layer`:body/face/head/hand/canvas),帽子壓住頭髮(`hideHairAbove`) | `web/src/game/art/avatar/layers.tsx` | +| 復刻像素轉換 | `web/src/game/art/avatar/pixel.tsx` | +| SVG 檢查轉檔(白名單元素與屬性;不准 script、style、文字、外部連結、url()、DOCTYPE;不能超出 200×220 畫布;檔案 16KB、形狀 400 個上限) | `backend/packages/protocol/src/avatar/svg.ts`、`backend/packages/protocol/scripts/build-avatar-catalog.ts`(`pnpm avatar:build`;`pnpm --filter @election2026/protocol avatar:check` 只檢查) | +| 部件檢查頁(每件部件 × 7 種臉+髮型 × 28/96/320 像素,可切畫風、部位) | `#/avatar-check` → `web/src/game/art/AvatarCheck.tsx` | + +- 魔術色:`#ff00ff` 主色、`#800080` 主色暗面、`#00ffff` 副色、`#008080` 副色暗面、`#ffff00` 膚色、`#808000` 膚色暗面、`#0000ff` 衣服色、`#000080` 衣服暗面、`#00ff00` 襯衫色(`art/avatar/README.md`)。其他顏色照原樣。 +- 64 像素以下(`size < 64`):胸前、手持物、外框不畫,部件上的字不印。 +- 預設色寫 `party` 的部件(競選背心、鴨舌帽…)跟角色的政黨色走(民進黨綠、國民黨藍、民眾黨青,其他用競選紅);換色存在 `tint`。 +- 舞台(捏人物)上的人物不畫外框(會被講台擋住),戴外框時右上角另外放一張加框的頭像卡。 + +### 1c 第一批 27 件(原創向量,LICENSES.md 加了一節) + +原圖在 `backend/packages/protocol/art/avatar/<部位>/*.svg`,全部手寫原創、不是 AI 生成、沒有用外部素材庫。 + +| 部位 | 部件(代號) | 怎麼拿到 | 價格 | 真人可穿 | +|---|---|---|---|---| +| 帽子 | 競選鴨舌帽(hat-campaign-cap,印號次) | 免費 | — | ✅ | +| 帽子 | 必勝頭帶(hat-victory-band) | 商店輪替 | 8 | | +| 帽子 | 斗笠(hat-bamboo) | 商店輪替(稀有) | 20 | | +| 帽子 | 機車安全帽(hat-helmet) | 商店輪替(稀有) | 24 | | +| 帽子 | 漁夫帽(hat-bucket) | 商店基本款 | 8 | | +| 口罩 | 素色口罩(mask-plain) | 免費 | — | ✅ | +| 口罩 | 號次口罩(mask-number) | 商店基本款 | 6 | | +| 背心外套 | 競選背心(outer-campaign-vest,號次+名字) | 免費 | — | ✅ | +| 背心外套 | 志工背心(outer-volunteer-vest) | 商店基本款 | 8 | | +| 背心外套 | 工地反光背心(outer-hivis) | 商店輪替 | 10 | | +| 背心外套 | 輕便雨衣(outer-raincoat) | 成就「逆轉勝」(稀有) | — | | +| 彩帶 | 候選人紅布條(sash-red,「3號 王小明」) | 免費 | — | ✅ | +| 彩帶 | 感謝鄉親謝票帶(sash-thanks) | 落選也打完一局 | — | ✅ | +| 彩帶 | 金色當選帶(sash-gold) | 成就「壓倒性勝利」(稀有) | — | ✅ | +| 胸前 | 當選紅胸花(chest-corsage) | 當選一次(稀有) | — | ✅ | +| 胸前 | 名牌(chest-name-tag) | 免費 | — | | +| 手持物 | 大聲公(held-megaphone) | 免費 | — | | +| 手持物 | 三角競選旗(held-flag) | 免費 | — | | +| 手持物 | 面紙包(held-tissue) | 商店基本款 | 6 | | +| 手持物 | 團扇(held-fan) | 商店輪替 | 6 | | +| 手持物 | 麥克風(held-mic) | 成就「辯論三戰全勝」(稀有) | — | | +| 手持物 | 保溫杯(held-thermos) | 商店輪替 | 8 | | +| 外框 | 選舉公報框(frame-gazette) | 免費 | — | | +| 外框 | 看板框(frame-billboard) | 商店輪替(稀有) | 20 | | +| 外框 | 報紙頭版框(frame-newspaper) | 商店輪替(稀有) | 24 | | +| 外框 | 金色當選框(frame-gold) | 成就「地方首長」(政治生涯選上縣市長,稀有) | — | | +| 外框 | 霓虹宣傳車框(frame-neon) | 限定:每年 11、12 月上架 | 36 | | + +- 名稱不用「凍蒜」:「凍蒜頭帶」改叫「必勝頭帶」(目錄規則會擋)。原方案的「安全帽:完成機車掃街小遊戲」「雨衣:雨天場次打贏」因為遊戲沒有記錄這兩件事,改成商店、成就「逆轉勝」。 +- 真人只開正式類(競選背心、彩帶、胸花、競選鴨舌帽、口罩),而且都不是商店部件(目錄規則會擋)。 + +### 1d 解鎖+服裝店+小鎮幣 + +| 東西 | 位置 | +|---|---| +| 小鎮幣與擁有清單(localStorage `tongsuan.wardrobe.v1`,照政策島的清洗寫法) | `web/src/game/shop/wardrobe.ts` | +| 拿到了沒、怎麼拿到、穿上/換色 | `web/src/game/shop/unlocks.ts`(成就與勝敗讀 `rogue/progress.ts`,只讀不改) | +| 服裝店(`#/shop`,GameScene 整頁不捲;試穿、確認後買、穿上;本週上架+基本款+限定;全部部件;小鎮幣紀錄) | `web/src/game/shop/ShopScreen.tsx`、`shop.css` | +| 捏人物新分頁:配件(加口罩)、行頭(帽子、背心外套、彩帶、胸前)、道具(手持物、外框)、畫風;沒拿到的格子灰色、寫怎麼拿到、稀有度角標 | `web/src/game/creator/LooksTabs.tsx`、`Pickers.tsx`、`options.ts`、`CreatorScreen.tsx`、`Stage.tsx`、`creator.css` | +| 結算發小鎮幣(結果畫面多一行「小鎮幣 +N」) | `web/src/game/rogue/finale.tsx`、`rogue-finale.css` | +| 首頁圓形圖示加「商店」 | `web/src/game/home/HomeScreen.tsx`(DOCK)、`home.css` | + +- **小鎮幣怎麼發**:每局打完(教學不算)當選 3、落選 2;S 評價 +2;第一次拿到的成就每個 +1;每日一戰 +2;政治生涯那一關選上 +2。同一局只發一次。普通款 6–10 幣(約 2–3 局)、稀有 20–24 幣(約 6–7 局)、限定 36 幣(約 10 局)。 +- **記帳**:分「免費取得」「付費取得」兩本(現在只有免費),買東西先扣免費的;沒有使用期限;每筆收支留紀錄(最多 1000 筆)。不能轉送、不能換現金、不抽獎。 +- **每週上架**:台灣時間星期一換貨;輪替的部件洗牌後每週 6 件,一輪每件都上一次(測試保證一年內一定再上架);`available.from` 在這一週的新品第一週一定上;基本款(`shelf: "always"`)一直都在;限定品(`available.months`)每年同一個時候回來。 + +### 畫風(做法 A:同一套部件換畫法,所有部件自動支援,真實政治人物也能用) + +| 畫風 | 做法 | +|---|---| +| 海報漫畫(預設,代號仍是 `comic`) | 見下面「1e 海報漫畫風」 | +| Q 版大頭 | 頭那一組放大 1.2 倍並往下移、身體那一組縮成 0.86;大眼睛加兩個反光點、鼻子變小、腮紅加深 | +| 復刻像素 | 把頭像畫到 256×280 的畫布,每 4×4 取一格(格子裡有夠多明顯更深的顏色就取深色,眼睛嘴巴才不會糊掉)變成 64×70 點陣,k-means 挑這張頭像自己的 16 色,外圍描一圈深色邊,再用每種顏色一條 path 畫回來(任何大小都銳利)。快取同一張頭像;瀏覽器不讓讀畫布時退回漫畫畫法。Chromium、WebKit 都試過 | +| 平面貼紙 | 去掉陰影,外面加粗白邊+細黑邊(SVG 濾鏡) | + +- 全遊戲畫風在設定(選戰畫面右上角齒輪「頭像畫風」,`web/src/game/hud/SettingsMenu.tsx`、`audio/settings.ts` 的 `avatarStyle`),也可以在捏人物的「畫風」分頁改;每個自創角色可以各自選(存在頭像的 `style`,優先於全遊戲設定)。 + +### 1e 海報漫畫風、破圖修正、新五官(2026-10-27) + +使用者覺得頭像「沒有特色、很 AI、會破圖、不夠精細、不像政治人物卡通化的特徵」,選了**海報風**;Grok **只畫通用素材**(維持 docs/14「不用 AI 畫真人」)。 + +- **破圖修正**:臉右邊那塊硬邊半透明橢圓陰影(切過臉頰)、跑出頭髮外面的分線(`side`/`volume`)、脖子上的橫向色帶,三個都拿掉。 +- **海報漫畫畫法**(`web/src/game/art/avatar/builtin.tsx`):每塊形狀描粗墨線(頭髮幾塊合起來描一圈外框,不留內線);暗面是「形狀減掉往左上挪一點的自己」剩下的一彎,一般大小平塗深一階,120 像素以上改成網點;不再用半透明黑色;黑髮高光是藍灰色筆觸;耳朵有 C 形內線、鼻子有鼻孔、嘴角有小勾、上眼皮粗墨線;平頭、光頭兩側、鬍渣用網點。64 像素以下線條加粗,省略網點、皺紋、鼻孔,眼睛只畫瞳孔加上眼皮(白眼球在這個大小會糊掉),眼鏡加粗。背景是競選看板的放射光芒(小圖只有平塗)。新部件(帽子、彩帶…)用 SVG 濾鏡自動描墨線外框,部件圖不用重畫。 +- **新五官**(目錄第 3 版,都是程式畫的 `builtin:`、真人可用;1f 又補了一批髮型、眼鏡、服裝):臉型「大下巴」、眼睛「下垂眼」「大眼」、眉毛「粗濃眉」、鼻子「圓鼻頭」、嘴巴「嘴角上揚」「開懷大笑」、髮型「平頭板寸」「中分」「側梳地中海」。 +- **政治人物誇張一點**(`web/src/game/art/likeness.ts` 的 `caricature`):臉寬、臉長偏離標準的量放大 2.2 倍、眉毛角度放大 1.5 倍(夾在協定範圍內);特徵資料本身沒改。 +- **美術參考**:Grok 畫了三張虛構人物的海報風參考稿(人物、髮型、五官),prompt 寫明虛構、不像任何真人;只當畫法的目標,**沒有放進遊戲**。 +- **政黨旗幟**(`web/src/game/PartyFlag.tsx`,使用者:「政黨有旗幟的都要畫出來」):查證後有黨旗的 14 個黨都畫(新黨、親民黨、建國黨、無黨團結聯盟、綠黨、喜樂島聯盟、國會政黨聯盟、台澎黨、客家黨、紅黨、台灣農民黨、民國黨、台灣工黨、中國青年黨),民眾黨沒有正式黨旗,改成黨色加「眾」字黨徽;只有黨徽的約 30 個黨不畫。勞動黨(一顆黃色五角星)、台灣主義黨(紅底一圈白色小星星)等使用者決定。 +- **不用單顆星星**(使用者:單顆紅星看起來像中國):部件上沒有號次時印「勝」(原本是「★」);地圖據點改「⚑」;最划算三區改大拇指;政治生涯的經驗、政績圖示改獎章。星等評分(★★☆、小遊戲三顆星)是黃色的一排,保留。 + +### 1f 歷屆候選人捏臉(第一批:第 11 屆立委,2024-10-27) + +使用者要「歷屆候選人都捏臉,缺的部件畫出來補進可以選的庫」,先拿 2024 年測試。 + +- **照片來源**:立法院網站的委員官方照片(g0v 的 `ly.govapi.tw/v2/legislators?屆=11` 有照片網址),框法一致。照片只當參考,不放進遊戲、不放進程式庫;每筆記 `ref`。 +- **怎麼判讀**:照片縮成 256 像素,依同一份判讀規則(臉型、臉寬臉長、髮型與分線、髮色、眼鏡款式、眉眼鼻嘴、皺紋、膚色、穿著顏色)記成頭像參數,不評論人、不寫外貌好壞。先自己判讀 6 位當校準範例,其餘 110 位分四批平行判讀,再逐筆檢查代號都在目錄裡、數值在協定範圍內。 +- **結果**:`web/src/game/art/likeness-2024.ts`(116 位,`likenessOf` 先查 `likeness.ts` 的 40 位、再查這份);`#/faces` 多一區。韓國瑜、黃珊珊、蔡其昌原本就有,不重做。 +- **同名同姓先不放**:吳宗憲、李柏毅、林月琴、林淑芬在歷屆資料裡不只一個人,頭像是照名字對的,放了會套到別人身上。要做得先讓候選人帶人物 id(`CandidatePublic` 現在沒有)。 +- **補進庫的部件**(判讀時發現畫不出來的,都做成通用部件,目錄第 3 版):髮型「抓立短髮」「高聳背頭」「長髮中分」「長波浪」「馬尾」「露耳短髮」「瀏海短髮」「齊瀏海長髮」,眼鏡「眉框眼鏡」,服裝「襯衫」(沒穿外套,身體是襯衫色)。 +- **還畫不出來的**(記下來,之後做):山羊鬍(現在 `beard` 只有整片鬍渣,要加鬍子款式欄位)、痣、耳環、髮箍、挑染/漸層染、兩鬢灰白、過耳的男性中長髮、格紋/直條紋布料、圍巾、原住民織紋背心、醫師白袍、運動外套。 +- **下一步**:2024 年沒選上的區域立委(約 250 位)可以用中選會選舉公報的候選人照片;不分區沒選上的大多沒有公開照片,維持預設頭像。 + +### 測試 + +- `backend/packages/protocol/test/avatar.test.ts`:舊存檔照樣過(每個舊選項)、看不懂的代號換預設、格式壞掉才擋、壞存檔不當機、真人不能穿 realPersonOk:false 和商店部件、目錄規則、產生的檔和原始檔一致、SVG 檢查擋掉 script/事件屬性/外部連結/超出畫布等、每週上架(6 件、一年內再上架、限定月份)。 +- `backend/packages/content/test/custom-avatar.test.ts`:開局時清洗自創角色的頭像。 +- `web/test/wardrobe.test.ts`:小鎮幣怎麼發、兩本帳、同一局只發一次、先扣免費的、沒上架不能買、清洗、解鎖條件、穿上換色不改舊物件、讀存檔時清洗(自創角色、真人頭像)。 + +### 還沒做(之後) + +- 帳號、真錢、伺服器記帳與「有沒有買」的檢查;寵物、背景圖、表情包、特效;目錄改由伺服器提供(`/api/avatar/catalog`)。 +- 政治生涯「任期」本身沒有另外發幣(只在那一關選上時 +2,因為任期畫面的檔案這次不能動)。 + +--- + +## 參考:開放真錢之前要注意的台灣法規 + +> 以下是 2026-10-27 查的,每點附官方出處。我不是律師;開真錢之前請律師或消保官看一次。查不到的地方照實寫查不到。 + +**先說名稱**:查不到「數位遊戲服務定型化契約應記載及不得記載事項」這個名稱。現行的是 **「網路連線遊戲服務定型化契約應記載及不得記載事項」**(經濟部 111.8.10 公告修正,112.1.1 生效;111.8.27 起改由數位發展部主管)。2023–2026 年沒查到新的修正或預告。 +出處:https://www.ey.gov.tw/Page/DFB720D019CCCB0A/964028ea-f1f6-4383-9c78-f7d0606086f3 (官方 PDF:https://www.ey.gov.tw/File/C27658C15073FF69?A=C ) + +| 規定 | 重點(白話) | 第一階段(只有遊戲內點數)要管嗎 | 出處 | +|---|---|---|---| +| 適用範圍 | 「連結網際網路至業者指定之伺服器所進行連線遊戲服務」都算。我們的網頁遊戲會連到自己的伺服器,**照字面應該在範圍內**(這是我們的解讀;官方對「網頁遊戲」「完全免費遊戲」適不適用的說法**查不到**;個人專案算不算「企業經營者」也**查不到**) | 收錢之後一定要管 | 同上 | +| **扭蛋要公告機率**(第六點) | 只要「直接或間接、部分或全部付費」的抽獎,就要在官網首頁、遊戲登入頁或購買頁公告每個獎項的**中獎機率百分比**,並加註「此為機會中獎商品,消費者購買或參與活動不代表即可獲得特定商品」。「直接」指轉蛋、抽卡、開箱、轉盤;「間接」指用付費材料合成、強化。**免費取得的抽獎可以不揭露。** 付費和免費點數都能抽的同一個池子,算「部分付費」,要公告 | 不收錢就不用;但我們推薦根本不做扭蛋 | 數產署「第六點處理注意事項」(2022.12.28):https://gamerating.org.tw/Message/MessageView?itemid=2530&mid=6 | +| 保底 | 應記載事項**沒有強制**。「範本」第九條列了保證獲取機制、稀有商品數量,並要求紀錄保存到活動結束後至少 180 日(範本只是參考) | — | https://www.ey.gov.tw/File/5B529FA70DF20494?A=C | +| 機率改了怎麼辦 | **沒有專門條文**。相關的是:廣告內容算契約的一部分(第三點)、收費調整要 30 日前公告(第五點)、契約變更沒公告又沒通知的無效(第十七點) | — | 應記載事項 PDF | +| 未成年人(第二點) | 未滿 18 歲要法定代理人同意;沒同意就付費的,家長可以依官網流程申請退還**未使用**的費用;官網首頁、登入頁或購買頁要用中文明顯標示這件事 | 收錢之後 | 應記載事項 PDF;民法第 12、13、77、79 條:https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=B0000001 | +| 7 日內可以反悔(第四點) | 開始玩之後 7 日內可以書面解除契約,未使用的付費點數要退。消保法第 19 條+「通訊交易解除權合理例外情事適用準則」第 2 條第 5 款(數位內容經消費者事先同意、經告知,可排除);但同準則第 3 條說,已經有應記載事項的行業,**照應記載事項**——所以線上遊戲回到第四點 | 收錢之後 | https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=J0170012 | +| 停止營運(第十九點) | 至少 30 日前公告並依玩家留的聯絡方式通知;沒做到的話,退未使用付費點數不得扣成本,還要另外補償 | 收錢之後(需要玩家聯絡方式=需要帳號) | 應記載事項 PDF | +| 點數不能設期限(不得記載事項第十點) | 不得記載付費點數的使用期限 | 現在就照做 | 應記載事項 PDF | +| 帳號與紀錄(第七、九點) | 契約終止後帳號資料至少留 30 日;遊戲歷程至少存 30 日,玩家申請要 7 日內提供(查詢費不超過 200 元) | 有帳號之後 | 應記載事項 PDF | +| 禁止場外轉賣(第十一點) | 玩家的使用權「不包括本遊戲服務範圍外之移轉、收益行為」——可以在條款裡禁止拿去外面賣 | 寫進條款 | 應記載事項 PDF | +| 違反的後果 | 違反的條款無效,沒寫的應記載事項仍算契約內容(消保法第 17 條);限期改正不改罰 3–30 萬元,再不改 5–50 萬元,可按次罰(第 56-1 條) | — | https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=J0170001 | +| **賣儲值點數要有履約保證** | 「線上遊戲點數(卡)定型化契約應記載及不得記載事項」(數位發展部 112.8.9 修正):預付金額購買、登錄到帳號使用的點數都算(非實體的也算)。發行人要擇一提供:金融機構足額保證至少 1 年、同業連帶擔保、信託專戶、同業公會聯合保證、其他經數發部許可的方式。可以區分的附贈點數不在保證範圍。不得記載使用期限、不得記載「餘額不得消費」 | **如果之後賣「小鎮幣包」就要**;直接用錢買單件外觀、不儲值,照定義看不像「預付點數」(這是我們對條文的解讀,請律師確認) | 我已打開官方 PDF 核對:https://www.ey.gov.tw/File/51EC75FADD57B227?A=C | +| **遊戲分級** | 「遊戲軟體分級管理辦法」(108.5.23 修正,現由數位發展部主管):五級(限制級 18+、輔導十五歲級、輔導十二歲級、保護級 6+、普遍級)。網頁遊戲也要:在起始網頁或連結處旁明顯標示(限制級標識至少 50×50 像素,其他至少 45×45 像素),並上市前到主管機關資料庫登錄。**用點數、虛擬幣、虛擬寶物付費的,要標示付費內容及金額、「遊戲部分內容或服務需另行支付其他費用」等警語**(第 13 條)。辦法裡沒有「機率」字樣,扭蛋不影響級別 | **分級跟商城無關,遊戲本身就要做**(docs/14 已經提過要自評:本作有賄選、黑函、政治諷刺);付費警語收錢後才要 | 我已打開條文核對:https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=J0030086 ;登錄說明:https://gamerating.org.tw/Faq?itemid=4&mid=14 | +| 稅 | 臺北國稅局說明:自 114.1.1 起每月起徵點貨物 10 萬元、勞務 5 萬元;個人網路銷售沒到可以暫免稅籍登記,到了就要登記,並在銷售頁明顯揭露統一編號和營業人名稱。遊戲虛擬物品算貨物還是勞務、發票怎麼開:**查不到** | 收錢之後 | https://www.etax.nat.gov.tw/etwmain/tax-info/network-transaction-taxtation-area/press/3EYDDZV | +| 收款方式 | 「電子支付機構管理條例」第 5 條:不是電子支付機構不能做代理收付,收款要走合法金流。只能在自己遊戲用的點數,照第 3 條第 10 款但書看不屬於「多用途支付」(解讀,金管會函釋**查不到**) | 收錢之後 | https://law.moj.gov.tw/LawClass/LawSingle.aspx?pcode=G0380237&flno=3 | +| 防詐 | 「詐欺犯罪危害防制條例」第 2 條第 8 款:營運連線遊戲的業者、發行遊戲點數的發行人都算「網路連線遊戲業者」;第 36 條要盡善良管理人注意義務防止被拿去詐騙、配合停權;第 37 條要保存連線或交易紀錄,司法機關調取時 3 日內提供 | 有帳號、能交易之後 | 我已打開條文核對:https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=D0080226 | +| 賭博疑慮 | 官方對「扭蛋算不算賭博」「虛擬物品換現金」的說法**查不到**。刑法第 266 條:用網路賭博財物處罰金,但「以供人暫時娛樂之物為賭者,不在此限」。律師文章多以「能不能換成現金」當判斷重點(非官方) | 我們的做法:不能換現金、不能轉送、不做扭蛋 | https://law.moj.gov.tw/LawClass/LawSingle.aspx?pcode=C0000001&flno=266 | +| 手機商店(如果之後上架) | Apple 3.1.1:隨機抽(loot box)要在購買前揭露每種物品的機率;用 App 內購買的遊戲幣不能過期。Google Play:隨機虛擬物品要在購買前、靠近購買處清楚揭露機率 | 上架才要 | https://developer.apple.com/app-store/review/guidelines/ ;https://support.google.com/googleplay/android-developer/answer/9858738 | + +**整理成一句話**:第一階段只用遊戲內點數、不收錢,上面大多還用不到(遊戲分級除外,那是遊戲本身就要做的)。真錢那天,最省事的組合是:**有帳號 → 直接用錢買單件外觀(不賣儲值點數、不做扭蛋)→ 走合法金流 → 條款照應記載事項寫 → 標示分級與付費警語**。 diff --git a/backend/docs/README.md b/backend/docs/README.md new file mode 100644 index 0000000..d6f3732 --- /dev/null +++ b/backend/docs/README.md @@ -0,0 +1,151 @@ +# 選舉小鎮 — 架構總覽 + +以台灣選舉為舞台的網頁遊戲。主要玩法是**選戰卡牌**:用政府開放資料建出真實的選民結構當底盤,8 週出牌拉票,最後開票夜一區一區翻過來。 +外圍有政治生涯(里長一路選到總統)、政策島、小遊戲、捏人物與服裝店、歷屆參選人資料庫。 + +> 本文件寫的是 2026-10-28 程式碼的實際狀態。舊的設計文件(十週行程版、多人連線、舊架構等)描述的東西已刪除或沒有做, +> 已經移除;程式註解裡提到的 docs/02、04–09、11–13、15–17、21 指的就是這些舊文件,原文在 2026-10-28 的備份裡。 + +## 全貌 + +``` +政府開放資料、中選會、Wikidata + │ + ▼ +backend/data/pipeline(Python)──► backend/data/build/ + ├─ packs/ 資料包:村里人口、選民群、歷史得票、地圖 + ├─ scenarios/ 劇本:真實候選人與得票,加上 calibration.json + ├─ people/ records.json(歷屆參選人)、genders.json、slogans.json + └─ council/ 議員選區 + │ ▲ + │ apps/sim 校準 ─────┘(舊十週引擎讓 AI 對打,寫 calibration.json) + ▼ +backend/packages ──► backend/apps/server(Fastify,REST /api)──► web(React + Vite) + │ │ + data/runs/<局>.json 瀏覽器 localStorage + (每一局卡牌的存檔) (進度、生涯、外觀、設定) +``` + +## 兩個程式庫 + +| 程式庫 | 內容 | 規則 | +|---|---|---| +| `backend/` | pnpm workspace:規則、伺服器、校準工具、Python 資料管線 | 所有結算都在這裡 | +| `web/` | React 19 + Vite;3D 小鎮用 three.js | 只依賴 `@election2026/protocol`,不含遊戲規則 | + +前端拿到的是伺服器算好的「玩家視角」,自己不算票。改畫面不用動後端,改規則不用動前端。 + +## 後端套件 + +| 套件 | 做什麼 | 誰用 | +|---|---|---| +| `packages/protocol` | 前後端契約:Zod 定義(資料包、劇本、卡牌的請求與回應、參選人資料)、頭像部件目錄、政黨清單;`pnpm schema` 產生 JSON Schema 給 Python 驗證 | 全部,包括前端 | +| `packages/rogue` | 選戰卡牌的規則:純函式,狀態可序列化,同一個種子同一局 | server、sim | +| `packages/engine` | 選民模型(docs/03),加上舊的十週選戰引擎 | rogue 開局用選民模型;十週引擎只給 sim | +| `packages/content` | 十週引擎的行動、事件、記者堵麥、議題;手工劇本;自創角色 | server、rogue、sim | +| `packages/scenarios` | 劇本目錄:手工劇本+管線產生的全台劇本,套上校準值 | server、sim | +| `packages/pack-loader` | 從磁碟讀取並驗證資料包、劇本、標語、性別 | server、sim | +| `apps/server` | Fastify API,速率限制;卡牌每一局放記憶體(最多 200 局)並寫到 `data/runs/` | 前端 | +| `apps/sim` | 校準(`calibrate-local.ts`)、回測、平衡報告(卡牌、生涯、政黨、大絕招、里長) | 開發者 | + +### rogue 裡面 + +| 檔案 | 內容 | +|---|---| +| `setup.ts`、`local.ts` | 開局:用選民模型算各區(或各里)底盤與地區特色;`local.ts` 是里長、議員關 | +| `rules.ts` | `createRun`、`endWeek`、`choose`、`ultimate`,以及從 `cards.ts` 轉出的 `playCard`:每個動作回傳新的狀態 | +| `state.ts` | `RunState`、`TOTAL_WEEKS = 8`、存檔版本 `SAVE_VERSION` 與 `migrateRun` | +| `data.ts`、`cards.ts` | 牌的資料與效果 | +| `rival.ts` | 對手每週的意圖與行動 | +| `route.ts`、`scenes.ts`、`content.ts` | 每週結束的「下一站」、辯論/民調/黑函週、堵麥與地方抉擇 | +| `advisors.ts`、`feats.ts`、`meta.ts`、`ultimate.ts`、`mechanics.ts` | 幕僚、成就、生涯能力與政策、大絕招、逆風等級 | +| `view.ts` | 給前端的玩家視角(含每張手牌打在每一區的預估) | +| `tutorial.ts`、`bots.ts` | 新手教學;模擬玩家(平衡報告用) | + +## API + +| 路由 | 用途 | +|---|---| +| `GET /api/health` | 健康檢查 | +| `GET /api/scenarios` | 劇本清單(候選人、能力值、查證過的標語) | +| `GET /api/packs/:packId/topology` | 地圖 | +| `GET /api/rogue/catalog` | 目錄:牌、幕僚、事件、成就、逆風等級、生涯能力、政策島建築(圖鑑、生涯、政策島用) | +| `POST /api/rogue/runs` | 開一局:劇本、候選人、種子、逆風、勢均力敵、每日一戰、自創角色、生涯帶過來的東西、里長/議員關 | +| `POST /api/rogue/tutorial` | 開新手教學 | +| `GET /api/rogue/runs/:id`、`/area` | 這一局的玩家視角、地圖範圍 | +| `GET /api/rogue/villages/:scenarioId` | 里長關選里用 | +| `POST /api/rogue/runs/:id/play`、`/end-week`、`/choose`、`/ultimate` | 出牌、結束這週、選下一站、大絕招 | +| `GET /api/people`、`/api/people/:id` | 歷屆參選人與客觀資歷分數(`records.json`) | + +## 前端 + +`web/src/App.tsx` 是 hash 路由;首頁和卡牌一開始就載入,其他畫面用到才下載。 + +| 資料夾(`web/src/game/`) | 畫面 | +|---|---| +| `home`、`start` | 首頁、會動的 3D 選戰小鎮 | +| `rogue` | 卡牌大廳、一局、開票夜、結果圖卡、圖鑑與成就、政治生涯 | +| `career` | 任期小遊戲(質詢、審預算…) | +| `island` | 政策工坊與政策島 | +| `minigames` | 掃街握手、造勢、看板等小遊戲 | +| `creator`、`shop`、`art` | 捏人物、服裝店、頭像繪製(部件目錄,docs/24) | +| `people` | 歷屆參選人 | +| `board3d`、`stage`、`news`、`audio`、`ui`、`hud` | 3D 棋盤、地圖、新聞台、音樂音效、共用元件、設定 | +| `../viewer`、`../map` | 資料檢視器(開發用) | + +玩家進度沒有帳號,存在瀏覽器 `localStorage`(鍵都以 `tongsuan.` 開頭:卡牌進度、生涯、政策島、外觀與小鎮幣、自創角色、小遊戲紀錄、設定)。 + +素材:`web/public/assets/` 是 CC0/OFL 素材(逐檔記在 `LICENSES.md`);`web/public/cards/` 是卡牌插圖,用 `art/` 裡的腳本產生;頭像部件是原創 SVG,放在 `backend/packages/protocol/art/avatar/`,`pnpm avatar:build` 轉成程式碼。 + +## 一局卡牌怎麼跑 + +1. 前端 `POST /api/rogue/runs`。伺服器從劇本目錄找劇本,讀資料包(同一份快取),`rogue/setup.ts` 用選民模型算出各區底盤,`createRun` 產生初始狀態。 +2. 每個動作(出牌、結束這週、選下一站)都是 `rules.ts` 的純函式:舊狀態 → 新狀態。伺服器存起來(記憶體+`data/runs/.json`),回傳 `view.ts` 算好的玩家視角。 +3. 種子決定一切:同一個種子、同樣的選擇就是同一局。每日一戰的種子由日期算出,「挑戰朋友」連結帶著種子。 + +## 資料管線 + +`backend/data/pipeline`,指令是 `election-data`(安裝方式見 `backend/README.md`): + +| 指令 | 產出 | +|---|---| +| `pack --county <代碼>` | 資料包:村里人口與 30 個選民群、歷史得票、村里屬性、地圖(`--before` 做回測用的資料包) | +| `local --year`、`races --year` | 縣市長、總統、區域立委劇本(候選人層級得票和中選會核對) | +| `donations` | 政治獻金(劇本的錢) | +| `records` | 歷屆參選人與資歷分數、議員選區 | +| `parties` | 歷屆政黨清單(也寫 `protocol/src/parties.ts`) | +| `python -m election_data.genders` | 候選人性別(給頭像) | +| `python -m election_data.people`、`.scoring` | 人物資料庫與 AI 評分(rubric-v1)。**目前遊戲沒有用到這兩份產出** | + +資料來源與授權見 docs/10;每個資料包的 `sources.json` 列出來源、版本與擷取日期。 + +## 測試與檢查 + +```bash +cd backend && pnpm typecheck && pnpm test # 協定、引擎、內容、卡牌、劇本、伺服器 +cd web && pnpm typecheck && pnpm test && pnpm build +cd backend/data/pipeline && .venv/bin/pytest && .venv/bin/ruff check src tests +``` + +## 原則 + +1. 規則只在後端,前端只依賴協定。 +2. 規則是純函式、狀態可序列化,同一個種子可以重現(測試、存檔、挑戰朋友都靠這點)。 +3. 內容是資料:牌、事件、幕僚、劇本都是資料檔,新增內容不改規則。 +4. 真實資料、真實人物有界線:不用照片、不用 AI 畫真人、不捏造真人引述、AI 控制的真實人物不用奧步(docs/14)。 + +## 文件 + +| 文件 | 內容 | +|---|---| +| [03-voter-model.md](03-voter-model.md) | 選民模型:選民群、投票公式、參數、校準 | +| [10-data-sources.md](10-data-sources.md) | 資料來源、授權、已查證的法規(部分資料源只是研究,文件開頭有說明) | +| [14-legal-and-ethics.md](14-legal-and-ethics.md) | 真實人物、政黨、選舉期間的法律與倫理界線 | +| [18-feedback-backlog.md](18-feedback-backlog.md) | 使用者回饋與改版紀錄(歷史紀錄;程式註解的「18 第 N 項」指這裡) | +| [19-classic-battles.md](19-classic-battles.md) | 歷史劇本:1996–2024 總統、2014 縣市長怎麼做出來的 | +| [20-campaign-slogans.md](20-campaign-slogans.md) | 真實候選人的競選標語與出處 | +| [22-rogue-v2.md](22-rogue-v2.md) | 選戰卡牌:玩法、機制、平衡 | +| [23-career-and-meta.md](23-career-and-meta.md) | 政治生涯、政策島、小遊戲、歷屆參選人與資歷分數 | +| [24-avatar-shop-plan.md](24-avatar-shop-plan.md) | 紙娃娃部件目錄、畫風、服裝店;附開放真錢前的法規整理 | +| [rubric-v1.md](rubric-v1.md) | AI 評分規則(由評分管線產生) | +| [appendix-1994-original.md](appendix-1994-original.md) | 1994 年原作《臺灣模擬選戰》的拆解紀錄 | diff --git a/backend/docs/appendix-1994-original.md b/backend/docs/appendix-1994-original.md new file mode 100644 index 0000000..a7cce5c --- /dev/null +++ b/backend/docs/appendix-1994-original.md @@ -0,0 +1,124 @@ +# 附錄:原作《臺灣模擬選戰》拆解紀錄 + +軟體世界(智冠科技),1994 年,DOS。 +本紀錄來自解讀原作資料檔與執行檔中的 Big5 文字,執行檔沒有被執行。僅作為設計研究,不進入遊戲內容。 + +## 開局 + +- 主選單:進行新遊戲、載入舊進度、登錄新政黨、登錄新人物 +- 兩種選舉:199X 立法委員選舉(當時為複數選區)、199Y 縣市長選舉 +- 設定:選擇選區、是否限制候選人總數(不可少於或等於應選人數)、遊戲者人數(同機多人) +- 捏臉:輪廓、眉毛、眼鼻、眼鏡、嘴、頭髮、鬍子;另有「傳統型」「俊美型」 +- 人物屬性:年紀、親和力、知名度、財產(百萬)、謀略、學歷;黨籍與黨職(無黨籍不可擁有黨職) + +## 資料檔 + +| 檔案 | 內容 | +|---|---| +| `DISTRICT.DAT` | 縣市 | +| `SECTIONS.DAT` | 約 390 個鄉鎮市區,每筆約 231 位元組:人口結構比例與一位地方人物(樁腳) | +| `MAPFILE/` | 29 組地圖,每組 A、B 兩張 | +| `REGPARTY.DAT` | 政黨(中國國民黨、民主進步黨、新黨、中華社民黨、工黨、勞動黨、勞工黨、中國青年黨、共和黨)與黨職 | +| `REGHUMAN.DAT` | 約 150 位真實人物:政府官員、政黨幹部、縣市長、企業家、藝人 | +| `GOVERNME.DAT` | 中央與地方政府機關(含臺灣省政府、省議會、各縣市政府與議會) | +| `ASSOC.DAT` | 社團:全國工業總會、全國商業總會、工商協進會、中小企業聯合會、消費者文教基金會、董氏基金會、農會、漁會、工會、公會、合作社、登山會、大佛寺、一貫道壇、基督教會、天主教會、同鄉會、老人會 | +| `ENTERPRI.DAT` | 35 個企業集團負責人 | +| `OCCUP.DAT` | 社會賢達的職業:醫師、律師、教授、作家、演藝人員、勞工、農夫、教師、工程師、公務員、上班族、藝術家、地方仕紳、大專校長、慈善家、運動員、自由業 | +| `EVENTS.XAT` | 依日期排列的時事新聞 | + +## 頭像 + +解讀自 `*.HHH` 部件檔(研究用途,不使用原作素材): + +| 檔案 | 部件 | 尺寸 | 數量 | +|---|---|---|---| +| `OUTLINE.HHH` | 輪廓(臉型、服裝、背景) | 72 × 90 | 36 | +| `HAIR.HHH` | 頭髮 | 72 × 90 | 36 | +| `EYENOSE.HHH` | 眼睛與鼻子 | 72 × 30 | 36 | +| `MOUTH.HHH` | 嘴 | 72 × 30 | 36 | +| `GLASS.HHH` | 眼鏡 | 72 × 30 | 36 | +| `EYEBROWS.HHH` | 眉毛 | 72 × 30 | 18 | +| `BEARD.HHH` | 鬍子 | 72 × 30 | 18 | + +- 格式:每個部件 4 位元組標頭(寬 − 1、高 − 1),接著逐列的 4 個位元平面(16 色),每個部件尾端 20 位元組。 +- 調色盤在 `DACSET.DCT`(PCX 標頭中的 16 色調色盤)。 +- 風格:正面半身,網點抖動做出臉部陰影,含領帶、襯衫領口、西裝與彩色背景,比例接近真人並帶政治漫畫的誇張。 +- 2026 版原本以此為頭像寫實程度的下限;2026-10-27 改成卡通化的向量頭像(docs/24)。 + +## 每個鄉鎮的人口結構 + +| 維度 | 分類 | +|---|---| +| 族群 | 閩南、客家、外省、原住民 | +| 職業 | 農民、漁民、工人、公教、工商、服務 | +| 學歷 | 研究所、大學、專科、高中、國中、國小、無 | +| 宗教 | 佛教、道教、一貫道、天主教、基督教、無 | +| 政黨傾向 | 執政、反對、其他、無 | +| 其他 | 暴力指數 | + +## 主畫面 + +- 情報:政府官員、政黨幹部、社團幹部、企業主管、社會賢達、競選總部、候選人、民意調查 +- 週行事曆、執行、天氣、金錢 +- 系統:儲存遊戲、音樂、音效、動畫、訊息延遲、**電腦接管** + +## 行動(共 30 項) + +| 類別 | 行動 | +|---|---| +| 正派 | 挖樁腳、抗議政府、控告他人、炮轟金牛、總部示威、辦政見會、街頭拉票、拜訪選民、刊登廣告、設服務處、募款餐會、提出政見、募款、敦請推薦、拜訪社團 | +| 管理 | 人事調整(延攬人才、招募義工、遣散義工)、設備管理(租宣傳車、退租車輛、印製海報、印製傳單) | +| 灰色 | 送紀念品、開流水席、聯歡晚會、斬雞頭 | +| 黑色 | 假槍擊、午夜拜票(冒名打電話陷害對手)、黑函、為敵買票(栽贓)、搓圓仔湯、買票 | +| 自我 | 鍛鍊身體(五千公尺、球類運動、重量訓練)、讀書、買學歷 | + +細節: + +- 送禮選項:賓士、BMW、勞力士、XO、中秋月餅、傻瓜相機 +- 書單:三國演義、國父思想、中華民國憲法、孫子兵法、四書五經、金賽性學報告、般若心經、官場現形記、總統嘉言錄 +- 買學歷:九所諧音野雞大學,例如「美國 第一野雞大學 文學博士」 +- 幕僚職位:總幹事、財務部長、組織部長、宣傳部長、助選員、顧問、保鏢 +- 「保鏢必須找體能超強,且社會份量不高者,否則再多錢也無用」 +- 「%s 已宣布退選,但選委會之登記未取消」 + +## 政見與訴求(1994 年的時代背景) + +政見:著重市政建設、台灣加入聯合國、兩岸直航、保護大陸台商、保護弱勢團體、修改兩性平等工作法、推動兩岸交流、 +軍備預算與採購公開、公共工程預算與招標公開、推動教育自由化、二次土地改革、保護水資源與防制污染、台灣獨立、保護野生動物、國會改革 + +抗議訴求:兩岸交流效率不彰、野生動物保育法、保障農民權益、老人福利法、反核、選委會立場不中立、健保費率過高、 +強制汽車第三責任險、公共場所安全、無殼蝸牛、輻射與海砂屋、敬老津貼、橫掃財閥金牛 + +## 攻防的罪名與指控 + +控告罪名:槍擊暴力事件、貪污瀆職、賄賂官員、競選資格不符、毀損他人選舉看板 + +到對手總部抗議的理由(**針對對手做過的行動**):送禮形同賄選、斬雞頭違反保育動物精神、聯歡會出現清涼秀、 +發送黑函、期約賄選、午夜拜票、人身攻擊、公帑私用、與黑社會掛勾、選舉經費超支 + +黑函內容:黑道人物、辦流水席大請客、黨部支持人選內定、私生活不檢點、外遇、濫用職權 + +斬雞頭誓詞:如有買票全家死光光、絕不與財團掛勾、老人年金未如期發放立即辭職、如果說謊當如此雞、絕不在任期中途辭職、絕不關說司法 + +## 隨機事件與新聞 + +- 時事新聞:電腦病毒、出口成長、飆車、登革熱、聯合國入會案、銀行搶案、水災、KTV 大火、立法院肢體衝突、颱風、 + 建築倒塌、聯考存廢、地震、軍購、連環車禍、青少棒奪冠、工程弊案、股市炒作、捷運火燒車、圍廠抗議、愛滋、 + CPU 降價、大陸偷渡客、國軍演習、選舉行情落空導致股市重挫 +- 彩蛋:「軟體世界出版《臺灣模擬選戰》,造成瘋狂搶購」、「軟體世界榮獲國家精品獎」 +- 選舉事件:選民自動捐款、保鏢被槍擊、競選總部被搗毀、資金耗盡選務停擺、候選人過度疲勞、政見會被嗆 +- 新聞形式:午間新聞、晚間新聞、報紙;開票由「寶島電視公司」實況轉播 + +## 對 2026 版的啟示 + +| 原作的設計 | 2026 版現在的做法 | +|---|---| +| 鄉鎮人口結構決定支持度 | 保留,改用真實開放資料並細到里(docs/03) | +| 30 項行動的正派到黑色光譜 | 改成卡牌:地面、組織、空戰、攻防、資金五派(docs/22) | +| 總部示威可以指控對手做過的事 | 打探拿把柄、有把柄才能全額爆料(docs/22) | +| 可以直接查看對手總部 | 每週看得到對手的意圖(docs/22) | +| 登記後退選名字仍在選票上 | 選民模型保留這條:退選者的支持者大多跑票(docs/03) | +| 電腦接管 | 沒做(沒有多人模式) | +| 同機多人 | 沒做;只有「朋友挑戰」(同一個種子各自玩) | +| 真實人物 | 保留:歷屆參選人使用真實姓名與公開資料,能力分數來自客觀資歷(docs/23);也可以捏自創角色;頭像不用照片(docs/14) | +| 捏臉系統 | 部件目錄、四種畫風、服裝店(docs/24) | diff --git a/backend/docs/rubric-v1.md b/backend/docs/rubric-v1.md new file mode 100644 index 0000000..c7554b9 --- /dev/null +++ b/backend/docs/rubric-v1.md @@ -0,0 +1,82 @@ +# 人物評分規則 v1 + +## 共通規則 + +1. 分數以全台灣的政治人物與公眾人物為比較基準,50 分代表一般水準。 +2. 每個分數都必須引用證據清單中的編號;沒有證據支持時,回報資料不足(insufficient),不要猜。 +3. 只使用與其公開角色相關的公開資訊。不考慮私生活、家人、外貌。 +4. 政黨、政治立場不是評分因素;同樣的表現不論政黨都給同樣的分數。 +5. 爭議中、尚未定案的指控不能作為扣分依據;只有確定判決或官方正式認定的事項可以。 +6. 理由用繁體中文寫一到兩句,直接說明依據,不超過 120 字。 + +## 親和力(affinity) + +與一般民眾互動的溫度與接地氣程度,包括基層走訪、服務案件、與選民面對面的互動。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 長期以基層經營著稱,親民形象被多家媒體反覆報導 | +| 60–79 | 有穩定、可查的地方走訪或服務紀錄 | +| 40–59 | 一般;公開資料沒有特別突出的正面或負面紀錄 | +| 20–39 | 公開報導多描述其距離感,基層互動紀錄少 | +| 0–19 | 多次因對待民眾的態度引發廣泛的公開批評 | + +## 口才(eloquence) + +辯論、質詢、受訪、演講的表達能力與臨場反應。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 在全國性辯論、質詢或重大記者會中的表現被廣泛報導為出色 | +| 60–79 | 公開發言條理清楚,有可查的良好表現紀錄 | +| 40–59 | 一般 | +| 20–39 | 公開發言常被報導為不清楚或失準 | +| 0–19 | 多次重大失言並造成廣泛負面報導 | + +## 謀略(strategy) + +選戰操盤、議程設定、協商與組織動員的成效。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 多次在困難選情中勝選,或主導重大政治協商、法案、組織改造成功 | +| 60–79 | 有可查的成功選戰或協商紀錄 | +| 40–59 | 一般 | +| 20–39 | 公開紀錄中策略失誤多於成功 | +| 0–19 | 多次重大策略失誤並被廣泛報導 | + +## 網路魅力(online) + +社群平台的經營成效與網路聲量,以公開的追蹤數與互動情形為主要依據。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 主要平台追蹤數居全國政治人物前列,經常產生大量互動 | +| 60–79 | 追蹤數與互動在同層級公職中屬前段 | +| 40–59 | 一般 | +| 20–39 | 社群經營有限 | +| 0–19 | 幾乎沒有經營社群,或網路聲量以負面為主 | + +## 形象(image) + +公眾對其清廉、專業、可信度的整體觀感,以公開民調的好感度、信任度為主要依據。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 公開民調的好感或信任度長期居前段 | +| 60–79 | 好感度高於同層級平均 | +| 40–59 | 一般或資料不足以判斷高低 | +| 20–39 | 好感度明顯低於同層級平均 | +| 0–19 | 長期居於各項民調的末段 | + +## 財力(wealth) + +個人可動用的財務資源,以公開的財產申報與公開報導為依據。 + +| 分數 | 描述 | +|---|---| +| 80–100 | 公開申報或報導顯示資產規模在政治人物中居前段 | +| 60–79 | 高於同層級平均 | +| 40–59 | 一般或資料不足 | +| 20–39 | 低於同層級平均 | +| 0–19 | 公開資料顯示資源非常有限 | diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..0be9a7b --- /dev/null +++ b/backend/package.json @@ -0,0 +1,18 @@ +{ + "name": "election-2026-backend", + "private": true, + "type": "module", + "packageManager": "pnpm@10.33.0", + "scripts": { + "test": "pnpm -r test", + "typecheck": "pnpm -r typecheck", + "schema": "pnpm --filter @election2026/protocol schema", + "avatar:build": "pnpm --filter @election2026/protocol avatar:build" + }, + "devDependencies": { + "@types/node": "^26.6.5", + "mapshaper": "^0.7.98", + "typescript": "^7.0.2", + "vitest": "^5.0.5" + } +} diff --git a/backend/packages/content/package.json b/backend/packages/content/package.json new file mode 100644 index 0000000..70b72c9 --- /dev/null +++ b/backend/packages/content/package.json @@ -0,0 +1,21 @@ +{ + "name": "@election2026/content", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "行動、議題、事件、劇本等遊戲內容(資料)(docs/05、docs/08)", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "@election2026/engine": "workspace:*", + "@election2026/protocol": "workspace:*" + }, + "devDependencies": { + "@election2026/pack-loader": "workspace:*" + } +} diff --git a/backend/packages/content/src/actions-more.ts b/backend/packages/content/src/actions-more.ts new file mode 100644 index 0000000..ba97643 --- /dev/null +++ b/backend/packages/content/src/actions-more.ts @@ -0,0 +1,722 @@ +import type { ActionDef, ActionEffect } from "@election2026/engine"; + +/** + * 第二輪行動(docs/05 設計總覽的其餘行動)。多數只靠資料描述:effects、outcome、gamble、secret。 + * 幅度比照第一版:一個約 15 萬成年人口的區,候選人本人跑一次地面行程,知名度約 +0.05、好感約 +0.008。 + * 黑暗面的行動是玩家的選擇,不是對真人的描述;AI 控制的真實人物不會使用(docs/14)。 + */ + +const DAY = ["weekdayMorning", "weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"] as const; +const MORNINGS = ["weekdayMorning", "weekendMorning"] as const; +const AFTERNOONS = ["weekdayAfternoon", "weekendAfternoon"] as const; +const EVENINGS = ["weekdayEvening", "weekendEvening"] as const; +const WEEKEND = ["weekendMorning", "weekendAfternoon", "weekendEvening"] as const; +const OLDER = ["50-64", "65+"] as const; +const MIDDLE = ["30-39", "40-49", "50-64"] as const; +const YOUNG = ["20-29", "30-39"] as const; +const DARK_RISK = "違法。知情的人越多、越接近投票日越容易有人講出去;被查到會上新聞,當選也可能無效"; + +type Base = Omit & + Partial>; + +const act = (a: Base): ActionDef => ({ visibility: "public", risk: null, phase: "campaign", amount: null, duration: 1, effects: [], ...a }); + +const aw = (base: number, scope: "target" | "city" = "target", ages?: ActionEffect["ages"]): ActionEffect => ({ stat: "awareness", base, scope, ...(ages ? { ages } : {}) }); +const fv = (base: number, scope: "target" | "city" = "target", ages?: ActionEffect["ages"]): ActionEffect => ({ stat: "favor", base, scope, ...(ages ? { ages } : {}) }); +const ht = (base: number, scope: "target" | "city" = "target"): ActionEffect => ({ stat: "heat", base, scope, supportersOnly: true }); +const hurt = (base: number, ages?: ActionEffect["ages"]): ActionEffect => ({ stat: "favor", base: -Math.abs(base), scope: "city", onOpponent: true, ...(ages ? { ages } : {}) }); + +export const MORE_ACTIONS: readonly ActionDef[] = [ + // ── 草根(不用錢:小候選人沒有金主也能每週持續運作) ── + act({ + id: "grassroots_walk", + name: "徒步掃街", + category: "ground", + description: "不坐宣傳車、不發贈品,候選人自己背著布條走路拜票。不花錢,只花體力。", + slots: [...DAY], + actors: ["candidate"], + target: "town", + cost: { money: 0, stamina: 16 }, + outdoor: true, + effects: [aw(0.035, "target"), fv(0.006, "target")], + news: { template: "{name}徒步走遍{town}大街小巷", value: 1 }, + }), + act({ + id: "facebook_live", + name: "臉書直播", + category: "media", + description: "拿手機開直播談政見、回留言。不花錢;運氣好會被分享爆紅。", + slots: [...EVENINGS], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 6 }, + effects: [aw(0.012, "city", YOUNG), fv(0.003, "city", YOUNG)], + risk: "約 25% 機率爆紅", + gamble: { + chance: 0.25, + success: { momentum: 0.02, effects: [aw(0.025, "city", YOUNG)], news: { template: "{name}深夜直播回留言,影片被大量分享", value: 3, tone: "positive" } }, + failure: { report: "直播觀看人數普普,忠實支持者留言打氣" }, + }, + }), + act({ + id: "volunteer_calls", + name: "志工電話問候", + category: "ground", + description: "志工用自己的手機打給親友鄰居,請他們投票時想到你。不花錢。", + slots: [...EVENINGS], + actors: ["team"], + target: "town", + cost: { money: 0, stamina: 0 }, + effects: [aw(0.015, "target", OLDER), ht(0.006)], + }), + // ── 地面戰 ── + act({ + id: "night_market", + name: "夜市拜票", + category: "ground", + description: "晚上到夜市邊逛邊拜票,年輕人與上班族最多。", + slots: [...EVENINGS], + actors: ["candidate", "team"], + target: "town", + cost: { money: 20_000, stamina: 10 }, + outdoor: true, + effects: [aw(0.04, "target"), fv(0.008, "target", ["20-29", "30-39", "40-49"])], + news: { template: "{name}到{town}夜市拜票", value: 1 }, + }), + act({ + id: "door_to_door", + name: "挨家挨戶拜訪", + category: "ground", + description: "一戶一戶敲門拜訪。觸及的人少,但每個人都記得你。佔兩個時段。", + slots: ["weekdayAfternoon", "weekendAfternoon"], + duration: 2, + actors: ["candidate", "team"], + target: "town", + cost: { money: 10_000, stamina: 18 }, + effects: [fv(0.02, "target"), aw(0.02, "target"), ht(0.01)], + news: { template: "{name}在{town}挨家挨戶拜訪", value: 1 }, + }), + act({ + id: "street_interview", + name: "街頭訪問(街訪)", + category: "ground", + description: "帶著攝影師在街頭隨機訪問路人,拍成影片放上網路。答得好會被轉傳,答不好也會。", + slots: [...DAY], + actors: ["candidate"], + target: "town", + cost: { money: 40_000, stamina: 10 }, + outdoor: true, + effects: [aw(0.03, "target"), aw(0.02, "city", YOUNG), fv(0.008, "target")], + news: { template: "{name}在{town}街頭訪問民眾", value: 2 }, + }), + act({ + id: "pilgrimage", + name: "參加遶境、進香", + category: "ritual", + description: "跟著遶境隊伍走一段,曝光很大,宮廟多的地方效果更好。", + slots: [...WEEKEND], + actors: ["candidate"], + target: "town", + cost: { money: 30_000, stamina: 20 }, + outdoor: true, + effects: [{ ...aw(0.07, "target"), attr: "temples" }, { ...fv(0.01, "target", OLDER), attr: "temples" }], + risk: "可能和對手撞場", + news: { template: "{name}到{town}參加遶境", value: 3 }, + }), + act({ + id: "church_visit", + name: "教會、佛寺拜訪", + category: "ritual", + description: "到教會、佛寺拜會,宗教族群的好感上升。", + slots: [...MORNINGS], + actors: ["candidate", "team"], + target: "town", + cost: { money: 10_000, stamina: 6 }, + effects: [fv(0.01, "target", MIDDLE), aw(0.015, "target")], + }), + act({ + id: "weddings_funerals", + name: "婚喪喜慶跑攤", + category: "ground", + description: "晚上跑喜宴、白天捻香。地方頭人看在眼裡,樁腳關係變好;紅白包是一筆開銷。", + slots: [...EVENINGS, "weekendMorning"], + actors: ["candidate", "team"], + target: "town", + cost: { money: 60_000, stamina: 12 }, + effects: [fv(0.012, "target", OLDER)], + outcome: { machine: 0.02 }, + }), + act({ + id: "banquet", + name: "辦桌、流水席", + category: "ground", + description: "在里民活動中心辦桌請長輩吃飯。長輩好感大增,但可能被檢舉「形同賄選」。", + slots: ["weekendAfternoon", "weekendEvening"], + actors: ["team"], + target: "town", + cost: { money: 300_000, stamina: 0 }, + effects: [fv(0.02, "target", OLDER), ht(0.015)], + risk: "約 12% 機率被檢舉形同賄選", + gamble: { + chance: 0.88, + success: { report: "{town}辦桌熱鬧,長輩吃得很開心" }, + failure: { + effects: [fv(-0.012, "city")], + tag: "奧步", + news: { template: "{name}陣營在{town}辦桌遭檢舉形同賄選", value: 6, tone: "negative" }, + }, + }, + }), + act({ + id: "concert", + name: "聯歡晚會、演唱會", + category: "ground", + description: "請樂團、歌手辦晚會,年輕人知名度大增;節目尺度沒控制好會出事。", + slots: ["weekendEvening"], + actors: ["candidate"], + target: "town", + cost: { money: 800_000, stamina: 15 }, + outdoor: true, + effects: [aw(0.06, "city", YOUNG), fv(0.006, "city", YOUNG)], + risk: "約 10% 機率節目尺度爭議", + gamble: { + chance: 0.9, + success: { momentum: 0.03, news: { template: "{name}在{town}辦聯歡晚會,年輕人擠爆會場", value: 4, tone: "positive" } }, + failure: { effects: [fv(-0.01, "city", OLDER)], news: { template: "{name}聯歡晚會出現清涼秀,挨批不當", value: 6, tone: "negative" } }, + }, + }), + act({ + id: "flags_billboards", + name: "插旗、立看板", + category: "ground", + description: "在主要路口插旗、立看板,旗海就是聲勢;看板可能被破壞。", + slots: [...DAY], + actors: ["team"], + target: "town", + cost: { money: 150_000, stamina: 0 }, + effects: [aw(0.05, "target")], + gamble: { + chance: 0.85, + success: { momentum: 0.01 }, + failure: { effects: [ht(0.015)], news: { template: "{name}在{town}的看板遭人破壞,支持者同仇敵愾", value: 3, tone: "neutral" } }, + }, + }), + act({ + id: "phone_banking", + name: "電話拜票", + category: "ground", + description: "義工打電話給支持者,提高投票意願;有人會以為是詐騙電話。", + slots: [...EVENINGS], + actors: ["team"], + target: "city", + cost: { money: 80_000, stamina: 0 }, + effects: [ht(0.012, "city")], + gamble: { chance: 0.9, success: {}, failure: { effects: [fv(-0.004, "city", OLDER)], report: "有民眾以為拜票電話是詐騙,向媒體投訴" } }, + }), + act({ + id: "homecoming", + name: "返鄉動員", + category: "org", + description: "安排在外地工作的人投票日回家投票。台灣沒有不在籍投票,越接近投票日越有效。", + slots: [...DAY], + actors: ["team"], + target: "city", + cost: { money: 500_000, stamina: 0 }, + effects: [ht(0.02, "city")], + risk: "免費接送有賄選疑慮", + gamble: { chance: 0.92, success: {}, failure: { tag: "奧步", news: { template: "{name}陣營包車接送返鄉投票,被質疑涉及賄選", value: 5, tone: "negative" } } }, + }), + // ── 空戰 ── + act({ + id: "radio_ad", + name: "報紙、廣播廣告", + category: "media", + description: "便宜,主要觸及長輩。", + slots: [...MORNINGS], + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "廣告預算", unit: "元", min: 100_000, max: 5_000_000, step: 100_000, default: 500_000, moneyPerUnit: 1 }, + effects: [aw(0.025, "city", OLDER), fv(0.004, "city", ["65+"])], + }), + act({ + id: "short_video", + name: "拍短影音、迷因", + category: "media", + description: "拍一支短影音。爆紅的話年輕人全認識你;翻車的話也全認識你。", + slots: [...DAY], + actors: ["candidate"], + target: "city", + cost: { money: 50_000, stamina: 6 }, + effects: [aw(0.015, "city", YOUNG)], + risk: "可能翻車", + gamble: { + chance: 0.55, + success: { effects: [aw(0.05, "city", YOUNG), fv(0.008, "city", YOUNG)], momentum: 0.02, news: { template: "{name}短影音爆紅,網友瘋傳", value: 5, tone: "positive", online: true } }, + failure: { effects: [fv(-0.004, "city", YOUNG)], news: { template: "{name}新影片被嫌尷尬,留言區一片吐槽", value: 3, tone: "negative", online: true } }, + }, + }), + act({ + id: "line_groups", + name: "經營 LINE 群組與社群", + category: "media", + description: "每天在 LINE 群組和社群發文,支持者的熱度慢慢累積;對話可能被截圖外流。", + slots: [...DAY], + actors: ["team"], + target: "city", + cost: { money: 30_000, stamina: 0 }, + effects: [ht(0.01, "city"), aw(0.01, "city", ["40-49", "50-64", "65+"])], + gamble: { chance: 0.95, success: {}, failure: { effects: [fv(-0.008, "city")], news: { template: "{name}陣營群組對話遭截圖外流", value: 4, tone: "negative", online: true } } }, + }), + act({ + id: "influencer_live", + name: "Podcast、網紅直播", + category: "media", + description: "上網紅的直播或 Podcast,年輕人的知名度與好感都上升;要付業配費,網紅本人也可能出包。", + slots: [...EVENINGS], + actors: ["candidate"], + target: "city", + cost: { money: 300_000, stamina: 8 }, + effects: [aw(0.04, "city", YOUNG), fv(0.008, "city", YOUNG)], + gamble: { chance: 0.9, success: {}, failure: { effects: [fv(-0.01, "city", YOUNG)], news: { template: "與{name}合作的網紅爆出爭議,被要求切割", value: 5, tone: "negative", online: true } } }, + }), + act({ + id: "press_conference", + name: "政策記者會", + category: "policy", + description: "開記者會發表一項政策,搶新聞版面;記者不一定會來。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "city", + cost: { money: 50_000, stamina: 6 }, + effects: [aw(0.02, "city")], + gamble: { + chance: 0.7, + success: { effects: [fv(0.006, "city", MIDDLE)], news: { template: "{name}召開記者會發表政策", value: 4, tone: "positive" } }, + failure: { report: "記者會撞上其他大新聞,來的記者不多" }, + }, + }), + act({ + id: "interview", + name: "接受專訪", + category: "media", + description: "接受報紙或電視專訪,建立深度形象。口才越好越加分,也可能失言。", + slots: [...AFTERNOONS], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 8 }, + effects: [fv(0.006, "city", MIDDLE)], + gamble: { chance: 0.92, success: { effects: [fv(0.004, "city")] }, failure: { effects: [fv(-0.01, "city")], news: { template: "{name}專訪失言,引發討論", value: 5, tone: "negative" } } }, + }), + act({ + id: "forum", + name: "公辦政見發表會", + category: "policy", + description: "選委會辦的政見發表會。來看的人不多,但電視會轉播,缺席會被拿來說嘴。", + slots: ["weekdayEvening"], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 8 }, + effects: [aw(0.02, "city"), fv(0.004, "city", MIDDLE)], + news: { template: "{name}出席公辦政見發表會", value: 2 }, + }), + // ── 組織戰 ── + act({ + id: "visit_associations", + name: "拜訪社團", + category: "org", + description: "拜會宗親會、同鄉會、商會、獅子會、扶輪社,地方組織與中年族群的好感上升。", + slots: [...AFTERNOONS, "weekdayEvening"], + actors: ["candidate", "team"], + target: "town", + cost: { money: 30_000, stamina: 8 }, + effects: [fv(0.01, "target", MIDDLE)], + outcome: { machine: 0.015 }, + }), + act({ + id: "endorsement", + name: "爭取推薦、請人站台", + category: "org", + description: "請地方名人、學者或前輩公開推薦你,借用他們的聲望;推薦人本身可能有爭議。", + slots: [...DAY], + actors: ["candidate"], + target: "city", + cost: { money: 50_000, stamina: 6 }, + effects: [fv(0.008, "city", MIDDLE)], + gamble: { + chance: 0.85, + success: { momentum: 0.015, news: { template: "多位地方人士公開推薦{name}", value: 3, tone: "positive" } }, + failure: { effects: [fv(-0.008, "city")], news: { template: "推薦{name}的人士被翻出舊爭議", value: 4, tone: "negative" } }, + }, + }), + act({ + id: "party_elder", + name: "請黨中央大咖站台", + kinds: ["mayor", "legislator"], + needsParty: true, + category: "org", + description: "請黨中央的重量級人物來站台。全國風向好時加分,風向差時中間選民會扣分。", + slots: [...EVENINGS], + actors: ["candidate"], + target: "town", + cost: { money: 100_000, stamina: 10 }, + special: "partyElder", + }), + act({ + id: "gifts", + name: "送禮給有力人士", + category: "org", + description: "逢年過節送禮給地方有力人士,關係變好;禮太重就形同賄賂。", + slots: [...DAY], + actors: ["team"], + target: "town", + cost: { money: 200_000, stamina: 0 }, + outcome: { machine: 0.03 }, + risk: "約 10% 機率被質疑形同賄賂", + gamble: { chance: 0.9, success: {}, failure: { tag: "奧步", effects: [fv(-0.01, "city")], news: { template: "{name}陣營送禮給地方人士,被質疑形同賄賂", value: 5, tone: "negative" } } }, + }), + act({ + id: "councilor_allies", + name: "議員盟友聯合造勢", + needsParty: true, + category: "org", + description: "和同黨議員一起辦活動,借用他們的地方組織;議員之後會要你回報。", + slots: [...WEEKEND], + actors: ["candidate"], + target: "town", + cost: { money: 200_000, stamina: 12 }, + effects: [ht(0.02), aw(0.02, "target")], + outcome: { machine: 0.03 }, + news: { template: "{name}與地方議員在{town}聯合造勢", value: 3 }, + }), + // ── 資金 ── + act({ + id: "big_donor", + name: "拜訪企業主募款", + category: "finance", + description: "拜訪企業主爭取大額捐款(營利事業每家上限 100 萬元)。錢多,但可能被貼上「財團」標籤。", + slots: [...AFTERNOONS], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 8 }, + special: "bigDonor", + }), + act({ + id: "party_fund", + name: "申請政黨補助", + needsParty: true, + category: "finance", + description: "向黨中央申請選舉補助。無黨籍不能申請。", + slots: [...DAY], + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + special: "partyFund", + }), + // ── 政策 ── + act({ + id: "white_paper", + name: "發表政策白皮書", + category: "policy", + description: "完整的政策白皮書,提高政見可信度,中壯年最在意;準備很花時間(佔兩個時段)。", + slots: ["weekdayAfternoon", "weekendAfternoon"], + duration: 2, + actors: ["candidate"], + target: "city", + cost: { money: 150_000, stamina: 10 }, + effects: [fv(0.01, "city", MIDDLE), aw(0.01, "city")], + news: { template: "{name}發表政策白皮書", value: 3 }, + }), + // ── 攻防 ── + act({ + id: "lawsuit", + name: "提告", + category: "offense", + description: "對散布不實訊息的人提告,新聞會持續好幾週;告太多會被說濫訴。", + slots: [...MORNINGS], + actors: ["candidate", "team"], + target: "city", + cost: { money: 200_000, stamina: 4 }, + effects: [fv(0.004, "city", OLDER)], + gamble: { + chance: 0.75, + success: { news: { template: "{name}宣布對散布不實訊息者提告", value: 3, tone: "neutral" } }, + failure: { effects: [fv(-0.006, "city", YOUNG)], news: { template: "{name}動輒提告,被批濫訴", value: 4, tone: "negative" } }, + }, + }), + act({ + id: "report_prosecutor", + name: "向檢調檢舉", + category: "offense", + description: "把對手的不法證據交給檢調。手上要有把柄才會受理;沒有證據會被批濫告。", + slots: [...MORNINGS], + actors: ["team"], + target: "opponent", + cost: { money: 50_000, stamina: 0 }, + special: "reportProsecutor", + }), + act({ + id: "protest_government", + name: "向政府陳情抗議", + category: "offense", + description: "帶著陳情書到政府機關抗議,和中央切割;反執政的選民好感上升。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "city", + cost: { money: 30_000, stamina: 8 }, + effects: [{ stat: "favor", base: 0.01, scope: "city", leans: ["middle", "c_lean"] }, aw(0.015, "city")], + news: { template: "{name}到政府機關陳情抗議", value: 3, tone: "neutral" }, + }), + act({ + id: "protest_hq", + name: "到對手總部抗議", + category: "offense", + description: "帶支持者到對手總部前抗議他做過的不當行為。對手真的有黑歷史才站得住腳。", + slots: [...AFTERNOONS], + actors: ["team"], + target: "opponent", + cost: { money: 50_000, stamina: 0 }, + special: "protestHq", + }), + act({ + id: "crisis_pr", + name: "危機公關(道歉、切割、撤換)", + category: "offense", + description: "出事之後道歉、切割、撤換相關的人,止血;被撤換的人可能帶著祕密離開。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "city", + cost: { money: 50_000, stamina: 6 }, + special: "crisisPR", + }), + act({ + id: "fact_check", + name: "反制網軍、查核闢謠", + category: "offense", + description: "成立闢謠小組,接下來兩週對手網軍的效果減半。", + slots: [...DAY], + actors: ["team"], + target: "city", + cost: { money: 200_000, stamina: 0 }, + special: "factCheck", + }), + // ── 黑暗面 ── + act({ + id: "promise_bribe", + name: "期約賄選", + category: "dark", + description: "私下承諾地方頭人當選後給工程或職位,換他們全力動員。知情的人少,但被查到很嚴重。", + slots: ["midnight"], + actors: ["team"], + target: "town", + cost: { money: 0, stamina: 0 }, + visibility: "secret", + risk: DARK_RISK, + effects: [ht(0.02)], + outcome: { machine: 0.08, report: "{town}的地方頭人答應全力動員(當選後要兌現)" }, + secret: { kind: "promise", label: "期約賄選", insiders: 4 }, + }), + act({ + id: "smear", + name: "抹黑、假訊息", + category: "dark", + description: "放出攻擊對手的假訊息。對手好感下降;被查核中心識破會反噬自己。", + slots: ["midnight"], + actors: ["team"], + target: "opponent", + cost: { money: 300_000, stamina: 0 }, + visibility: "secret", + risk: "約 20% 機率被查核識破", + effects: [], + gamble: { + chance: 0.8, + success: { effects: [hurt(0.015)], news: { template: "網路流傳針對{opponent}的不實訊息", value: 3, tone: "negative", online: true } }, + failure: { effects: [fv(-0.02, "city")], tag: "奧步", news: { template: "查核中心證實攻擊{opponent}的訊息不實,源頭指向{name}陣營", value: 7, tone: "negative", online: true } }, + }, + secret: { kind: "smear", label: "散布假訊息", insiders: 5 }, + }), + act({ + id: "impersonate", + name: "冒名騷擾(午夜拜票)", + category: "dark", + description: "半夜冒用對手的名義打電話、傳簡訊騷擾選民,讓人討厭對手。原作的「午夜拜票」。", + slots: ["midnight"], + actors: ["team"], + target: "opponent", + cost: { money: 200_000, stamina: 0 }, + visibility: "secret", + risk: DARK_RISK, + effects: [hurt(0.012, OLDER)], + outcome: { news: { template: "有人冒用{opponent}名義半夜打電話拜票,民眾不堪其擾", value: 4, tone: "negative" } }, + secret: { kind: "impersonate", label: "冒名騷擾", insiders: 15 }, + }), + act({ + id: "frame_vote_buying", + name: "栽贓買票", + category: "dark", + description: "安排人用對手的名義買票,讓對手被懷疑。原作的「為敵買票」。知情的人很多,被揭穿就全毀。", + slots: ["midnight"], + actors: ["team"], + target: "town", + cost: { money: 1_000_000, stamina: 0 }, + visibility: "secret", + risk: DARK_RISK, + special: "frame", + }), + act({ + id: "staged_attack", + name: "苦肉計", + category: "dark", + description: "自導自演受害事件,博取同情、拉高熱度。被揭穿就全毀。原作的「假槍擊」。", + slots: ["weekdayEvening", "weekendEvening"], + actors: ["candidate"], + target: "city", + cost: { money: 300_000, stamina: 10 }, + visibility: "public", + risk: "被揭穿會重創形象", + effects: [ht(0.03, "city"), fv(0.01, "city", OLDER)], + outcome: { momentum: 0.05, news: { template: "{name}造勢途中遭人潑漆,支持者憤慨", value: 8, tone: "neutral" } }, + secret: { kind: "staged", label: "自導自演苦肉計", insiders: 6 }, + }), + act({ + id: "buyout", + name: "搓圓仔湯", + category: "dark", + description: "出價請對手退選。登記後退選名字仍在選票上。真實人物一律不收,只會讓你被抓包的機率變高。", + slots: ["midnight"], + actors: ["team"], + target: "opponent", + cost: { money: 0, stamina: 0 }, + amount: { label: "開價", unit: "元", min: 1_000_000, max: 30_000_000, step: 1_000_000, default: 5_000_000, moneyPerUnit: 1 }, + visibility: "secret", + risk: DARK_RISK, + special: "buyout", + }), + act({ + id: "slush_fund", + name: "帳外資金、白手套", + category: "dark", + description: "透過白手套收不入帳的錢,不算進法定經費上限;違反政治獻金法。", + slots: ["midnight"], + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + visibility: "secret", + risk: DARK_RISK, + outcome: { fundraisingMultiple: 0.8, report: "白手套送來一筆帳外資金" }, + secret: { kind: "slush", label: "帳外資金", insiders: 5 }, + }), + act({ + id: "fake_poll", + name: "散布假民調、假賽馬", + category: "dark", + description: "放出對自己有利的假民調、地下賽馬消息,影響棄保。", + slots: ["midnight"], + actors: ["team"], + target: "city", + cost: { money: 150_000, stamina: 0 }, + visibility: "secret", + risk: "被揭穿會被批操弄民調", + outcome: { momentum: 0.04, news: { template: "網路流傳一份{name}大幅領先的民調", value: 3, tone: "neutral", online: true } }, + secret: { kind: "fakePoll", label: "散布假民調", insiders: 8 }, + }), + // ── 儀式 ── + act({ + id: "chicken_oath", + name: "斬雞頭", + category: "ritual", + description: "到廟口斬雞頭發誓清白,長輩買單、形象上升;動保團體會抗議,之後奧步被揭發會加倍嚴重。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "town", + cost: { money: 20_000, stamina: 8 }, + effects: [fv(0.012, "city", OLDER)], + outcome: { tag: "發誓", news: { template: "{name}在{town}廟口斬雞頭發誓", value: 7, tone: "neutral" } }, + gamble: { chance: 0.6, success: {}, failure: { effects: [fv(-0.008, "city", YOUNG)], news: { template: "動保團體抗議{name}斬雞頭", value: 4, tone: "negative" } } }, + }), + act({ + id: "invite_oath", + name: "邀對手斬雞頭", + category: "ritual", + description: "公開邀對手一起斬雞頭發誓。對方不來會被說心虛;你自己違誓會更慘。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "opponent", + cost: { money: 20_000, stamina: 6 }, + special: "inviteOath", + }), + act({ + id: "live_pledge", + name: "直播發誓、簽切結書", + category: "ritual", + description: "斬雞頭的現代版:直播簽切結書。年輕人比較能接受。", + slots: [...DAY], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 4 }, + effects: [fv(0.008, "city", YOUNG), aw(0.01, "city", YOUNG)], + outcome: { tag: "發誓", news: { template: "{name}直播簽署切結書", value: 3, tone: "neutral", online: true } }, + }), + // ── 自我管理 ── + act({ + id: "workout", + name: "鍛鍊身體", + category: "self", + description: "晨跑、重訓。體力上限 +5(最高 130)。", + slots: [...MORNINGS], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 6 }, + visibility: "local", + outcome: { staminaMax: 5, report: "鍛鍊身體,體力上限提高" }, + }), + act({ + id: "study", + name: "讀書、進修", + category: "self", + description: "讀書、聽簡報,口才與論述變好(上政論節目、專訪更加分)。", + slots: [...DAY], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 4 }, + visibility: "local", + outcome: { eloquence: 4, report: "讀了幾本書,論述更紮實(口才 +4)" }, + }), + act({ + id: "debate_training", + name: "辯論特訓", + category: "self", + description: "幕僚扮演對手模擬攻防,口才 +6。", + slots: [...EVENINGS], + actors: ["candidate"], + target: "city", + cost: { money: 100_000, stamina: 8 }, + visibility: "local", + outcome: { eloquence: 6, report: "完成辯論特訓(口才 +6)" }, + }), + act({ + id: "media_training", + name: "媒體訓練", + category: "self", + description: "請公關顧問上課,失言機率降低三成。", + slots: [...AFTERNOONS], + actors: ["candidate"], + target: "city", + cost: { money: 150_000, stamina: 4 }, + visibility: "local", + outcome: { gaffeReduction: 0.3, report: "上完媒體訓練,之後比較不會失言" }, + }), + // ── 人事後勤 ── + act({ + id: "fire_staff", + name: "撤換幕僚", + category: "logistics", + description: "請一位幕僚離開,省下薪水;知道祕密的人可能帶著祕密離開。", + slots: [...DAY], + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 2 }, + visibility: "local", + special: "fireStaff", + }), +]; diff --git a/backend/packages/content/src/actions.ts b/backend/packages/content/src/actions.ts new file mode 100644 index 0000000..5373f47 --- /dev/null +++ b/backend/packages/content/src/actions.ts @@ -0,0 +1,584 @@ +import type { ActionDef } from "@election2026/engine"; +import { MORE_ACTIONS } from "./actions-more.ts"; + +/** + * MVP 行動目錄(docs/05)。效果幅度是初始值,以回測與平衡報告調整(apps/sim)。 + * base:在一個約 15 萬成年人口的區、由候選人本人執行時的幅度;幕僚執行依能力打 4–7 折。 + * 價格參考 2022 桃園市長候選人的政治獻金支出科目(監察院),對照表在 docs/05「價格從哪裡來」。 + */ + +const DAY = ["weekdayMorning", "weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"] as const; +const MORNINGS = ["weekdayMorning", "weekendMorning"] as const; +const EVENINGS = ["weekdayEvening", "weekendEvening"] as const; +const OLDER = ["50-64", "65+"] as const; +const MIDDLE_AGED_UP = ["40-49", "50-64", "65+"] as const; +const YOUNGER = ["20-29", "30-39", "40-49"] as const; + +const DARK_RISK = "違反選罷法。知情的人越多、越接近投票日越容易有人檢舉;被查到會上新聞、當選也可能被判無效"; + +export const CAMPAIGN_ACTIONS: readonly ActionDef[] = [ + // ── 地面戰 ── + { + id: "street_canvass", + name: "掃街拜票", + category: "ground", + description: "在一個區沿街握手、發面紙。人越密集的地方效果越好。", + slots: [...DAY], + duration: 1, + actors: ["candidate", "team"], + target: "town", + cost: { money: 30_000, stamina: 12 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + outdoor: true, + effects: [ + { stat: "awareness", base: 0.05, scope: "target", attr: "density" }, + { stat: "favor", base: 0.008, scope: "target" }, + ], + news: { template: "{name}在{town}掃街拜票", value: 1 }, + }, + { + id: "market_visit", + name: "菜市場拜票", + category: "ground", + description: "早上到傳統市場拜票,長輩最多。", + slots: [...MORNINGS], + duration: 1, + actors: ["candidate", "team"], + target: "town", + cost: { money: 10_000, stamina: 8 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + outdoor: true, + effects: [ + { stat: "awareness", base: 0.05, scope: "target", ages: OLDER }, + { stat: "favor", base: 0.012, scope: "target", ages: MIDDLE_AGED_UP }, + ], + news: { template: "{name}到{town}市場拜票,攤商熱情握手", value: 1 }, + }, + { + id: "temple_visit", + name: "宮廟參拜", + category: "ritual", + description: "到宮廟上香、拜會管委會。宮廟越多的地方效果越好,也會帶動長輩的投票意願。", + slots: ["weekdayMorning", "weekdayAfternoon", "weekendMorning", "weekendAfternoon"], + duration: 1, + actors: ["candidate"], + target: "town", + cost: { money: 20_000, stamina: 8 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + effects: [ + { stat: "awareness", base: 0.04, scope: "target", ages: OLDER, attr: "temples" }, + { stat: "favor", base: 0.012, scope: "target", ages: OLDER, attr: "temples" }, + { stat: "heat", base: 0.04, scope: "target", ages: OLDER, supportersOnly: true, attr: "temples" }, + ], + news: { template: "{name}到{town}宮廟參拜祈福", value: 1 }, + }, + { + id: "factory_visit", + name: "工業區拜票", + category: "ground", + description: "到工業區、科技廠門口拜票,接觸上班族與外地移入的年輕家庭。", + slots: ["weekdayMorning", "weekdayAfternoon"], + duration: 1, + actors: ["candidate", "team"], + target: "town", + cost: { money: 20_000, stamina: 10 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + effects: [ + { stat: "awareness", base: 0.05, scope: "target", ages: YOUNGER, attr: "lowDensity" }, + { stat: "favor", base: 0.01, scope: "target", ages: YOUNGER, attr: "lowDensity" }, + ], + news: { template: "{name}到{town}工業區拜票", value: 1 }, + }, + { + id: "sound_truck", + name: "宣傳車掃街", + category: "ground", + description: "租宣傳車在一個區繞行廣播,衝知名度很有效,好感幾乎不會增加。", + slots: ["weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"], + duration: 1, + actors: ["team"], + target: "town", + cost: { money: 30_000, stamina: 0 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + outdoor: true, + effects: [{ stat: "awareness", base: 0.06, scope: "target" }], + }, + { + id: "rally", + name: "造勢晚會", + category: "ground", + description: "辦一場造勢晚會,佔下午搭台與晚上兩個時段。拉高支持者的投票熱度與整體聲勢;下雨颱風會打折。", + slots: [...EVENINGS], + duration: 2, + actors: ["candidate"], + target: "town", + cost: { money: 0, stamina: 20 }, + // 張善政陣營「集會支出」約 1,142 萬元,以 6–8 場估算一場約 150 萬元 + amount: { label: "活動規模", unit: "元", min: 500_000, max: 8_000_000, step: 100_000, default: 1_500_000, moneyPerUnit: 1 }, + visibility: "public", + risk: "人數不如預期會被媒體拿來比較", + phase: "campaign", + outdoor: true, + special: "rally", + effects: [ + { stat: "heat", base: 0.15, scope: "target", supportersOnly: true }, + { stat: "heat", base: 0.04, scope: "city", supportersOnly: true }, + { stat: "awareness", base: 0.04, scope: "target" }, + ], + }, + // ── 組織戰 ── + { + id: "open_office", + name: "設立競選服務處", + category: "org", + description: "在一個區設服務處:之後這個區的行動效果加成,地方組織每週慢慢增強。開辦費 20 萬元,之後每週租金 5 萬元。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "town", + cost: { money: 200_000, stamina: 0 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + special: "office", + effects: [], + news: { template: "{name}{town}競選服務處成立", value: 2 }, + }, + { + id: "recruit_machine", + name: "拜託里長與地方頭人", + category: "org", + description: "請地方頭人、里長幫忙站台與動員(合法的餐敘、活動經費)。談的條件越好越容易成功。", + slots: ["weekdayAfternoon", "weekdayEvening", "weekendAfternoon", "weekendEvening"], + duration: 1, + actors: ["candidate", "team"], + target: "town", + cost: { money: 0, stamina: 6 }, + amount: { label: "誠意(活動經費)", unit: "元", min: 200_000, max: 3_000_000, step: 100_000, default: 600_000, moneyPerUnit: 1 }, + visibility: "local", + risk: "可能談不成,錢照樣花掉", + phase: "campaign", + special: "machine", + effects: [], + }, + { + id: "hire_staff", + name: "找幕僚", + category: "logistics", + description: "多找一位幕僚,下週起多一排行程可以排。最多 6 位,每位每週薪水 1.5 萬元。", + slots: [...DAY], + duration: 1, + actors: ["candidate", "team"], + target: "city", + cost: { money: 100_000, stamina: 4 }, + amount: null, + visibility: "local", + risk: null, + phase: "campaign", + special: "hireStaff", + effects: [], + }, + { + id: "recruit_volunteers", + name: "招募義工", + category: "logistics", + description: "義工越多,團隊代替候選人跑行程的效果越好。聲勢好的時候比較容易招到人。", + slots: ["weekendMorning", "weekendAfternoon"], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 50_000, stamina: 0 }, + amount: null, + visibility: "local", + risk: null, + phase: "campaign", + special: "recruit", + effects: [], + }, + { + id: "print_flyers", + name: "印製文宣", + category: "logistics", + description: "印 DM 與面紙。地面行動會自動帶出去,每次用掉 2,000 份、知名度效果提高兩成。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "份數", unit: "份", min: 10_000, max: 200_000, step: 10_000, default: 50_000, moneyPerUnit: 3 }, + visibility: "local", + risk: null, + phase: "campaign", + special: "flyers", + effects: [], + }, + // ── 空戰 ── + { + id: "tv_ad", + name: "電視廣告", + category: "media", + description: "全區播出的電視廣告。中高齡觀眾為主,投越多越有效但效果遞減。(兩大黨候選人的宣傳支出約 2,800–4,900 萬元)", + slots: [...EVENINGS], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "廣告預算", unit: "元", min: 500_000, max: 20_000_000, step: 100_000, default: 3_000_000, moneyPerUnit: 1 }, + visibility: "public", + risk: null, + phase: "campaign", + special: "tvAd", + effects: [ + { stat: "awareness", base: 0.03, scope: "city", ages: MIDDLE_AGED_UP }, + { stat: "favor", base: 0.006, scope: "city", ages: MIDDLE_AGED_UP }, + ], + }, + { + id: "online_ad", + name: "網路廣告", + category: "media", + description: "社群與影音平台廣告。年輕族群為主,可以小額投放。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "廣告預算", unit: "元", min: 100_000, max: 10_000_000, step: 100_000, default: 800_000, moneyPerUnit: 1 }, + visibility: "public", + risk: null, + phase: "campaign", + special: "onlineAd", + effects: [ + { stat: "awareness", base: 0.03, scope: "city", ages: YOUNGER }, + { stat: "favor", base: 0.005, scope: "city", ages: YOUNGER }, + ], + }, + { + id: "talk_show", + name: "上政論節目", + category: "media", + description: "上電視政論節目。口才好加分,但有一定機率失言。", + slots: ["weekdayEvening"], + duration: 1, + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 10 }, + amount: null, + visibility: "public", + risk: "約 8% 機率失言上新聞", + phase: "campaign", + special: "talkShow", + effects: [], + }, + // ── 政策 ── + { + id: "announce_policy", + name: "提出主打政見", + category: "policy", + description: "選 1–3 個議題當主打。之後每週在意這些議題的族群會慢慢增加好感。可以重新提出來換議題。", + slots: [...MORNINGS], + duration: 1, + actors: ["candidate"], + target: "city", + cost: { money: 100_000, stamina: 8 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + special: "policy", + effects: [{ stat: "awareness", base: 0.015, scope: "city" }], + news: { template: "{name}發表主打政見", value: 4 }, + }, + // ── 錢 ── + { + id: "fundraiser_dinner", + name: "募款餐會", + category: "finance", + description: "辦募款餐會,聲勢越好募得越多。能募多少依候選人的募款能力(歷史劇本依真實政治獻金收入推算)。也會拉高在場支持者的熱度。", + slots: [...EVENINGS], + duration: 1, + actors: ["candidate"], + target: "town", + cost: { money: 100_000, stamina: 12 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + special: "fundraiser", + effects: [{ stat: "heat", base: 0.05, scope: "target", supportersOnly: true }], + }, + { + id: "small_donations", + name: "網路小額募款", + category: "finance", + description: "在網路上開放小額捐款。金額不大,但聲勢好時會多很多。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 20_000, stamina: 0 }, + amount: null, + visibility: "local", + risk: null, + phase: "campaign", + special: "smallDonations", + effects: [], + }, + { + id: "self_fund", + name: "自掏腰包", + category: "finance", + description: "拿個人財產投入選戰,上限是候選人的個人財力。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "金額", unit: "元", min: 500_000, max: 50_000_000, step: 500_000, default: 1_000_000, moneyPerUnit: 0 }, + visibility: "local", + risk: null, + phase: "campaign", + special: "selfFund", + effects: [], + }, + // ── 攻防 ── + { + id: "expose_press", + name: "爆料記者會", + category: "offense", + description: "開記者會攻擊對手。手上有把柄才有殺傷力;沒有證據的爆料會被批抹黑,中間選民反感。", + slots: ["weekdayMorning", "weekdayAfternoon"], + duration: 1, + actors: ["candidate", "team"], + target: "opponent", + cost: { money: 50_000, stamina: 6 }, + amount: null, + visibility: "public", + risk: "沒有把柄時會反傷自己", + phase: "campaign", + special: "expose", + effects: [], + }, + { + id: "rebuttal_press", + name: "澄清記者會", + category: "offense", + description: "被爆料後兩週內澄清效果最好;沒事開澄清記者會只有一點點效果。", + slots: ["weekdayMorning", "weekdayAfternoon", "weekendMorning"], + duration: 1, + actors: ["candidate", "team"], + target: "city", + cost: { money: 30_000, stamina: 5 }, + amount: null, + visibility: "public", + risk: null, + phase: "campaign", + special: "rebuttal", + effects: [], + }, + { + id: "investigate", + name: "打探對手", + category: "offense", + description: "請人調查對手。可能找到把柄(對手做過黑的機會比較大),或估出對手的資金。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "opponent", + cost: { money: 500_000, stamina: 0 }, + amount: null, + visibility: "secret", + risk: "約 6% 機率被抓包上新聞", + phase: "campaign", + special: "intel", + effects: [], + }, + { + id: "internal_poll", + name: "內參民調", + category: "logistics", + description: "委託一份只有自己看得到的民調,含各區支持度。投票前 10 天也可以做(只是不能公布)。", + slots: [...DAY], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 600_000, stamina: 0 }, + amount: null, + visibility: "secret", + risk: null, + phase: "campaign", + special: "internalPoll", + effects: [], + }, + // ── 黑暗面(docs/06)── + { + id: "vote_buying", + name: "買票", + category: "dark", + description: "透過樁腳發錢買票。每票約 1,000 元(含樁腳抽成),投票日兌現七成。", + slots: ["midnight"], + duration: 1, + actors: ["team"], + target: "town", + cost: { money: 0, stamina: 0 }, + amount: { label: "票數", unit: "票", min: 100, max: 20_000, step: 100, default: 1_000, moneyPerUnit: 1_000 }, + visibility: "secret", + risk: DARK_RISK, + phase: "campaign", + special: "voteBuying", + effects: [], + }, + { + id: "troll_army", + name: "網軍帶風向", + category: "dark", + description: "外包網軍在網路上攻擊對手。", + slots: ["midnight"], + duration: 1, + actors: ["team"], + target: "opponent", + cost: { money: 800_000, stamina: 0 }, + amount: null, + visibility: "secret", + risk: "約 12% 機率被查核中心揭露,反傷自己", + phase: "campaign", + special: "trolls", + effects: [], + }, + // ── 自己 ── + { + id: "rest", + name: "休息", + category: "self", + description: "候選人休息半天,恢復 30 點體力。", + slots: [...DAY], + duration: 1, + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: -30 }, + amount: null, + visibility: "local", + risk: null, + phase: "campaign", + special: "rest", + effects: [], + }, +]; + +export const EVE_ACTIONS: readonly ActionDef[] = [ + { + id: "eve_rally", + name: "選前之夜造勢", + category: "ground", + description: "最後一場、也是最大的一場造勢。聲勢加成是平常的 1.5 倍。", + slots: ["weekendEvening"], + duration: 1, + actors: ["candidate"], + target: "town", + cost: { money: 0, stamina: 0 }, + amount: { label: "活動規模", unit: "元", min: 500_000, max: 15_000_000, step: 100_000, default: 3_000_000, moneyPerUnit: 1 }, + visibility: "public", + risk: null, + phase: "eve", + outdoor: true, + special: "rally", + effects: [ + { stat: "heat", base: 0.12, scope: "city", supportersOnly: true }, + { stat: "heat", base: 0.1, scope: "target" }, + { stat: "awareness", base: 0.02, scope: "city" }, + ], + }, + { + id: "kneel", + name: "下跪拜票", + category: "ritual", + description: "在台上向選民下跪搶救。支持者會更想去投票,但年輕選民可能反感。", + slots: ["weekendAfternoon", "weekendEvening"], + duration: 1, + actors: ["candidate"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: null, + visibility: "public", + risk: "年輕選民可能反感", + phase: "eve", + special: "kneel", + effects: [ + { stat: "heat", base: 0.12, scope: "city", supportersOnly: true }, + { stat: "favor", base: 0.01, scope: "city", ages: OLDER }, + { stat: "favor", base: -0.006, scope: "city", ages: ["20-29", "30-39"] }, + ], + }, + { + id: "eve_phone_bank", + name: "電話催票", + category: "logistics", + description: "義工打電話提醒支持者明天去投票。", + slots: ["weekendMorning", "weekendAfternoon", "weekendEvening"], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 300_000, stamina: 0 }, + amount: null, + visibility: "local", + risk: null, + phase: "eve", + effects: [{ stat: "heat", base: 0.06, scope: "city", supportersOnly: true }], + }, + { + id: "eve_online_ad", + name: "最後一波網路廣告", + category: "media", + description: "投票前一天的網路廣告,提醒年輕人回家投票。", + slots: ["weekendMorning", "weekendAfternoon", "weekendEvening"], + duration: 1, + actors: ["team"], + target: "city", + cost: { money: 0, stamina: 0 }, + amount: { label: "廣告預算", unit: "元", min: 100_000, max: 5_000_000, step: 100_000, default: 800_000, moneyPerUnit: 1 }, + visibility: "public", + risk: null, + phase: "eve", + special: "onlineAd", + effects: [ + { stat: "awareness", base: 0.02, scope: "city", ages: YOUNGER }, + { stat: "favor", base: 0.005, scope: "city", ages: YOUNGER }, + { stat: "heat", base: 0.04, scope: "city", ages: ["20-29", "30-39"], supportersOnly: true }, + ], + }, + { + id: "eve_vote_buying", + name: "投票前夜買票", + category: "dark", + description: "最後一晚發錢。比平常貴(每票約 1,500 元),但離投票日最近、跑票較少。", + slots: ["midnight"], + duration: 1, + actors: ["team"], + target: "town", + cost: { money: 0, stamina: 0 }, + amount: { label: "票數", unit: "票", min: 100, max: 20_000, step: 100, default: 1_000, moneyPerUnit: 1_500 }, + visibility: "secret", + risk: `${DARK_RISK}。投票前夜查賄最嚴`, + phase: "eve", + special: "voteBuying", + effects: [], + }, +]; + +export const ACTIONS: readonly ActionDef[] = [...CAMPAIGN_ACTIONS, ...MORE_ACTIONS, ...EVE_ACTIONS]; diff --git a/backend/packages/content/src/candidates.ts b/backend/packages/content/src/candidates.ts new file mode 100644 index 0000000..9c5d228 --- /dev/null +++ b/backend/packages/content/src/candidates.ts @@ -0,0 +1,20 @@ +import type { CandidateStats } from "@election2026/protocol"; +import type { Scenario, ScenarioCandidate } from "@election2026/engine"; + +const clamp = (x: number) => Math.round(Math.min(10, Math.max(0, x))); + +/** 開始畫面的能力值(0–10):由劇本數字換算,財力是和同場最有錢的人比 */ +export function candidateStats(scenario: Scenario, c: ScenarioCandidate): CandidateStats { + const total = (x: ScenarioCandidate) => x.startingMoney + x.fundraising * scenario.weeks; + const richest = Math.max(...scenario.candidates.map(total), 1); + return { + fame: clamp(c.awareness * 10), + eloquence: clamp(c.eloquence / 10), + wealth: clamp(10 * Math.sqrt(total(c) / richest)), + network: clamp((c.machine / 0.4) * 7 + c.staff * 0.6), + charisma: Math.max(1, clamp(5 + (c.appeal ?? 0) * 1.5)), + }; +} + +/** 去掉「(2018)」這種時期標記,拿來查性別、頭像 */ +export const personName = (name: string) => name.replace(/(\d{4})$/, ""); diff --git a/backend/packages/content/src/custom.ts b/backend/packages/content/src/custom.ts new file mode 100644 index 0000000..acff9ee --- /dev/null +++ b/backend/packages/content/src/custom.ts @@ -0,0 +1,76 @@ +import type { Scenario, ScenarioCandidate } from "@election2026/engine"; +import { cleanAvatar, type CustomCandidate, type PartySlotKey } from "@election2026/protocol"; + +/** + * 把玩家的自創角色放進劇本(docs/04、docs/15)。 + * 取代某位候選人時沿用他的號次與「個人魅力」校準值(代表那個位置的基本盤); + * 以新候選人加入時,從一般小黨候選人的水準起步,再看知名度點數。 + * 頭像照部件目錄清洗(docs/24):看不懂的部件代號換成預設值,不擋開局。 + */ + +export const CUSTOM_ID = "custom"; + +const SLOT: Record = { 民主進步黨: "a", 中國國民黨: "b", 台灣民眾黨: "c" }; + +/** 出身的加成(設計文件 04 的出身表,數值是遊戲設定) */ +const BACKGROUND: Record> = { + 醫師: { eloquence: 6, awareness: 0.03 }, + 律師: { eloquence: 10 }, + 教授: { eloquence: 6, strategy: 4 }, + 前藝人: { awareness: 0.12 }, + 網紅: { awareness: 0.06, fundraising: 1.3 }, + 政二代: { machine: 0.1, awareness: 0.04 }, + 基層里長: { machine: 0.08, awareness: -0.04 }, + 企業家: { money: 8_000_000 }, + 前官員: { strategy: 10, awareness: 0.04 }, + 社運出身: { awareness: 0.04, eloquence: 4 }, +}; + +export class CustomCandidateError extends Error {} + +export function withCustomCandidate(scenario: Scenario, custom: CustomCandidate, realNames: ReadonlySet): Scenario { + const name = custom.name.trim(); + if (realNames.has(name) || realNames.has(name.replace(/(\d{4})$/, ""))) throw new CustomCandidateError(`「${name}」是真實人物的名字,自創角色請換一個名字`); + const replaced = custom.replace ? scenario.candidates.find((c) => c.id === custom.replace) : undefined; + if (custom.replace && !replaced) throw new CustomCandidateError("要取代的候選人不在這個劇本裡"); + // 民進黨、國民黨、民眾黨有自己的選民槽位;其他政黨和無黨籍一樣算「其他」 + const slot = (custom.party && SLOT[custom.party]) || "other"; + const major = slot === "a" || slot === "b"; + const bonus = BACKGROUND[custom.background]; + const { fame, eloquence, strategy, wealth, network } = custom.stats; + const others = scenario.candidates.filter((c) => c.id !== replaced?.id); + const minorAppeals = others.map((c) => c.appeal ?? 0).sort((a, b) => a - b); + const newcomerAppeal = (minorAppeals[Math.min(1, minorAppeals.length - 1)] ?? 0) + fame * 0.15; + const startingMoney = (major ? 12_000_000 : slot === "c" ? 5_000_000 : 2_000_000) + wealth * 2_000_000 + (bonus.money ?? 0); + const candidate: ScenarioCandidate = { + id: CUSTOM_ID, + name, + personId: null, + party: custom.party, + slot, + number: replaced?.number ?? Math.max(...scenario.candidates.map((c) => c.number)) + 1, + description: `${custom.background}出身,${custom.party ? `${custom.party}提名` : "無黨籍參選"}。(自創角色)`, + awareness: Math.min(0.85, Math.max(0.15, 0.25 + fame * 0.04 + (bonus.awareness ?? 0))), + eloquence: Math.min(100, 30 + eloquence * 6 + (bonus.eloquence ?? 0)), + strategy: Math.min(100, 30 + strategy * 6 + (bonus.strategy ?? 0)), + startingMoney, + fundraising: Math.round(((major ? 1_500_000 : slot === "c" ? 600_000 : 250_000) + wealth * 100_000) * (bonus.fundraising ?? 1)), + realFinance: null, + wealth: 2_000_000 + wealth * 2_000_000, + machine: Math.min(0.9, 0.05 + network * 0.03 + (major ? 0.15 : 0) + (bonus.machine ?? 0)), + staff: Math.min(6, 2 + Math.floor(network / 3) + (major ? 1 : 0)), + appeal: replaced?.appeal ?? newcomerAppeal, + aiStyle: "balanced", + avatar: cleanAvatar(custom.avatar).spec, + }; + const candidates = replaced ? scenario.candidates.map((c) => (c.id === replaced.id ? candidate : c)) : [...scenario.candidates, candidate]; + return { + ...scenario, + id: `${scenario.id}+custom`, + hypothetical: true, + candidates, + // 被取代的人不再是真實結果的對照對象 + actual: replaced ? null : scenario.actual, + notes: [`自創角色「${name}」${replaced ? `取代 ${replaced.name}` : "以新候選人加入"},結果不會和真實開票一樣。`, ...scenario.notes], + }; +} diff --git a/backend/packages/content/src/encounters.ts b/backend/packages/content/src/encounters.ts new file mode 100644 index 0000000..02cac34 --- /dev/null +++ b/backend/packages/content/src/encounters.ts @@ -0,0 +1,309 @@ +import type { EncounterDef } from "@election2026/engine"; + +/** + * 拜票副本(docs/08 的延伸):候選人本人跑地面行程時,可以「親自走一趟」,隨機遇到三個人。 + * 每個選項的分數(-2 到 +2)加總後決定這次行程的效果倍率;有些選項另外影響聲勢、體力、標籤或上新聞。 + * 人物都是虛構的路人,不寫真實人物的話。{town} 是區名、{temple} 是宮廟名稱。 + * activities 寫行動 id;"*" 表示所有有副本的地面行程都可能遇到。 + */ + +const STREET = ["street_canvass", "night_market", "door_to_door", "street_interview"]; +const MARKET = ["market_visit", "night_market"]; +const TEMPLE = ["temple_visit", "pilgrimage"]; + +export const ENCOUNTERS: readonly EncounterDef[] = [ + // ── 通用 ── + { + id: "heckler", + activities: ["*"], + who: "路過的中年男子", + line: "「你們這些政治人物選前才出現啦!」他大聲嗆你,旁邊的人都在看。", + options: [ + { id: "listen", label: "停下來聽他說完,請他留電話", score: 2, text: "他講了十分鐘,最後說「好啦,至少你有在聽」。" }, + { id: "joke", label: "笑笑說「所以我現在出現了」", score: 1, text: "旁邊的人笑了,氣氛緩和下來。" }, + { id: "argue", label: "跟他辯回去", score: -2, text: "兩人越吵越大聲,有人開始錄影。", news: { template: "{name}在{town}拜票與民眾起口角", value: 4, tone: "negative" } }, + ], + }, + { + id: "selfie_kids", + activities: ["*"], + who: "一群放學的國中生", + line: "「可以合照嗎?」他們拿著手機圍過來,還要你比一個奇怪的手勢。", + options: [ + { id: "pose", label: "照做,還多比一個愛心", score: 1, text: "照片被傳到班級群組,你成了今天的話題。", momentum: 0.005 }, + { id: "quick", label: "快速拍一張就走", score: 0, text: "他們有點失望,但還是說謝謝。" }, + { id: "civics", label: "順便跟他們聊投票年齡", score: 1, text: "他們說爸媽會投給你——至少有一個說會。" }, + ], + }, + { + id: "lost_grandma", + activities: ["*"], + who: "一位迷路的阿嬤", + line: "阿嬤拉著你的手問:「少年仔,衛生所要怎麼走?」", + options: [ + { id: "walk", label: "親自陪她走過去", score: 2, text: "走了兩條街。阿嬤說要叫全家投給你。", stamina: -5 }, + { id: "staff", label: "請幕僚陪她過去", score: 1, text: "阿嬤很感謝,但一直回頭看你。" }, + { id: "point", label: "比方向給她看", score: -1, text: "阿嬤看起來還是很困惑,旁邊的店家搖頭。" }, + ], + }, + { + id: "reporter_ambush", + activities: ["*"], + who: "跟拍的記者", + line: "記者把麥克風塞到你面前:「請問您對對手昨天的說法有什麼回應?」", + options: [ + { id: "policy", label: "把話題拉回自己的政見", score: 1, text: "新聞只剪了你講政見的那段。" }, + { id: "attack", label: "狠狠回擊對手", score: 0, text: "支持者很爽,中間選民覺得又在吵。", momentum: 0.01 }, + { id: "nocomment", label: "「今天只拜票,不回應」", score: -1, text: "標題變成「閃避回應」。" }, + ], + }, + { + id: "rain_sudden", + activities: ["*"], + who: "午後雷陣雨", + line: "突然下起大雨,騎樓下擠滿躲雨的人。", + options: [ + { id: "stay", label: "淋雨繼續握手", score: 2, text: "全身濕透,照片很有畫面。", stamina: -8 }, + { id: "umbrella", label: "發雨傘給大家", score: 1, text: "雨傘印著你的號次,在街上走來走去。", money: -20000 }, + { id: "leave", label: "先撤退", score: -1, text: "預定的行程只跑了一半。" }, + ], + }, + { + id: "migrant_worker", + activities: ["*"], + who: "幾位外籍移工", + line: "他們好奇地看著你的競選背心,用中文問你是誰。", + options: [ + { id: "chat", label: "停下來跟他們聊工作和生活", score: 1, text: "他們沒有投票權,但附近的老闆看到了,覺得你很親切。" }, + { id: "skip", label: "微笑點頭,繼續往前", score: 0, text: "沒什麼特別的。" }, + ], + }, + { + id: "supporter_gift", + activities: ["*"], + who: "熱情的支持者", + line: "一位大姊塞給你一袋自己做的粽子:「一定要吃喔!」", + options: [ + { id: "eat", label: "當場吃一顆,大讚好吃", score: 1, text: "大姊笑得很開心,說要幫你拉票。" }, + { id: "share", label: "分給幕僚和路人", score: 1, text: "大家一起吃,氣氛很好。" }, + { id: "refuse", label: "婉拒,說不能收禮", score: -1, text: "大姊很受傷:「這又不是賄賂!」" }, + ], + }, + { + id: "youtuber", + activities: ["*"], + who: "拍街頭企劃的 YouTuber", + line: "「可以接受我們的快問快答嗎?會上傳喔!」", + options: [ + { + id: "play", + label: "玩!", + score: 1, + text: "", + roll: { + chance: 0.6, + success: { score: 2, text: "影片點閱破百萬,你答題的樣子被做成梗圖。", momentum: 0.02 }, + failure: { score: -1, text: "連問三題都答錯,留言區很殘忍。" }, + }, + }, + { id: "decline", label: "婉拒,說行程很趕", score: 0, text: "YouTuber 改去訪問你的對手。" }, + ], + }, + // ── 掃街、夜市、挨家挨戶、街訪 ── + { + id: "shop_owner", + activities: STREET, + who: "騎樓下的店老闆", + line: "「生意越來越難做,房租又一直漲,你要怎麼幫我們?」", + options: [ + { id: "promise", label: "承諾推動店家租金補貼", score: 1, text: "老闆把你的文宣貼在收銀台旁邊。" }, + { id: "buy", label: "先跟他買一些東西", score: 1, text: "老闆很開心,介紹隔壁的店家給你認識。", money: -3000 }, + { id: "vague", label: "「我們會研究」", score: -1, text: "老闆翻了一個白眼。" }, + ], + }, + { + id: "scooter_parking", + activities: STREET, + who: "停機車的上班族", + line: "「騎樓都被機車擋住,走路要走到馬路上,你管不管?」", + options: [ + { id: "plan", label: "說明你的人行道改善計畫", score: 1, text: "他點點頭,拍了你的政見文宣。" }, + { id: "together", label: "跟他一起把擋路的機車移好", score: 2, text: "畫面被路人拍下來,說你很接地氣。" }, + { id: "dodge", label: "「這是市府的問題」", score: -1, text: "他說:「那你選什麼?」" }, + ], + }, + { + id: "night_food", + activities: ["night_market"], + who: "雞排攤老闆", + line: "「來啦!吃一塊,我請你!」攤位前排了一長串人。", + options: [ + { id: "line", label: "乖乖排隊付錢買", score: 2, text: "排隊的人都在看,說你不搞特權。" }, + { id: "take", label: "接受老闆請客", score: 0, text: "老闆很高興,但有人在網路上酸你插隊。" }, + { id: "photo", label: "幫老闆拍廣告照", score: 1, text: "老闆把照片印成海報掛在攤位上。" }, + ], + }, + { + id: "door_dog", + activities: ["door_to_door"], + who: "一隻很兇的狗", + line: "門一開,一隻小型犬衝出來狂吠,主人在後面喊「牠不咬人啦!」", + options: [ + { id: "squat", label: "蹲下來讓牠聞手", score: 2, text: "狗狗搖尾巴了,主人說你是好人。" }, + { id: "back", label: "後退兩步,站在門外講", score: 0, text: "主人禮貌地收下文宣。" }, + ], + }, + { + id: "door_elder_alone", + activities: ["door_to_door"], + who: "獨居的老伯", + line: "老伯說孩子都在外地,很久沒人來找他說話了。", + options: [ + { id: "sit", label: "進去坐下來陪他聊半小時", score: 2, text: "他拿出年輕時當兵的照片給你看。", stamina: -6 }, + { id: "care", label: "幫他聯絡里長的關懷服務", score: 1, text: "老伯說「你是第一個問我需要什麼的人」。" }, + { id: "flyer", label: "留下文宣就走", score: -1, text: "老伯把門關上。" }, + ], + }, + { + id: "interview_pension", + activities: ["street_interview"], + who: "退休老師", + line: "「年金改革讓我們很失望,你的立場是什麼?」攝影機正在拍。", + options: [ + { id: "respect", label: "先肯定他的付出,再說你的做法", score: 1, text: "他沒有完全同意,但說你態度很好。" }, + { id: "honest", label: "直說制度要能永續", score: 0, text: "影片底下吵成一團,有人支持有人罵。", momentum: 0.005 }, + { id: "dodge", label: "轉移話題", score: -2, text: "他對著鏡頭說:「看吧,又在閃。」" }, + ], + }, + { + id: "interview_youth", + activities: ["street_interview"], + who: "大學生", + line: "「畢業起薪這麼低,我們為什麼要投給你?」", + options: [ + { id: "plan", label: "講你的青年就業方案", score: 1, text: "她說會去看你的政見網站。" }, + { id: "ask", label: "反問她最希望政府做什麼,認真記下來", score: 2, text: "她說從沒有候選人問過她意見。" }, + { id: "lecture", label: "勸她要多吃苦", score: -2, text: "這段被剪成短影音,標題是「又一個說教的」。", news: { template: "{name}街訪說教惹議", value: 4, tone: "negative" } }, + ], + }, + { + id: "interview_parent", + activities: ["street_interview"], + who: "推著嬰兒車的爸爸", + line: "「托嬰中心排不到,我跟太太只好輪流請假。」", + options: [ + { id: "promise", label: "承諾增設公共托嬰", score: 1, text: "他說選舉完會回來檢查。" }, + { id: "empathize", label: "說你也曾經這樣蠟燭兩頭燒", score: 1, text: "他拍拍你的肩:「辛苦了,一起加油。」" }, + ], + }, + // ── 市場 ── + { + id: "veg_price", + activities: MARKET, + who: "賣菜阿嬤", + line: "「颱風過後菜價這麼貴,你知道一把高麗菜多少錢嗎?」", + options: [ + { id: "know", label: "說出正確的價錢", score: 2, text: "阿嬤很驚訝:「你有在買菜喔!」" }, + { id: "buy", label: "直接跟她買一大袋", score: 1, text: "阿嬤多送你兩根蔥。", money: -800 }, + { id: "guess", label: "隨便猜一個", score: -2, text: "猜錯了一大截,旁邊的人都在笑。" }, + ], + }, + { + id: "fish_stall", + activities: ["market_visit"], + who: "魚販", + line: "魚販雙手都是魚鱗,大笑著伸手要跟你握手。", + options: [ + { id: "shake", label: "毫不猶豫握下去", score: 2, text: "整個市場都在說「這個人不嫌髒」。" }, + { id: "elbow", label: "改成碰手肘", score: 0, text: "魚販笑一笑,說沒關係。" }, + { id: "wipe", label: "握完馬上拿濕紙巾擦手", score: -2, text: "這個畫面被拍下來了。", news: { template: "{name}市場握手後擦手畫面遭瘋傳", value: 5, tone: "negative" } }, + ], + }, + { + id: "market_rival", + activities: MARKET, + who: "對手的宣傳車", + line: "對手的宣傳車剛好開到市場門口,喇叭放得震天響。", + options: [ + { id: "wave", label: "大方對宣傳車揮手致意", score: 1, text: "攤販說你很有風度。" }, + { id: "louder", label: "叫自己的人喊得更大聲", score: -1, text: "兩邊比大聲,攤販在抱怨。" }, + { id: "move", label: "移到市場另一頭", score: 0, text: "避開了,但也少跑了半個市場。" }, + ], + }, + // ── 宮廟、遶境 ── + { + id: "temple_keeper", + activities: TEMPLE, + who: "{temple}的廟公", + line: "廟公遞上三炷香:「先跟神明報告一下你是誰。」", + options: [ + { id: "pray", label: "恭敬上香,照順序拜每一尊", score: 2, text: "廟公點頭:「這個少年有在拜。」" }, + { id: "quick", label: "只拜主殿", score: 0, text: "沒有失禮,但廟公有點意外。" }, + { id: "wrong", label: "拿錯順序,從側殿開始拜", score: -1, text: "廟公默默把你帶回主殿。" }, + ], + }, + { + id: "temple_committee", + activities: TEMPLE, + who: "{temple}管委會主委", + line: "「我們廟前的停車場一直沒做,你當選後可以幫忙嗎?」", + options: [ + { id: "promise", label: "拍胸脯答應", score: 1, text: "主委很高興,說初一十五會幫你廣播。", tag: "地方承諾" }, + { id: "process", label: "說會依程序評估", score: 0, text: "主委說「那再看看」。" }, + { id: "donate", label: "當場添香油錢", score: 1, text: "功德榜上多了你的名字。", money: -6000 }, + ], + }, + { + id: "divination", + activities: TEMPLE, + who: "擲筊", + line: "信徒起鬨:「來擲筊問神明會不會當選!」", + options: [ + { + id: "throw", + label: "擲!", + score: 0, + text: "", + roll: { + chance: 0.5, + success: { score: 2, text: "連續三個聖筊!現場歡聲雷動。", momentum: 0.02, news: { template: "{name}到{town}廟宇擲出連續聖筊", value: 4, tone: "positive" } }, + failure: { score: -1, text: "連擲三次都是笑筊,大家尷尬地笑了。" }, + }, + }, + { id: "humble", label: "「神明自有安排」,婉拒", score: 1, text: "長輩們覺得你很謙虛。" }, + ], + }, + { + id: "procession_crowd", + activities: ["pilgrimage"], + who: "陣頭", + line: "八家將的陣頭停在你面前,信徒示意你讓路。", + options: [ + { id: "kneel", label: "跟信徒一起跪下讓神轎過", score: 2, text: "長輩們很感動,說你懂規矩。" }, + { id: "step", label: "退到路邊行禮", score: 1, text: "沒有失禮。" }, + { id: "photo", label: "趁機拍照打卡", score: -2, text: "被罵不懂規矩。" }, + ], + }, + // ── 工業區 ── + { + id: "shift_change", + activities: ["factory_visit"], + who: "下班的作業員", + line: "「我們輪三班,加班費常常算不清楚。」", + options: [ + { id: "labor", label: "承諾加強勞動檢查", score: 2, text: "她的同事都過來拿你的文宣。" }, + { id: "listen", label: "請她多說一點,記下來", score: 1, text: "她說「希望你真的會看」。" }, + { id: "boss", label: "說要跟老闆溝通看看", score: -1, text: "她聳聳肩走了。" }, + ], + }, + { + id: "factory_boss", + activities: ["factory_visit"], + who: "工廠老闆", + line: "「缺工很嚴重,移工名額能不能放寬?」", + options: [ + { id: "yes", label: "支持放寬", score: 0, text: "老闆很高興,但旁邊的本地勞工臉色不太好。" }, + { id: "balance", label: "說要兼顧本地勞工權益", score: 1, text: "兩邊都覺得你講得合理。" }, + ], + }, +]; diff --git a/backend/packages/content/src/events.ts b/backend/packages/content/src/events.ts new file mode 100644 index 0000000..fc24bc5 --- /dev/null +++ b/backend/packages/content/src/events.ts @@ -0,0 +1,742 @@ +import type { ActionEffect, EventDef } from "@election2026/engine"; + +/** + * 表態事件(docs/08)。原則: + * - 都是虛構的一般情境,不寫真實人物說過的話,不針對特定政黨。 + * - 每個選項都讓某些人高興、某些人不高興;沒有完美答案。 + * - 幅度:全區好感 0.01 約等於一筆 300 萬元電視廣告的 1.5 倍,事件有感但不會一次定生死。 + * {name} 會換成候選人名字。 + */ + +const OLDER = ["50-64", "65+"] as const; +const YOUNGER = ["20-29", "30-39"] as const; +const MIDDLE = ["30-39", "40-49", "50-64"] as const; +const PARENTS = ["30-39", "40-49"] as const; + +const favor = (base: number, ages?: readonly ("20-29" | "30-39" | "40-49" | "50-64" | "65+")[]): ActionEffect => ({ stat: "favor", base, scope: "city", ...(ages ? { ages } : {}) }); +const aware = (base: number, ages?: readonly ("20-29" | "30-39" | "40-49" | "50-64" | "65+")[]): ActionEffect => ({ stat: "awareness", base, scope: "city", ...(ages ? { ages } : {}) }); +const heat = (base: number): ActionEffect => ({ stat: "heat", base, scope: "city", supportersOnly: true }); +const swing = (base: number): ActionEffect => ({ stat: "favor", base, scope: "city", leans: ["middle", "a_lean", "b_lean", "c_lean"] }); +const core = (base: number): ActionEffect => ({ stat: "favor", base, scope: "city", leans: ["a_core", "b_core"] }); + +export const EVENTS: readonly EventDef[] = [ + { + id: "typhoon_visit", + title: "颱風夜,要不要到淹水區?", + body: "颱風帶來豪雨,低窪地區開始積水。記者問你今晚的行程。", + art: "scene-typhoon", + weight: 1.2, + fallback: "stay", + options: [ + { + id: "go", + label: "穿雨衣到現場幫忙", + outcome: { text: "", stamina: -15 }, + roll: { + chance: 0.65, + success: { text: "你幫忙清淤的照片在網路上傳開,長輩說「這個人有在做事」。", effects: [favor(0.012, OLDER), aware(0.02)], momentum: 0.03, news: { title: "{name}颱風夜到淹水區幫忙清淤", tone: "positive" } }, + failure: { text: "攝影機比救災人員還多,網路上有人說你在作秀。", effects: [favor(-0.008, YOUNGER), aware(0.015)], news: { title: "{name}颱風夜視察被批作秀", tone: "negative" } }, + }, + }, + { id: "online", label: "在網路上整理防災資訊", outcome: { text: "防災懶人包被分享了上千次,年輕人覺得實用。", effects: [favor(0.006, YOUNGER), aware(0.008, YOUNGER)] } }, + { id: "stay", label: "照原訂行程", outcome: { text: "沒有出錯,但對手出現在淹水現場,你被拿來比較。", effects: [favor(-0.006, OLDER)] } }, + ], + }, + { + id: "energy_question", + title: "政論節目追問:核電要不要延役?", + body: "節目直播中,主持人突然問你的能源立場。這題會被剪成短影音。", + art: "talk_show", + weight: 1, + fallback: "dodge", + options: [ + { id: "extend", label: "支持延役,先顧電價與供電", outcome: { text: "長輩與工商界叫好,環保團體發新聞稿批評。", effects: [favor(0.01, OLDER), favor(-0.008, YOUNGER)], news: { title: "{name}表態支持核電延役", tone: "neutral" } } }, + { id: "green", label: "反對,加速發展綠能", outcome: { text: "年輕選民按讚,但被追問「缺電怎麼辦」時回答有點虛。", effects: [favor(0.01, YOUNGER), favor(-0.008, OLDER)], news: { title: "{name}主張加速綠能轉型", tone: "neutral" } } }, + { id: "dodge", label: "「這題應該交給公投決定」", outcome: { text: "兩邊都不滿意,短影音標題是「又在閃」。", effects: [swing(-0.006)], news: { title: "{name}被問能源政策避重就輕", tone: "negative" } } }, + ], + }, + { + id: "temple_or_forum", + title: "遶境和青年論壇撞期", + body: "宮廟主委邀你下週扛轎,同一天下午,大學青年政策論壇也邀了你。", + art: "scene-procession", + kinds: ["mayor", "legislator"], + weight: 1, + fallback: "basket", + options: [ + { id: "temple", label: "親自去扛轎", outcome: { text: "主委很有面子,答應幫你牽線幾位里長。", effects: [favor(0.012, OLDER), heat(0.01)], stamina: -10 } }, + { id: "forum", label: "去青年論壇", outcome: { text: "論壇直播反應很好,但對手出現在遶境隊伍最前面。", effects: [favor(0.012, YOUNGER), favor(-0.006, OLDER)] } }, + { id: "basket", label: "派幕僚送花籃", outcome: { text: "禮數到了,但主委私下說「人沒來就是不重視」。", effects: [favor(-0.004, OLDER)] } }, + ], + }, + { + id: "billboard_complaint", + title: "對手開記者會:你的看板佔用人行道", + body: "照片拍得很清楚,有幾面看板確實擋到人行道。記者在總部外面等你回應。", + art: "expose_press", + weight: 1, + fallback: "silent", + options: [ + { id: "sorry", label: "公開道歉,今晚全部拆掉", outcome: { text: "新聞只播了一天,網友說「至少敢認錯」。", effects: [swing(0.006)], money: -100_000, news: { title: "{name}道歉並拆除違規看板", tone: "neutral" } } }, + { id: "counter", label: "反控對方也有違規看板", outcome: { text: "雙方互相爆料上了頭條,支持者很熱血,但中間選民覺得兩邊都一樣。", effects: [heat(0.015), swing(-0.006)], news: { title: "看板之亂延燒 {name}反控對手也違規", tone: "negative" } } }, + { id: "silent", label: "不回應", outcome: { text: "對手連續三天追打,標題變成「心虛不敢回應」。", effects: [swing(-0.008)] } }, + ], + }, + { + id: "food_safety", + title: "知名餐廳爆發食物中毒", + body: "一家連鎖餐廳有幾十人送醫,衛生單位正在調查。媒體問你的看法。", + art: "market_visit", + weight: 0.9, + fallback: "wait", + options: [ + { id: "tough", label: "要求加重罰則、全面稽查", outcome: { text: "家長們很買單,但餐飲公會說你在打擊整個產業。", effects: [favor(0.01, PARENTS), favor(-0.004, MIDDLE)], news: { title: "{name}要求食安加重罰則", tone: "positive" } } }, + { id: "visit", label: "到醫院慰問患者家屬", outcome: { text: "家屬感謝你來,但也有人說「這時候來拍照」。", effects: [aware(0.012), favor(0.004, OLDER)], stamina: -8 } }, + { id: "wait", label: "等調查結果再說", outcome: { text: "說法很穩,但沒有人記得你說了什麼。", effects: [] } }, + ], + }, + { + id: "housing_debate", + title: "青年團體邀你談居住正義", + body: "租屋族團體辦座談,要候選人回答:房價這麼高,你要怎麼辦?", + art: "announce_policy", + weight: 1, + fallback: "decline", + options: [ + { id: "social", label: "承諾大量興建社會住宅", outcome: { text: "年輕人與租屋族熱烈鼓掌,有房的長輩擔心房價下跌。", effects: [favor(0.014, YOUNGER), favor(-0.006, ["50-64", "65+"])], news: { title: "{name}承諾大量興建社會住宅", tone: "positive" } } }, + { id: "subsidy", label: "主打租金補貼與青年首購", outcome: { text: "大家都覺得不錯,但學者說補貼會推高房價。", effects: [favor(0.007, YOUNGER), favor(0.003, MIDDLE)] } }, + { id: "decline", label: "婉拒出席", outcome: { text: "座談會上你的名牌前是空的,照片被到處轉傳。", effects: [favor(-0.01, YOUNGER)], news: { title: "居住正義座談 {name}缺席", tone: "negative" } } }, + ], + }, + { + id: "longterm_care", + title: "長照家屬到總部陳情", + body: "一群照顧失智長輩的家屬,希望你承諾增加長照據點與喘息服務。", + art: "street_canvass", + weight: 1, + fallback: "study", + options: [ + { id: "promise", label: "當場承諾增加長照預算", outcome: { text: "家屬感動落淚,長輩很買單;財經記者問錢從哪裡來。", effects: [favor(0.012, OLDER), favor(0.004, MIDDLE)], news: { title: "{name}承諾擴大長照服務", tone: "positive" } } }, + { id: "listen", label: "坐下來聽完每個人的故事", outcome: { text: "花了一整個下午,家屬說你是第一個認真聽的候選人。", effects: [favor(0.008, OLDER), heat(0.008)], stamina: -10 } }, + { id: "study", label: "說會研究看看", outcome: { text: "家屬失望離開,有人在臉書上抱怨。", effects: [favor(-0.006, OLDER)] } }, + ], + }, + { + id: "celebrity_endorse", + title: "一位知名藝人想幫你站台", + body: "他的粉絲很多,但幾年前有過爭議言論,網路上還有人記得。", + art: "rally", + weight: 0.8, + fallback: "decline", + options: [ + { + id: "accept", + label: "接受,請他來造勢晚會", + outcome: { text: "" }, + roll: { + chance: 0.6, + success: { text: "現場爆滿,年輕人搶著合照,聲勢大漲。", effects: [aware(0.025, YOUNGER), favor(0.006, YOUNGER)], momentum: 0.05, news: { title: "人氣藝人站台 {name}造勢晚會爆滿", tone: "positive" } }, + failure: { text: "舊爭議被翻出來,你一直被問「你認同他說的話嗎」。", effects: [aware(0.015), swing(-0.01)], news: { title: "{name}找爭議藝人站台挨批", tone: "negative" } }, + }, + }, + { id: "decline", label: "婉拒,維持形象", outcome: { text: "風平浪靜,但少了一次衝聲量的機會。", effects: [] } }, + ], + }, + { + id: "party_elder", + title: "黨內大老要來幫你站台", + body: "他在支持者心中很有份量,但中間選民對他的評價兩極。", + art: "party_elder", + kinds: ["mayor", "legislator"], + party: true, + weight: 0.9, + fallback: "polite", + options: [ + { id: "welcome", label: "熱烈歡迎,一起掃街", outcome: { text: "鐵票支持者士氣大振,中間選民有點卻步。", effects: [core(0.012), heat(0.015), swing(-0.006)], momentum: 0.02 } }, + { id: "polite", label: "感謝,但改成私下拜會", outcome: { text: "雙方客客氣氣,大老有點不高興。", effects: [core(-0.004)] } }, + ], + }, + { + id: "meme", + title: "你的舊照片被做成迷因爆紅", + body: "一張你多年前表情很誇張的照片,被網友改成各種梗圖。", + art: "online_ad", + weight: 0.9, + fallback: "ignore", + options: [ + { + id: "embrace", + label: "自己拍影片自嘲跟風", + outcome: { text: "" }, + roll: { + chance: 0.7, + success: { text: "影片衝上熱門,年輕人說你很有梗。", effects: [aware(0.03, YOUNGER), favor(0.008, YOUNGER)], momentum: 0.03, news: { title: "{name}自嘲迷因爆紅", tone: "positive" } }, + failure: { text: "影片太刻意,被說「老人硬要裝年輕」。", effects: [aware(0.015, YOUNGER), favor(-0.005, YOUNGER)] }, + }, + }, + { id: "clarify", label: "請網友尊重,不要亂改", outcome: { text: "反而被做成更多梗圖。", effects: [aware(0.01, YOUNGER), favor(-0.006, YOUNGER)] } }, + { id: "ignore", label: "不理它", outcome: { text: "熱度一週就退了。", effects: [aware(0.006, YOUNGER)] } }, + ], + }, + { + id: "extra_debate", + title: "對手公開提議加開一場辯論", + body: "對手在臉書上嗆聲:敢不敢再辯一場?", + art: "talk_show", + weight: 0.8, + weeks: [3, 9], + fallback: "refuse", + options: [ + { + id: "accept", + label: "接受挑戰", + outcome: { text: "", stamina: -10 }, + roll: { + chance: 0.5, + success: { text: "你在辯論中表現沉穩,被評為「贏了這一場」。", effects: [swing(0.012), aware(0.015)], momentum: 0.04, news: { title: "加場辯論 {name}表現獲好評", tone: "positive" } }, + failure: { text: "一個問題答不出來,被剪成短片到處傳。", effects: [swing(-0.01)], momentum: -0.03, news: { title: "加場辯論 {name}答詢卡關", tone: "negative" } }, + }, + }, + { id: "refuse", label: "婉拒,說行程已滿", outcome: { text: "對手說你「怯戰」,支持者有點洩氣。", effects: [heat(-0.008), swing(-0.004)] } }, + ], + }, + { + id: "pedestrian_safety", + title: "路口車禍,行人安全又上新聞", + body: "一位長者在斑馬線上被車撞。網路上又在討論「行人地獄」。", + art: "street_canvass", + weight: 0.9, + kinds: ["mayor", "legislator"], + fallback: "condolence", + options: [ + { id: "plan", label: "提出路口改善與降速計畫", outcome: { text: "年輕家長和通勤族支持,但機車族擔心更塞。", effects: [favor(0.01, PARENTS), favor(-0.004, ["20-29"])], news: { title: "{name}提出行人安全改善計畫", tone: "positive" } } }, + { id: "site", label: "到事故路口現場勘查", outcome: { text: "里長陪你走了一圈,地方覺得你有在關心。", effects: [favor(0.006, OLDER), aware(0.006)], stamina: -6 } }, + { id: "condolence", label: "發文致哀", outcome: { text: "很得體,但大家想聽的是你要怎麼做。", effects: [] } }, + ], + }, + { + id: "delivery_workers", + title: "外送員團體要求立法保障", + body: "外送員在總部前舉牌,希望候選人支持保險與最低收入保障。", + art: "factory_visit", + weight: 0.8, + fallback: "neutral", + options: [ + { id: "support", label: "簽署支持保障法案", outcome: { text: "外送員與年輕勞工叫好,平台業者與部分店家擔心成本上升。", effects: [favor(0.01, YOUNGER), favor(-0.004, ["40-49", "50-64"])], news: { title: "{name}支持外送員權益保障", tone: "positive" } } }, + { id: "talk", label: "請業者與外送員一起坐下談", outcome: { text: "兩邊都覺得你很中立,也都覺得你沒有表態。", effects: [swing(0.003)] } }, + { id: "neutral", label: "不表態", outcome: { text: "外送員把你的名字寫在「不友善候選人」名單上。", effects: [favor(-0.008, YOUNGER)] } }, + ], + }, + { + id: "childcare", + title: "年輕爸媽問:托育補助夠不夠?", + body: "親子團體的問卷寄到總部,題目是你會不會加碼托育與育兒補助。", + art: "announce_policy", + weight: 0.9, + fallback: "later", + options: [ + { id: "more", label: "加碼育兒津貼", outcome: { text: "年輕爸媽很開心;也有人問「沒有小孩的人怎麼辦」。", effects: [favor(0.012, PARENTS), favor(-0.003, ["20-29", "65+"])], news: { title: "{name}加碼育兒津貼", tone: "positive" } } }, + { id: "centers", label: "主打增設公立托嬰中心", outcome: { text: "政見扎實,但要等好幾年才看得到。", effects: [favor(0.007, PARENTS)] } }, + { id: "later", label: "說政見會再完整公布", outcome: { text: "親子團體評分表上,你那欄是空白。", effects: [favor(-0.005, PARENTS)] } }, + ], + }, + { + id: "staff_gaffe", + title: "幕僚在私人群組失言被截圖", + body: "一位幕僚在群組裡開了不得體的玩笑,截圖被傳到網路上。", + art: "expose_press", + weight: 0.8, + weeks: [2, 10], + fallback: "silent", + options: [ + { id: "fire", label: "立刻請他離開,公開道歉", outcome: { text: "處理得很快,風波兩天就平息。", effects: [swing(0.004)], news: { title: "幕僚失言 {name}道歉並撤換", tone: "neutral" } } }, + { id: "defend", label: "說只是私人玩笑", outcome: { text: "網路上越吵越大,連支持者都覺得不妥。", effects: [swing(-0.012), heat(-0.006)], news: { title: "{name}陣營失言風波延燒", tone: "negative" } } }, + { id: "silent", label: "不回應,等它過去", outcome: { text: "對手每天都提一次。", effects: [swing(-0.007)] } }, + ], + }, + { + id: "wedding_rounds", + title: "週末晚上有三場喜宴", + body: "三位里長家都在辦喜事,都希望你去敬酒。", + art: "fundraiser_dinner", + kinds: ["mayor", "legislator"], + weight: 1, + fallback: "one", + options: [ + { id: "all", label: "三攤都跑", outcome: { text: "一晚喝了九杯,里長們很有面子;隔天你累壞了。", effects: [favor(0.01, OLDER), heat(0.01)], stamina: -20 } }, + { id: "one", label: "只去最重要的一攤", outcome: { text: "另外兩位里長有點不高興。", effects: [favor(0.003, OLDER)] } }, + { id: "gift", label: "都送禮金不出席", outcome: { text: "禮到了,但地方說你「架子很大」。", effects: [favor(-0.004, OLDER)], money: -30_000 } }, + ], + }, + { + id: "district_favor", + title: "地方人士請你幫忙關說", + body: "一位很有影響力的地方人士,希望你幫他的違建「去跟公所講一下」。", + art: "recruit_machine", + kinds: ["legislator", "mayor"], + weight: 0.8, + fallback: "refuse", + options: [ + { + id: "help", + label: "答應幫忙打個電話", + outcome: { text: "" }, + roll: { + chance: 0.6, + success: { text: "他很感激,答應動員整個社區的人投給你。", effects: [heat(0.012), favor(0.006, OLDER)] }, + failure: { text: "通話內容被錄下來爆料,你被批「關說違建」。", effects: [swing(-0.014)], momentum: -0.04, news: { title: "{name}被爆替違建關說", tone: "negative" } }, + }, + }, + { id: "refuse", label: "婉拒,依法處理", outcome: { text: "他很不高興,說會叫大家「好好想一想」。", effects: [favor(-0.005, OLDER), swing(0.003)] } }, + ], + }, + { + id: "cross_strait", + title: "外國媒體專訪:你的兩岸政策是什麼?", + body: "國際媒體的專訪會在全球播出,國內媒體也會逐字分析。", + art: "talk_show", + kinds: ["president"], + weight: 1.4, + fallback: "status_quo", + options: [ + { id: "sovereignty", label: "強調主權與國防", outcome: { text: "核心支持者很振奮,部分中間選民擔心緊張升高。", effects: [{ stat: "favor", base: 0.012, scope: "city", leans: ["a_core", "a_lean"] }, { stat: "favor", base: -0.006, scope: "city", leans: ["b_core", "b_lean"] }], news: { title: "{name}接受外媒專訪 強調主權與國防", tone: "neutral" } } }, + { id: "exchange", label: "強調和平與交流", outcome: { text: "工商界支持,但有人擔心你「太軟」。", effects: [{ stat: "favor", base: 0.012, scope: "city", leans: ["b_core", "b_lean"] }, { stat: "favor", base: -0.006, scope: "city", leans: ["a_core", "a_lean"] }], news: { title: "{name}接受外媒專訪 強調和平交流", tone: "neutral" } } }, + { id: "status_quo", label: "強調維持現狀、務實", outcome: { text: "兩邊都不太興奮,中間選民覺得穩。", effects: [swing(0.006)] } }, + ], + }, + { + id: "running_mate_rumor", + title: "媒體傳出你的搭檔人選不合", + body: "報導說你和副手在幾個政策上意見不同,競選總部氣氛緊張。", + art: "hire_staff", + kinds: ["president"], + weight: 1, + fallback: "deny", + options: [ + { id: "together", label: "兩人一起公開掃街", outcome: { text: "合照很有默契,傳言不攻自破。", effects: [swing(0.006)], stamina: -10, news: { title: "{name}與副手聯袂掃街破除不合傳言", tone: "positive" } } }, + { id: "deny", label: "發聲明否認", outcome: { text: "聲明寫得很硬,記者覺得「越描越黑」。", effects: [swing(-0.005)] } }, + ], + }, + { + id: "fundraising_offer", + title: "一位企業主想捐一大筆錢", + body: "他的公司願意捐 100 萬元(營利事業捐給同一位候選人的法定上限),但暗示當選後在某個開發案上「多關照」。", + art: "fundraiser_dinner", + weight: 0.8, + fallback: "refuse", + options: [ + { + id: "accept", + label: "收下,不承諾任何事", + outcome: { text: "", money: 1_000_000 }, + roll: { + chance: 0.75, + success: { text: "錢進了政治獻金專戶,選戰手頭寬裕許多。", effects: [] }, + failure: { text: "對手查到這位企業主的開發案爭議,你被質疑「利益交換」。", effects: [swing(-0.012)], momentum: -0.03, news: { title: "{name}被質疑收受開發商獻金", tone: "negative" } }, + }, + }, + { id: "refuse", label: "婉拒,堅持小額募款", outcome: { text: "支持者知道後很感動,小額捐款多了一些。", effects: [heat(0.006)], money: 300_000 } }, + ], + }, + + // ── 總統 ── + { + id: "local_lords", + title: "各縣市長要不要幫你站台?", + body: "同陣營的縣市長都有自己的盤算。有人想上台幫你,也有人怕被你的爭議拖累。", + art: "party_elder", + kinds: ["president"], + party: true, + weight: 1.2, + fallback: "let", + options: [ + { id: "tour", label: "排一輪縣市長聯合造勢", outcome: { text: "地方組織全動起來,支持者熱度大增。", effects: [heat(0.02), core(0.006)], stamina: -15, news: { title: "{name}與多位縣市長聯合造勢", tone: "positive" } } }, + { id: "selective", label: "只找形象好的縣市長", outcome: { text: "中間選民觀感不錯,但沒被找的人有點不爽。", effects: [swing(0.006), core(-0.003)] } }, + { id: "let", label: "讓各縣市自己決定", outcome: { text: "有的縣市很拚,有的幾乎沒動作。", effects: [] } }, + ], + }, + { + id: "defense_budget", + title: "記者問:國防預算要不要再增加?", + body: "國際情勢緊張,國防預算是大選的必考題。", + art: "press_conference", + kinds: ["president"], + weight: 1, + fallback: "maintain", + options: [ + { id: "raise", label: "大幅增加國防預算", outcome: { text: "主張強化國防的選民叫好,有人擔心排擠社福。", effects: [{ stat: "favor", base: 0.01, scope: "city", leans: ["a_core", "a_lean", "middle"] }, favor(-0.004, ["65+"])], news: { title: "{name}主張大幅增加國防預算", tone: "neutral" } } }, + { id: "maintain", label: "維持現有規模,強調效率", outcome: { text: "說法穩健,但沒有亮點。", effects: [swing(0.003)] } }, + { id: "dialogue", label: "強調對話降低衝突", outcome: { text: "主張和平的選民支持,也有人說你太天真。", effects: [{ stat: "favor", base: 0.01, scope: "city", leans: ["b_core", "b_lean"] }, { stat: "favor", base: -0.006, scope: "city", leans: ["a_core", "a_lean"] }], news: { title: "{name}強調以對話降低衝突", tone: "neutral" } } }, + ], + }, + { + id: "power_outage", + title: "大停電!半個台灣暗了三小時", + body: "電廠跳機造成大停電,能源政策成為焦點。", + art: "scene-typhoon", + kinds: ["president", "mayor"], + weight: 0.9, + fallback: "comfort", + options: [ + { id: "blame", label: "痛批現行能源政策", outcome: { text: "受不了停電的民眾叫好,也有人覺得你在消費災難。", effects: [favor(0.008, ["40-49", "50-64", "65+"]), favor(-0.004, YOUNGER)], momentum: 0.01, news: { title: "大停電 {name}痛批能源政策", tone: "neutral" } } }, + { id: "plan", label: "提出電網韌性計畫", outcome: { text: "專家說計畫可行,但太專業了沒什麼人看。", effects: [swing(0.006)], news: { title: "{name}提出電網韌性計畫", tone: "positive" } } }, + { id: "comfort", label: "呼籲大家互相幫忙、關心長輩", outcome: { text: "溫暖但沒什麼記憶點。", effects: [favor(0.003, OLDER)] } }, + ], + }, + { + id: "talent_drain", + title: "年輕人說:我想出國工作", + body: "一份調查顯示,越來越多年輕人想到海外工作,記者問你怎麼看。", + art: "online_ad", + kinds: ["president"], + weight: 0.8, + fallback: "free", + options: [ + { id: "wages", label: "承諾推動加薪與住宅政策", outcome: { text: "年輕人覺得你懂他們。", effects: [favor(0.01, YOUNGER)] } }, + { id: "free", label: "「出去闖闖也很好」", outcome: { text: "有人覺得開明,有人覺得你不在乎。", effects: [favor(0.002, YOUNGER), favor(-0.003, OLDER)] } }, + ], + }, + { + id: "vp_debate", + title: "副總統候選人電視辯論", + body: "你的副手明晚要上電視辯論。要怎麼準備?", + art: "talk_show", + kinds: ["president"], + weeks: [4, 9], + weight: 1, + fallback: "trust", + options: [ + { + id: "attack", + label: "請副手主攻對手弱點", + outcome: { text: "" }, + roll: { + chance: 0.55, + success: { text: "副手表現犀利,支持者大振。", effects: [heat(0.015), swing(0.004)], momentum: 0.03, news: { title: "副總統辯論 {name}陣營副手表現亮眼", tone: "positive" } }, + failure: { text: "攻擊太兇,被批沒有風度。", effects: [swing(-0.008)], news: { title: "副總統辯論 {name}陣營副手火力過猛挨批", tone: "negative" } }, + }, + }, + { id: "policy", label: "請副手專心講政策", outcome: { text: "穩穩的,沒有失分。", effects: [swing(0.004)] } }, + { id: "trust", label: "相信副手自己發揮", outcome: { text: "表現中規中矩。", effects: [] } }, + ], + }, + // ── 縣市長 ── + { + id: "mrt_delay", + title: "捷運工程又延宕了", + body: "地方期待多年的捷運再度延後通車,記者問你有什麼辦法。", + art: "press_conference", + kinds: ["mayor"], + weight: 1, + fallback: "promise", + options: [ + { id: "deadline", label: "承諾任內一定通車", outcome: { text: "通勤族很期待,也有人說你在開支票。", effects: [favor(0.008, MIDDLE)], news: { title: "{name}承諾任內捷運通車", tone: "positive" } } }, + { id: "bus", label: "先推公車與自行車道改善", outcome: { text: "務實,年輕人比較買單。", effects: [favor(0.006, YOUNGER)] } }, + { id: "promise", label: "說要先檢討延宕原因", outcome: { text: "大家覺得你在打官腔。", effects: [swing(-0.004)] } }, + ], + }, + { + id: "water_cut", + title: "乾旱,部分地區開始分區供水", + body: "水庫見底,部分里開始停水。居民一肚子火。", + art: "scene-typhoon", + kinds: ["mayor"], + weight: 0.8, + fallback: "saving", + options: [ + { id: "trucks", label: "自費安排水車送水", outcome: { text: "受影響的里很感謝你,花了一筆錢。", effects: [favor(0.012, OLDER)], money: -300_000, news: { title: "{name}安排水車到缺水區送水", tone: "positive" } } }, + { id: "infra", label: "提出水資源建設計畫", outcome: { text: "長期來看很好,但現在沒水的人不太在乎。", effects: [swing(0.004)] } }, + { id: "saving", label: "呼籲大家節約用水", outcome: { text: "被說「講了等於沒講」。", effects: [swing(-0.004)] } }, + ], + }, + { + id: "incinerator", + title: "垃圾焚化爐選址,居民抗爭", + body: "新的焚化爐預定地附近的居民拉布條抗議,要你表態。", + art: "protest_government", + kinds: ["mayor", "legislator"], + weight: 0.9, + fallback: "evaluate", + options: [ + { id: "oppose", label: "站在居民這邊反對", outcome: { text: "預定地附近的里很感激,其他地區的人擔心垃圾沒地方去。", effects: [favor(0.006, OLDER)], momentum: 0.01 } }, + { id: "support", label: "支持興建,但加強回饋", outcome: { text: "理性的說法,但當地居民很不滿。", effects: [swing(0.004), heat(-0.005)] } }, + { id: "evaluate", label: "說要重新評估", outcome: { text: "兩邊都不滿意。", effects: [swing(-0.003)] } }, + ], + }, + { + id: "social_housing_site", + title: "社會住宅預定地,鄰居反對", + body: "有居民擔心社宅會讓房價下跌、治安變差,在說明會上大聲抗議。", + art: "announce_policy", + kinds: ["mayor"], + weight: 0.8, + fallback: "communicate", + options: [ + { id: "proceed", label: "堅持興建,說明社宅不是問題", outcome: { text: "年輕人支持你,附近的屋主很生氣。", effects: [favor(0.01, YOUNGER), favor(-0.006, OLDER)] } }, + { id: "move", label: "答應另覓地點", outcome: { text: "屋主滿意,年輕人覺得你退縮。", effects: [favor(0.004, OLDER), favor(-0.006, YOUNGER)] } }, + { id: "communicate", label: "辦更多場說明會", outcome: { text: "爭議繼續延燒。", effects: [] } }, + ], + }, + { + id: "dengue", + title: "登革熱疫情升溫", + body: "南部爆發登革熱群聚,病例一週內翻倍。", + art: "street_canvass", + kinds: ["mayor", "legislator"], + weight: 0.7, + fallback: "remind", + options: [ + { id: "clean", label: "帶志工清積水孳生源", outcome: { text: "里民看到你挽起袖子在做事。", effects: [favor(0.01, OLDER), aware(0.008)], stamina: -10, news: { title: "{name}帶志工清除病媒蚊孳生源", tone: "positive" } } }, + { id: "remind", label: "發文提醒大家防蚊", outcome: { text: "有做事,但沒什麼人注意。", effects: [favor(0.002)] } }, + ], + }, + { + id: "urban_renewal", + title: "老公寓住戶問:都更什麼時候才會動?", + body: "四五十年的老公寓沒有電梯,長輩爬樓梯很辛苦。", + art: "door_to_door", + kinds: ["mayor"], + weight: 0.8, + fallback: "listen", + options: [ + { id: "speed", label: "承諾加速都更審議", outcome: { text: "老屋住戶很期待,有人擔心建商得利。", effects: [favor(0.01, OLDER)] } }, + { id: "elevator", label: "主打老公寓加裝電梯補助", outcome: { text: "務實又看得到,長輩很買單。", effects: [favor(0.012, ["65+"])], news: { title: "{name}主打老公寓加裝電梯補助", tone: "positive" } } }, + { id: "listen", label: "說會帶回去研究", outcome: { text: "長輩嘆了一口氣。", effects: [favor(-0.003, OLDER)] } }, + ], + }, + // ── 區域立委 ── + { + id: "pothole", + title: "選區道路坑坑洞洞,里民陳情", + body: "一位機車騎士摔車受傷,里長帶著居民到你的服務處陳情。", + art: "recruit_machine", + kinds: ["legislator"], + weight: 1, + fallback: "forward", + options: [ + { id: "site", label: "當天就去現場會勘,找主管機關", outcome: { text: "里長說你是最快到的。", effects: [favor(0.01, OLDER)], stamina: -8, news: { title: "{name}到現場會勘道路坑洞", tone: "positive" } } }, + { id: "forward", label: "請助理把陳情轉給主管機關", outcome: { text: "程序正確,但里民覺得沒誠意。", effects: [favor(-0.002, OLDER)] } }, + ], + }, + { + id: "party_line", + title: "黨團要你跟著黨的立場表態", + body: "一個在選區很有爭議的法案,黨團要求大家一致支持。", + art: "announce_policy", + kinds: ["legislator"], + party: true, + weight: 1, + fallback: "follow", + options: [ + { id: "follow", label: "跟黨團一致", outcome: { text: "黨內很滿意,但選區有人不高興。", effects: [core(0.006), swing(-0.006)] } }, + { id: "district", label: "以選區民意為優先", outcome: { text: "中間選民覺得你有骨氣,黨內有人說你不合群。", effects: [swing(0.01), core(-0.006)], news: { title: "{name}不跟黨團同調 強調選區民意優先", tone: "neutral" } } }, + ], + }, + { + id: "councilor_rift", + title: "同黨議員說他不挺你", + body: "選區裡一位同黨議員對提名不滿,放話不會幫你助選。", + art: "councilor_allies", + kinds: ["legislator", "mayor"], + party: true, + weight: 0.8, + fallback: "ignore", + options: [ + { id: "visit", label: "親自登門拜訪,請他幫忙", outcome: { text: "談了一個晚上,他答應出席你的造勢。", effects: [core(0.006), heat(0.01)], stamina: -6 } }, + { id: "public", label: "公開喊話團結", outcome: { text: "媒體把它寫成「黨內不和」。", effects: [swing(-0.004)], news: { title: "{name}陣營傳黨內不和", tone: "negative" } } }, + { id: "ignore", label: "不理他,專心跑自己的", outcome: { text: "他的樁腳在選區裡按兵不動。", effects: [heat(-0.008)] } }, + ], + }, + { + id: "fishing_port", + title: "漁民抱怨漁港淤積", + body: "港口淤積,漁船進出困難,漁會理事長請你幫忙。", + art: "flags_billboards", + kinds: ["legislator"], + weight: 0.6, + fallback: "later", + options: [ + { id: "budget", label: "承諾爭取疏濬預算", outcome: { text: "漁會說會動員會員投給你。", effects: [favor(0.008, OLDER), heat(0.008)] } }, + { id: "later", label: "說選後再處理", outcome: { text: "漁民很失望。", effects: [favor(-0.004, OLDER)] } }, + ], + }, + // ── 無黨籍、小黨 ── + { + id: "party_courtship", + title: "有政黨想找你合作", + body: "一個政黨表示願意不推人禮讓你,條件是你要支持他們的幾項政策。", + art: "hire_staff", + party: false, + weight: 1, + fallback: "independent", + options: [ + { id: "accept", label: "接受合作", outcome: { text: "多了一批政黨支持者,但有人覺得你不再獨立。", effects: [core(0.01), heat(0.012), swing(-0.004)], money: 500_000, news: { title: "{name}獲政黨禮讓支持", tone: "positive" } } }, + { id: "independent", label: "婉拒,堅持獨立參選", outcome: { text: "中間選民覺得你有個性。", effects: [swing(0.006)] } }, + ], + }, + { + id: "underdog_media", + title: "媒體想報導「黑馬」", + body: "一家網路媒體想做專題,報導一般人怎麼跟大黨候選人拚。", + art: "interview", + party: false, + weight: 1.2, + fallback: "accept", + options: [ + { id: "accept", label: "接受採訪,講自己的故事", outcome: { text: "專題被轉傳,很多人第一次認識你。", effects: [aware(0.03), favor(0.006, YOUNGER)], momentum: 0.02 } }, + { id: "decline", label: "婉拒,說要專心跑基層", outcome: { text: "錯過了一次曝光。", effects: [] } }, + ], + }, + // ── 通用 ── + { + id: "exhausted", + title: "你累倒了", + body: "連續幾週行程滿檔,今天早上起床頭暈,醫生建議休息。", + art: "rest", + weight: 0.7, + weeks: [3, 10], + fallback: "push", + options: [ + { id: "rest", label: "聽醫生的,休息兩天", outcome: { text: "體力恢復了,但這週少跑了幾場。", stamina: 30 } }, + { id: "push", label: "吊完點滴繼續跑", outcome: { text: "支持者很心疼,但你的狀態很差。", effects: [heat(0.01)], stamina: -15, news: { title: "{name}吊完點滴繼續拚行程", tone: "neutral" } } }, + ], + }, + { + id: "family_story", + title: "媒體要拍你的家人", + body: "電視台想做一集「候選人的家」,要拍你的家人和日常生活。", + art: "tv_ad", + weight: 0.8, + fallback: "decline", + options: [ + { id: "accept", label: "答應,讓大家看看真實的你", outcome: { text: "溫馨的畫面讓很多長輩對你改觀。", effects: [favor(0.01, OLDER), aware(0.01)] } }, + { id: "decline", label: "婉拒,保護家人隱私", outcome: { text: "記者說可以理解。", effects: [] } }, + ], + }, + { + id: "hq_blackout", + title: "競選總部停電,活動被迫延後", + body: "今晚的支持者大會開到一半,整棟大樓停電。", + art: "open_office", + weight: 0.6, + fallback: "cancel", + options: [ + { id: "candle", label: "點蠟燭、拿手機燈繼續講", outcome: { text: "畫面意外地很有氣氛,被支持者拍成影片。", effects: [heat(0.012)], momentum: 0.01 } }, + { id: "cancel", label: "宣布延期", outcome: { text: "支持者有點掃興。", effects: [heat(-0.005)] } }, + ], + }, + { + id: "poll_dispute", + title: "一份民調把你算得很低", + body: "某民調機構的數字比其他家低很多,你的支持者很不服氣。", + art: "internal_poll", + weight: 0.8, + weeks: [3, 8], + fallback: "ignore", + options: [ + { id: "question", label: "公開質疑民調方法", outcome: { text: "支持者熱度提高,但中間選民覺得你輸不起。", effects: [heat(0.01), swing(-0.004)] } }, + { id: "humble", label: "「民調只是參考,我們繼續努力」", outcome: { text: "說法得體。", effects: [swing(0.004)] } }, + { id: "ignore", label: "不回應", outcome: { text: "沒事。", effects: [] } }, + ], + }, + { + id: "degree_rumor", + title: "網路謠言質疑你的學歷", + body: "有人在網路上說你的碩士論文是抄的,還附了幾張截圖。", + art: "online_ad", + weight: 0.6, + fallback: "ignore", + options: [ + { id: "publish", label: "公開論文全文與口試紀錄", outcome: { text: "謠言很快就被破解了。", effects: [swing(0.006)], news: { title: "{name}公開論文全文回應學歷質疑", tone: "neutral" } } }, + { id: "sue", label: "對造謠者提告", outcome: { text: "新聞延燒了一週,大家記住的是「論文」兩個字。", effects: [swing(-0.004)] } }, + { id: "ignore", label: "不理它", outcome: { text: "謠言在長輩的群組裡流傳。", effects: [favor(-0.006, OLDER)] } }, + ], + }, + { + id: "volunteer_heatstroke", + title: "一位志工在烈日下中暑", + body: "掃街的志工昏倒送醫,媒體問競選團隊是不是太操。", + art: "recruit_volunteers", + weight: 0.6, + fallback: "statement", + options: [ + { id: "visit", label: "親自到醫院探望,調整行程", outcome: { text: "志工家屬很感動,團隊士氣提升。", effects: [heat(0.008)], stamina: -5 } }, + { id: "statement", label: "發新聞稿說明", outcome: { text: "被批冷淡。", effects: [swing(-0.004)] } }, + ], + }, + { + id: "staff_poached", + title: "對手想挖角你的幕僚", + body: "你的文宣主任私下說,對手開了兩倍的薪水找他。", + art: "hire_staff", + weight: 0.6, + weeks: [2, 8], + fallback: "let", + options: [ + { id: "raise", label: "加薪留人", outcome: { text: "他留下來了,而且更拚了。", money: -300_000 } }, + { id: "loyalty", label: "跟他聊理想,請他留下", outcome: { text: "", stamina: -4 }, roll: { chance: 0.6, success: { text: "他被你說服了。" }, failure: { text: "他還是走了,帶走了一些文宣素材。", effects: [heat(-0.008)] } } }, + { id: "let", label: "尊重他的選擇", outcome: { text: "他走了,文宣進度落後一週。", effects: [aware(-0.006, YOUNGER)] } }, + ], + }, + { + id: "scam_impersonation", + title: "詐騙集團冒用你的名義", + body: "有長輩接到電話,對方自稱是你的競選總部,要他們匯款「贊助」。", + art: "phone_banking", + weight: 0.6, + fallback: "warn", + options: [ + { id: "warn", label: "立刻發布防詐提醒,報警處理", outcome: { text: "處理得很快,長輩覺得你很負責。", effects: [favor(0.006, OLDER)] } }, + { id: "press", label: "開記者會呼籲大家注意", outcome: { text: "新聞效果不錯。", effects: [aware(0.01), favor(0.004, OLDER)] } }, + ], + }, + { + id: "earthquake", + title: "半夜發生規模六的地震", + body: "有老舊建築傾斜,居民在外面過夜。", + art: "scene-typhoon", + weight: 0.5, + fallback: "post", + options: [ + { id: "visit", label: "一早就到現場關心", outcome: { text: "居民說你來得很快。", effects: [favor(0.01, OLDER)], stamina: -8, news: { title: "{name}一早到地震受損現場關心", tone: "positive" } } }, + { id: "post", label: "發文關心,請大家注意安全", outcome: { text: "得體,但沒什麼印象。", effects: [] } }, + ], + }, + { + id: "supporter_excess", + title: "支持者在網路上罵得太兇", + body: "你的一些支持者在對手的粉絲團洗版,用詞很難聽,被截圖上新聞。", + art: "troll_army", + weight: 0.6, + fallback: "silent", + options: [ + { id: "calm", label: "公開呼籲支持者理性", outcome: { text: "中間選民覺得你有格局。", effects: [swing(0.006), heat(-0.004)] } }, + { id: "silent", label: "不回應", outcome: { text: "對手把截圖貼滿全網。", effects: [swing(-0.006)] } }, + ], + }, + { + id: "flyer_typo", + title: "選舉公報上你的政見印錯了", + body: "選舉公報已經寄到每一戶,你的政見有一個很明顯的錯字,網友在笑。", + art: "print_flyers", + weight: 0.5, + fallback: "ignore", + options: [ + { id: "joke", label: "自嘲拍影片「我們會更細心」", outcome: { text: "大家笑完就忘了,還多了一點好感。", effects: [favor(0.004, YOUNGER)] } }, + { id: "blame", label: "說是印刷廠的錯", outcome: { text: "被批推卸責任。", effects: [swing(-0.004)] } }, + { id: "ignore", label: "不理它", outcome: { text: "梗圖流傳了好幾天。", effects: [] } }, + ], + }, + { + id: "truck_noise", + title: "宣傳車太吵被投訴", + body: "住戶投訴你的宣傳車一大早就在巷子裡放音樂,影響小孩睡覺。", + art: "sound_truck", + weight: 0.6, + fallback: "continue", + options: [ + { id: "adjust", label: "調整路線與時段,公開道歉", outcome: { text: "住戶接受道歉。", effects: [favor(0.004, PARENTS)] } }, + { id: "continue", label: "照原路線跑", outcome: { text: "投訴越來越多,上了地方新聞。", effects: [favor(-0.006, PARENTS)] } }, + ], + }, +]; diff --git a/backend/packages/content/src/finance.ts b/backend/packages/content/src/finance.ts new file mode 100644 index 0000000..e06d567 --- /dev/null +++ b/backend/packages/content/src/finance.ts @@ -0,0 +1,29 @@ +/** + * 歷史劇本的錢從哪裡來(docs/05「價格從哪裡來」)。 + * + * 2022 桃園市長候選人的政治獻金首次申報收支結算,來源:監察院政治獻金公開查閱平臺。 + * 由資料管線產生:election-data donations --election 111年直轄市市長選舉 --area 桃園市 + * → data/build/finance/111年直轄市市長選舉-桃園市.json(內容測試會比對這裡的數字)。 + */ +export const TAOYUAN_2022_FINANCE: Readonly> = { + 張善政: { income: 41_857_762, spending: 46_187_061 }, + 賴香伶: { income: 6_372_697, spending: 6_552_320 }, + 鄭運鵬: { income: 58_260_977, spending: 61_106_707 }, + 鄭寶清: { income: 3_046_781, spending: 3_050_000 }, +}; + +/** 起始資金佔真實收入的比例;其餘要在選戰中自己募 */ +export const STARTING_SHARE = 0.35; + +const toTenThousand = (n: number) => Math.round(n / 10_000) * 10_000; + +/** + * 由真實收入推算:起始資金=收入的 35%;每週募款能力=其餘 65% 平均到每一週。 + * 每週都辦募款餐會加網路小額募款、聲勢普通時,整場募到的錢會接近真實收入。 + */ +export function financeFromIncome(income: number, weeks: number): { startingMoney: number; fundraising: number } { + return { + startingMoney: toTenThousand(income * STARTING_SHARE), + fundraising: toTenThousand((income * (1 - STARTING_SHARE)) / weeks), + }; +} diff --git a/backend/packages/content/src/index.ts b/backend/packages/content/src/index.ts new file mode 100644 index 0000000..e85497d --- /dev/null +++ b/backend/packages/content/src/index.ts @@ -0,0 +1,22 @@ +import type { Content, Scenario } from "@election2026/engine"; +import { ACTIONS } from "./actions.ts"; +import { ENCOUNTERS } from "./encounters.ts"; +import { EVENTS } from "./events.ts"; +import { PRESS } from "./press.ts"; +import { ISSUES } from "./issues.ts"; +import { TAOYUAN_2022_MAYOR } from "./scenarios/taoyuan-2022-mayor.ts"; +import { TAOYUAN_2022_MAYOR_EVEN } from "./scenarios/taoyuan-2022-mayor-even.ts"; + +export { ACTIONS, CAMPAIGN_ACTIONS, EVE_ACTIONS } from "./actions.ts"; +export { ISSUES } from "./issues.ts"; +export { EVENTS } from "./events.ts"; +export { ENCOUNTERS } from "./encounters.ts"; +export { PRESS } from "./press.ts"; +export { TAOYUAN_2022_FINANCE, financeFromIncome } from "./finance.ts"; +export { scenariosFromSpec } from "./local2022.ts"; +export { CUSTOM_ID, CustomCandidateError, withCustomCandidate } from "./custom.ts"; + +export const CONTENT: Content = { actions: ACTIONS, issues: ISSUES, events: EVENTS, encounters: ENCOUNTERS, press: PRESS }; + +export const SCENARIOS: readonly Scenario[] = [TAOYUAN_2022_MAYOR_EVEN, TAOYUAN_2022_MAYOR]; +export { candidateStats, personName } from "./candidates.ts"; diff --git a/backend/packages/content/src/issues.ts b/backend/packages/content/src/issues.ts new file mode 100644 index 0000000..1ca174d --- /dev/null +++ b/backend/packages/content/src/issues.ts @@ -0,0 +1,44 @@ +import type { IssueDef } from "@election2026/engine"; + +/** + * MVP 議題(docs/05)。appeal 是各年齡層在意的程度,初始值依常識設定, + * 之後以 TEDS 與台灣民意基金會的議題調查校正(docs/13 待辦)。 + */ +export const ISSUES: readonly IssueDef[] = [ + { + id: "transport", + name: "交通建設", + description: "捷運綠線、機場捷運延伸、塞車與停車。", + appeal: { "20-29": 0.6, "30-39": 0.7, "40-49": 0.6, "50-64": 0.5, "65+": 0.4 }, + }, + { + id: "housing", + name: "居住正義", + description: "房價、社會住宅、租屋補貼。", + appeal: { "20-29": 0.9, "30-39": 0.8, "40-49": 0.5, "50-64": 0.3, "65+": 0.2 }, + }, + { + id: "elder_care", + name: "長照與醫療", + description: "長照據點、醫療資源、高齡友善。", + appeal: { "20-29": 0.2, "30-39": 0.4, "40-49": 0.7, "50-64": 0.8, "65+": 0.9 }, + }, + { + id: "jobs", + name: "產業與就業", + description: "航空城、產業園區、薪資與工作機會。", + appeal: { "20-29": 0.7, "30-39": 0.7, "40-49": 0.6, "50-64": 0.5, "65+": 0.3 }, + }, + { + id: "childcare", + name: "托育與教育", + description: "公共托育、幼兒園、校園設施。", + appeal: { "20-29": 0.4, "30-39": 0.9, "40-49": 0.6, "50-64": 0.2, "65+": 0.1 }, + }, + { + id: "safety", + name: "治安與防詐", + description: "詐騙、治安、交通安全。", + appeal: { "20-29": 0.3, "30-39": 0.4, "40-49": 0.5, "50-64": 0.7, "65+": 0.8 }, + }, +]; diff --git a/backend/packages/content/src/local2022.ts b/backend/packages/content/src/local2022.ts new file mode 100644 index 0000000..73bc199 --- /dev/null +++ b/backend/packages/content/src/local2022.ts @@ -0,0 +1,269 @@ +import type { Scenario, ScenarioCandidate } from "@election2026/engine"; +import type { LocalCalibration, LocalElectionSpec, PartySlotKey } from "@election2026/protocol"; +import { financeFromIncome } from "./finance.ts"; + +/** + * 管線產生的選舉劇本(2014、2018、2022 縣市長;2020、2024 區域立委;1996 年起歷屆總統): + * 事實(候選人、得票、經費上限、政治獻金)來自管線,能力值依明確的規則推得, + * 不針對個別真人調整(docs/14 政治中立)。 + */ + +const WEEKS = 10; +/** 個人可以自掏腰包的上限:沒有可靠的公開資料,所有人一律相同(遊戲設定) */ +const WEALTH = 5_000_000; +/** 沒有政治獻金資料(或幾乎沒有)的候選人,最少有這些資金可以選 */ +const MIN_START = 300_000; +const MIN_FUNDRAISING = 30_000; + +const PARTY_SLOT: Record = { 民主進步黨: "a", 中國國民黨: "b", 台灣民眾黨: "c" }; + +/** + * 以無黨籍登記、但有政黨公開支持的候選人:選民模型用支持政黨的槽位計算。 + * 每一筆都要有公開可查的依據。 + */ +const ENDORSED: Record = { + 黃珊珊: { slot: "c", note: "無黨籍參選,台灣民眾黨支持。" }, +}; + +/** 桃園四位候選人在歷史劇本已有查證過的簡介 */ +const DESCRIPTIONS: Record = { + 張善政: "前行政院長,中國國民黨提名。", + 賴香伶: "時任不分區立法委員,台灣民眾黨提名。", + 鄭運鵬: "時任立法委員,民主進步黨提名。", + 鄭寶清: "前立法委員,無黨籍參選。", +}; + +const BIG = 10_000_000; + +/** 開局知名度:依選舉層級與政黨,同一套規則套用到所有人 */ +const AWARENESS = { + president: { major: 0.88, c: 0.82, big: 0.5, party: 0.3, independent: 0.3 }, + mayor: { major: 0.62, c: 0.48, big: 0.48, party: 0.3, independent: 0.32 }, + legislator: { major: 0.5, c: 0.4, big: 0.4, party: 0.25, independent: 0.28 }, +} as const; + +function candidateFrom(spec: LocalElectionSpec, c: LocalElectionSpec["candidates"][number], appeal: number): ScenarioCandidate { + const endorsed = spec.kind === "mayor" ? ENDORSED[c.name] : undefined; + const slot = endorsed?.slot ?? (c.party ? (PARTY_SLOT[c.party] ?? "other") : "other"); + const major = slot === "a" || slot === "b"; + const income = c.finance?.income ?? 0; + const big = income >= BIG; + const money = income >= MIN_START ? financeFromIncome(income, WEEKS) : { startingMoney: MIN_START, fundraising: MIN_FUNDRAISING }; + return { + id: `${idPrefix(spec)}-${c.number}`, + name: c.name, + personId: null, + party: c.party, + slot, + number: c.number, + description: + (spec.kind === "mayor" ? DESCRIPTIONS[c.name] : undefined) ?? + endorsed?.note ?? + `${c.party ? `${c.party}提名` : "無黨籍參選"}${c.runningMate ? `,副手${c.runningMate}` : ""}。`, + awareness: AWARENESS[spec.kind][major ? "major" : slot === "c" ? "c" : big ? "big" : c.party ? "party" : "independent"], + eloquence: 55, + strategy: 55, + startingMoney: Math.max(MIN_START, money.startingMoney), + fundraising: Math.max(MIN_FUNDRAISING, money.fundraising), + realFinance: c.finance, + runningMate: c.runningMate ?? null, + wealth: WEALTH, + machine: major ? 0.3 : big ? 0.15 : slot === "c" ? 0.08 : 0.05, + staff: (major ? 4 : slot === "c" || big ? 3 : 2) + (spec.kind === "president" && (major || slot === "c") ? 1 : 0), + appeal, + aiStyle: slot === "b" ? "balanced" : slot === "a" ? "ground" : slot === "c" ? "air" : big ? "ground" : "air", + }; +} + +const money = (n: number) => `${(n / 10_000).toLocaleString()} 萬元`; + +const yearOf = (spec: LocalElectionSpec) => spec.electionDate.slice(0, 4); + +/** 候選人 id 的前綴;2022 縣市長沿用最早的格式(縣市代碼),其他都帶年份 */ +export function idPrefix(spec: LocalElectionSpec): string { + const year = yearOf(spec); + if (spec.kind === "president") return `pres${year}`; + if (spec.kind === "legislator") return `leg${year}-${spec.countyCode}-${spec.districtCode}`; + return year === "2022" ? spec.countyCode : `${year}-${spec.countyCode}`; +} + +/** 劇本 id(不含 -even):local2022-63000、pres2020、leg2024-63000-01 */ +export function scenarioBaseId(spec: LocalElectionSpec): string { + return spec.kind === "mayor" ? `local${yearOf(spec)}-${spec.countyCode}` : idPrefix(spec); +} + +/** 經費上限的人口基準:投票月前第六個月的月底(選罷法施行細則) */ +function capMonth(spec: LocalElectionSpec): string { + const [y, m] = spec.electionDate.split("-").map(Number) as [number, number]; + const months = y * 12 + (m - 1) - 6; + return `${Math.floor(months / 12)} 年 ${(months % 12) + 1} 月底`; +} + +/** 已和中選會公告逐一核對過的經費上限(公告日期、核對了哪些) */ +const SAME_AS_2020 = "同一算法重算 2020 年得到中選會公告的 4 億 3,029.7 萬元"; +/** 1996–2008 年:法條與當年公告都還沒核對,用現行公式推估 */ +const OLD_FORMULA = "依現行公式推估;當年的法定公式與中選會公告數字尚未核對"; +const CAP_VERIFIED: Record = { + "2014-mayor": "六都的上限與中選會 2014 年公告的數字逐一核對一致,其他縣市用同一公式", + "2018-mayor": "與中選會 2018 年 8 月 16 日公告的六都上限逐一核對一致", + "2022-mayor": "與中選會公告的各縣市上限核對一致", + "2012-president": SAME_AS_2020, + "2016-president": SAME_AS_2020, + "2020-president": "與中選會公告的 4 億 3,029.7 萬元一致", + "2024-president": SAME_AS_2020, + "1996-president": OLD_FORMULA, + "2000-president": OLD_FORMULA, + "2004-president": OLD_FORMULA, + "2008-president": OLD_FORMULA, +}; + +/** 人口基準不是「投票月前第六個月底」的特例(戶政司沒有那個月的開放資料) */ +const CAP_MONTH_OVERRIDE: Record = { + "1996-president": "1995 年底(9 月底沒有月報)", +}; + +function capNote(spec: LocalElectionSpec): string { + const pop = spec.capPopulation.toLocaleString(); + const when = CAP_MONTH_OVERRIDE[spec.electionId] ?? capMonth(spec); + const verified = CAP_VERIFIED[spec.electionId]; + const tail = verified ? `;${verified}` : ""; + if (spec.kind === "president") return `經費上限 ${money(spec.spendingCap)}:總統副總統選罷法第 38 條(${when}全國人口 ${pop} 人 × 70% × 20 元+1 億元${tail})。`; + if (spec.kind === "legislator") return `經費上限 ${money(spec.spendingCap)}:選罷法第 41 條(${when}選區人口 ${pop} 人 × 70% × 30 元+1,000 萬元,依法定公式計算,逐區數字待與中選會公告核對)。`; + const fixed = ["63000", "64000", "65000", "66000", "67000", "68000"].includes(spec.countyCode) ? "5,000 萬元" : "3,000 萬元"; + return `經費上限 ${money(spec.spendingCap)}:選罷法第 41 條(${when}${spec.countyName}人口 ${pop} 人 × 70% × 20 元+${fixed}${tail})。`; +} + +/** + * 玩家看到的「上次選舉」:必須早於這場選舉,而且在資料包的歷屆得票裡。 + * 縣市長、總統看上一次總統選舉;立委看上一次縣市長選舉。 + * 1996 年是第一次總統直選,之前沒有總統選舉,改看 1995 年的區域立委(各黨得票加總)。 + */ +function previousElection(spec: LocalElectionSpec): string { + const year = Number(yearOf(spec)); + if (spec.kind === "legislator") return `${year - 2}-mayor`; + if (spec.kind === "president" && year === 1996) return "1995-legislator"; + return year % 4 === 0 ? `${year - 4}-president` : `${year - 2}-president`; +} + +/** 個別選舉的資料說明(管線的特殊處理),照實寫進備註 */ +const DATA_NOTES: Record = { + "2004-president": + "2004 年連戰、宋楚瑜搭檔參選,所以算各地的政黨傾向時,2000 年宋楚瑜(無黨籍)與 2001 年立委親民黨的票,算在國民黨一側。", + "1996-president": "1996 年是第一次總統直選,之前沒有總統選舉;各地的政黨傾向用 1995 年立委選舉各黨的得票推算。", +}; + +/** 2014 年以前的中選會資料用流水號代碼,各里得票是用名稱對到現在的村里(管線 legacy.py) */ +const LEGACY_BEFORE = 2014; +/** 戶政司村里單一年齡人口開放資料的第一年 */ +const VILLAGE_POPULATION_FROM = 2018; + +function notesFor(spec: LocalElectionSpec, even: boolean): string[] { + const year = spec.electionDate.slice(0, 4); + const hasFinance = spec.candidates.some((c) => c.finance); + const money = hasFinance + ? [ + `起始資金與募款能力:依各候選人 ${year} 年的政治獻金收入(監察院首次申報)推算。起始資金是收入的 35%,其餘 65% 要在選戰中自己募;沒有申報資料的候選人用最低設定。`, + "政治獻金只記錄捐款和用捐款付的支出,政黨直接付的廣告等不在內,真實花費可能更多。", + ] + : [`監察院政治獻金公開平臺上沒有 ${year} 年這場選舉的候選人申報資料,所有候選人一律用最低的起始資金與募款能力(遊戲設定,不是真實數字)。`]; + const legacy = + Number(year) < LEGACY_BEFORE + ? [ + `${year} 年的中選會資料用自己的流水號代碼,各里得票依縣市、鄉鎮、村里名稱對到現在的村里;後來合併或改名、對不到的里,票數只算進縣市總數。地圖一個縣市一區,開票對照以縣市為準。`, + ] + : []; + return [ + ...(even ? ["這是假設情境:調整候選人的個人魅力,讓前兩名在 AI 對打下平均打平,結果不會和真實開票一樣。"] : []), + capNote(spec), + ...money, + ...legacy, + ...(DATA_NOTES[spec.electionId] ? [DATA_NOTES[spec.electionId]!] : []), + `得票、投票率、各區人口是中選會與內政部的真實資料。個人魅力、投票率倍率由 ${year} 年真實開票校準。`, + ...(Number(year) < VILLAGE_POPULATION_FROM + ? ["戶政司的村里年齡人口 2018 年才開放,各里的人口與年齡結構用的是現在的戶籍資料;各里選舉人數取自這場選舉之前最近一次的開票紀錄。"] + : []), + "知名度、口才、幕僚人數、個人財力(自掏腰包上限 500 萬元)依政黨與募款規模一律套用同一套規則,是遊戲設定,不代表對真人的評價。", + ]; +} + +const SOURCES = [ + { label: "中選會選舉資料庫", url: "https://db.cec.gov.tw/" }, + { label: "監察院政治獻金公開查閱平臺", url: "https://ardata.cy.gov.tw/" }, +]; +/** 2016 年以前的經費上限人口:戶政司的縣市人口統計(村里人口開放資料 2018 年才開始) */ +const RIS_STATS = { label: "內政部戶政司 人口統計資料(縣市人口)", url: "https://www.ris.gov.tw/app/portal/346" }; +const EXTRA_SOURCES: Record = { + "2014-mayor": [RIS_STATS], + "2016-president": [RIS_STATS], + "2012-president": [RIS_STATS], + "2008-president": [RIS_STATS], + "2004-president": [RIS_STATS], + "2000-president": [RIS_STATS], + "1996-president": [RIS_STATS], + "2022-mayor": [{ label: "中央社:2022 地方首長競選經費最高金額出爐", url: "https://www.cna.com.tw/news/aipl/202207150284.aspx" }], + "2018-mayor": [ + { + label: "中選會 107 年 8 月 16 日公告(含競選經費最高金額)", + url: "https://clarify.cec.gov.tw/upload/file/2018-08-23/e4220a05-4ac1-4498-8dfd-ef2b7ae91aa7/bad86c809ff1fb3589765c2d1d48bd10.pdf", + }, + ], +}; + +/** 立委選區涵蓋的鄉鎮市區:「北投區、士林區(部分)」 */ +export function districtScope(spec: LocalElectionSpec): string { + return (spec.towns ?? []).map((t) => `${t.name}${t.partial ? "(部分)" : ""}`).join("、"); +} + +function title(spec: LocalElectionSpec): string { + const year = yearOf(spec); + if (spec.kind === "president") return `${year} 總統大選`; + if (spec.kind === "legislator") return `${year} 立委 ${spec.areaName}`; + return `${year} ${spec.countyName}${spec.office}`; +} + +/** 一場選舉產生兩個劇本:歷史重演、勢均力敵(有校準結果時) */ +export function scenariosFromSpec(spec: LocalElectionSpec, calibration?: LocalCalibration["counties"][string]): Scenario[] { + const prefix = idPrefix(spec); + const ids = new Map(spec.candidates.map((c) => [`#${c.number}`, `${prefix}-${c.number}`])); + const place = spec.kind === "mayor" ? `${spec.countyName}${spec.office}` : spec.kind === "president" ? "總統" : `${spec.areaName}立委`; + const year = spec.electionDate.slice(0, 4); + const byVillage = Object.fromEntries( + Object.entries(spec.byVillage).map(([code, v]) => [code, Object.fromEntries(Object.entries(v.votes).map(([n, votes]) => [ids.get(n)!, votes]))]), + ); + const base = (even: boolean): Scenario => { + const appeal = (even ? calibration?.evenAppeal : calibration?.appeal) ?? {}; + return { + id: `${scenarioBaseId(spec)}${even ? "-even" : ""}`, + name: `${title(spec)}:${even ? "勢均力敵" : "歷史重演"}`, + description: even + ? `假設情境:資料、候選人、資金都和 ${year} 年相同,只把前兩名的聲勢調成不分上下。選戰打得好就能贏。` + : `照 ${year} 年真實情勢重演${place}選舉,最後和真實開票結果對照。`, + packId: spec.packId, + villages: spec.kind === "legislator" ? Object.keys(spec.byVillage) : undefined, + weeks: WEEKS, + electionDate: spec.electionDate, + region: { + countyCode: spec.countyCode, + countyName: spec.countyName, + office: spec.office, + kind: spec.kind, + area: spec.areaName, + regionLevel: spec.regionLevel, + scope: districtScope(spec), + }, + hypothetical: even, + blackoutFromWeek: 9, + publicPollWeeks: [2, 4, 6, 8], + spendingCap: spec.spendingCap, + mood: { a: 0, b: 0, c: 0, other: 0 }, + publicHistoryElection: previousElection(spec), + bountyMultiplier: 1, + turnoutScale: calibration?.turnoutScale ?? 0.78, + notes: notesFor(spec, even), + sources: [...SOURCES, ...(EXTRA_SOURCES[spec.electionId] ?? [])], + actual: { electionId: spec.electionId, byVillage }, + candidates: spec.candidates.map((c) => candidateFrom(spec, c, appeal[String(c.number)] ?? 0)), + }; + }; + return calibration?.evenAppeal ? [base(true), base(false)] : [base(false)]; +} diff --git a/backend/packages/content/src/press.ts b/backend/packages/content/src/press.ts new file mode 100644 index 0000000..af56deb --- /dev/null +++ b/backend/packages/content/src/press.ts @@ -0,0 +1,285 @@ +import type { ActionEffect, PressDef } from "@election2026/engine"; + +type AgeBand = NonNullable[number]; + +/** + * 記者堵麥的提問(docs/07)。觸發條件在引擎(press.ts),這裡只寫題目與選項。 + * 幅度比照行動:候選人本人掃街一次,一區好感約 +0.008;全市的效果要更小。 + * 新聞標題只描述玩家選的動作,不寫成真人的引述;對手只是被點名,不指控犯罪(docs/14)。 + */ + +const OLDER: readonly AgeBand[] = ["50-64", "65+"]; +const YOUNG: readonly AgeBand[] = ["20-29", "30-39"]; +const MIDDLE: readonly AgeBand[] = ["30-39", "40-49", "50-64"]; + +const favor = (base: number, ages?: readonly AgeBand[]): ActionEffect => ({ stat: "favor", base, scope: "city", ...(ages ? { ages } : {}) }); +const aware = (base: number, ages?: readonly AgeBand[]): ActionEffect => ({ stat: "awareness", base, scope: "city", ...(ages ? { ages } : {}) }); +const heat = (base: number): ActionEffect => ({ stat: "heat", base, scope: "city", supportersOnly: true }); +const hurt = (base: number): ActionEffect => ({ stat: "favor", base: -Math.abs(base), scope: "city", onOpponent: true }); + +export const PRESS: readonly PressDef[] = [ + // ── 被攻擊 ── + { + id: "attacked_presser", + trigger: "attacked", + question: "{opponent}陣營這週猛烈攻擊你,你要怎麼回應?", + fallback: "ignore", + options: [ + { + id: "clarify", + label: "開記者會逐條澄清", + hint: "花 5 萬、體力 −10;挽回中間選民", + outcome: { text: "你把指控一條一條講清楚,中間選民比較能接受。", money: -50_000, stamina: -10, effects: [favor(0.008, MIDDLE)], news: { title: "{name}開記者會逐條回應{opponent}陣營指控", tone: "neutral" } }, + }, + { + id: "counter", + label: "強力反擊", + hint: "打擊對手、支持者熱血;三成機率被批互咬", + outcome: { text: "" }, + roll: { + chance: 0.7, + success: { text: "反擊打中要害,支持者大聲叫好。", effects: [hurt(0.01), heat(0.01)], momentum: 0.02, news: { title: "{name}強力反擊{opponent},支持者叫好", tone: "positive" } }, + failure: { text: "兩邊你來我往,選民看了很厭煩。", effects: [favor(-0.006), hurt(0.004)], news: { title: "{name}與{opponent}隔空互嗆,選民搖頭", tone: "negative" } }, + }, + }, + { + id: "ignore", + label: "冷處理,不回應", + hint: "不花資源;一半機率風波自己平息", + outcome: { text: "" }, + roll: { + chance: 0.5, + success: { text: "風波很快被其他新聞蓋過去。" }, + failure: { text: "沉默被解讀成心虛,話題繼續延燒。", effects: [favor(-0.006)] }, + }, + }, + ], + }, + { + id: "attacked_video", + trigger: "attacked", + question: "網路上流傳批評你的影片,有人說是{opponent}陣營放的,你怎麼看?", + fallback: "ignore", + options: [ + { + id: "selfie", + label: "拍一支自嘲影片回應", + hint: "體力 −6;四成機率爆紅,年輕人買單", + outcome: { text: "", stamina: -6 }, + roll: { + chance: 0.4, + success: { text: "自嘲影片比原本的攻擊還紅,年輕人覺得你很有梗。", effects: [aware(0.02, YOUNG), favor(0.008, YOUNG)], momentum: 0.02, news: { title: "{name}拍影片自嘲回應網路攻擊,網友大讚有梗", tone: "positive" } }, + failure: { text: "影片沒什麼人看,但也沒有扣分。" }, + }, + }, + { + id: "takedown", + label: "要求平台下架、存證", + hint: "花 10 萬;止血,但有人批評小題大作", + outcome: { text: "影片被下架,傳播速度變慢,也有人說你玻璃心。", money: -100_000, effects: [favor(0.004, OLDER), favor(-0.003, YOUNG)] }, + }, + { id: "ignore", label: "不理它", hint: "不花資源;影片繼續流傳", outcome: { text: "影片繼續流傳,好在看的人不多。", effects: [favor(-0.003)] } }, + ], + }, + // ── 自己的負面新聞 ── + { + id: "own_scandal_presser", + trigger: "own_scandal", + question: "關於這則新聞,選民在等你的說法。你要怎麼處理?", + fallback: "silent", + options: [ + { + id: "apologize", + label: "公開道歉、承擔責任", + hint: "聲勢小跌;止血,長輩比較能接受", + outcome: { text: "你誠懇道歉,風波慢慢平息。", momentum: -0.01, effects: [favor(0.007, OLDER), favor(0.004)], news: { title: "{name}公開道歉,表示會檢討改進", tone: "neutral" } }, + }, + { + id: "deny", + label: "全盤否認", + hint: "成功就沒事;失敗會被追打得更慘", + outcome: { text: "" }, + roll: { + chance: 0.55, + success: { text: "你的說法站得住腳,媒體轉移焦點。", momentum: 0.01 }, + failure: { text: "否認之後又被翻出更多資料,越描越黑。", effects: [favor(-0.012)], momentum: -0.02, news: { title: "{name}否認後再被翻出新資料,越描越黑", tone: "negative" } }, + }, + }, + { + id: "pivot", + label: "轉移焦點,大談政見", + hint: "體力 −8;中年選民加分,風波還在", + outcome: { text: "你把話題拉回政見,有人買單,也有人說你避重就輕。", stamina: -8, effects: [favor(0.005, MIDDLE), favor(-0.003)] }, + }, + { id: "silent", label: "不回應", hint: "不花資源;負面印象留著", outcome: { text: "你沒有回應,負面印象慢慢累積。", effects: [favor(-0.006)] } }, + ], + }, + // ── 對手出包 ── + { + id: "opp_scandal_presser", + trigger: "opp_scandal", + question: "{opponent}這週負面新聞纏身,你要趁機追打嗎?", + fallback: "no_comment", + options: [ + { + id: "pile_on", + label: "乘勝追擊", + hint: "打擊對手、拉抬聲勢;三成機率被批消費對手", + outcome: { text: "" }, + roll: { + chance: 0.7, + success: { text: "你的追問讓對手更難招架。", effects: [hurt(0.012)], momentum: 0.02, opponentMomentum: -0.02, news: { title: "{name}要求{opponent}給選民一個交代", tone: "neutral" } }, + failure: { text: "選民覺得你在消費對手,觀感變差。", effects: [favor(-0.008)], news: { title: "{name}追打{opponent},被批選舉只會攻擊", tone: "negative" } }, + }, + }, + { + id: "high_road", + label: "保持風度,回到政策", + hint: "中間選民與長輩加分", + outcome: { text: "你不跟著攻擊,中間選民覺得你有風度。", effects: [favor(0.006, MIDDLE), favor(0.004, OLDER)], news: { title: "{name}不跟進攻擊,呼籲選戰回歸政策", tone: "positive" } }, + }, + { id: "no_comment", label: "不予置評", hint: "不花資源,沒有效果", outcome: { text: "你沒有表態,讓新聞自己發酵。" } }, + ], + }, + // ── 自己的好消息 ── + { + id: "my_win_next", + trigger: "my_win", + question: "這週你聲勢看漲,接下來打算怎麼做?", + fallback: "humble", + options: [ + { + id: "amplify", + label: "加碼買廣告放大聲量", + hint: "花 30 萬;全區知名度、聲勢上升", + outcome: { text: "趁熱打鐵,廣告讓更多人認識你。", money: -300_000, effects: [aware(0.02)], momentum: 0.02 }, + }, + { + id: "fundraise", + label: "趁勢發起小額募款", + hint: "八成機率募到 20–40 萬", + outcome: { text: "" }, + roll: { + chance: 0.8, + success: { text: "支持者踴躍小額捐款。", money: 300_000, news: { title: "{name}小額募款湧入,支持者踴躍響應", tone: "positive" } }, + failure: { text: "募款反應普通,只募到一點點。", money: 60_000 }, + }, + }, + { id: "humble", label: "低調感謝支持", hint: "長輩好感小升", outcome: { text: "你謙虛的態度讓長輩很有好感。", effects: [favor(0.004, OLDER)] } }, + ], + }, + // ── 對手造勢成功 ── + { + id: "rival_win_response", + trigger: "rival_win", + question: "{opponent}這週聲勢很旺,你會擔心嗎?", + fallback: "own_pace", + options: [ + { + id: "mock", + label: "酸對方人數灌水", + hint: "一半機率削弱對手聲勢;失敗被批酸民", + outcome: { text: "" }, + roll: { + chance: 0.5, + success: { text: "媒體開始質疑對方的人數,對方聲勢受挫。", opponentMomentum: -0.025 }, + failure: { text: "被網友批評酸言酸語,年輕人反感。", effects: [favor(-0.006, YOUNG)], news: { title: "{name}質疑{opponent}造勢人數,被網友批酸", tone: "negative" } }, + }, + }, + { + id: "bigger", + label: "宣布要辦更大的造勢", + hint: "花 20 萬;聲勢上升、支持者動起來", + outcome: { text: "支持者被點燃,準備下一場大活動。", money: -200_000, momentum: 0.015, effects: [heat(0.01)], news: { title: "{name}宣布將舉辦大型造勢,與{opponent}互別苗頭", tone: "neutral" } }, + }, + { id: "own_pace", label: "我們走自己的路", hint: "支持者投票意願小升", outcome: { text: "你穩住陣腳,支持者覺得安心。", effects: [heat(0.006)] } }, + ], + }, + // ── 民調落後 ── + { + id: "poll_behind_chase", + trigger: "poll_behind", + question: "最新民調你落後{leader},要怎麼追?", + fallback: "doubt_poll", + options: [ + { + id: "tactical", + label: "喊話棄保,集中選票", + hint: "一半機率聲勢大漲;失敗被批情勒", + outcome: { text: "" }, + roll: { + chance: 0.5, + success: { text: "棄保喊話奏效,游離選民開始靠過來。", momentum: 0.03, news: { title: "{name}喊話棄保,呼籲集中選票", tone: "neutral" } }, + failure: { text: "喊棄保被其他陣營批評情緒勒索。", effects: [favor(-0.006)], news: { title: "{name}喊棄保,被批情緒勒索", tone: "negative" } }, + }, + }, + { + id: "underdog", + label: "打悲情牌,請支持者出來", + hint: "支持者投票意願上升", + outcome: { text: "支持者被你的處境打動,更想去投票。", effects: [heat(0.015)], momentum: 0.01 }, + }, + { id: "doubt_poll", label: "民調不準,看真正的民意", hint: "支持者投票意願小升", outcome: { text: "支持者相信民調不準,士氣還在。", effects: [heat(0.004)] } }, + ], + }, + // ── 民調領先 ── + { + id: "poll_lead_guard", + trigger: "poll_lead", + question: "最新民調你領先,會不會輕敵?", + fallback: "humble", + options: [ + { + id: "no_slack", + label: "繃緊神經,一票都不能少", + hint: "體力 −5;支持者投票意願上升", + outcome: { text: "你提醒支持者不能鬆懈。", stamina: -5, effects: [heat(0.012)] }, + }, + { + id: "declare", + label: "宣稱勝選在望", + hint: "聲勢上升;三成機率支持者以為穩了不去投", + outcome: { text: "", momentum: 0.02 }, + roll: { + chance: 0.7, + success: { text: "勝選氣氛讓更多人想站在你這邊。", momentum: 0.01 }, + failure: { text: "支持者以為穩贏,投票意願下降。", effects: [heat(-0.012)] }, + }, + }, + { id: "humble", label: "謙虛,民調只是參考", hint: "中間選民好感小升", outcome: { text: "你的謙虛讓中間選民有好感。", effects: [favor(0.004, MIDDLE)] } }, + ], + }, + // ── 平靜的一週 ── + { + id: "quiet_message", + trigger: "quiet", + question: "選戰剩 {weeksLeft} 週,你最想跟選民說什麼?", + fallback: "economy", + options: [ + { id: "economy", label: "拚經濟、顧荷包", hint: "中年選民好感上升", outcome: { text: "上班族覺得你懂他們的壓力。", effects: [favor(0.005, MIDDLE)] } }, + { id: "youth", label: "給年輕人機會", hint: "年輕人好感上升,長輩略降", outcome: { text: "年輕人覺得被看見,有些長輩不以為然。", effects: [favor(0.007, YOUNG), favor(-0.002, OLDER)] } }, + { id: "care", label: "長照與醫療", hint: "長輩好感上升,年輕人略降", outcome: { text: "長輩與照顧家人的人很有感。", effects: [favor(0.007, OLDER), favor(-0.002, YOUNG)] } }, + ], + }, + { + id: "quiet_trivia", + trigger: "quiet", + question: "記者在行程空檔突然問你:「最近一次搭公車是什麼時候?」", + fallback: "honest", + options: [ + { id: "honest", label: "老實說好久沒搭了", hint: "誠實加分,但有點距離感", outcome: { text: "大家覺得你誠實,也覺得你有點不食人間煙火。", effects: [favor(0.002, OLDER), favor(-0.002, YOUNG)] } }, + { + id: "card", + label: "掏出悠遊卡證明", + hint: "四成機率被拍成梗圖爆紅", + outcome: { text: "" }, + roll: { + chance: 0.4, + success: { text: "你掏卡的畫面被做成梗圖,網路一片好評。", effects: [aware(0.015, YOUNG), favor(0.004, YOUNG)], news: { title: "{name}當場掏出悠遊卡,網友笑稱最強回應", tone: "positive" } }, + failure: { text: "卡片餘額被拍到只剩個位數,網友笑翻但沒加分。" }, + }, + }, + { id: "dodge", label: "把話題拉回政見", hint: "沒有效果", outcome: { text: "記者覺得你很無趣。" } }, + ], + }, +]; diff --git a/backend/packages/content/src/scenarios/taoyuan-2022-mayor-even.ts b/backend/packages/content/src/scenarios/taoyuan-2022-mayor-even.ts new file mode 100644 index 0000000..8cea8e4 --- /dev/null +++ b/backend/packages/content/src/scenarios/taoyuan-2022-mayor-even.ts @@ -0,0 +1,20 @@ +import type { Scenario } from "@election2026/engine"; +import { TAOYUAN_2022_MAYOR } from "./taoyuan-2022-mayor.ts"; + +/** + * 假設劇本:2022 桃園市長,但全國風向藍綠打平(M1 平衡報告的建議)。 + * 資料、候選人、資金都和歷史劇本相同,只換風向,讓每位候選人都有機會靠策略贏。 + * 風向由 apps/sim even.ts 校準:AI 對打下前兩名平均打平,第三、四名維持真實得票率。 + */ +export const TAOYUAN_2022_MAYOR_EVEN: Scenario = { + ...TAOYUAN_2022_MAYOR, + id: "taoyuan-2022-mayor-even", + name: "2022 桃園市長:勢均力敵", + hypothetical: true, + description: "假設情境:資料、候選人、資金都和 2022 年相同,只把全國風向調成藍綠不分上下。選戰打得好就能贏。", + mood: { a: 0.703, b: 0.875, c: -0.961, other: -0.617 }, + notes: [ + "這是假設情境:全國風向調成藍綠打平,所以結果不會和真實開票一樣。", + ...TAOYUAN_2022_MAYOR.notes, + ], +}; diff --git a/backend/packages/content/src/scenarios/taoyuan-2022-mayor.ts b/backend/packages/content/src/scenarios/taoyuan-2022-mayor.ts new file mode 100644 index 0000000..240719d --- /dev/null +++ b/backend/packages/content/src/scenarios/taoyuan-2022-mayor.ts @@ -0,0 +1,139 @@ +import type { Scenario, ScenarioCandidate } from "@election2026/engine"; +import { TAOYUAN_2022_FINANCE, financeFromIncome } from "../finance.ts"; + +/** + * 歷史劇本:2022 桃園市長選舉重演(M1 回測用,docs/13)。 + * 資料包只用 2022-11-26 以前的選舉估算政黨傾向,玩家看到的「上一次選舉」是 2020 總統大選,不會先看到答案。 + * 號次與政黨取自中選會 votedata(2022-111年地方公職人員選舉/C1)。 + * 候選人能力值是遊戲用的初始設定,不是對真人的評價;AI 評分完成後改用評分結果(docs/16)。 + */ + +const WEEKS = 10; + +/** + * 中選會公告的競選經費最高金額:選罷法第 41 條,人口總數 × 70% × 20 元+直轄市長固定金額 5,000 萬元。 + * 人口以 2022-05-31 桃園市 2,262,765 人計算。 + */ +const SPENDING_CAP = 81_679_000; + +/** 錢的設定一律由真實政治獻金收入推算 */ +function money(name: string): Pick { + const real = TAOYUAN_2022_FINANCE[name]; + if (!real) throw new Error(`沒有 ${name} 的政治獻金資料`); + return { ...financeFromIncome(real.income, WEEKS), realFinance: real }; +} + +/** 個人可以自掏腰包的上限:沒有可靠的公開資料,四人一律相同(遊戲設定) */ +const WEALTH = 5_000_000; + +export const TAOYUAN_2022_MAYOR: Scenario = { + id: "taoyuan-2022-mayor", + name: "2022 桃園市長:歷史重演", + description: "照 2022 年真實的全國風向重演。真實差距約 12 個百分點,扮演張善政以外的候選人非常困難;最後和真實開票結果對照。", + packId: "68000-before-2022-11-26", + weeks: WEEKS, + electionDate: "2022-11-26", + region: { countyCode: "68000", countyName: "桃園市", office: "市長", kind: "mayor" }, + blackoutFromWeek: 9, + publicPollWeeks: [2, 4, 6, 8], + spendingCap: SPENDING_CAP, + // 全國風向:apps/sim backtest 校準 12 輪的結果(2026-10-25,加入幕僚與真實資金之後)。只有全市總數拿來校準,各區分布是驗證用 + mood: { a: 0.363, b: 1.184, c: -0.934, other: -0.613 }, + publicHistoryElection: "2020-president", + bountyMultiplier: 1, + notes: [ + "經費上限 8,167.9 萬元:中選會依選罷法第 41 條公告(2022 年 5 月底桃園市人口 2,262,765 人 × 70% × 20 元+5,000 萬元)。", + "起始資金與募款能力:依四位候選人 2022 年的政治獻金收入(監察院首次申報)推算。起始資金是收入的 35%,其餘 65% 要在選戰中自己募。", + "政治獻金只記錄捐款和用捐款付的支出,政黨直接付的廣告等不在內,真實花費可能更多。", + "行動的價格參考真實支出科目:宣傳、集會、競選辦事處、人事、宣傳車。", + "得票、投票率、各區人口是中選會與內政部的真實資料。", + "知名度、口才、幕僚人數、個人財力(自掏腰包上限 500 萬元)是遊戲設定,不代表對真人的評價。", + ], + sources: [ + { label: "監察院政治獻金公開查閱平臺", url: "https://ardata.cy.gov.tw/" }, + { label: "中選會:111 年直轄市長、縣(市)長選舉候選人競選經費最高金額", url: "https://web.cec.gov.tw/central/article/35487" }, + { label: "中央社:2022 地方首長競選經費最高金額出爐", url: "https://www.cna.com.tw/news/aipl/202207150284.aspx" }, + { label: "中選會選舉資料庫", url: "https://db.cec.gov.tw/" }, + ], + // 投票率倍率:回測校準(2020 總統大選的投票率 → 2022 地方選舉;真實 59.5%) + turnoutScale: 0.778, + actual: { + electionId: "2022-mayor", + partyToCandidate: { + 中國國民黨: "chang-san-cheng", + 台灣民眾黨: "lai-hsiang-ling", + 民主進步黨: "cheng-yun-peng", + 無黨籍: "cheng-pao-ching", + }, + }, + candidates: [ + { + id: "chang-san-cheng", + name: "張善政", + personId: "Q10294207", + party: "中國國民黨", + slot: "b", + number: 1, + description: "前行政院長,中國國民黨提名。", + awareness: 0.72, + eloquence: 58, + strategy: 62, + ...money("張善政"), + wealth: WEALTH, + machine: 0.3, + staff: 4, + aiStyle: "balanced", + }, + { + id: "lai-hsiang-ling", + name: "賴香伶", + personId: null, + party: "台灣民眾黨", + slot: "c", + number: 2, + description: "時任不分區立法委員,台灣民眾黨提名。", + awareness: 0.42, + eloquence: 60, + strategy: 52, + ...money("賴香伶"), + wealth: WEALTH, + machine: 0.05, + staff: 3, + aiStyle: "air", + }, + { + id: "cheng-yun-peng", + name: "鄭運鵬", + personId: null, + party: "民主進步黨", + slot: "a", + number: 3, + description: "時任立法委員,民主進步黨提名。", + awareness: 0.6, + eloquence: 62, + strategy: 55, + ...money("鄭運鵬"), + wealth: WEALTH, + machine: 0.3, + staff: 4, + aiStyle: "ground", + }, + { + id: "cheng-pao-ching", + name: "鄭寶清", + personId: null, + party: null, + slot: "other", + number: 4, + description: "前立法委員,無黨籍參選。", + awareness: 0.4, + eloquence: 50, + strategy: 48, + ...money("鄭寶清"), + wealth: WEALTH, + machine: 0.1, + staff: 2, + aiStyle: "ground", + }, + ], +}; diff --git a/backend/packages/content/test/content.test.ts b/backend/packages/content/test/content.test.ts new file mode 100644 index 0000000..dc0af21 --- /dev/null +++ b/backend/packages/content/test/content.test.ts @@ -0,0 +1,181 @@ +import { existsSync, readFileSync } from "node:fs"; +import { actionInfo, STAFF_ROLES } from "@election2026/engine"; +import { ActionInfo } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { TAOYUAN_2022_FINANCE, financeFromIncome } from "../src/finance.ts"; +import { ACTIONS, ENCOUNTERS, EVENTS, ISSUES, SCENARIOS } from "../src/index.ts"; + +describe("行動目錄", () => { + it("每個行動都符合協定", () => { + for (const a of ACTIONS) expect(ActionInfo.safeParse(actionInfo(a)).success, a.id).toBe(true); + }); + + it("幕僚的專長牌都存在、幕僚能做、是競選期間的牌", () => { + const byId = new Map(ACTIONS.map((a) => [a.id, a])); + for (const role of STAFF_ROLES) { + for (const id of role.deck) { + const a = byId.get(id); + expect(a, `${role.name}:${id}`).toBeDefined(); + expect(a!.actors, `${role.name}:${id}`).toContain("team"); + expect(a!.phase, `${role.name}:${id}`).toBe("campaign"); + } + } + }); + + it("id 不重複", () => { + expect(new Set(ACTIONS.map((a) => a.id)).size).toBe(ACTIONS.length); + }); + + it("規模的預設值落在範圍內、對齊級距", () => { + for (const a of ACTIONS.filter((x) => x.amount)) { + const { min, max, step, default: d } = a.amount!; + expect(min <= d && d <= max, a.id).toBe(true); + expect((d - min) % step, a.id).toBe(0); + expect((max - min) % step, a.id).toBe(0); + } + }); + + it("黑暗面在午夜偷偷做;公開演出的黑暗面(苦肉計)一定留下祕密紀錄;午夜只能做祕密行動", () => { + for (const a of ACTIONS) { + if (a.category === "dark" && a.visibility === "secret") expect(a.slots, a.id).toEqual(["midnight"]); + if (a.category === "dark" && a.visibility !== "secret") expect(a.secret, a.id).toBeDefined(); + if (a.slots.includes("midnight")) expect(a.visibility, a.id).toBe("secret"); + } + }); + + it("新行動:id 不重複、擲骰機率合理、要指定對手的行動都有特殊處理或對手效果", () => { + const ids = ACTIONS.map((a) => a.id); + expect(new Set(ids).size).toBe(ids.length); + expect(ACTIONS.length).toBeGreaterThanOrEqual(75); + for (const a of ACTIONS) { + if (a.gamble) expect(a.gamble.chance, a.id).toBeGreaterThan(0), expect(a.gamble.chance, a.id).toBeLessThan(1); + if (a.target === "opponent") { + const hitsOpponent = [a.effects, a.outcome?.effects, a.gamble?.success.effects].some((list) => list?.some((e) => e.onOpponent)); + expect(a.special !== undefined || hitsOpponent, a.id).toBe(true); + } + } + }); + + it("兩個時段的行動不能排在每段的第一個時段", () => { + for (const a of ACTIONS.filter((x) => x.duration === 2)) { + expect(a.slots.some((s) => s === "weekdayMorning" || s === "weekendMorning" || s === "midnight"), a.id).toBe(false); + } + }); + + it("AI 用到的行動都存在,而且由正確的角色執行", () => { + const source = readFileSync(new URL("../../engine/src/ai.ts", import.meta.url), "utf-8"); + const byCandidate = [...source.matchAll(/add\(p, CANDIDATE, (?:style === "ground" \? "\w+" : )?"(\w+)"/g)].map((m) => ["candidate", m[1]]); + // 團隊事務寫成 addTeam(p, staff, "x") 或 team("x") + const byTeam = [...source.matchAll(/(?:addTeam\(p, staff, |\bteam\()"(\w+)"/g)].map((m) => ["team", m[1]]); + const ground = source.slice(source.indexOf("const STAFF_GROUND"), source.indexOf("};", source.indexOf("const STAFF_GROUND"))); + const byStaff = [...ground.matchAll(/"(\w+)"/g)].map((m) => ["team", m[1]]); + const used = [...byCandidate, ...byTeam, ...byStaff]; + expect(byCandidate.length).toBeGreaterThan(8); + expect(byTeam.length).toBeGreaterThan(10); + expect(byStaff.length).toBeGreaterThan(5); + for (const [actor, id] of used) { + const a = ACTIONS.find((x) => x.id === id); + expect(a, id).toBeDefined(); + expect(a!.actors, id).toContain(actor); + } + }); +}); + +describe("歷史劇本的錢", () => { + it("和資料管線產生的政治獻金資料一致", () => { + const file = new URL("../../../data/build/finance/111年直轄市市長選舉-桃園市.json", import.meta.url); + if (!existsSync(file)) return; // 資料是管線產物,沒有建置時略過 + const built = JSON.parse(readFileSync(file, "utf-8")) as { candidates: { name: string; income: number; spending: number }[] }; + for (const [name, real] of Object.entries(TAOYUAN_2022_FINANCE)) { + const row = built.candidates.find((c) => c.name === name); + expect(row, name).toBeDefined(); + expect({ income: row!.income, spending: row!.spending }, name).toEqual(real); + } + }); + + it("起始資金加上十週的募款能力等於真實收入", () => { + for (const real of Object.values(TAOYUAN_2022_FINANCE)) { + const f = financeFromIncome(real.income, 10); + expect(Math.abs(f.startingMoney + f.fundraising * 10 - real.income)).toBeLessThan(60_000); + } + }); + + it("劇本的錢都由真實資料推算,經費上限是中選會公告的數字", () => { + const s = SCENARIOS.find((x) => x.id === "taoyuan-2022-mayor")!; + expect(s.spendingCap).toBe(81_679_000); + for (const c of s.candidates) { + expect(c.realFinance, c.name).toEqual(TAOYUAN_2022_FINANCE[c.name]); + expect(c.startingMoney).toBe(financeFromIncome(c.realFinance!.income, s.weeks).startingMoney); + expect(c.realFinance!.spending).toBeLessThanOrEqual(s.spendingCap); + } + }); +}); + +describe("議題", () => { + it("id 不重複,在意程度介於 0 到 1", () => { + expect(new Set(ISSUES.map((i) => i.id)).size).toBe(ISSUES.length); + for (const i of ISSUES) for (const v of Object.values(i.appeal)) expect(v >= 0 && v <= 1).toBe(true); + }); +}); + +describe("劇本", () => { + it("候選人 id 與號次不重複,真實結果對照到存在的候選人", () => { + for (const s of SCENARIOS) { + const ids = s.candidates.map((c) => c.id); + expect(new Set(ids).size, s.id).toBe(ids.length); + expect(new Set(s.candidates.map((c) => c.number)).size, s.id).toBe(ids.length); + for (const id of Object.values(s.actual?.partyToCandidate ?? {})) expect(ids, s.id).toContain(id); + expect(s.blackoutFromWeek).toBeLessThanOrEqual(s.weeks); + } + }); + + it("真實人物不會被設定成會買票、放網軍的 AI(docs/14)", () => { + for (const s of SCENARIOS) { + for (const c of s.candidates) { + if (c.personId !== null || s.actual !== null) expect(c.aiStyle, `${s.id} ${c.name}`).not.toBe("dirty"); + } + } + }); +}); + +describe("表態事件", () => { + it("格式正確:id 不重複、預設選項存在、至少兩個選項、幅度有上限", () => { + const ids = new Set(); + for (const e of EVENTS) { + expect(ids.has(e.id), e.id).toBe(false); + ids.add(e.id); + expect(e.options.length, e.id).toBeGreaterThanOrEqual(2); + expect(e.options.some((o) => o.id === e.fallback), e.id).toBe(true); + const outcomes = e.options.flatMap((o) => [o.outcome, ...(o.roll ? [o.roll.success, o.roll.failure] : [])]); + for (const out of outcomes) { + for (const f of out.effects ?? []) expect(Math.abs(f.base), e.id).toBeLessThanOrEqual(0.03); + expect(Math.abs(out.momentum ?? 0), e.id).toBeLessThanOrEqual(0.06); + } + // 擲骰的選項成功、失敗都要有文字 + for (const o of e.options) if (o.roll) expect(o.roll.success.text && o.roll.failure.text, `${e.id}/${o.id}`).toBeTruthy(); + } + }); + + it("不寫真實人物:事件文字裡沒有任何劇本候選人的名字", () => { + const names = SCENARIOS.flatMap((s) => s.candidates.map((c) => c.name)); + const text = JSON.stringify(EVENTS); + for (const n of names) expect(text.includes(n), n).toBe(false); + }); +}); + +describe("拜票副本", () => { + it("遭遇都掛在存在的行動上,分數在 -2 到 +2,每個行動至少有三個遭遇可抽", () => { + const ids = new Set(ACTIONS.map((a) => a.id)); + const seen = new Set(); + for (const e of ENCOUNTERS) { + expect(seen.has(e.id), e.id).toBe(false); + seen.add(e.id); + for (const a of e.activities) expect(a === "*" || ids.has(a), `${e.id}:${a}`).toBe(true); + for (const o of e.options) { + for (const r of [o, ...(o.roll ? [o.roll.success, o.roll.failure] : [])]) expect(Math.abs(r.score), `${e.id}/${o.id}`).toBeLessThanOrEqual(2); + } + } + const activities = new Set(ENCOUNTERS.flatMap((e) => e.activities).filter((a) => a !== "*")); + for (const a of activities) expect(ENCOUNTERS.filter((e) => e.activities.includes(a) || e.activities.includes("*")).length, a).toBeGreaterThanOrEqual(3); + }); +}); diff --git a/backend/packages/content/test/custom-avatar.test.ts b/backend/packages/content/test/custom-avatar.test.ts new file mode 100644 index 0000000..3fcf9c0 --- /dev/null +++ b/backend/packages/content/test/custom-avatar.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { CUSTOM_ID, SCENARIOS, withCustomCandidate } from "../src/index.ts"; + +const avatar = { skin: "#eebd98", hair: "short", hairColor: "#1f1b18", outfit: "suit", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: false, beard: false, bg: "#dfe8f0" }; +const custom = (a: Record) => ({ name: "測試人", party: null, background: "律師" as const, stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: a as typeof avatar, replace: null }); + +describe("自創角色的頭像(docs/24)", () => { + const scenario = SCENARIOS[0]!; + it("舊存檔的頭像原封不動放進劇本", () => { + const s = withCustomCandidate(scenario, custom(avatar), new Set()); + expect(s.candidates.find((c) => c.id === CUSTOM_ID)?.avatar).toEqual(avatar); + }); + + it("看不懂的部件代號換成預設、不擋開局", () => { + const s = withCustomCandidate(scenario, custom({ ...avatar, hair: "hair-from-2030", wear: { hat: "hat-campaign-cap", pet: "pet-dragon" }, style: "oil-paint" }), new Set()); + const a = s.candidates.find((c) => c.id === CUSTOM_ID)?.avatar; + expect(a?.hair).toBe("short"); + expect(a?.wear).toEqual({ hat: "hat-campaign-cap" }); + expect(a?.style).toBeUndefined(); + }); +}); diff --git a/backend/packages/content/test/scenarios.test.ts b/backend/packages/content/test/scenarios.test.ts new file mode 100644 index 0000000..a903b29 --- /dev/null +++ b/backend/packages/content/test/scenarios.test.ts @@ -0,0 +1,42 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { autoplay, createMatch, DEFAULT_PARAMS, playWeek, viewFor, type World } from "@election2026/engine"; +import { DEFAULT_PACKS_ROOT, loadPack } from "@election2026/pack-loader"; +import { PlayerView } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { CONTENT, SCENARIOS } from "../src/index.ts"; + +/** 用真實資料包整場跑一次。資料包是管線產物,沒有建置時略過 */ +for (const scenario of SCENARIOS) { + const built = existsSync(join(DEFAULT_PACKS_ROOT, scenario.packId, "manifest.json")); + describe.skipIf(!built)(`劇本 ${scenario.id}`, () => { + const world = async (): Promise => ({ scenario, pack: await loadPack(scenario.packId), content: CONTENT, params: DEFAULT_PARAMS }); + + it("每位候選人都能玩,每週的視角都符合協定,AI 指令全部合法", async () => { + const w = await world(); + for (const cand of scenario.candidates) { + let state = createMatch(w, "m", 1, cand.id); + while (state.phase !== "finished") { + const view = viewFor(state, w, cand.id); + const parsed = PlayerView.safeParse(view); + expect(parsed.success, parsed.success ? "" : parsed.error.message).toBe(true); + const out = playWeek(state, w); + expect(out.errors).toEqual({}); + state = out.state; + } + expect(PlayerView.safeParse(viewFor(state, w, cand.id)).success).toBe(true); + } + }); + + it("開票有效票與各里加總一致,歷史劇本附上真實結果", async () => { + const w = await world(); + const r = autoplay(w, "m", 2).result!; + expect(Object.values(r.votes).reduce((a, b) => a + b, 0)).toBe(r.valid); + expect(Object.keys(r.byVillage)).toHaveLength(w.pack.villages.length); + if (scenario.actual) { + const total = Object.values(r.actualShares ?? {}).reduce((a, b) => a + b, 0); + expect(total).toBeCloseTo(1, 6); + } + }); + }); +} diff --git a/backend/packages/content/tsconfig.json b/backend/packages/content/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/packages/content/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/packages/content/vitest.config.ts b/backend/packages/content/vitest.config.ts new file mode 100644 index 0000000..5539adc --- /dev/null +++ b/backend/packages/content/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ test: { include: ["test/**/*.test.ts"] } }); diff --git a/backend/packages/engine/package.json b/backend/packages/engine/package.json new file mode 100644 index 0000000..20118da --- /dev/null +++ b/backend/packages/engine/package.json @@ -0,0 +1,10 @@ +{ + "name": "@election2026/engine", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "選戰模擬的規則引擎:純函式,不碰網路、畫面、檔案(docs/11)", + "exports": { ".": "./src/index.ts" }, + "scripts": { "test": "vitest run", "typecheck": "tsc -p tsconfig.json" }, + "dependencies": { "@election2026/protocol": "workspace:*" } +} diff --git a/backend/packages/engine/src/ai.ts b/backend/packages/engine/src/ai.ts new file mode 100644 index 0000000..a03a107 --- /dev/null +++ b/backend/packages/engine/src/ai.ts @@ -0,0 +1,282 @@ +import type { ActionInfo, Order, PlayerView, Slot, StaffInfo } from "@election2026/protocol"; +import type { Rng } from "./rng.ts"; +import type { ScenarioCandidate } from "./types.ts"; + +/** + * AI 陣營(docs/12):只用自己的玩家視角規劃,不讀選民模型的真實數值,所以不會作弊。 + * 候選人本人跑最重要的行程,幕僚分頭把其他區跑過一輪;花錢依剩下的週數控制節奏。 + * 玩家的「幕僚建議行程」也是用這個規劃器。 + */ + +type Style = ScenarioCandidate["aiStyle"]; + +/** 誰來執行:候選人本人,或某位幕僚 */ +type Performer = { actor: "candidate"; staffId: null } | { actor: "team"; staffId: string }; + +interface Planner { + view: PlayerView; + orders: Order[]; + used: Map>; + money: number; + stamina: number; + /** 本週可以自由花的錢(廣告、造勢、樁腳);地面行程很便宜,不受這個限制 */ + budget: number; + spent: number; +} + +const PUBLIC_SLOTS: Slot[] = ["weekdayMorning", "weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"]; +const CANDIDATE: Performer = { actor: "candidate", staffId: null }; + +const key = (p: Performer) => p.staffId ?? "candidate"; + +function cost(a: ActionInfo, amount: number | null): number { + return a.cost.money + (a.amount && amount ? amount * a.amount.moneyPerUnit : 0); +} + +function snap(a: ActionInfo, value: number): number { + if (!a.amount) return 0; + const { min, max, step } = a.amount; + const clamped = Math.min(max, Math.max(min, value)); + return min + Math.floor((clamped - min) / step) * step; +} + +interface AddOptions { + slot?: Slot; + target?: string | null; + amount?: number; + opponentId?: string; + issueIds?: string[]; + /** 算進本週自由預算 */ + discretionary?: boolean; +} + +/** 嘗試加入一筆指令;時段、錢、體力、預算不夠就略過 */ +function add(p: Planner, who: Performer, id: string, opts: AddOptions = {}): boolean { + const a = p.view.actions.find((x) => x.id === id); + if (!a || !a.actors.includes(who.actor)) return false; + const amount = a.amount ? snap(a, opts.amount ?? a.amount.default) : null; + const price = cost(a, amount); + if (price > p.money) return false; + if (opts.discretionary && p.spent + price > p.budget) return false; + if (who.actor === "candidate" && a.cost.stamina > p.stamina) return false; + const busy = p.used.get(key(who)) ?? new Set(); + const slot = (opts.slot ? [opts.slot] : a.slots).find((s) => { + if (!a.slots.includes(s) || busy.has(s)) return false; + if (a.duration === 2) { + const prev = PUBLIC_SLOTS[PUBLIC_SLOTS.indexOf(s) - 1]; + return prev !== undefined && !busy.has(prev); + } + return true; + }); + if (!slot) return false; + busy.add(slot); + if (a.duration === 2) busy.add(PUBLIC_SLOTS[PUBLIC_SLOTS.indexOf(slot) - 1]); + p.used.set(key(who), busy); + p.money -= price; + if (opts.discretionary) p.spent += price; + if (who.actor === "candidate") p.stamina -= a.cost.stamina; + p.orders.push({ + actor: who.actor, + staffId: who.staffId, + slot, + actionId: id, + target: a.target === "town" ? (opts.target ?? null) : null, + amount, + opponentId: a.target === "opponent" ? (opts.opponentId ?? null) : null, + issueIds: opts.issueIds ?? null, + }); + return true; +} + +/** 團隊事務:交給第一位這個時段有空的幕僚 */ +function addTeam(p: Planner, staff: readonly StaffInfo[], id: string, opts: AddOptions = {}): boolean { + return staff.some((m) => add(p, { actor: "team", staffId: m.id }, id, opts)); +} + +/** 依人口、選情接近程度、自己的基本盤排序行政區;focus 裡的區排最前面;counter 時對手上週去過的區加分(打對台) */ +function rankTowns(view: PlayerView, party: string | null, rng: Rng, focus: readonly string[] = [], counter = false): string[] { + const rivalTowns = new Set(counter ? view.rivalTrail.map((v) => v.townCode) : []); + const internal = [...view.polls].reverse().find((p) => p.kind === "internal" && p.byTown); + const lateGame = view.week > view.totalWeeks / 2; + return [...view.towns] + .map((t) => { + const shares = Object.values(t.lastShares).sort((a, b) => b - a); + let swing = 1 - Math.min(1, (shares[0] ?? 0) - (shares[1] ?? 0)); + const own = party ? (t.lastShares[party] ?? 0.2) : 0.2; + if (internal?.byTown?.[t.code]) { + const row = internal.byTown[t.code]; + const mine = row[view.self.candidateId] ?? 0; + const best = Math.max(...Object.entries(row).filter(([id]) => id !== view.self.candidateId).map(([, v]) => v), 0); + swing = 1 - Math.min(1, Math.abs(mine - best) * 3); + } + const score = t.adults * (0.5 + swing) * (lateGame ? 0.7 + own : 1) * (0.85 + 0.3 * rng.next()) * (rivalTowns.has(t.code) ? 1.6 : 1) * (focus.includes(t.code) ? 1e6 : 1); + return { code: t.code, score }; + }) + .sort((a, b) => b.score - a.score) + .map((x) => x.code); +} + +function leaderOpponent(view: PlayerView): string | null { + const poll = [...view.polls].reverse().find((p) => p.kind === "public") ?? [...view.polls].reverse()[0]; + const others = view.candidates.filter((c) => !c.isPlayer); + if (!poll) return others[0]?.id ?? null; + return others.sort((a, b) => (poll.shares[b.id] ?? 0) - (poll.shares[a.id] ?? 0))[0]?.id ?? null; +} + +function trailing(view: PlayerView): boolean { + const poll = [...view.polls].reverse().find((p) => p.kind === "public"); + if (!poll) return false; + const mine = poll.shares[view.self.candidateId] ?? 0; + return Object.entries(poll.shares).some(([id, v]) => id !== view.self.candidateId && v > mine); +} + +/** 幕僚在各時段適合跑的地面行程 */ +const STAFF_GROUND: Record = { + weekdayMorning: ["market_visit", "street_canvass"], + weekdayAfternoon: ["factory_visit", "sound_truck", "street_canvass"], + weekdayEvening: ["street_canvass", "sound_truck"], + weekendMorning: ["market_visit", "street_canvass"], + weekendAfternoon: ["street_canvass", "sound_truck"], + weekendEvening: ["street_canvass"], + midnight: [], +}; + +export interface PlanOptions { + /** 玩家已經排好的行程:佔掉的時段、錢、體力先扣掉,回傳值不含這些 */ + fixed?: readonly Order[]; + /** 只排幕僚(玩家自己出牌時,候選人本人的時段由玩家決定) */ + teamOnly?: boolean; + /** 優先跑的區 */ + focus?: readonly string[]; + /** 懂戰術:候選人本人集中在兩個區打組合拳,優先去對手上週跑過的區打對台(困難 AI、平衡報告用) */ + tactics?: boolean; +} + +function orderPrice(view: PlayerView, o: Order): number { + const a = view.actions.find((x) => x.id === o.actionId); + return a ? cost(a, o.amount) : 0; +} + +export function planOrders(view: PlayerView, style: Style, rng: Rng, options: PlanOptions = {}): Order[] { + if (view.phase === "finished") return []; + const me = view.candidates.find((c) => c.isPlayer)!; + const weeksLeft = view.totalWeeks - view.week + 1; + const fixed = options.fixed ?? []; + // 固定支出在結算一開始就扣,規劃時先扣掉;玩家已排的行程也先扣 + const committed = fixed.reduce((sum, o) => sum + orderPrice(view, o), 0); + const money = Math.max(0, view.self.money - view.self.upkeep - committed); + const room = Math.max(0, view.self.spendingCap - view.self.spent - view.self.upkeep - committed); + const p: Planner = { + view, + orders: [], + used: new Map(), + money: Math.min(money, room), + stamina: view.self.stamina - fixed.filter((o) => o.actor === "candidate").reduce((s, o) => s + (view.actions.find((a) => a.id === o.actionId)?.cost.stamina ?? 0), 0), + budget: Math.max(300_000, (Math.min(money, room) / Math.max(1, weeksLeft)) * 1.2), + spent: 0, + }; + for (const o of fixed) { + const a = view.actions.find((x) => x.id === o.actionId); + const k = o.staffId ?? "candidate"; + const busy = p.used.get(k) ?? new Set(); + busy.add(o.slot); + if (a?.duration === 2) { + const prev = PUBLIC_SLOTS[PUBLIC_SLOTS.indexOf(o.slot) - 1]; + if (prev) busy.add(prev); + } + p.used.set(k, busy); + } + const staff = view.self.staff; + const towns = rankTowns(view, me.party, rng, options.focus, options.tactics); + const town = (i: number) => towns[i % towns.length]; + const leader = leaderOpponent(view); + const teamOnly = options.teamOnly ?? false; + const already = (id: string) => fixed.some((o) => o.actionId === id) || p.orders.some((o) => o.actionId === id); + + if (view.phase === "eve") { + if (!teamOnly) add(p, CANDIDATE, "eve_rally", { target: town(0), amount: Math.min(p.money * 0.4, 5_000_000) }); + if (!teamOnly && trailing(view) && style !== "air") add(p, CANDIDATE, "kneel"); + if (!already("eve_phone_bank")) addTeam(p, staff, "eve_phone_bank"); + if (!already("eve_online_ad")) addTeam(p, staff, "eve_online_ad", { amount: Math.min(p.money * 0.3, 1_500_000) }); + if (style === "dirty") addTeam(p, staff, "eve_vote_buying", { target: town(1), amount: 1_500 }); + return p.orders; + } + + // 懂戰術:本人六個時段只跑前兩個區(每區三種行程,組合拳 +20%) + if (!teamOnly) planCandidate(p, view, style, rng, options.tactics ? towns.flatMap((t) => [t, t, t]) : towns, leader); + // 玩家出牌(或懂戰術)時,幕僚從重點區(本人跑的區)開始跟著跑,疊出組合拳 + planTeam(p, view, style, rng, towns, leader, already, teamOnly || options.tactics ? 0 : 6); + return p.orders; +} + +/** 候選人本人:最重要的六個時段 */ +function planCandidate(p: Planner, view: PlayerView, style: Style, rng: Rng, towns: string[], leader: string | null): void { + const me = view.candidates.find((c) => c.isPlayer)!; + const weeksLeft = view.totalWeeks - view.week + 1; + const town = (i: number) => towns[i % towns.length]; + if (p.stamina < 40) add(p, CANDIDATE, "rest", { slot: "weekdayAfternoon" }); + if (me.issueIds.length === 0) { + const issues = [...view.issues].sort(() => rng.next() - 0.5).slice(0, 3).map((i) => i.id); + add(p, CANDIDATE, "announce_policy", { slot: "weekdayMorning", issueIds: issues }); + } else if (leader && (view.self.leverage[leader] ?? 0) > 0 && style !== "ground") { + add(p, CANDIDATE, "expose_press", { slot: "weekdayMorning", opponentId: leader }); + } else if (me.tags.length > 0 && rng.chance(0.6)) { + add(p, CANDIDATE, "rebuttal_press", { slot: "weekdayMorning" }); + } else { + add(p, CANDIDATE, "market_visit", { slot: "weekdayMorning", target: town(0) }); + } + add(p, CANDIDATE, style === "ground" ? "temple_visit" : "street_canvass", { slot: "weekdayAfternoon", target: town(1) }); + if (view.self.money < view.self.upkeep * 4 + p.budget * 2 || rng.chance(0.6)) { + add(p, CANDIDATE, "fundraiser_dinner", { slot: "weekdayEvening", target: town(2) }); + } else { + add(p, CANDIDATE, "talk_show", { slot: "weekdayEvening" }); + } + add(p, CANDIDATE, "temple_visit", { slot: "weekendMorning", target: town(3) }); + const rallyWeek = view.week % 2 === 0 || weeksLeft <= 3; + const rallied = + rallyWeek && + add(p, CANDIDATE, "rally", { slot: "weekendEvening", target: town(rng.int(3)), amount: Math.min(p.budget * 0.5, 4_000_000), discretionary: true }); + if (!rallied) { + add(p, CANDIDATE, "street_canvass", { slot: "weekendAfternoon", target: town(4) }); + add(p, CANDIDATE, "fundraiser_dinner", { slot: "weekendEvening", target: town(5) }); + } + +} + +/** 幕僚:團隊事務,然後分頭跑地面行程;already 是這週已經排過的行動(玩家打出的牌) */ +function planTeam(p: Planner, view: PlayerView, style: Style, rng: Rng, towns: string[], leader: string | null, already: (id: string) => boolean, firstTown: number): void { + const staff = view.self.staff; + const town = (i: number) => towns[i % towns.length]; + const team = (id: string, opts: AddOptions = {}) => !already(id) && addTeam(p, staff, id, opts); + // 團隊事務 + team("small_donations"); + if (view.week <= 3 && staff.length < 4 && view.self.money > 5_000_000) team("hire_staff"); + if (view.week <= 3 && view.self.officeTowns.length < 3) team("open_office", { target: towns.find((t) => !view.self.officeTowns.includes(t)) }); + if (view.week <= 3) team("recruit_volunteers"); + if (view.week === 1 || view.week === 5) team("print_flyers", { amount: 60_000, discretionary: true }); + if (view.week <= view.totalWeeks - 2) { + team("recruit_machine", { target: town(rng.int(4)), amount: Math.min(p.budget * 0.15, 1_200_000), discretionary: true }); + } + if (view.week >= 3) team("online_ad", { amount: Math.min(p.budget * 0.2, 2_000_000), discretionary: true }); + if (view.week >= 5 && style !== "ground") team("tv_ad", { amount: Math.min(p.budget * 0.35, 5_000_000), discretionary: true }); + if ([3, 6, 9].includes(view.week)) team("internal_poll"); + if (leader && [4, 7].includes(view.week) && style !== "ground" && rng.chance(style === "dirty" ? 0.9 : 0.5)) { + team("investigate", { opponentId: leader }); + } + if (style === "dirty") { + if (view.week >= view.totalWeeks - 2) team("vote_buying", { target: town(1), amount: 1_200 }); + else if (leader && view.week >= 5 && rng.chance(0.5)) team("troll_army", { opponentId: leader }); + } + + // 幕僚分頭跑地面行程:從 firstTown 開始輪(AI 從候選人沒去的區開始),盡量讓每區都有人去 + let next = firstTown; + for (const m of staff) { + for (const slot of PUBLIC_SLOTS) { + if (p.used.get(m.id)?.has(slot)) continue; + if (p.money < Math.max(300_000, view.self.upkeep)) break; + const who: Performer = { actor: "team", staffId: m.id }; + const target = town(next); + if (STAFF_GROUND[slot].some((id) => add(p, who, id, { slot, target }))) next++; + } + } +} diff --git a/backend/packages/engine/src/autoplay.ts b/backend/packages/engine/src/autoplay.ts new file mode 100644 index 0000000..b262cbc --- /dev/null +++ b/backend/packages/engine/src/autoplay.ts @@ -0,0 +1,41 @@ +import type { Order } from "@election2026/protocol"; +import { planOrders } from "./ai.ts"; +import { createMatch } from "./match.ts"; +import { makeRng } from "./rng.ts"; +import { resolveTurn, type World } from "./turn.ts"; +import type { MatchState } from "./types.ts"; +import { viewFor } from "./view.ts"; + +/** AI 陣營本週的指令:只看得到自己的玩家視角(docs/12) */ +export function aiOrders(state: MatchState, world: World, candidateId: string): Order[] { + const cand = world.scenario.candidates.find((c) => c.id === candidateId); + if (!cand) throw new Error(`找不到候選人 ${candidateId}`); + return planOrders(viewFor(state, world, candidateId), cand.aiStyle, makeRng(state.seed, "ai", candidateId, state.week)); +} + +/** 結算一週:指定的陣營用給定指令,其餘由 AI 規劃 */ +export function playWeek( + state: MatchState, + world: World, + given: Record = {}, + eventChoices: Readonly> = {}, + pressReplies: Readonly> = {}, +) { + const orders: Record = {}; + for (const c of world.scenario.candidates) { + const withdrawn = state.candidates.find((x) => x.id === c.id)?.withdrawn; + const planned = given[c.id] ?? (withdrawn ? [] : aiOrders(state, world, c.id)); + // 簡單難度:AI 每三個行程少跑一個 + orders[c.id] = given[c.id] || world.scenario.rules?.aiLevel !== "easy" ? planned : planned.filter((_, i) => i % 3 !== 2); + } + return resolveTurn(state, world, orders, eventChoices, pressReplies); +} + +/** 全部由 AI 打完一整場(回測、平衡報告用) */ +export function autoplay(world: World, matchId: string, seed: number): MatchState { + let state = createMatch(world, matchId, seed, world.scenario.candidates[0].id); + for (let guard = 0; state.phase !== "finished" && guard < world.scenario.weeks + 2; guard++) { + state = playWeek(state, world).state; + } + return state; +} diff --git a/backend/packages/engine/src/dark.ts b/backend/packages/engine/src/dark.ts new file mode 100644 index 0000000..ff0fb30 --- /dev/null +++ b/backend/packages/engine/src/dark.ts @@ -0,0 +1,76 @@ +import { applyEffect } from "./effects.ts"; +import type { ExecContext } from "./execute.ts"; +import type { SecretRecord } from "./types.ts"; + +/** + * 通風報信(docs/06):知情者越多、越接近投票日、檢舉獎金越高,越可能有人講出去。 + * 每週對每筆尚未曝光的祕密紀錄判定一次。 + */ +export function weeklyLeakChance(record: SecretRecord, week: number, totalWeeks: number, bounty: number): number { + const crackdown = week >= totalWeeks - 1 ? 1.5 : 1; + let p: number; + if (record.kind === "voteBuying") { + const recipients = 1 - 0.97 ** (record.recipients / 1000); + const machines = 1 - 0.99 ** record.machines; + p = 1 - (1 - recipients) * (1 - machines); + } else if (record.kind === "trolls") { + p = 0.02; + } else { + // 其他黑暗面:每位知情者每週約 1.5% 機率講出去 + p = 1 - 0.985 ** record.recipients; + } + if (record.candidateKnows) p *= 1.1; + return Math.min(0.95, p * crackdown * bounty); +} + +export function rollLeaks(ctx: ExecContext): void { + const { state, scenario, rng } = ctx; + scenario.candidates.forEach((cand, ci) => { + const self = state.candidates[ci]; + self.secrets = self.secrets.map((record) => { + if (record.exposed) return record; + const p = weeklyLeakChance(record, state.week, scenario.weeks, scenario.bountyMultiplier); + if (!rng.chance(p)) return record; + const what = record.label ?? (record.kind === "voteBuying" ? "買票" : "網軍帶風向"); + // 發過誓(斬雞頭、切結書)的人被踢爆,傷害加重 + const oath = self.oath ? 1.5 : 1; + if (self.oath) { + ctx.news.push({ title: `${cand.name}違背發過的誓言,網友翻出斬雞頭影片`, value: 6, candidateId: cand.id, townCode: null, topic: "oath_broken", tone: "negative", online: true }); + } + const where = record.townIndex !== null ? ctx.pack.towns[record.townIndex].name : ""; + const roll = rng.next(); + if (roll < 0.5) { + // 流向檢調 + self.underInvestigation = self.underInvestigation || ["voteBuying", "promise", "frame", "slush", "buyout"].includes(record.kind); + self.tags = [...new Set([...self.tags, "檢調約談"])]; + self.scandalWeek = state.week; + applyEffect(ctx, ci, { stat: "favor", base: -0.04 * oath, scope: "city" }, null, 1); + ctx.news.push({ + title: `檢調查${where}${what},${cand.name}陣營相關人士遭約談`, + value: 10, + candidateId: cand.id, + townCode: record.townIndex !== null ? ctx.pack.towns[record.townIndex].code : null, + topic: "investigation", tone: "negative", + }); + ctx.report(cand.id, "leak", `有人向檢調檢舉${where}${what},陣營人員被約談`); + } else if (roll < 0.8) { + // 流向媒體 + self.tags = [...new Set([...self.tags, "奧步"])]; + self.scandalWeek = state.week; + applyEffect(ctx, ci, { stat: "favor", base: -0.03 * oath * (record.kind === "staged" || record.kind === "frame" ? 1.6 : 1), scope: "city" }, null, 1); + ctx.news.push({ title: `媒體踢爆${cand.name}陣營疑似${what}`, value: 8, candidateId: cand.id, townCode: null, topic: "media_expose", tone: "negative" }); + ctx.report(cand.id, "leak", `${where}${what}的消息被媒體踢爆`); + } else { + // 流向對手:變成對手手上的把柄 + const others = scenario.candidates.filter((c) => c.id !== cand.id); + const holder = rng.pick(others); + const hi = scenario.candidates.findIndex((c) => c.id === holder.id); + const lev = state.candidates[hi].leverage; + lev[cand.id] = (lev[cand.id] ?? 0) + 1; + ctx.report(holder.id, "intel", `有人私下向你透露:${cand.name}陣營在${where}${what}。可以用來爆料`); + ctx.news.push({ title: `傳出${cand.name}陣營疑似${what},真假不明`, value: 3, candidateId: cand.id, townCode: null, topic: "rumor", tone: "negative", online: true }); + } + return { ...record, exposed: true }; + }); + }); +} diff --git a/backend/packages/engine/src/economy.ts b/backend/packages/engine/src/economy.ts new file mode 100644 index 0000000..e0446eb --- /dev/null +++ b/backend/packages/engine/src/economy.ts @@ -0,0 +1,37 @@ +import type { Rng } from "./rng.ts"; +import type { CandidateState } from "./types.ts"; + +/** + * 錢的規則(docs/04、docs/05)。價格參考 2022 桃園市長候選人的政治獻金支出科目, + * 對照表在 docs/05「價格從哪裡來」。 + */ + +/** 服務處每週租金:鄭運鵬陣營「租用競選辦事處支出」約 444 萬元,約 16 週、5 處估算 */ +export const OFFICE_RENT = 50_000; + +/** 每週固定支出:服務處租金+幕僚薪水 */ +export function weeklyUpkeep(c: Pick): number { + return c.offices.length * OFFICE_RENT + c.staff.reduce((s, m) => s + m.salary, 0); +} + +/** 聲勢越好越好募款:聲勢 0 時為 1 倍,介於 0.5–2.5 倍 */ +export function fundraisingMultiplier(momentum: number): number { + return Math.min(2.5, Math.max(0.5, 1 + 2 * momentum)); +} + +/** + * 草根底線:沒有大額金主的小候選人,靠聲勢也募得到錢(不然一開局就動不了)。 + * 募款能力很高的大黨候選人不受影響。 + */ +const DINNER_FLOOR = 250_000; +const DONATION_FLOOR = 150_000; + +/** 募款餐會:每週募款能力的七成 */ +export function dinnerYield(fundraising: number, momentum: number, weather: number, rng: Rng): number { + return Math.round(Math.max(0.7 * fundraising, DINNER_FLOOR) * fundraisingMultiplier(momentum) * weather * (0.85 + 0.3 * rng.next())); +} + +/** 網路小額募款:每週募款能力的三成 */ +export function smallDonationYield(fundraising: number, momentum: number, rng: Rng): number { + return Math.round(Math.max(0.3 * fundraising, DONATION_FLOOR) * fundraisingMultiplier(momentum) * (0.8 + 0.4 * rng.next())); +} diff --git a/backend/packages/engine/src/effects.ts b/backend/packages/engine/src/effects.ts new file mode 100644 index 0000000..5ddbd78 --- /dev/null +++ b/backend/packages/engine/src/effects.ts @@ -0,0 +1,93 @@ +import { AGE_BANDS, LEANS } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, N_LEANS, type PackData } from "./pack.ts"; +import type { ModelParams } from "./params.ts"; +import type { ActionEffect, MatchState, Scenario } from "./types.ts"; + +export interface EffectContext { + pack: PackData; + scenario: Scenario; + params: ModelParams; + /** 工作中的狀態副本(resolveTurn 在副本上運算,不修改輸入) */ + state: MatchState; +} + +const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x)); + +function attrMultiplier(effect: ActionEffect, pack: PackData, v: number): number { + const village = pack.villages[v]; + switch (effect.attr) { + case "temples": + return clamp(village.templesPer1000 / pack.meanTemples, 0.3, 2.5); + case "density": + return clamp((village.density / pack.meanDensity) ** 0.3, 0.5, 1.6); + case "lowDensity": + return clamp((pack.meanDensity / Math.max(village.density, 1)) ** 0.3, 0.5, 1.6); + default: + return 1; + } +} + +/** 一個區的觸及係數:區越大,每個人分到的效果越小(docs/03 的規模報酬遞減) */ +export function townReach(pack: PackData, params: ModelParams, townIndex: number): number { + return clamp((params.refAdults / Math.max(pack.towns[townIndex].adults, 1)) ** params.reachExponent, 0.5, 3); +} + +/** + * 套用一個效果。magnitude 已包含執行者倍率、天氣、服務處、撞場、投入規模等。 + * 飽和:知名度與熱度越接近 1 越難上升;好感度越接近 ±1 越難再推。 + */ +export function applyEffect( + ctx: EffectContext, + candidateIndex: number, + effect: ActionEffect, + townIndex: number | null, + magnitude: number, + opponentIndex: number | null = null, +): void { + const { pack, params, state, scenario } = ctx; + const target = effect.onOpponent ? opponentIndex : candidateIndex; + if (target === null || target === undefined) return; + const villages = + effect.scope === "target" && townIndex !== null ? pack.towns[townIndex].villages : pack.villages.map((_, i) => i); + const reach = effect.scope === "target" && townIndex !== null ? townReach(pack, params, townIndex) : 1; + const ageMask = AGE_BANDS.map((a) => !effect.ages || effect.ages.includes(a)); + const leanMask = LEANS.map((l) => !effect.leans || effect.leans.includes(l)); + const slot = scenario.candidates[candidateIndex].slot; + const supporterMask = LEANS.map((_, l) => params.partyMatch[slot][l] > 0); + const nCells = pack.cells.length; + const array = effect.stat === "awareness" ? state.awareness : effect.stat === "favor" ? state.favor : state.heat; + const offset = target * nCells; + + for (const v of villages) { + const delta = effect.base * magnitude * reach * attrMultiplier(effect, pack, v); + const base = v * CELLS_PER_VILLAGE; + for (let k = 0; k < CELLS_PER_VILLAGE; k++) { + const a = Math.floor(k / N_LEANS); + const l = k % N_LEANS; + if (!ageMask[a] || !leanMask[l]) continue; + if (effect.supportersOnly && !supporterMask[l]) continue; + const idx = offset + base + k; + const x = array[idx]; + if (effect.stat === "favor") { + array[idx] = clamp(x + delta * (1 - Math.abs(x)), -1, 1); + } else { + array[idx] = clamp(delta >= 0 ? x + delta * (1 - x) : x + delta * x, 0, 1); + } + } + } +} + +/** 每週的自然衰退:知名度往開局值回落、好感度往 0、熱度往基準、聲勢往 0、組織往開局值 */ +export function applyDecay(ctx: EffectContext, baselineAwareness: Float32Array, baselineMachine: Float32Array): void { + const { state, params } = ctx; + const d = params.decay; + for (let i = 0; i < state.awareness.length; i++) { + state.awareness[i] -= d.awareness * (state.awareness[i] - baselineAwareness[i]); + state.favor[i] *= 1 - d.favor; + state.heat[i] = params.heatBaseline + (state.heat[i] - params.heatBaseline) * (1 - d.heat); + } + for (let i = 0; i < state.machine.length; i++) { + state.machine[i] = baselineMachine[i] + (state.machine[i] - baselineMachine[i]) * (1 - d.machine); + } + state.momentum = state.momentum.map((m) => m * (1 - d.momentum)); +} diff --git a/backend/packages/engine/src/election.ts b/backend/packages/engine/src/election.ts new file mode 100644 index 0000000..b93e85e --- /dev/null +++ b/backend/packages/engine/src/election.ts @@ -0,0 +1,149 @@ +import type { ElectionResult } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, type PackData } from "./pack.ts"; +import type { ModelParams } from "./params.ts"; +import { perceivedViability } from "./polls.ts"; +import type { Rng } from "./rng.ts"; +import type { MatchState, Scenario } from "./types.ts"; +import { computeVoteModel } from "./voter.ts"; + +/** 最大餘數法:把整數 total 依權重分配 */ +function apportion(total: number, weights: readonly number[]): number[] { + const sum = weights.reduce((a, b) => a + Math.max(0, b), 0); + if (total <= 0 || sum <= 0) return weights.map(() => 0); + const raw = weights.map((w) => (total * Math.max(0, w)) / sum); + const base = raw.map(Math.floor); + let rest = total - base.reduce((a, b) => a + b, 0); + const order = raw.map((r, i) => [r - base[i], i] as const).sort((a, b) => b[0] - a[0]); + for (const [, i] of order) { + if (rest <= 0) break; + base[i] += 1; + rest -= 1; + } + return base; +} + +/** 真實結果(歷史劇本):政黨票 → 候選人 */ +export function actualShares(scenario: Scenario, pack: PackData): Record | null { + const actual = scenario.actual; + if (!actual) return null; + const totals: Record = {}; + if (actual.byVillage) { + for (const row of Object.values(actual.byVillage)) { + for (const [cid, n] of Object.entries(row)) totals[cid] = (totals[cid] ?? 0) + n; + } + const sum = Object.values(totals).reduce((a, b) => a + b, 0) || 1; + return Object.fromEntries(Object.entries(totals).map(([k, n]) => [k, n / sum])); + } + for (const v of pack.villages) { + const r = pack.history.byVillage[v.code]?.[actual.electionId]; + if (!r) continue; + for (const [party, n] of Object.entries(r.votes)) { + const cid: string | undefined = actual.partyToCandidate?.[party]; + if (cid) totals[cid] = (totals[cid] ?? 0) + n; + } + } + const sum = Object.values(totals).reduce((a, b) => a + b, 0) || 1; + return Object.fromEntries(Object.entries(totals).map(([k, n]) => [k, n / sum])); +} + +/** 投票日:天氣、投票率、抽樣、買票兌現、選後司法(docs/02、docs/06) */ +export function runElectionDay(state: MatchState, scenario: Scenario, pack: PackData, params: ModelParams, rng: Rng): ElectionResult { + const rainy = rng.chance(0.2); + const model = computeVoteModel(state, scenario, pack, params, perceivedViability(state, scenario), rainy ? 0.97 : 1); + const nCand = scenario.candidates.length; + const nCells = pack.cells.length; + const byVillage: Record = {}; + const ballotsByVillage: number[] = []; + let electors = 0; + + pack.villages.forEach((village, v) => { + let expectedVoters = 0; + const expected = new Array(nCand).fill(0); + for (let k = 0; k < CELLS_PER_VILLAGE; k++) { + const i = v * CELLS_PER_VILLAGE + k; + const casting = pack.cells[i] * model.turnout[i]; + expectedVoters += casting; + for (let c = 0; c < nCand; c++) expected[c] += casting * model.probs[c * nCells + i]; + } + const scaleToElectors = village.adults > 0 ? village.electors / village.adults : 1; + const voters = Math.max(0, Math.round(rng.normal(expectedVoters * scaleToElectors, Math.sqrt(expectedVoters * 0.1)))); + const sampled = expected.map((e) => { + const p = expectedVoters > 0 ? e / expectedVoters : 0; + return Math.max(0, p + rng.normal(0, Math.sqrt((p * (1 - p)) / Math.max(voters, 1)))); + }); + const invalid = Math.round(voters * params.invalidRate); + byVillage[village.code] = apportion(voters - invalid, sampled); + ballotsByVillage[v] = voters; + electors += village.electors; + }); + + // 買票兌現:一半是原本不投票的人被動員,一半從其他候選人轉來 + state.candidates.forEach((cand, ci) => { + cand.boughtVotes.forEach((bought, t) => { + if (bought <= 0) return; + const effective = Math.round(bought * params.voteBuyingConversion); + const town = pack.towns[t]; + const shares = apportion(effective, town.villages.map((v) => pack.villages[v].adults)); + town.villages.forEach((v, j) => { + const row = byVillage[pack.villages[v].code]; + const add = shares[j]; + const switched = Math.floor(add / 2); + const others = row.map((n, c) => (c === ci ? 0 : n)); + const taken = apportion(Math.min(switched, others.reduce((a, b) => a + b, 0)), others); + taken.forEach((n, c) => (row[c] -= n)); + row[ci] += add; + ballotsByVillage[v] += add - switched; + }); + }); + }); + + const votes = new Array(nCand).fill(0); + const byTown: Record = Object.fromEntries(pack.towns.map((t) => [t.code, new Array(nCand).fill(0)])); + pack.villages.forEach((village) => { + const row = byVillage[village.code]; + row.forEach((n, c) => { + votes[c] += n; + byTown[pack.towns[village.townIndex].code][c] += n; + }); + }); + const valid = votes.reduce((a, b) => a + b, 0); + const ballots = ballotsByVillage.reduce((a, b) => a + b, 0); + const top = Math.max(...votes); + const leaders = votes.map((n, c) => (n === top ? c : -1)).filter((c) => c >= 0); + const winner = leaders.length > 1 ? rng.pick(leaders) : leaders[0]; // 同票依法抽籤 + + const post: string[] = []; + let voided = false; + state.candidates.forEach((cand, ci) => { + if (!cand.underInvestigation) return; + const name = scenario.candidates[ci].name; + if (ci === winner) { + voided = rng.chance(0.4); + post.push(voided ? `${name}陣營賄選案判決確定,當選無效。` : `${name}陣營賄選案證據不足,當選有效。`); + } else { + post.push(`${name}陣營賄選案起訴。`); + } + }); + if (rainy) post.unshift("投票日下雨,投票率略低。"); + + const toRecord = (row: readonly number[]) => + Object.fromEntries(scenario.candidates.map((c, i) => [c.id, row[i]])); + const countingOrder = pack.villages + .map((v, i) => ({ code: v.code, key: ballotsByVillage[i] * (0.7 + 0.6 * rng.next()) })) + .sort((a, b) => a.key - b.key) + .map((x) => x.code); + + return { + electors, + ballots, + valid, + votes: toRecord(votes), + winnerId: scenario.candidates[winner].id, + byTown: Object.fromEntries(Object.entries(byTown).map(([code, row]) => [code, toRecord(row)])), + byVillage: Object.fromEntries(Object.entries(byVillage).map(([code, row]) => [code, toRecord(row)])), + countingOrder, + postElection: post, + voided, + actualShares: actualShares(scenario, pack), + }; +} diff --git a/backend/packages/engine/src/encounters.ts b/backend/packages/engine/src/encounters.ts new file mode 100644 index 0000000..446b547 --- /dev/null +++ b/backend/packages/engine/src/encounters.ts @@ -0,0 +1,50 @@ +import type { Order } from "@election2026/protocol"; +import type { ExecContext } from "./execute.ts"; +import { fill } from "./news.ts"; +import type { EncounterDef, EncounterResult } from "./types.ts"; + +/** 每一分讓效果增減 8%;三個遭遇最多 ±6 分,倍率 0.52–1.48 */ +export const ENCOUNTER_STEP = 0.08; + +/** 這個遭遇會不會在這個行動出現 */ +export const encounterFits = (e: EncounterDef, actionId: string) => e.activities.includes(actionId) || e.activities.includes("*"); + +/** + * 結算拜票副本:只認候選人本人親自跑、而且遭遇真的屬於這個行動的選擇;不合格的部分直接忽略(效果照常)。 + * 回傳效果倍率,並套用各選項的聲勢、體力、錢、標籤與新聞。 + */ +export function resolveEncounter(ctx: ExecContext, ci: number, order: Order, encounters: readonly EncounterDef[], vars: Record): number { + const play = order.encounter; + if (!play || order.actor !== "candidate") return 1; + const { state, scenario, rng } = ctx; + const cand = scenario.candidates[ci]; + const self = state.candidates[ci]; + const byId = new Map(encounters.map((e) => [e.id, e])); + let score = 0; + const lines: string[] = []; + play.ids.slice(0, 3).forEach((id, i) => { + const e = byId.get(id); + const option = e?.options.find((o) => o.id === play.picks[i]); + if (!e || !option || !encounterFits(e, order.actionId)) return; + let result: EncounterResult = option; + if (option.roll) result = rng.chance(option.roll.chance) ? option.roll.success : option.roll.failure; + score += result.score; + if (result.momentum) state.momentum[ci] += result.momentum; + if (result.stamina) self.stamina = Math.max(0, Math.min(self.staminaMax, self.stamina + result.stamina)); + if (result.money) { + // 副本裡的小花費在驗證行程之後才發生,最多花到 0 + const paid = Math.max(-self.money, result.money); + self.money += paid; + if (paid < 0) self.spent -= paid; + } + if (result.tag) self.tags = [...new Set([...self.tags, result.tag])]; + if (result.news) { + ctx.news.push({ title: fill(result.news.template, vars), value: result.news.value, candidateId: cand.id, townCode: order.target, topic: "encounter", art: order.actionId, tone: result.news.tone }); + } + lines.push(fill(e.who, vars)); + }); + const multiplier = Math.max(0.4, 1 + ENCOUNTER_STEP * score); + const grade = score >= 4 ? "很好" : score >= 1 ? "不錯" : score >= -1 ? "普通" : "不太好"; + ctx.report(cand.id, "action", `${vars.town}親自走一趟(遇到${lines.join("、")}):表現${grade},效果 ×${multiplier.toFixed(2)}`); + return multiplier; +} diff --git a/backend/packages/engine/src/events.ts b/backend/packages/engine/src/events.ts new file mode 100644 index 0000000..88b02e3 --- /dev/null +++ b/backend/packages/engine/src/events.ts @@ -0,0 +1,151 @@ +import type { ElectionKind } from "@election2026/protocol"; +import { applyEffect } from "./effects.ts"; +import type { ExecContext } from "./execute.ts"; +import { makeRng } from "./rng.ts"; +import type { ActionEffect, MatchState, Scenario } from "./types.ts"; + +/** + * 表態事件(docs/08):每週每位候選人抽一張,要選一個回應。 + * 每個選項都讓某些人高興、某些人不高興;有些選項要等決定之後才擲出結果(例如颱風真正的風雨)。 + * 內容即資料(content/events.ts),這裡只負責抽牌、AI 選擇與套用效果。 + */ + +export interface EventOutcome { + /** 給自己看的結果(戰報);{name} 會換成候選人名字 */ + text: string; + effects?: readonly ActionEffect[]; + /** 聲勢變化,約 ±0.02–0.06 */ + momentum?: number; + /** 對手的聲勢變化(記者堵麥時,被點名的那位) */ + opponentMomentum?: number; + /** 錢的變化(元),負的是花費 */ + money?: number; + stamina?: number; + /** 上新聞的標題({name} 會換成候選人名字);沒有就不上新聞 */ + news?: { title: string; tone: "positive" | "neutral" | "negative" }; +} + +export interface EventOption { + id: string; + label: string; + outcome: EventOutcome; + /** 決定之後才擲骰:chance 是 success 的機率 */ + roll?: { chance: number; success: EventOutcome; failure: EventOutcome }; +} + +export interface EventDef { + id: string; + title: string; + body: string; + /** 卡牌插圖(web/public/cards/.webp) */ + art: string; + /** 只出現在這些選舉;沒寫就全部都會 */ + kinds?: readonly ElectionKind[]; + /** 只給有政黨(true)或無黨籍(false)的候選人;沒寫就都會 */ + party?: boolean; + /** 出現的週數範圍(含) */ + weeks?: readonly [number, number]; + weight: number; + options: readonly EventOption[]; + /** 沒有回應時套用的選項 */ + fallback: string; +} + +/** 抽下一週的事件:已經看過的不再出現,選舉種類與週數要符合 */ +export function drawEvent(events: readonly EventDef[], scenario: Scenario, state: MatchState, candidateIndex: number): string | null { + const cand = state.candidates[candidateIndex]; + const kind = scenario.region.kind ?? "mayor"; + const hasParty = scenario.candidates[candidateIndex]?.party !== null; + const pool = events.filter( + (e) => + !cand.seenEvents.includes(e.id) && + (!e.kinds || e.kinds.includes(kind)) && + (e.party === undefined || e.party === hasParty) && + (!e.weeks || (state.week >= e.weeks[0] && state.week <= e.weeks[1])), + ); + if (pool.length === 0) return null; + const rng = makeRng(state.seed, "event", cand.id, state.week); + const total = pool.reduce((s, e) => s + e.weight, 0); + let r = rng.next() * total; + for (const e of pool) { + r -= e.weight; + if (r <= 0) return e.id; + } + return pool[pool.length - 1]!.id; +} + +/** AI 的選擇:不回應以外的選項隨機挑一個(真實人物 AI 不設奧步,事件選項本身也沒有違法的) */ +export function aiEventChoice(event: EventDef, state: MatchState, candidateIndex: number): string { + const rng = makeRng(state.seed, "event-choice", state.candidates[candidateIndex].id, state.week); + const options = event.options.filter((o) => o.id !== event.fallback); + return (options.length ? rng.pick(options) : event.options[0]!).id; +} + +const fill = (text: string, name: string) => text.replaceAll("{name}", name); + +/** 套用一個選項的結果(固定部分+擲骰部分);回傳實際的結果與擲骰說明 */ +export function applyOptionOutcome(ctx: ExecContext, ci: number, option: EventOption, opponent: number | null): { outcome: EventOutcome; rolled: string } { + const { state } = ctx; + const cand = state.candidates[ci]; + let outcome = option.outcome; + let rolled = ""; + if (option.roll) { + const ok = ctx.rng.chance(option.roll.chance); + outcome = ok ? option.roll.success : option.roll.failure; + rolled = ok ? "(運氣站在你這邊)" : "(運氣不好)"; + } + const parts = option.roll ? [option.outcome, outcome] : [option.outcome]; + for (const effect of parts.flatMap((o) => o.effects ?? [])) applyEffect(ctx, ci, effect, null, 1, opponent); + const sum = (f: (o: EventOutcome) => number | undefined) => parts.reduce((s, o) => s + (f(o) ?? 0), 0); + state.momentum[ci] = Math.max(-0.5, Math.min(1, state.momentum[ci] + sum((o) => o.momentum))); + const oppMomentum = sum((o) => o.opponentMomentum); + if (oppMomentum && opponent !== null) state.momentum[opponent] = Math.max(-0.5, Math.min(1, state.momentum[opponent] + oppMomentum)); + const money = sum((o) => o.money); + if (money) { + const paid = Math.max(-cand.money, money); + cand.money += paid; + if (paid < 0) cand.spent -= paid; + } + const stamina = sum((o) => o.stamina); + if (stamina) cand.stamina = Math.max(0, Math.min(cand.staminaMax, cand.stamina + stamina)); + return { outcome, rolled }; +} + +/** + * 結算每位候選人這週的事件。choices:候選人 id → 選項 id(沒給的候選人由 AI 決定)。 + * 回傳後清掉待回應的事件;下一週的事件在推進週數之後另外抽。 + */ +export function resolveEvents(ctx: ExecContext, events: readonly EventDef[], choices: Readonly>, isPlayer: (id: string) => boolean): void { + const { state, scenario } = ctx; + const byId = new Map(events.map((e) => [e.id, e])); + state.candidates.forEach((cand, ci) => { + const pending = cand.event; + if (!pending) return; + const event = byId.get(pending); + cand.event = null; + if (!event) return; + const sc = scenario.candidates[ci]; + const wanted = choices[cand.id] ?? (isPlayer(cand.id) ? event.fallback : aiEventChoice(event, state, ci)); + const option = event.options.find((o) => o.id === wanted) ?? event.options.find((o) => o.id === event.fallback)!; + const opponent = state.candidates.findIndex((_, i) => i !== ci); + const { outcome, rolled } = applyOptionOutcome(ctx, ci, option, opponent >= 0 ? opponent : null); + ctx.report(cand.id, "event", `${event.title}:你選了「${option.label}」。${fill(outcome.text, sc.name)}${rolled}`); + // 只有玩家自己的表態上新聞:AI 控制的真實人物隨機表態若上報,等於替真人捏造立場(docs/14) + const news = isPlayer(cand.id) ? (outcome.news ?? option.outcome.news) : undefined; + if (news) ctx.news.push({ title: fill(news.title, sc.name), value: 5, candidateId: cand.id, townCode: null, topic: `event:${event.id}`, art: event.art, tone: news.tone }); + }); +} + +/** 推進到新的一週之後,替每位候選人抽事件 */ +export function dealEvents(events: readonly EventDef[], scenario: Scenario, state: MatchState): void { + if (state.phase !== "campaign") return; + if (scenario.rules?.noEvents) { + state.candidates.forEach((cand) => (cand.event = null)); + return; + } + state.candidates.forEach((cand, ci) => { + const id = drawEvent(events, scenario, state, ci); + cand.event = id; + if (id) cand.seenEvents = [...cand.seenEvents, id]; + }); +} diff --git a/backend/packages/engine/src/execute.ts b/backend/packages/engine/src/execute.ts new file mode 100644 index 0000000..169b455 --- /dev/null +++ b/backend/packages/engine/src/execute.ts @@ -0,0 +1,488 @@ +import type { Order, ReportItem } from "@election2026/protocol"; +import { dinnerYield, OFFICE_RENT, smallDonationYield } from "./economy.ts"; +import { applyEffect, type EffectContext } from "./effects.ts"; +import type { Rng } from "./rng.ts"; +import { MAX_STAFF, staffMember } from "./staff.ts"; +import type { ActionDef, ActionEffect, ActionOutcome, Content } from "./types.ts"; +import { resolveEncounter } from "./encounters.ts"; +import { fill } from "./news.ts"; +import { orderCost } from "./validate.ts"; + +export interface NewsDraft { + title: string; + value: number; + candidateId: string | null; + /** 被攻擊、被點名的候選人 */ + targetId?: string | null; + /** 配圖(卡牌插圖名稱) */ + art?: string | null; + townCode: string | null; + tone: "positive" | "neutral" | "negative"; + /** 主題:行動 id 或事件種類,前端用來挑配圖 */ + topic: string; + online?: boolean; + /** 同一週、同一種行動的新聞合併成一則(例如「甲、乙發表主打政見」) */ + merge?: { key: string; template: string; vars: Record }; +} + +export interface ExecContext extends EffectContext { + content: Content; + rng: Rng; + news: NewsDraft[]; + report: (candidateId: string, kind: ReportItem["kind"], text: string) => void; + wantsInternalPoll: Set; + /** 黑馬加成:每位候選人知名度效果的倍率(知名度越低越大,1–1.5) */ + underdog?: readonly number[]; +} + +const WEATHER_OUTDOOR = { sunny: 1, rain: 0.7, typhoon: 0.3 } as const; +const FLYERS_PER_ACTION = 2_000; + + +const money = (n: number): string => `${Math.round(n / 10_000).toLocaleString()} 萬元`; + +/** 執行一筆已驗證的指令。clash:效果倍率(撞場 0.8,乘上組合拳、打對台的加成)。 */ +export function executeOrder(ctx: ExecContext, ci: number, order: Order, action: ActionDef, clash: number): void { + const { state, pack, scenario, rng } = ctx; + const cand = scenario.candidates[ci]; + const self = state.candidates[ci]; + const town = order.target ? pack.towns.findIndex((t) => t.code === order.target) : null; + const opponent = order.opponentId ? scenario.candidates.findIndex((c) => c.id === order.opponentId) : null; + const vars = { + name: cand.name, + town: town !== null ? pack.towns[town].name : "", + opponent: opponent !== null ? scenario.candidates[opponent].name : "", + }; + + // 付錢與體力;前面的行程(副本裡的花費、擲骰的結果)可能把錢花掉了,付不出來就取消 + const cost = orderCost(action, order); + if (cost > self.money) { + ctx.report(cand.id, "cancelled", `「${action.name}」執行時錢不夠,取消`); + return; + } + self.money -= cost; + self.spent += cost; + if (order.actor === "candidate") self.stamina = Math.min(self.staminaMax, self.stamina - action.cost.stamina); + + // 倍率:執行者(候選人 1、幕僚依能力 0.4–0.7)、義工、文宣、服務處、天氣、撞場、投入規模 + const member = order.staffId ? self.staff.find((m) => m.id === order.staffId) : undefined; + let magnitude = member ? member.skill * (1 + Math.min(0.5, self.volunteers / 4_000)) : 1; + if (town !== null && self.offices.includes(town)) magnitude *= 1.25; + if (action.outdoor) magnitude *= WEATHER_OUTDOOR[state.weather]; + magnitude *= clash; + if (order.encounter && ctx.content.encounters) magnitude *= resolveEncounter(ctx, ci, order, ctx.content.encounters, vars); + const scale = action.amount && order.amount ? (order.amount / action.amount.default) ** 0.7 : 1; + let awarenessBoost = 1; + if (action.category === "ground" && self.flyers >= FLYERS_PER_ACTION) { + self.flyers -= FLYERS_PER_ACTION; + awarenessBoost = 1.2; + } + const apply = (effects: readonly ActionEffect[], extra = 1) => { + for (const e of effects) { + const boost = e.stat === "awareness" ? awarenessBoost * (ctx.underdog?.[ci] ?? 1) : 1; + applyEffect(ctx, ci, e, town, magnitude * scale * extra * boost, opponent); + } + }; + + const special = action.special; + if (!special || ["tvAd", "onlineAd", "policy", "kneel", "rally"].includes(special)) apply(action.effects); + + switch (special) { + case "rally": { + const gain = 0.05 * scale * WEATHER_OUTDOOR[state.weather] * clash * (state.phase === "eve" ? 1.5 : 1); + state.momentum[ci] += gain; + const crowd = Math.round((1 + 2 * scale) * (1 + Math.max(0, state.momentum[ci])) * 10) / 10; + ctx.news.push({ + title: `${cand.name}${vars.town}造勢晚會,主辦單位宣稱 ${crowd} 萬人到場`, + value: 3 + 3 * scale, + candidateId: cand.id, + townCode: order.target, + topic: action.id, tone: "positive", + }); + break; + } + case "office": + if (town !== null && !self.offices.includes(town)) { + self.offices.push(town); + ctx.report(cand.id, "action", `${vars.town}服務處成立,之後每週租金 ${money(OFFICE_RENT)}`); + } + break; + case "machine": { + if (town === null) break; + const price = 300_000 * Math.sqrt(pack.towns[town].adults / 100_000); + const ratio = (order.amount ?? 0) / price; + if (rng.chance(Math.min(0.9, 0.35 + 0.45 * ratio))) { + const idx = ci * pack.towns.length + town; + state.machine[idx] = Math.min(0.9, state.machine[idx] + 0.06 * Math.sqrt(ratio)); + ctx.report(cand.id, "action", `${vars.town}有幾位里長願意幫忙(地方組織增強)`); + } else { + ctx.report(cand.id, "action", `${vars.town}的樁腳嫌條件不夠,沒有談成`); + } + break; + } + case "talkShow": { + const skill = (cand.eloquence + self.bonus.eloquence - 50) / 25; + const gaffe = rng.chance(0.08 * (1 - self.bonus.gaffe)); + const delta = gaffe ? -0.012 : 0.008 * skill + rng.normal(0, 0.004); + const favor: ActionEffect = { stat: "favor", base: delta, scope: "city", ages: ["40-49", "50-64", "65+"] }; + applyEffect(ctx, ci, favor, null, 1); + ctx.news.push({ + title: gaffe ? `${cand.name}上政論節目失言,網路熱議` : `${cand.name}上政論節目談政見`, + value: gaffe ? 6 : 1.5, + candidateId: cand.id, + townCode: null, + topic: "talk_show", tone: gaffe ? "negative" : delta >= 0 ? "positive" : "neutral", + online: gaffe, + }); + break; + } + case "fundraiser": { + const raised = dinnerYield(cand.fundraising, state.momentum[ci], WEATHER_OUTDOOR[state.weather], rng); + self.money += raised; + apply(action.effects); + ctx.report(cand.id, "money", `${vars.town}募款餐會募得 ${money(raised)}`); + break; + } + case "smallDonations": { + const raised = smallDonationYield(cand.fundraising, state.momentum[ci], rng); + self.money += raised; + ctx.report(cand.id, "money", `網路小額募款收到 ${money(raised)}`); + break; + } + case "selfFund": + self.money += order.amount ?? 0; + self.wealth -= order.amount ?? 0; + ctx.report(cand.id, "money", `自掏腰包 ${money(order.amount ?? 0)}`); + break; + case "policy": + self.issueIds = [...(order.issueIds ?? [])]; + break; + case "expose": { + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + const hasDirt = (self.leverage[opp.id] ?? 0) > 0; + if (hasDirt) { + self.leverage[opp.id] -= 1; + applyEffect(ctx, ci, { stat: "favor", base: -0.035, scope: "city", onOpponent: true }, null, 1, opponent); + state.candidates[opponent].scandalWeek = state.week; + ctx.news.push({ title: `${cand.name}陣營開記者會爆料${opp.name},提出具體證據`, value: 8, candidateId: opp.id, townCode: null, topic: "expose", tone: "negative" }); + } else { + applyEffect(ctx, ci, { stat: "favor", base: -0.012, scope: "city", onOpponent: true }, null, 1, opponent); + applyEffect(ctx, ci, { stat: "favor", base: -0.008, scope: "city", leans: ["middle"], ages: ["20-29", "30-39", "40-49"] }, null, 1); + ctx.news.push({ title: `${cand.name}炮轟${opp.name},但拿不出證據,被批抹黑`, value: 4, candidateId: cand.id, townCode: null, topic: "smear", tone: "negative" }); + } + break; + } + case "rebuttal": { + const recent = self.scandalWeek !== null && state.week - self.scandalWeek <= 2; + applyEffect(ctx, ci, { stat: "favor", base: recent ? 0.02 : 0.003, scope: "city" }, null, 1); + ctx.news.push({ title: `${cand.name}召開記者會澄清`, value: recent ? 3 : 1, candidateId: cand.id, townCode: null, topic: "rebuttal", tone: "neutral" }); + break; + } + case "intel": { + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + const caught = rng.chance(0.06); + const p = state.candidates[opponent].secrets.length > 0 ? 0.5 : 0.15; + if (caught) { + applyEffect(ctx, ci, { stat: "favor", base: -0.01, scope: "city" }, null, 1); + ctx.news.push({ title: `${cand.name}陣營被爆雇用徵信社跟監對手`, value: 6, candidateId: cand.id, townCode: null, topic: "spy_caught", tone: "negative" }); + ctx.report(cand.id, "intel", "打探行動被抓包,上了新聞"); + } else if (rng.chance(p)) { + self.leverage[opp.id] = (self.leverage[opp.id] ?? 0) + 1; + ctx.report(cand.id, "intel", `打探到${opp.name}的把柄,可以用來爆料`); + } else { + const bracket = Math.round(state.candidates[opponent].money / 5_000_000) * 500; + ctx.report(cand.id, "intel", `沒有找到${opp.name}的把柄;估計對方資金約 ${bracket.toLocaleString()} 萬元`); + } + break; + } + case "internalPoll": + ctx.wantsInternalPoll.add(ci); + break; + case "voteBuying": { + if (town === null) break; + const votes = order.amount ?? 0; + self.boughtVotes[town] += votes; + self.secrets.push({ + id: `${cand.id}-vb-${state.week}-${town}`, + week: state.week, + kind: "voteBuying", + townIndex: town, + recipients: votes, + machines: Math.ceil(votes / 400), + candidateKnows: order.actor === "candidate", + exposed: false, + }); + ctx.report(cand.id, "action", `${vars.town}買了 ${votes.toLocaleString()} 票(投票日兌現,有人可能會講出去)`); + break; + } + case "trolls": { + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + if (rng.chance(0.12)) { + applyEffect(ctx, ci, { stat: "favor", base: -0.02, scope: "city" }, null, 1); + self.tags = [...new Set([...self.tags, "奧步"])]; + ctx.news.push({ title: `查核中心揭露攻擊${opp.name}的假訊息來自${cand.name}陣營外包`, value: 7, candidateId: cand.id, townCode: null, topic: "fact_check", tone: "negative", online: true }); + } else { + const shielded = state.candidates[opponent].bonus.shieldUntil >= state.week; + applyEffect(ctx, ci, { stat: "favor", base: shielded ? -0.006 : -0.012, scope: "city", ages: ["20-29", "30-39", "40-49"], onOpponent: true }, null, 1, opponent); + self.secrets.push({ id: `${cand.id}-tr-${state.week}-${opp.id}`, week: state.week, kind: "trolls", townIndex: null, recipients: 1, machines: 0, candidateKnows: false, exposed: false }); + ctx.news.push({ title: `網路出現大量批評${opp.name}的貼文`, value: 2, candidateId: opp.id, townCode: null, topic: "troll_posts", tone: "negative", online: true }); + } + break; + } + case "recruit": { + const recruited = Math.round(150 * (1 + 2 * Math.max(0, state.momentum[ci]))); + self.volunteers += recruited; + ctx.report(cand.id, "action", `招募到 ${recruited} 位義工`); + break; + } + case "flyers": + self.flyers += order.amount ?? 0; + break; + case "hireStaff": + if (self.staff.length < MAX_STAFF) { + const hired = staffMember(self.staff.length); + self.staff = [...self.staff, hired]; + ctx.report(cand.id, "action", `${hired.name}加入團隊,下週起可以排行程(週薪 ${money(hired.salary)})`); + } else { + ctx.report(cand.id, "action", `團隊已滿 ${MAX_STAFF} 位幕僚,沒有再找人`); + } + break; + case "buyout": { + // 搓圓仔湯:真實人物不收(不替真人捏造收賄),只有自創角色可能點頭;被拒絕時可能被對方抖出來 + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + const fictional = opp.personId === null && opp.id === "custom"; + const offer = order.amount ?? 0; + const willing = fictional && offer >= 5_000_000 && rng.chance(0.4); + if (willing) { + state.candidates[opponent].withdrawn = true; + ctx.news.push({ title: `${opp.name}突然宣布停止競選活動,名字仍會留在選票上`, value: 9, candidateId: opp.id, townCode: null, topic: "withdraw", tone: "neutral" }); + ctx.report(cand.id, "action", `${opp.name}收下條件,宣布停止競選`); + } else { + self.money += Math.round(offer * 0.9); + self.spent -= Math.round(offer * 0.9); + ctx.report(cand.id, "action", `${opp.name}陣營沒有接受,錢退回了大部分`); + if (rng.chance(0.35)) { + self.tags = [...new Set([...self.tags, "奧步"])]; + self.scandalWeek = state.week; + applyEffect(ctx, ci, { stat: "favor", base: -0.03, scope: "city" }, null, 1); + ctx.news.push({ title: `${opp.name}陣營指控有人出價勸退,矛頭指向${cand.name}陣營`, value: 9, candidateId: cand.id, townCode: null, topic: "buyout_exposed", tone: "negative" }); + } + } + self.secrets.push({ id: `${cand.id}-bo-${state.week}-${opp.id}`, week: state.week, kind: "buyout", label: "搓圓仔湯", townIndex: null, recipients: 6, machines: 2, candidateKnows: order.actor === "candidate", exposed: false }); + break; + } + case "frame": { + // 栽贓:新聞不點名(不替真人捏造買票),但對手的好感會受傷;知情者多,被揭穿就很慘 + if (opponent === null) break; + applyEffect(ctx, ci, { stat: "favor", base: -0.02, scope: "city", onOpponent: true }, null, 1, opponent); + ctx.news.push({ title: `${vars.town || "地方"}傳出有陣營買票的傳言,檢調表示會了解`, value: 4, candidateId: null, townCode: order.target, topic: "rumor", tone: "negative", online: true }); + self.secrets.push({ id: `${cand.id}-fr-${state.week}`, week: state.week, kind: "frame", label: "栽贓對手買票", townIndex: town, recipients: 40, machines: 4, candidateKnows: order.actor === "candidate", exposed: false }); + break; + } + case "inviteOath": { + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + const accepted = rng.chance(0.35); + if (accepted) { + state.candidates[opponent].oath = true; + applyEffect(ctx, ci, { stat: "favor", base: 0.006, scope: "city", ages: ["50-64", "65+"] }, null, 1); + ctx.news.push({ title: `${cand.name}、${opp.name}同台發誓,場面火爆`, value: 6, candidateId: cand.id, townCode: null, topic: "oath", tone: "neutral" }); + } else { + applyEffect(ctx, ci, { stat: "favor", base: -0.008, scope: "city", leans: ["middle"], onOpponent: true }, null, 1, opponent); + ctx.news.push({ title: `${cand.name}邀${opp.name}斬雞頭發誓,對方沒有回應`, value: 4, candidateId: cand.id, townCode: null, topic: "oath", tone: "neutral" }); + } + break; + } + case "reportProsecutor": { + // 向檢調檢舉:要有把柄才會受理;新聞只寫「遞交資料」,不寫對手有罪 + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + if ((self.leverage[opp.id] ?? 0) > 0) { + self.leverage[opp.id] -= 1; + applyEffect(ctx, ci, { stat: "favor", base: -0.025, scope: "city", onOpponent: true }, null, 1, opponent); + state.momentum[opponent] -= 0.04; + ctx.news.push({ title: `${cand.name}陣營向檢調遞交資料,要求調查選舉不法`, value: 7, candidateId: cand.id, townCode: null, topic: "report", tone: "neutral" }); + ctx.report(cand.id, "intel", `檢調受理了你遞交的資料,${opp.name}的選情受到影響`); + } else { + applyEffect(ctx, ci, { stat: "favor", base: -0.008, scope: "city", leans: ["middle"] }, null, 1); + ctx.news.push({ title: `${cand.name}陣營檢舉對手,被批拿不出證據`, value: 4, candidateId: cand.id, townCode: null, topic: "smear", tone: "negative" }); + ctx.report(cand.id, "intel", "手上沒有把柄,檢調沒有受理,還被批評濫告"); + } + break; + } + case "protestHq": { + // 到對手總部抗議:對手真的有負面標籤才站得住腳 + if (opponent === null) break; + const opp = scenario.candidates[opponent]; + const grounds = state.candidates[opponent].tags.some((t) => ["奧步", "檢調約談"].includes(t)); + if (grounds) { + applyEffect(ctx, ci, { stat: "favor", base: -0.015, scope: "city", onOpponent: true }, null, 1, opponent); + applyEffect(ctx, ci, { stat: "heat", base: 0.02, scope: "city", supportersOnly: true }, null, 1); + ctx.news.push({ title: `${cand.name}支持者到${opp.name}總部前抗議,要求說清楚`, value: 6, candidateId: opp.id, townCode: null, topic: "protest", tone: "negative" }); + } else { + applyEffect(ctx, ci, { stat: "favor", base: -0.01, scope: "city", leans: ["middle"] }, null, 1); + ctx.news.push({ title: `${cand.name}陣營到對手總部抗議,被批製造衝突`, value: 4, candidateId: cand.id, townCode: null, topic: "protest", tone: "negative" }); + } + break; + } + case "crisisPR": { + const had = self.tags.some((t) => ["奧步", "檢調約談", "財團"].includes(t)); + self.tags = self.tags.filter((t) => !["奧步", "財團"].includes(t)); + applyEffect(ctx, ci, { stat: "favor", base: had ? 0.015 : 0.002, scope: "city" }, null, 1); + ctx.news.push({ title: had ? `${cand.name}公開道歉並撤換相關人員` : `${cand.name}召開記者會說明`, value: had ? 5 : 1, candidateId: cand.id, townCode: null, topic: "rebuttal", tone: "neutral" }); + // 被撤換的人可能帶著祕密離開 + if (had && self.secrets.some((x) => !x.exposed) && rng.chance(0.2)) { + const holder = rng.pick(scenario.candidates.filter((c) => c.id !== cand.id)); + const hi = scenario.candidates.findIndex((c) => c.id === holder.id); + state.candidates[hi].leverage[cand.id] = (state.candidates[hi].leverage[cand.id] ?? 0) + 1; + ctx.report(cand.id, "leak", "被撤換的人很不滿,可能把內情告訴了對手"); + } + break; + } + case "factCheck": + self.bonus = { ...self.bonus, shieldUntil: state.week + 2 }; + ctx.report(cand.id, "action", "成立闢謠小組:接下來兩週,對手網軍的效果減半"); + break; + case "fireStaff": { + if (self.staff.length === 0) break; + const fired = self.staff[self.staff.length - 1]!; + self.staff = self.staff.slice(0, -1); + ctx.report(cand.id, "action", `${fired.name}離開團隊,下週起少一份薪水`); + if (self.secrets.some((x) => !x.exposed) && rng.chance(0.3)) { + const holder = rng.pick(scenario.candidates.filter((c) => c.id !== cand.id)); + const hi = scenario.candidates.findIndex((c) => c.id === holder.id); + state.candidates[hi].leverage[cand.id] = (state.candidates[hi].leverage[cand.id] ?? 0) + 1; + ctx.report(cand.id, "leak", `${fired.name}帶著陣營的祕密離開,可能已經告訴對手`); + } + break; + } + case "bigDonor": { + const raised = Math.round(cand.fundraising * (0.6 + 0.5 * rng.next())); + self.money += raised; + ctx.report(cand.id, "money", `拜訪企業主募得 ${money(raised)}`); + if (rng.chance(0.25)) { + self.tags = [...new Set([...self.tags, "財團"])]; + applyEffect(ctx, ci, { stat: "favor", base: -0.008, scope: "city", ages: ["20-29", "30-39"] }, null, 1); + ctx.news.push({ title: `${cand.name}密集拜訪企業主,被批「財團候選人」`, value: 4, candidateId: cand.id, townCode: null, topic: "big_donor", tone: "negative" }); + } + break; + } + case "partyFund": { + if (!cand.party) { + ctx.report(cand.id, "money", "無黨籍沒有政黨可以補助"); + break; + } + const granted = Math.round(Math.min(5_000_000, Math.max(800_000, cand.fundraising * 0.3))); + self.money += granted; + ctx.report(cand.id, "money", `${cand.party}補助 ${money(granted)},黨中央希望你配合黨的政策主軸`); + break; + } + case "partyElder": { + // 黨中央大咖站台:全國風向好時加分,風向差時扣分(執政包袱) + const mood = state.mood[cand.slot] ?? 0; + applyEffect(ctx, ci, { stat: "heat", base: 0.025, scope: "city", supportersOnly: true }, null, 1); + applyEffect(ctx, ci, { stat: "favor", base: mood >= 0 ? 0.008 : -0.01, scope: "city", leans: ["middle"] }, null, 1); + ctx.news.push({ title: `黨中央重量級人士到場為${cand.name}站台`, value: 5, candidateId: cand.id, townCode: order.target, topic: "party_elder", tone: mood >= 0 ? "positive" : "neutral" }); + break; + } + case "kneel": + self.tags = [...new Set([...self.tags, "下跪搶救"])]; + ctx.news.push({ title: `${cand.name}選前之夜下跪拜票,支持者淚灑會場`, value: 9, candidateId: cand.id, townCode: null, topic: "kneel", tone: "neutral" }); + break; + default: + break; + } + + if (action.outcome) applyOutcome(ctx, ci, action.outcome, town, opponent, vars, magnitude * scale, order.target, action.id); + if (action.gamble) { + const ok = rng.chance(action.gamble.chance); + applyOutcome(ctx, ci, ok ? action.gamble.success : action.gamble.failure, town, opponent, vars, magnitude * scale, order.target, action.id); + } + if (action.secret) { + self.secrets.push({ + id: `${cand.id}-${action.id}-${state.week}-${town ?? "c"}`, + week: state.week, + kind: action.secret.kind, + label: action.secret.label, + townIndex: town, + recipients: action.secret.insiders, + machines: 0, + candidateKnows: order.actor === "candidate", + exposed: false, + }); + } + + if (action.news && special !== "rally") { + ctx.news.push({ + title: fill(action.news.template, vars), + value: action.news.value * magnitude, + candidateId: cand.id, + targetId: order.opponentId ?? null, + townCode: order.target, + tone: action.news.tone ?? "positive", + topic: action.id, + merge: { key: `${action.id}|${order.target ?? ""}`, template: action.news.template, vars }, + }); + } + if (order.actor === "candidate" || action.visibility === "public") { + const who = member ? `${member.name}:` : ""; + ctx.report(cand.id, "action", `${who}${action.name}${vars.town ? `(${vars.town})` : ""}${vars.opponent ? `(對象:${vars.opponent})` : ""}`); + } +} + +/** 套用行動的結果(固定的或擲骰出來的)。magnitude 已含執行者、服務處、天氣、規模 */ +function applyOutcome( + ctx: ExecContext, + ci: number, + out: ActionOutcome, + town: number | null, + opponent: number | null, + vars: Record, + magnitude: number, + townCode: string | null, + art: string, +): void { + const { state, scenario, pack } = ctx; + const cand = scenario.candidates[ci]; + const self = state.candidates[ci]; + for (const e of out.effects ?? []) applyEffect(ctx, ci, e, town, magnitude, opponent); + if (out.momentum) state.momentum[ci] += out.momentum * Math.min(1.5, magnitude); + if (out.opponentMomentum && opponent !== null) state.momentum[opponent] += out.opponentMomentum; + const gained = (out.money ?? 0) + Math.round((out.fundraisingMultiple ?? 0) * cand.fundraising); + if (gained) self.money = Math.max(0, self.money + gained); + if (out.machine && town !== null) { + const idx = ci * pack.towns.length + town; + state.machine[idx] = Math.min(0.9, Math.max(0, state.machine[idx] + out.machine * magnitude)); + } + if (out.staminaMax) self.staminaMax = Math.min(130, self.staminaMax + out.staminaMax); + if (out.eloquence || out.gaffeReduction) { + self.bonus = { + ...self.bonus, + eloquence: Math.min(20, self.bonus.eloquence + (out.eloquence ?? 0)), + gaffe: Math.min(0.8, self.bonus.gaffe + (out.gaffeReduction ?? 0)), + }; + } + if (out.tag) { + self.tags = [...new Set([...self.tags, out.tag])]; + if (out.tag === "發誓") self.oath = true; + } + if (out.removeTags) self.tags = self.tags.filter((t) => !out.removeTags!.includes(t)); + if (out.report) ctx.report(cand.id, gained > 0 ? "money" : "action", fill(out.report, vars) + (gained > 0 ? `(${money(gained)})` : "")); + if (out.news) { + ctx.news.push({ + title: fill(out.news.template, vars), + value: out.news.value, + candidateId: cand.id, + townCode, + topic: "outcome", + art, + targetId: opponent !== null ? scenario.candidates[opponent]!.id : null, + tone: out.news.tone, + online: out.news.online, + }); + } +} diff --git a/backend/packages/engine/src/index.ts b/backend/packages/engine/src/index.ts new file mode 100644 index 0000000..c2a46e4 --- /dev/null +++ b/backend/packages/engine/src/index.ts @@ -0,0 +1,21 @@ +export * from "./types.ts"; +export * from "./rng.ts"; +export * from "./params.ts"; +export * from "./pack.ts"; +export * from "./voter.ts"; +export * from "./validate.ts"; +export * from "./turn.ts"; +export * from "./match.ts"; +export * from "./view.ts"; +export * from "./ai.ts"; +export * from "./election.ts"; +export * from "./polls.ts"; +export { weeklyLeakChance } from "./dark.ts"; +export * from "./autoplay.ts"; +export { mergeSimilar } from "./news.ts"; +export * from "./events.ts"; +export * from "./encounters.ts"; +export * from "./press.ts"; +export { intelView, townMeans } from "./intel.ts"; +export { COMBO_MAX, COMBO_STEP, COUNTER_BONUS, comboBonus, lastWeekVisits, mainRival, planTactics } from "./tactics.ts"; +export { STAFF_ROLES, staffRole } from "./staff.ts"; diff --git a/backend/packages/engine/src/intel.ts b/backend/packages/engine/src/intel.ts new file mode 100644 index 0000000..e1d0fe4 --- /dev/null +++ b/backend/packages/engine/src/intel.ts @@ -0,0 +1,57 @@ +import type { Intel } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, type PackData } from "./pack.ts"; +import type { MatchState } from "./types.ts"; + +/** + * 幕僚情報:各區成年人加權的平均知名度與好感。 + * 引擎存真實數字算漲跌,給玩家看的只有等級(docs/07:玩家看不到選民模型的真實數字)。 + */ +export function townMeans(state: MatchState, pack: PackData, ci: number): { aw: number[]; fv: number[] } { + const nCells = pack.cells.length; + const nTowns = pack.towns.length; + const aw = new Array(nTowns).fill(0); + const fv = new Array(nTowns).fill(0); + const w = new Array(nTowns).fill(0); + for (let i = 0; i < nCells; i++) { + const t = pack.villages[Math.floor(i / CELLS_PER_VILLAGE)]!.townIndex; + const n = pack.cells[i]!; + aw[t] += n * state.awareness[ci * nCells + i]!; + fv[t] += n * state.favor[ci * nCells + i]!; + w[t] += n; + } + return { aw: aw.map((x, t) => (w[t] ? x / w[t] : 0)), fv: fv.map((x, t) => (w[t] ? x / w[t] : 0)) }; +} + +/** 更新玩家的情報(這週的變成上週的) */ +export function refreshIntel(state: MatchState, pack: PackData, ci: number): void { + const cand = state.candidates[ci]; + const now = townMeans(state, pack, ci); + cand.intel = { aw: now.aw, fv: now.fv, prevAw: cand.intel?.aw ?? now.aw, prevFv: cand.intel?.fv ?? now.fv }; +} + +const AW_STEPS = [0.3, 0.5, 0.68, 0.82]; +const FV_STEPS = [-0.02, 0.0, 0.02, 0.045]; +const level = (x: number, steps: readonly number[]) => steps.filter((s) => x >= s).length; +const trend = (now: number, prev: number, eps: number) => (now - prev > eps ? 1 : prev - now > eps ? -1 : 0); + +/** 給玩家看的情報:等級 0–4 與漲跌 */ +export function intelView(state: MatchState, pack: PackData, ci: number): Intel | null { + const intel = state.candidates[ci]?.intel; + if (!intel) return null; + const weights = pack.towns.map((t) => t.adults); + const total = weights.reduce((a, b) => a + b, 0) || 1; + const mean = (xs: readonly number[]) => xs.reduce((s, x, t) => s + x * weights[t]!, 0) / total; + return { + reach: level(mean(intel.aw), AW_STEPS), + warmth: level(mean(intel.fv), FV_STEPS), + reachTrend: trend(mean(intel.aw), mean(intel.prevAw), 0.004), + warmthTrend: trend(mean(intel.fv), mean(intel.prevFv), 0.0015), + towns: pack.towns.map((t, i) => ({ + code: t.code, + reach: level(intel.aw[i]!, AW_STEPS), + warmth: level(intel.fv[i]!, FV_STEPS), + reachTrend: trend(intel.aw[i]!, intel.prevAw[i]!, 0.008), + warmthTrend: trend(intel.fv[i]!, intel.prevFv[i]!, 0.002), + })), + }; +} diff --git a/backend/packages/engine/src/match.ts b/backend/packages/engine/src/match.ts new file mode 100644 index 0000000..3e85344 --- /dev/null +++ b/backend/packages/engine/src/match.ts @@ -0,0 +1,107 @@ +import { CELLS_PER_VILLAGE, N_AGES, N_LEANS } from "./pack.ts"; +import { staffMember } from "./staff.ts"; +import { dealEvents } from "./events.ts"; +import { aggregate, computeVoteModel, shares } from "./voter.ts"; +import { refreshIntel } from "./intel.ts"; +import { drawPress } from "./press.ts"; +import type { CandidateGoal, MatchState } from "./types.ts"; +import type { World } from "./turn.ts"; + +/** 年齡層的知名度係數:長輩對傳統政治人物較熟 */ +const AGE_AWARENESS = [0.9, 0.95, 1.0, 1.04, 1.07]; + +/** 建立比賽的開局狀態(docs/11 createMatch) */ +export function createMatch(world: World, matchId: string, seed: number, playerId: string): MatchState { + const { scenario, pack, params } = world; + if (!scenario.candidates.some((c) => c.id === playerId)) throw new Error(`劇本中沒有候選人 ${playerId}`); + const nCand = scenario.candidates.length; + const nCells = pack.cells.length; + const nTowns = pack.towns.length; + const awareness = new Float32Array(nCand * nCells); + const favor = new Float32Array(nCand * nCells); + const heat = new Float32Array(nCand * nCells).fill(params.heatBaseline); + const machine = new Float32Array(nCand * nTowns); + + scenario.candidates.forEach((cand, ci) => { + for (let i = 0; i < nCells; i++) { + const k = i % CELLS_PER_VILLAGE; + const a = Math.floor(k / N_LEANS); + const l = k % N_LEANS; + const supporter = params.partyMatch[cand.slot][l] > 0 ? 0.05 : 0; + awareness[ci * nCells + i] = Math.min(0.98, cand.awareness * AGE_AWARENESS[a % N_AGES] + supporter); + } + machine.fill(cand.machine, ci * nTowns, (ci + 1) * nTowns); + }); + + const state: MatchState = { + matchId, + scenarioId: scenario.id, + seed, + week: 1, + phase: "campaign", + weather: "sunny", + playerId, + mood: { ...scenario.mood }, + awareness, + favor, + heat, + machine, + baseline: { awareness: awareness.slice(), machine: machine.slice() }, + momentum: scenario.candidates.map(() => 0), + candidates: scenario.candidates.map((c) => ({ + id: c.id, + money: c.startingMoney, + spent: 0, + wealth: c.wealth, + stamina: 100, + staminaMax: 100, + volunteers: 100, + flyers: 0, + offices: [], + staff: Array.from({ length: c.staff }, (_, i) => staffMember(i)), + issueIds: [], + leverage: {}, + tags: [], + secrets: [], + boughtVotes: new Array(nTowns).fill(0), + underInvestigation: false, + scandalWeek: null, + bonus: { eloquence: 0, gaffe: 0, shieldUntil: 0 }, + withdrawn: false, + oath: false, + event: null, + seenEvents: [], + goal: { kind: "win", target: 0.5 }, + press: [], + intel: null, + })), + news: [], + polls: [], + reports: Object.fromEntries(scenario.candidates.map((c) => [c.id, []])), + result: null, + log: [], + }; + dealEvents(world.content.events ?? [], scenario, state); + const goals = initialGoals(state, world); + const out = { ...state, candidates: state.candidates.map((c, ci) => ({ ...c, goal: goals[ci]! })) }; + const pi = scenario.candidates.findIndex((c) => c.id === playerId); + refreshIntel(out, pack, pi); + // 開場就有記者問:選戰剛開打,你最想說什麼 + out.candidates[pi]!.press = drawPress(world.content.press ?? [], scenario, out, playerId, [], null); + return out; +} + +/** + * 開局選情決定每個人的目標:前兩名、得票兩成以上的人要拚當選; + * 其他人的目標是把得票率拉到開局的 1.8 倍(3%–25%),達到就算「雖敗猶榮」。 + */ +export function initialGoals(state: MatchState, world: World): CandidateGoal[] { + const { scenario, pack, params } = world; + const share = shares(aggregate(computeVoteModel(state, scenario, pack, params, null), pack, scenario.candidates.length).votes); + const rank = share.map((s, i) => [s, i] as const).sort((a, b) => b[0] - a[0]).map(([, i]) => i); + return share.map((s, ci) => + rank.indexOf(ci) < 2 && s >= 0.2 + ? { kind: "win", target: 0.5 } + : { kind: "share", target: Math.round(Math.min(0.25, Math.max(0.03, s * 1.8 + 0.01)) * 1000) / 1000 }, + ); +} diff --git a/backend/packages/engine/src/news.ts b/backend/packages/engine/src/news.ts new file mode 100644 index 0000000..18a8c34 --- /dev/null +++ b/backend/packages/engine/src/news.ts @@ -0,0 +1,62 @@ +import type { NewsItem } from "@election2026/protocol"; +import type { NewsDraft } from "./execute.ts"; +import type { Rng } from "./rng.ts"; + +/** 版面有限:頭條 1、要聞 3、地方 5、網路熱議 3(docs/07) */ +const TIERS: { tier: NewsItem["tier"]; count: number }[] = [ + { tier: "headline", count: 1 }, + { tier: "main", count: 3 }, + { tier: "local", count: 5 }, +]; + +export function fill(template: string, vars: Record): string { + return template.replace(/\{(\w+)\}/g, (_, k: string) => vars[k] ?? ""); +} + +/** 同一週、同一種行動(同一區)的新聞合併成一則,新聞價值略高於其中最大的一則 */ +export function mergeSimilar(drafts: readonly NewsDraft[]): NewsDraft[] { + const out: NewsDraft[] = []; + const groups = new Map(); + for (const d of drafts) { + if (!d.merge) { + out.push(d); + continue; + } + const group = groups.get(d.merge.key); + if (group) group.push(d); + else { + groups.set(d.merge.key, [d]); + out.push(d); // 佔住第一則出現的位置,合併後替換 + } + } + return out.map((d) => { + const group = d.merge ? groups.get(d.merge.key) : undefined; + if (!group || group.length < 2) return d; + const names = [...new Set(group.map((g) => g.merge!.vars.name))]; + return { + ...d, + title: fill(d.merge!.template, { ...d.merge!.vars, name: names.join("、") }), + value: Math.max(...group.map((g) => g.value)) + 0.5 * (group.length - 1), + candidateId: names.length > 1 ? null : d.candidateId, + }; + }); +} + +export function layoutNews(input: readonly NewsDraft[], week: number, rng: Rng): NewsItem[] { + const drafts = mergeSimilar(input); + const scored = drafts.map((d, i) => ({ d, i, score: d.value * (0.85 + 0.3 * rng.next()) })); + const online = scored.filter((s) => s.d.online).sort((a, b) => b.score - a.score).slice(0, 3); + const rest = scored.filter((s) => !s.d.online).sort((a, b) => b.score - a.score); + const out: NewsItem[] = []; + let cursor = 0; + for (const { tier, count } of TIERS) { + for (const s of rest.slice(cursor, cursor + count)) { + out.push({ id: `n-${week}-${s.i}`, week, tier, title: s.d.title, candidateId: s.d.candidateId, townCode: s.d.townCode, tone: s.d.tone, topic: s.d.topic, targetId: s.d.targetId ?? null, art: s.d.art ?? null }); + } + cursor += count; + } + for (const s of online) { + out.push({ id: `n-${week}-${s.i}`, week, tier: "online", title: s.d.title, candidateId: s.d.candidateId, townCode: s.d.townCode, tone: s.d.tone, topic: s.d.topic, targetId: s.d.targetId ?? null, art: s.d.art ?? null }); + } + return out; +} diff --git a/backend/packages/engine/src/pack.ts b/backend/packages/engine/src/pack.ts new file mode 100644 index 0000000..08566e0 --- /dev/null +++ b/backend/packages/engine/src/pack.ts @@ -0,0 +1,146 @@ +import { + AGE_BANDS, + LEANS, + type CellsBlock, + type DataPackManifest, + type HistoryBlock, + type TownRecord, + type VillageRecord, +} from "@election2026/protocol"; + +export const N_AGES = AGE_BANDS.length; +export const N_LEANS = LEANS.length; +export const CELLS_PER_VILLAGE = N_AGES * N_LEANS; + +export interface VillageData { + code: string; + name: string; + townIndex: number; + adults: number; + electors: number; + baseTurnout: number; + density: number; + templesPer1000: number; +} + +export interface TownData { + code: string; + name: string; + adults: number; + electors: number; + villages: number[]; + hakkaShare: number | null; +} + +/** 引擎使用的資料包:由已解析的 JSON 建立,不讀檔(讀檔在伺服器與模擬工具) */ +export interface PackData { + packId: string; + countyCode: string; + partySlots: { a: string; b: string; c: string }; + villages: VillageData[]; + towns: TownData[]; + /** 每個選民群的成年人口,順序:村里 → 年齡 → 傾向 */ + cells: Float32Array; + history: HistoryBlock; + meanTemples: number; + meanDensity: number; +} + +export interface PackFiles { + manifest: DataPackManifest; + villages: VillageRecord[]; + towns: TownRecord[]; + cells: CellsBlock; + history: HistoryBlock; +} + +export interface PackOptions { + /** 遊戲裡的「區」:鄉鎮市區(預設),或縣市(總統選舉) */ + regionLevel?: "town" | "county"; + /** 只保留這些村里(立委選區) */ + villages?: ReadonlySet; +} + +/** 區的代碼:鄉鎮市區 8 碼;縣市層級用「縣市代碼+000」補成 8 碼 */ +export const regionCodeOf = (villageCode: string, level: "town" | "county" = "town"): string => + level === "county" ? `${villageCode.slice(0, 5)}000` : villageCode.slice(0, 8); + +export function buildPackData(input: PackFiles, options: PackOptions = {}): PackData { + const level = options.regionLevel ?? "town"; + const keep = options.villages; + const kept = keep ? input.villages.filter((v) => keep.has(v.code)) : input.villages; + const files: PackFiles = + level === "county" + ? { + ...input, + villages: kept.map((v) => ({ ...v, townCode: regionCodeOf(v.code, "county"), townName: v.countyName })), + towns: [...new Map(kept.map((v) => [regionCodeOf(v.code, "county"), v])).values()].map((v) => ({ + ...input.towns.find((t) => t.code === v.townCode)!, + code: regionCodeOf(v.code, "county"), + name: v.countyName, + hakkaShare: null, + })), + } + : { ...input, villages: kept, towns: input.towns.filter((t) => kept.some((v) => v.townCode === t.code)) }; + const townIndex = new Map(files.towns.map((t, i) => [t.code, i])); + const villages: VillageData[] = files.villages.map((v) => { + const t = townIndex.get(v.townCode); + if (t === undefined) throw new Error(`村里 ${v.code} 的區 ${v.townCode} 不在資料包中`); + return { + code: v.code, + name: v.name, + townIndex: t, + adults: v.population.adults, + electors: v.electors ?? v.population.adults, + baseTurnout: v.baseTurnout ?? 0.65, + density: v.attributes.densityPerKm2, + templesPer1000: v.attributes.templesPer1000, + }; + }); + const towns: TownData[] = files.towns.map((t) => ({ + code: t.code, + name: t.name, + adults: 0, + electors: 0, + villages: [], + hakkaShare: t.hakkaShare, + })); + villages.forEach((v, i) => { + const town = towns[v.townIndex]; + town.villages.push(i); + town.adults += v.adults; + town.electors += v.electors; + }); + const cells = new Float32Array(villages.length * CELLS_PER_VILLAGE); + villages.forEach((v, i) => { + const row = files.cells.values[v.code]; + if (!row) throw new Error(`村里 ${v.code} 沒有選民群資料`); + cells.set(row, i * CELLS_PER_VILLAGE); + }); + const totalAdults = villages.reduce((s, v) => s + v.adults, 0) || 1; + const weighted = (fn: (v: VillageData) => number) => villages.reduce((s, v) => s + fn(v) * v.adults, 0) / totalAdults; + return { + packId: files.manifest.packId, + countyCode: files.manifest.scope.countyCode, + partySlots: files.manifest.partySlots, + villages, + towns, + cells, + history: files.history, + meanTemples: weighted((v) => v.templesPer1000) || 1, + meanDensity: weighted((v) => v.density) || 1, + }; +} + +/** 某次歷史選舉在一群村里的各政黨得票率 */ +export function historicalShares(pack: PackData, electionId: string, villageIdx: readonly number[]): Record { + const totals: Record = {}; + let valid = 0; + for (const i of villageIdx) { + const r = pack.history.byVillage[pack.villages[i].code]?.[electionId]; + if (!r) continue; + valid += r.valid; + for (const [party, n] of Object.entries(r.votes)) totals[party] = (totals[party] ?? 0) + n; + } + return Object.fromEntries(Object.entries(totals).map(([p, n]) => [p, valid ? n / valid : 0])); +} diff --git a/backend/packages/engine/src/params.ts b/backend/packages/engine/src/params.ts new file mode 100644 index 0000000..3625490 --- /dev/null +++ b/backend/packages/engine/src/params.ts @@ -0,0 +1,59 @@ +import type { Lean, PartySlotKey } from "@election2026/protocol"; + +/** + * 選民模型參數(docs/03)。全部是初始值,以歷史回測校準(apps/sim backtest)。 + */ +export interface ModelParams { + betaParty: number; + betaFavor: number; + betaMachine: number; + betaMomentum: number; + betaMood: number; + betaViability: number; + tau: number; + considerA0: number; + considerSlope: number; + /** 各政黨傾向中,會依「誰有機會贏」調整投票的策略性選民比例 */ + strategicShare: Record; + kappa: number; + heatBaseline: number; + /** 年齡層投票率相對係數,依村里平均正規化 */ + ageTurnout: readonly number[]; + decay: { awareness: number; favor: number; heat: number; momentum: number; machine: number }; + /** 行動效果以這個成年人口數為基準,區越大、每人分到的效果越小 */ + refAdults: number; + reachExponent: number; + /** 政黨契合:槽位 × 傾向(順序同 LEANS) */ + partyMatch: Record; + invalidRate: number; + /** 買到的票真的照做的比例 */ + voteBuyingConversion: number; +} + +export const DEFAULT_PARAMS: ModelParams = { + betaParty: 2.0, + betaFavor: 1.5, + betaMachine: 0.6, + betaMomentum: 0.4, + betaMood: 1.0, + betaViability: 0.5, + tau: 1.0, + considerA0: 0.3, + considerSlope: 0.08, + strategicShare: { a_core: 0.05, a_lean: 0.25, middle: 0.35, b_lean: 0.25, b_core: 0.05, c_lean: 0.35 }, + kappa: 0.25, + heatBaseline: 0.3, + ageTurnout: [0.82, 0.88, 0.98, 1.08, 1.06], + decay: { awareness: 0.02, favor: 0.1, heat: 0.15, momentum: 0.25, machine: 0.05 }, + refAdults: 150_000, + reachExponent: 0.4, + // LEANS 順序:a_core, a_lean, middle, b_lean, b_core, c_lean + partyMatch: { + a: [1.0, 0.55, 0, -0.55, -1.0, -0.35], + b: [-1.0, -0.55, 0, 0.55, 1.0, -0.25], + c: [-0.6, -0.15, 0.25, -0.15, -0.6, 1.0], + other: [-0.3, -0.1, 0.1, -0.1, -0.3, -0.1], + }, + invalidRate: 0.015, + voteBuyingConversion: 0.7, +}; diff --git a/backend/packages/engine/src/polls.ts b/backend/packages/engine/src/polls.ts new file mode 100644 index 0000000..80a2646 --- /dev/null +++ b/backend/packages/engine/src/polls.ts @@ -0,0 +1,69 @@ +import type { Poll } from "@election2026/protocol"; +import type { PackData } from "./pack.ts"; +import type { Rng } from "./rng.ts"; +import type { MatchState, Scenario } from "./types.ts"; +import { aggregate, shares, type VoteModel } from "./voter.ts"; + +/** 公開民調機構:各有固定的機構效應(docs/07);名稱為示意,正式版改用真實機構並附出處 */ +export const POLLSTERS = [ + { name: "民調機構甲", house: { a: 0.015, b: -0.01, c: 0, other: 0 } }, + { name: "民調機構乙", house: { a: -0.01, b: 0.015, c: 0, other: 0 } }, +] as const; + +/** 由選民模型產生民調:真實支持率 + 機構效應 + 抽樣誤差 + 未表態 */ +export function makePoll( + state: MatchState, + scenario: Scenario, + pack: PackData, + model: VoteModel, + rng: Rng, + kind: "public" | "internal", + owner: string | null, +): Poll & { owner: string | null } { + const nCand = scenario.candidates.length; + const agg = aggregate(model, pack, nCand); + const truth = shares(agg.votes); + const pollster = kind === "public" ? POLLSTERS[state.week % POLLSTERS.length] : null; + const n = kind === "public" ? 1_068 : 2_000; + const weeksLeft = scenario.weeks - state.week; + const undecided = Math.max(0.06, 0.1 + 0.012 * weeksLeft + rng.normal(0, 0.01)); + const noisy = truth.map((p, c) => { + const house = pollster ? pollster.house[scenario.candidates[c].slot] : 0; + return Math.max(0.005, p + house + rng.normal(0, Math.sqrt((p * (1 - p)) / n))); + }); + const total = noisy.reduce((a, b) => a + b, 0); + const pollShares = Object.fromEntries( + scenario.candidates.map((c, i) => [c.id, Math.round(((noisy[i] / total) * (1 - undecided)) * 1000) / 1000]), + ); + let byTown: Poll["byTown"] = null; + if (kind === "internal") { + byTown = Object.fromEntries( + pack.towns.map((t, ti) => { + const townShares = shares(agg.byTown[ti]); + const sd = Math.sqrt(0.25 / Math.max(80, (n * t.adults) / (agg.voters || 1))); + return [t.code, Object.fromEntries(scenario.candidates.map((c, i) => [c.id, Math.max(0, townShares[i] + rng.normal(0, sd))]))]; + }), + ); + } + return { + id: `${kind}-${state.week}-${owner ?? pollster?.name ?? ""}`, + week: state.week, + kind, + pollster: pollster?.name ?? "內參民調", + sampleSize: n, + marginOfError: Math.round(196 * Math.sqrt(0.25 / n) * 10) / 10, + shares: pollShares, + undecided: Math.round(undecided * 1000) / 1000, + byTown, + owner, + }; +} + +/** 被認知的勝選機率:最近一次公開民調中,各候選人相對領先者的比例(棄保的依據) */ +export function perceivedViability(state: MatchState, scenario: Scenario): number[] | null { + const last = [...state.polls].reverse().find((p) => p.kind === "public"); + if (!last) return null; + const values = scenario.candidates.map((c) => last.shares[c.id] ?? 0); + const max = Math.max(...values, 0.01); + return values.map((v) => v / max); +} diff --git a/backend/packages/engine/src/press.ts b/backend/packages/engine/src/press.ts new file mode 100644 index 0000000..cb6f6cb --- /dev/null +++ b/backend/packages/engine/src/press.ts @@ -0,0 +1,145 @@ +import type { NewsItem, Poll } from "@election2026/protocol"; +import { applyOptionOutcome, type EventOption } from "./events.ts"; +import type { ExecContext } from "./execute.ts"; +import { makeRng } from "./rng.ts"; +import type { MatchState, Scenario } from "./types.ts"; + +/** + * 記者堵麥(docs/07):上週跟你有關的新聞,記者追問你要怎麼回應。 + * 新聞不再只是看的東西:被攻擊要不要反擊、對手出包要不要追打、民調落後要不要喊棄保,都是選擇。 + * 只有玩家有:AI 控制的真實人物如果也回應,等於替真人捏造發言(docs/14)。 + */ + +export type PressTrigger = "attacked" | "own_scandal" | "opp_scandal" | "my_win" | "rival_win" | "poll_behind" | "poll_lead" | "quiet"; + +export interface PressOption extends EventOption { + /** 選項下方的一行代價與效果說明 */ + hint: string; +} + +export interface PressDef { + id: string; + trigger: PressTrigger; + /** 記者的提問;{opponent}、{leader}、{weeksLeft} 會換掉 */ + question: string; + options: readonly PressOption[]; + /** 不回應時套用的選項 */ + fallback: string; +} + +export interface PendingPress { + key: string; + defId: string; + trigger: PressTrigger; + /** 被點名的對手(候選人 id) */ + opponent: string | null; + headline: string | null; + vars: Record; +} + +/** 優先順序:自己的負面新聞最急,其次是被攻擊、民調,最後才是好消息 */ +const PRIORITY: readonly PressTrigger[] = ["own_scandal", "attacked", "poll_behind", "poll_lead", "opp_scandal", "my_win", "rival_win"]; +const MAX_QUESTIONS = 2; + +/** 回應記者的新聞配圖 */ +const PRESS_ART: Record = { + attacked: "rebuttal_press", + own_scandal: "crisis_pr", + opp_scandal: "press_conference", + my_win: "rally", + rival_win: "rally", + poll_behind: "internal_poll", + poll_lead: "internal_poll", + quiet: "interview", +}; + +interface Hit { + trigger: PressTrigger; + opponent: string | null; + headline: string | null; +} + +/** 從這週的新聞與民調找出記者會追問的事 */ +export function pressHits(scenario: Scenario, state: MatchState, me: string, news: readonly NewsItem[], poll: Poll | null): Hit[] { + const hits: Hit[] = []; + const others = new Set(scenario.candidates.filter((c) => c.id !== me && !state.candidates.find((x) => x.id === c.id)?.withdrawn).map((c) => c.id)); + for (const n of news) { + // 自己回應記者產生的新聞已經處理過,不再連環追問 + if (n.candidateId === me && n.topic?.startsWith("press:")) continue; + if (n.targetId === me && n.candidateId && n.candidateId !== me) hits.push({ trigger: "attacked", opponent: n.candidateId, headline: n.title }); + else if (n.candidateId === me && n.tone === "negative") hits.push({ trigger: "own_scandal", opponent: null, headline: n.title }); + else if (n.candidateId && others.has(n.candidateId) && n.tone === "negative" && n.targetId !== me) + hits.push({ trigger: "opp_scandal", opponent: n.candidateId, headline: n.title }); + else if (n.candidateId === me && n.tone === "positive" && (n.tier === "headline" || n.tier === "main")) + hits.push({ trigger: "my_win", opponent: null, headline: n.title }); + else if (n.candidateId && others.has(n.candidateId) && n.tone === "positive" && n.tier === "headline") + hits.push({ trigger: "rival_win", opponent: n.candidateId, headline: n.title }); + } + if (poll) { + const ranked = Object.entries(poll.shares).sort((a, b) => b[1] - a[1]); + const leader = ranked[0]?.[0] ?? null; + if (leader === me) hits.push({ trigger: "poll_lead", opponent: ranked[1]?.[0] ?? null, headline: null }); + else if (leader) hits.push({ trigger: "poll_behind", opponent: leader, headline: null }); + } + return hits; +} + +/** 抽這週的提問:依優先順序取不同種類的事,最多兩題;什麼都沒發生就問一題平靜週的 */ +export function drawPress(defs: readonly PressDef[], scenario: Scenario, state: MatchState, me: string, news: readonly NewsItem[], poll: Poll | null): PendingPress[] { + if (defs.length === 0) return []; + const hits = pressHits(scenario, state, me, news, poll); + const chosen: Hit[] = []; + for (const t of PRIORITY) { + const hit = hits.find((h) => h.trigger === t); + if (hit && chosen.length < MAX_QUESTIONS) chosen.push(hit); + } + if (chosen.length === 0) chosen.push({ trigger: "quiet", opponent: null, headline: null }); + const rng = makeRng(state.seed, "press", me, state.week); + const nameOf = (id: string | null) => scenario.candidates.find((c) => c.id === id)?.name ?? "對手"; + return chosen.flatMap((hit, i) => { + const pool = defs.filter((d) => d.trigger === hit.trigger); + if (pool.length === 0) return []; + const def = rng.pick(pool); + const vars = { + opponent: nameOf(hit.opponent), + leader: nameOf(hit.opponent), + weeksLeft: String(Math.max(1, scenario.weeks - state.week)), + }; + return [{ key: `p${state.week}-${i}`, defId: def.id, trigger: hit.trigger, opponent: hit.opponent, headline: hit.headline, vars }]; + }); +} + +export const fillPress = (text: string, vars: Record) => text.replace(/\{(\w+)\}/g, (_, k: string) => vars[k] ?? ""); + +/** 結算玩家對上週提問的回應(沒回應就套用不回應) */ +export function resolvePress(ctx: ExecContext, defs: readonly PressDef[], ci: number, replies: Readonly>): void { + const { state, scenario } = ctx; + const cand = state.candidates[ci]; + const pending = cand.press; + cand.press = []; + const byId = new Map(defs.map((d) => [d.id, d])); + const name = scenario.candidates[ci].name; + for (const q of pending) { + const def = byId.get(q.defId); + if (!def) continue; + const wanted = replies[q.key] ?? def.fallback; + const option = def.options.find((o) => o.id === wanted) ?? def.options.find((o) => o.id === def.fallback)!; + const oi = q.opponent ? scenario.candidates.findIndex((c) => c.id === q.opponent) : -1; + const { outcome, rolled } = applyOptionOutcome(ctx, ci, option, oi >= 0 ? oi : null); + const vars = { ...q.vars, name }; + ctx.report(cand.id, "event", `記者追問「${fillPress(def.question, vars)}」:你選了「${option.label}」。${fillPress(outcome.text, vars)}${rolled}`); + const news = outcome.news ?? option.outcome.news; + if (news) { + ctx.news.push({ + title: fillPress(news.title, vars), + value: 5, + candidateId: cand.id, + targetId: q.opponent, + townCode: null, + topic: `press:${q.trigger}`, + art: PRESS_ART[q.trigger], + tone: news.tone, + }); + } + } +} diff --git a/backend/packages/engine/src/rng.ts b/backend/packages/engine/src/rng.ts new file mode 100644 index 0000000..6ee77ce --- /dev/null +++ b/backend/packages/engine/src/rng.ts @@ -0,0 +1,50 @@ +/** + * 決定性亂數:同樣的種子與標籤一定產生同樣的序列(docs/11:規則程式碼內不准使用 Math.random)。 + */ + +function fnv1a(text: string): number { + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + return hash >>> 0; +} + +export interface Rng { + next(): number; + normal(mean?: number, sd?: number): number; + int(maxExclusive: number): number; + chance(p: number): boolean; + pick(items: readonly T[]): T; +} + +/** mulberry32,再以 FNV-1a 把標籤混進種子 */ +export function makeRng(seed: number, ...labels: (string | number)[]): Rng { + let state = (seed ^ fnv1a(labels.join("|"))) >>> 0; + const next = (): number => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + return { + next, + normal(mean = 0, sd = 1) { + const u = Math.max(next(), 1e-12); + const v = next(); + return mean + sd * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); + }, + int(maxExclusive) { + return Math.floor(next() * maxExclusive); + }, + chance(p) { + return next() < p; + }, + pick(items) { + if (items.length === 0) throw new Error("不能從空清單中挑選"); + return items[Math.floor(next() * items.length)]; + }, + }; +} diff --git a/backend/packages/engine/src/staff.ts b/backend/packages/engine/src/staff.ts new file mode 100644 index 0000000..23671b0 --- /dev/null +++ b/backend/packages/engine/src/staff.ts @@ -0,0 +1,40 @@ +import type { StaffMember } from "./types.ts"; + +export interface StaffRole { + name: string; + skill: number; + /** 專長,一兩個字(卡牌角落顯示) */ + specialty: string; + /** 每週帶進手牌的專長牌(行動 id,都要能由幕僚執行) */ + deck: readonly string[]; +} + +/** 幕僚職稱、能力與專長牌,依序招募(docs/04)。都是遊戲角色,不對應真實人物 */ +export const STAFF_ROLES: readonly StaffRole[] = [ + { name: "競選總幹事", skill: 0.7, specialty: "調度", deck: ["small_donations", "recruit_volunteers", "investigate", "internal_poll", "party_fund", "hire_staff"] }, + { name: "組織部主任", skill: 0.6, specialty: "組織", deck: ["recruit_machine", "visit_associations", "weddings_funerals", "church_visit", "open_office", "gifts"] }, + { name: "文宣部主任", skill: 0.55, specialty: "文宣", deck: ["tv_ad", "radio_ad", "flags_billboards", "sound_truck", "print_flyers", "rebuttal_press"] }, + { name: "青年部主任", skill: 0.5, specialty: "網路", deck: ["online_ad", "line_groups", "night_market", "factory_visit", "fact_check"] }, + { name: "後援會會長", skill: 0.45, specialty: "後援", deck: ["phone_banking", "banquet", "homecoming", "volunteer_calls", "small_donations"] }, + { name: "義工隊長", skill: 0.4, specialty: "地面", deck: ["street_canvass", "volunteer_calls", "door_to_door", "market_visit", "print_flyers"] }, +]; + +/** 依幕僚代號(staff-N)找職位;找不到時當成最後一個職位 */ +export function staffRole(staffId: string): StaffRole { + const n = Number(staffId.replace(/^staff-/, "")); + return STAFF_ROLES[Number.isInteger(n) && n >= 1 ? (n - 1) % STAFF_ROLES.length : STAFF_ROLES.length - 1]!; +} + +export const MAX_STAFF = STAFF_ROLES.length; + +/** + * 每位幕僚的週薪。2022 桃園市長兩大黨候選人的政治獻金「人事費用支出」約 72–138 萬元, + * 以約 16 週、4–6 位專職人員估算,每人每週約 1.5 萬元。 + */ +export const STAFF_SALARY = 15_000; + +export function staffMember(index: number): StaffMember { + const role = STAFF_ROLES[index]; + if (!role) throw new Error(`幕僚最多 ${MAX_STAFF} 位`); + return { id: `staff-${index + 1}`, name: role.name, skill: role.skill, salary: STAFF_SALARY }; +} diff --git a/backend/packages/engine/src/tactics.ts b/backend/packages/engine/src/tactics.ts new file mode 100644 index 0000000..307df93 --- /dev/null +++ b/backend/packages/engine/src/tactics.ts @@ -0,0 +1,142 @@ +import type { Order } from "@election2026/protocol"; +import type { ExecContext, NewsDraft } from "./execute.ts"; +import type { ActionDef, MatchState, Scenario } from "./types.ts"; + +/** + * 戰術加成(docs/21):讓「怎麼打」比「打什麼」更重要。 + * - 組合拳:同一週在同一區打出不同的行程,這區的行程全部加成(兩種 +15%、三種 +30%、四種以上 +40%)。 + * - 打對台:到對手上週公開跑過的區跑地面、宮廟行程,效果 +30%。 + * 平衡報告(apps/sim balance):勢均力敵的桃園,懂戰術的打法勝率約 50%,一般 AI 打法約 20%。 + * 規則對所有陣營都一樣;前端用同樣的規則顯示加成(web/src/game/plan/tactics.ts)。 + */ +export const COMBO_STEP = 0.15; +export const COMBO_MAX = 0.4; +export const COUNTER_BONUS = 0.3; +const COUNTER_CATEGORIES: ReadonlySet = new Set(["ground", "ritual"]); + +export interface Visit { + ci: number; + townCode: string; + actionId: string; +} + +/** 公開、打在某一區的行程才算「去過」;祕密行動、午夜行動不算 */ +function isVisible(o: Order, action: ActionDef | undefined): action is ActionDef { + return !!action && o.target !== null && o.slot !== "midnight" && action.visibility !== "secret"; +} + +/** 上週各候選人「本人」公開跑過的區(每人每區一筆;幕僚代跑的不算,不然幾乎每區都有人去過) */ +export function lastWeekVisits(state: MatchState, scenario: Scenario, actions: ReadonlyMap): Visit[] { + const entry = state.log.find((l) => l.week === state.week - 1); + if (!entry) return []; + return scenario.candidates.flatMap((c, ci) => { + const seen = new Map(); + for (const o of entry.orders[c.id] ?? []) { + if (o.actor !== "candidate" || seen.has(o.target ?? "") || !isVisible(o, actions.get(o.actionId))) continue; + seen.set(o.target!, { ci, townCode: o.target!, actionId: o.actionId }); + } + return [...seen.values()]; + }); +} + +/** + * 主要對手:最近一次公開民調裡,除了自己以外最高的人;還沒有民調時,先看兩大黨的候選人。 + * 打對台只算主要對手的足跡,地圖上才不會到處都是對手去過的區。 + */ +export function mainRival(state: MatchState, scenario: Scenario, ci: number): number | null { + const rivals = scenario.candidates.map((c, i) => ({ c, i })).filter(({ i }) => i !== ci && !state.candidates[i]?.withdrawn); + if (rivals.length === 0) return null; + const poll = [...state.polls].reverse().find((p) => p.kind === "public"); + if (poll) return rivals.sort((a, b) => (poll.shares[b.c.id] ?? 0) - (poll.shares[a.c.id] ?? 0))[0]!.i; + return (rivals.find(({ c }) => c.slot === "a" || c.slot === "b") ?? rivals[0]!).i; +} + +export const comboBonus = (kinds: number): number => Math.min(COMBO_MAX, COMBO_STEP * Math.max(0, kinds - 1)); + +export interface Tactics { + /** 這筆行程的加成倍率(1 表示沒有加成) */ + multiplier: (ci: number, order: Order) => number; + /** 各陣營這週拿到的加成(給戰報) */ + notes: { ci: number; kind: "combo" | "counter"; townCode: string; bonus: number; kinds?: number; rival?: number; byCandidate?: boolean }[]; +} + +/** 依這週所有陣營排好的行程,算出每筆行程的組合拳、打對台加成 */ +export function planTactics(state: MatchState, scenario: Scenario, actions: ReadonlyMap, valid: readonly (readonly Order[])[]): Tactics { + const visits = lastWeekVisits(state, scenario, actions); + const kinds = valid.map((list) => { + const byTown = new Map>(); + for (const o of list) { + if (!isVisible(o, actions.get(o.actionId))) continue; + const set = byTown.get(o.target!) ?? new Set(); + set.add(o.actionId); + byTown.set(o.target!, set); + } + return byTown; + }); + // 主要對手本人上週來過這區 + const rivals = scenario.candidates.map((_, ci) => mainRival(state, scenario, ci)); + const rivalAt = (ci: number, town: string): Visit | undefined => visits.find((v) => v.ci === rivals[ci] && v.townCode === town); + + const notes: Tactics["notes"] = []; + kinds.forEach((byTown, ci) => { + for (const [town, set] of byTown) { + if (set.size >= 2) notes.push({ ci, kind: "combo", townCode: town, bonus: comboBonus(set.size), kinds: set.size }); + } + const countered = new Map(); + for (const o of valid[ci] ?? []) { + const action = actions.get(o.actionId); + if (!isVisible(o, action) || !COUNTER_CATEGORIES.has(action.category)) continue; + const rival = rivalAt(ci, o.target!); + if (!rival) continue; + const prev = countered.get(o.target!); + // 候選人本人去打對台才上新聞;幕僚代跑只有加成 + if (prev) countered.set(o.target!, { ...prev, byCandidate: prev.byCandidate || o.actor === "candidate" }); + else countered.set(o.target!, { ci, kind: "counter", townCode: o.target!, bonus: COUNTER_BONUS, rival: rival.ci, byCandidate: o.actor === "candidate" }); + } + notes.push(...countered.values()); + }); + + return { + notes, + multiplier: (ci, o) => { + const action = actions.get(o.actionId); + if (!isVisible(o, action)) return 1; + let m = 1 + comboBonus(kinds[ci]?.get(o.target!)?.size ?? 0); + if (COUNTER_CATEGORIES.has(action.category) && rivalAt(ci, o.target!)) m *= 1 + COUNTER_BONUS; + return m; + }, + }; +} + +const pctText = (x: number): string => `+${Math.round(x * 100)}%`; + +/** + * 把加成寫進戰報(每種最多三筆,幕僚代跑的行程很多時不洗版); + * 候選人本人去打對台的,上一則地方新聞。 + */ +export function reportTactics(ctx: ExecContext, tactics: Tactics, drafts: NewsDraft[]): void { + const { scenario, pack } = ctx; + const townName = (code: string) => pack.towns.find((t) => t.code === code)?.name ?? ""; + scenario.candidates.forEach((cand, ci) => { + const mine = tactics.notes.filter((n) => n.ci === ci); + for (const n of mine.filter((x) => x.kind === "combo").sort((a, b) => b.bonus - a.bonus).slice(0, 3)) { + ctx.report(cand.id, "tactic", `組合拳:${townName(n.townCode)}打出 ${n.kinds} 種行程,這區效果 ${pctText(n.bonus)}`); + } + const counters = mine.filter((x) => x.kind === "counter"); + for (const n of counters.slice(0, 3)) { + ctx.report(cand.id, "tactic", `打對台:${scenario.candidates[n.rival!]!.name}上週跑過${townName(n.townCode)},你的地面行程效果 ${pctText(n.bonus)}`); + } + const headline = counters.find((n) => n.byCandidate); + if (headline) { + drafts.push({ + title: `${cand.name}前進${townName(headline.townCode)},和${scenario.candidates[headline.rival!]!.name}打對台`, + value: 2, + candidateId: cand.id, + targetId: scenario.candidates[headline.rival!]!.id, + townCode: headline.townCode, + topic: "clash", + tone: "neutral", + }); + } + }); +} diff --git a/backend/packages/engine/src/turn.ts b/backend/packages/engine/src/turn.ts new file mode 100644 index 0000000..7d1144f --- /dev/null +++ b/backend/packages/engine/src/turn.ts @@ -0,0 +1,270 @@ +import { AGE_BANDS, SLOTS, type Order, type ReportItem } from "@election2026/protocol"; +import { rollLeaks } from "./dark.ts"; +import { weeklyUpkeep } from "./economy.ts"; +import { applyDecay } from "./effects.ts"; +import { runElectionDay } from "./election.ts"; +import { dealEvents, resolveEvents } from "./events.ts"; +import { executeOrder, type ExecContext, type NewsDraft } from "./execute.ts"; +import { layoutNews } from "./news.ts"; +import { CELLS_PER_VILLAGE, N_LEANS, type PackData } from "./pack.ts"; +import type { ModelParams } from "./params.ts"; +import { makePoll, perceivedViability } from "./polls.ts"; +import { makeRng } from "./rng.ts"; +import type { CandidateState, Content, MatchState, Scenario } from "./types.ts"; +import { validateOrders } from "./validate.ts"; +import { computeVoteModel } from "./voter.ts"; +import { refreshIntel } from "./intel.ts"; +import { drawPress, resolvePress } from "./press.ts"; +import { planTactics, reportTactics } from "./tactics.ts"; + +export interface World { + scenario: Scenario; + pack: PackData; + content: Content; + params: ModelParams; +} + +export interface TurnOutcome { + state: MatchState; + /** 候選人 id → 被剔除的指令與原因 */ + errors: Record; +} + +const STAMINA_REGEN = 25; +const PUBLIC_ACTORS = ["candidate", "team"] as const; + +function cloneCandidate(c: CandidateState): CandidateState { + return { + ...c, + offices: [...c.offices], + staff: c.staff.map((m) => ({ ...m })), + issueIds: [...c.issueIds], + leverage: { ...c.leverage }, + tags: [...c.tags], + secrets: c.secrets.map((s) => ({ ...s })), + boughtVotes: [...c.boughtVotes], + seenEvents: [...c.seenEvents], + bonus: { ...c.bonus }, + press: c.press.map((q) => ({ ...q, vars: { ...q.vars } })), + intel: c.intel && { aw: [...c.intel.aw], fv: [...c.intel.fv], prevAw: [...c.intel.prevAw], prevFv: [...c.intel.prevFv] }, + }; +} + +/** 深複製:resolveTurn 只在副本上運算,絕不修改輸入(docs/11 三條規則) */ +export function cloneState(s: MatchState): MatchState { + return { + ...s, + mood: { ...s.mood }, + awareness: s.awareness.slice(), + favor: s.favor.slice(), + heat: s.heat.slice(), + machine: s.machine.slice(), + momentum: [...s.momentum], + candidates: s.candidates.map(cloneCandidate), + news: [...s.news], + polls: [...s.polls], + reports: Object.fromEntries(Object.entries(s.reports).map(([k, v]) => [k, [...v]])), + log: [...s.log], + }; +} + +/** 黑馬加成:平均知名度 60% 以上沒有加成,越低越大,最多 1.5 倍(抽樣計算,避免全國地圖太慢) */ +export function underdogFactors(state: MatchState, nCells: number): number[] { + const stride = Math.max(1, Math.floor(nCells / 4000)); + return state.candidates.map((_, ci) => { + let sum = 0; + let n = 0; + for (let i = 0; i < nCells; i += stride) { + sum += state.awareness[ci * nCells + i]!; + n++; + } + const mean = n ? sum / n : 1; + return Math.min(1.5, Math.max(1, 1 + (0.6 - mean))); + }); +} + +/** 每週持續效果:服務處經營地方組織、主打政見吸引在意的族群 */ +function persistentEffects(state: MatchState, world: World): void { + const { pack, content } = world; + const nCells = pack.cells.length; + state.candidates.forEach((cand, ci) => { + for (const t of cand.offices) { + const idx = ci * pack.towns.length + t; + state.machine[idx] = Math.min(0.9, state.machine[idx] + 0.01); + } + const issues = content.issues.filter((i) => cand.issueIds.includes(i.id)); + if (issues.length === 0) return; + const perAge = AGE_BANDS.map((a) => issues.reduce((s, i) => s + i.appeal[a], 0) * 0.003); + for (let i = 0; i < nCells; i++) { + const a = Math.floor((i % CELLS_PER_VILLAGE) / N_LEANS); + const idx = ci * nCells + i; + state.favor[idx] = Math.min(1, state.favor[idx] + perAge[a] * (1 - Math.abs(state.favor[idx]))); + } + }); +} + +/** 突發事件(第一版只有天氣與全國風向;完整事件庫在 M6,docs/08) */ +function rollEvents(ctx: ExecContext, world: World): void { + const { state, rng } = ctx; + const r = rng.next(); + state.weather = r < 0.06 ? "typhoon" : r < 0.26 ? "rain" : "sunny"; + if (state.weather === "typhoon") { + ctx.news.push({ title: "颱風逼近,下週戶外活動恐受影響", value: 7, candidateId: null, townCode: null, topic: "typhoon", tone: "neutral" }); + } + if (rng.chance(0.08)) { + const slots = [...new Set(world.scenario.candidates.map((c) => c.slot).filter((s) => s === "a" || s === "b"))]; + if (slots.length) { + const slot = rng.pick(slots); + const party = slot === "a" ? world.pack.partySlots.a : world.pack.partySlots.b; + const delta = rng.chance(0.5) ? 0.04 : -0.04; + state.mood[slot] += delta; + ctx.news.push({ + title: delta > 0 ? `${party}中央政策獲好評,地方選情受惠` : `${party}中央政策爭議延燒,地方候選人受波及`, + value: 6, + candidateId: null, + townCode: null, + topic: "national_mood", tone: delta > 0 ? "positive" : "negative", + }); + } + } +} + +/** + * 結算一週(docs/02 的結算順序)。orders:候選人 id → 本週指令。 + * 選前之夜(phase = eve)結算後直接進行投票日與開票。 + */ +export function resolveTurn( + input: MatchState, + world: World, + orders: Record, + /** 表態事件的選擇:候選人 id → 選項 id;玩家沒選就套用事件的預設(不回應),AI 自己選 */ + eventChoices: Readonly> = {}, + /** 記者堵麥的回應:提問 key → 選項 id(只有玩家) */ + pressReplies: Readonly> = {}, +): TurnOutcome { + if (input.phase === "finished") return { state: input, errors: {} }; + const { scenario, pack, content, params } = world; + const state = cloneState(input); + const rng = makeRng(state.seed, "turn", state.week); + const actions = new Map(content.actions.map((a) => [a.id, a])); + const drafts: NewsDraft[] = []; + const weekReports: Record = Object.fromEntries(scenario.candidates.map((c) => [c.id, []])); + const ctx: ExecContext = { + pack, + scenario, + params, + state, + content, + rng, + news: drafts, + report: (id, kind, text) => weekReports[id]?.push({ kind, text, week: state.week }), + wantsInternalPoll: new Set(), + underdog: underdogFactors(state, pack.cells.length), + }; + + // 1. 自然衰退(第一週之後)與固定支出:先付固定支出,指令再用剩下的錢驗證;付不出來時先關服務處、再請幕僚離開 + if (state.week > 1) applyDecay(ctx, input.baseline.awareness, input.baseline.machine); + state.candidates.forEach((cand, ci) => { + const id = scenario.candidates[ci].id; + while (weeklyUpkeep(cand) > cand.money && (cand.offices.length > 0 || cand.staff.length > 0)) { + if (cand.offices.length > 0) { + const closed = cand.offices.pop()!; + ctx.report(id, "money", `付不出租金,${pack.towns[closed].name}服務處關閉`); + } else { + const left = cand.staff.pop()!; + ctx.report(id, "money", `付不出薪水,${left.name}離開團隊`); + } + } + const due = weeklyUpkeep(cand); + cand.money -= due; + cand.spent += due; + }); + + // 2. 驗證 + const errors: Record = {}; + const valid = scenario.candidates.map((c) => { + const v = validateOrders(state, scenario, pack, content, c.id, orders[c.id] ?? []); + if (v.errors.length) errors[c.id] = v.errors; + v.errors.forEach((e) => ctx.report(c.id, "cancelled", e)); + return v.orders; + }); + state.log = [...state.log, { week: state.week, orders: Object.fromEntries(scenario.candidates.map((c, i) => [c.id, valid[i]])) }]; + + + // 2.5 表態事件:先回應這週的事件,再出門跑行程 + resolveEvents(ctx, content.events ?? [], eventChoices, (id) => id === state.playerId); + const pi = scenario.candidates.findIndex((c) => c.id === state.playerId); + if (pi >= 0) resolvePress(ctx, content.press ?? [], pi, pressReplies); + + // 3. 依時段執行公開行動;同時段同區的候選人本人行程視為撞場;組合拳、打對台另外加成 + const tactics = planTactics(state, scenario, actions, valid); + reportTactics(ctx, tactics, drafts); + for (const slot of SLOTS) { + if (slot === "midnight") continue; + const here = valid.flatMap((list, ci) => list.filter((o) => o.slot === slot).map((o) => ({ o, ci }))); + for (const actor of PUBLIC_ACTORS) { + for (const { o, ci } of here.filter((x) => x.o.actor === actor)) { + const action = actions.get(o.actionId)!; + const clashed = + actor === "candidate" && + o.target !== null && + action.category === "ground" && + here.some((x) => x.ci !== ci && x.o.actor === "candidate" && x.o.target === o.target); + if (clashed && ci === Math.min(...here.filter((x) => x.o.target === o.target).map((x) => x.ci))) { + const title = `${pack.towns.find((t) => t.code === o.target)?.name}撞場:候選人同時段拜票`; + if (!drafts.some((d) => d.title === title)) drafts.push({ title, value: 1.5, candidateId: null, townCode: o.target, topic: "clash", tone: "neutral" }); + } + executeOrder(ctx, ci, o, action, (clashed ? 0.8 : 1) * tactics.multiplier(ci, o)); + } + } + } + // 4. 午夜:祕密行動 + valid.forEach((list, ci) => list.filter((o) => o.slot === "midnight").forEach((o) => executeOrder(ctx, ci, o, actions.get(o.actionId)!, 1))); + + // 5. 通風報信、持續效果、事件 + rollLeaks(ctx); + persistentEffects(state, world); + if (state.phase === "campaign") rollEvents(ctx, world); + + // 6. 新聞與民調 + state.news = [...state.news, ...layoutNews(drafts, state.week, rng)]; + const viability = perceivedViability(state, scenario); + const needModel = state.phase === "campaign" && (scenario.publicPollWeeks.includes(state.week) || ctx.wantsInternalPoll.size > 0); + if (needModel) { + const model = computeVoteModel(state, scenario, pack, params, viability); + if (scenario.publicPollWeeks.includes(state.week) && state.week < scenario.blackoutFromWeek) { + state.polls = [...state.polls, makePoll(state, scenario, pack, model, rng, "public", null)]; + } + for (const ci of ctx.wantsInternalPoll) { + state.polls = [...state.polls, makePoll(state, scenario, pack, model, rng, "internal", scenario.candidates[ci].id)]; + } + } + + // 6.5 幕僚情報與記者堵麥(只有玩家) + if (pi >= 0) { + refreshIntel(state, pack, pi); + if (state.phase === "campaign") { + const weekNews = state.news.filter((n) => n.week === state.week); + const poll = state.polls.find((p) => p.week === state.week && p.kind === "public") ?? null; + state.candidates[pi]!.press = drawPress(content.press ?? [], scenario, state, state.playerId, weekNews, poll); + } + } + + // 7. 體力恢復、報告、推進 + state.candidates.forEach((cand) => { + cand.stamina = Math.min(cand.staminaMax, cand.stamina + STAMINA_REGEN); + }); + state.reports = Object.fromEntries(scenario.candidates.map((c) => [c.id, weekReports[c.id]])); + + if (state.phase === "eve") { + state.result = runElectionDay(state, scenario, pack, params, makeRng(state.seed, "election")); + state.phase = "finished"; + } else if (state.week >= scenario.weeks) { + state.phase = "eve"; + state.week += 1; + } else { + state.week += 1; + dealEvents(content.events ?? [], scenario, state); + } + return { state, errors }; +} diff --git a/backend/packages/engine/src/types.ts b/backend/packages/engine/src/types.ts new file mode 100644 index 0000000..04272eb --- /dev/null +++ b/backend/packages/engine/src/types.ts @@ -0,0 +1,353 @@ +import type { PendingPress, PressDef } from "./press.ts"; +import type { EventDef } from "./events.ts"; +import type { + ActionInfo, + AgeBand, + AvatarSpecData, + ElectionResult, + Lean, + NewsItem, + Order, + PartySlotKey, + Poll, + ReportItem, +} from "@election2026/protocol"; + +/** 行動效果作用在哪個選民狀態(docs/03) */ +export type EffectStat = "awareness" | "favor" | "heat"; + +export interface ActionEffect { + stat: EffectStat; + /** 在一個約 15 萬成年人口的區、由候選人本人執行時的基準幅度 */ + base: number; + scope: "target" | "city"; + ages?: readonly AgeBand[]; + leans?: readonly Lean[]; + /** 只作用在支持者(政黨契合為正的選民群) */ + supportersOnly?: boolean; + /** 依村里屬性加權:宮廟密度、人口密度(越密越強)、低密度(越鄉下越強) */ + attr?: "temples" | "density" | "lowDensity"; + /** 作用在對手身上(負面效果) */ + onOpponent?: boolean; +} + +/** 需要程式邏輯的特殊效果;一般效果用 effects 描述(內容即資料,docs/05) */ +export type SpecialKind = + | "rally" + | "office" + | "machine" + | "tvAd" + | "onlineAd" + | "talkShow" + | "fundraiser" + | "smallDonations" + | "selfFund" + | "policy" + | "expose" + | "rebuttal" + | "intel" + | "internalPoll" + | "voteBuying" + | "trolls" + | "rest" + | "recruit" + | "flyers" + | "kneel" + | "hireStaff" + | "buyout" + | "frame" + | "inviteOath" + | "reportProsecutor" + | "protestHq" + | "crisisPR" + | "factCheck" + | "fireStaff" + | "bigDonor" + | "partyFund" + | "partyElder"; + +/** 行動的固定結果或擲骰結果(內容即資料,多數新行動只靠這個描述) */ +export interface ActionOutcome { + effects?: readonly ActionEffect[]; + /** 自己的聲勢 */ + momentum?: number; + /** 對手的聲勢(要指定對手的行動) */ + opponentMomentum?: number; + /** 錢的變化(元):固定數字,或依募款能力的倍數 */ + money?: number; + fundraisingMultiple?: number; + /** 地方組織(樁腳)變化,作用在目標區 */ + machine?: number; + staminaMax?: number; + /** 訓練:口才、失言機率 */ + eloquence?: number; + gaffeReduction?: number; + tag?: string; + removeTags?: readonly string[]; + /** 給自己看的戰報({name}、{town}、{opponent} 會被替換) */ + report?: string; + news?: { template: string; value: number; tone: "positive" | "neutral" | "negative"; online?: boolean }; +} + +export interface ActionDef extends ActionInfo { + effects: readonly ActionEffect[]; + special?: SpecialKind; + /** 一定會發生的結果(錢、組織、訓練、標籤…) */ + outcome?: ActionOutcome; + /** 結果要擲骰:chance 是 success 的機率,例如短影音爆紅、辦桌被檢舉 */ + gamble?: { chance: number; success: ActionOutcome; failure: ActionOutcome }; + /** 黑暗面:留下一筆祕密紀錄,知情者越多越容易有人講出去 */ + secret?: { kind: SecretKind; label: string; insiders: number }; + /** 只在這些選舉能用;沒寫就都能用 */ + kinds?: readonly ("mayor" | "legislator" | "president")[]; + /** 要有政黨才能用(例如請黨中央站台、申請政黨補助) */ + needsParty?: boolean; + /** 公開行動上新聞的標題樣板:{name} 候選人、{town} 區、{opponent} 對手 */ + news?: { template: string; value: number; tone?: "positive" | "neutral" | "negative" }; + /** 戶外活動,受天氣影響 */ + outdoor?: boolean; +} + +export interface IssueDef { + id: string; + name: string; + description: string; + /** 各年齡層對這個議題的在意程度(0–1) */ + appeal: Readonly>; +} + +export interface StaffMember { + id: string; + /** 職稱,例如「競選總幹事」;幕僚是遊戲角色,不是真實人物 */ + name: string; + /** 代替候選人執行時的效果倍率(設計文件 04:0.3–0.7) */ + skill: number; + /** 每週薪水(元) */ + salary: number; +} + +export interface ScenarioCandidate { + id: string; + name: string; + personId: string | null; + party: string | null; + slot: PartySlotKey; + number: number; + description: string; + /** 開局知名度(0–1) */ + awareness: number; + eloquence: number; + strategy: number; + startingMoney: number; + /** 可以自掏腰包的上限(元) */ + wealth: number; + /** 開局的地方組織強度(0–1) */ + machine: number; + /** 開局幕僚人數 */ + staff: number; + /** 個人魅力:效用的固定加分(由回測校準;無黨籍候選人的個人號召力主要靠這個) */ + appeal?: number; + /** 自創角色的捏臉設定;真實人物沒有 */ + avatar?: AvatarSpecData | null; + /** 總統選舉的副手(真實資料,或玩家選的虛構副手類型) */ + runningMate?: string | null; + /** 性別(中選會資料),給 Q 版頭像挑男女 */ + gender?: "m" | "f" | null; + /** 當年查證過的競選標語與出處 */ + slogan?: string | null; + sloganSource?: string | null; + /** + * 募款能力:每週辦一場募款餐會加上網路小額募款,預期募到的金額(元)。 + * 歷史劇本由真實的政治獻金收入推算(content 的 finance.ts)。 + */ + fundraising: number; + /** 歷史劇本:真實的政治獻金收支(元),給玩家對照 */ + realFinance: { income: number; spending: number } | null; + aiStyle: "balanced" | "ground" | "air" | "dirty"; +} + +/** 開局可以調的規則;劇本沒寫就照預設 */ +export interface ScenarioRules { + /** AI 難度:簡單的 AI 每週少跑三分之一行程,困難的 AI 錢比較多 */ + aiLevel: "easy" | "normal" | "hard"; + /** 關掉黑暗面:所有人都不能用違法行動 */ + noDark: boolean; + /** 關掉表態事件 */ + noEvents: boolean; +} + +export interface Scenario { + id: string; + rules?: ScenarioRules; + name: string; + description: string; + packId: string; + weeks: number; + /** 投票日(YYYY-MM-DD) */ + electionDate: string; + /** 投票前不得發布民調的週數起點(含) */ + blackoutFromWeek: number; + publicPollWeeks: readonly number[]; + spendingCap: number; + /** 全國風向:各政黨槽位的偏好分數加成(由歷史回測校準) */ + mood: Readonly>; + /** 給玩家看的「上一次選舉」;歷史劇本必須早於該次選舉,避免洩漏答案 */ + publicHistoryElection: string; + candidates: readonly ScenarioCandidate[]; + /** + * 歷史劇本的真實結果:partyToCandidate 從資料包的政黨得票對照(每黨一人時可用); + * byVillage 是候選人層級的各里得票(多位無黨籍時必須用這個)。 + */ + actual: { + electionId: string; + partyToCandidate?: Readonly>; + byVillage?: Readonly>>>; + } | null; + region: { + countyCode: string; + countyName: string; + office: string; + kind?: "mayor" | "legislator" | "president"; + area?: string; + regionLevel?: "town" | "county"; + /** 立委選區涵蓋的鄉鎮市區(給玩家看的文字) */ + scope?: string; + }; + /** 立委選區:只用資料包裡的這些村里 */ + villages?: readonly string[]; + hypothetical?: boolean; + /** 不在籍投票、檢舉獎金等法規開關(docs/01b) */ + bountyMultiplier: number; + /** 數字的出處,以及哪些是遊戲設定(給玩家看) */ + notes: readonly string[]; + sources: readonly { label: string; url: string }[]; + /** + * 投票率倍率:資料包的基本投票率是多次選舉的加權平均,地方選舉通常比總統大選低。 + * 歷史劇本由回測校準;新劇本以同類選舉的經驗值設定。 + */ + turnoutScale: number; +} + +export interface Content { + actions: readonly ActionDef[]; + issues: readonly IssueDef[]; + /** 表態事件(docs/08);沒有就不抽事件 */ + events?: readonly EventDef[]; + /** 拜票副本的遭遇 */ + encounters?: readonly EncounterDef[]; + /** 記者堵麥的提問 */ + press?: readonly PressDef[]; +} + +/** 副本裡一個選項的結果:score(-2 到 +2)累加成這次行程的效果倍率 */ +export interface EncounterResult { + score: number; + text: string; + momentum?: number; + stamina?: number; + money?: number; + tag?: string; + news?: { template: string; value: number; tone: "positive" | "neutral" | "negative" }; +} + +export interface EncounterOption extends EncounterResult { + id: string; + label: string; + /** 要擲骰的選項:chance 是 success 的機率 */ + roll?: { chance: number; success: EncounterResult; failure: EncounterResult }; +} + +/** 拜票副本的一個遭遇(虛構的路人與狀況) */ +export interface EncounterDef { + id: string; + /** 會在哪些行動出現(行動 id);"*" 是所有有副本的行動 */ + activities: readonly string[]; + who: string; + line: string; + options: readonly EncounterOption[]; +} + +export type SecretKind = "voteBuying" | "trolls" | "promise" | "smear" | "impersonate" | "frame" | "staged" | "slush" | "fakePoll" | "buyout"; + +export interface SecretRecord { + id: string; + week: number; + kind: SecretKind; + /** 通風報信時新聞用的說法,例如「期約賄選」;沒有就依 kind */ + label?: string; + townIndex: number | null; + /** 收錢的選民人數(買票)或外包數 */ + recipients: number; + machines: number; + candidateKnows: boolean; + exposed: boolean; +} + +export interface CandidateState { + id: string; + money: number; + spent: number; + wealth: number; + stamina: number; + staminaMax: number; + volunteers: number; + flyers: number; + offices: number[]; + staff: StaffMember[]; + issueIds: string[]; + leverage: Record; + tags: string[]; + secrets: SecretRecord[]; + /** 每個區買到的票數(投票日兌現) */ + boughtVotes: number[]; + underInvestigation: boolean; + scandalWeek: number | null; + /** 訓練加成:口才、失言機率的折扣、闢謠護盾到第幾週 */ + bonus: { eloquence: number; gaffe: number; shieldUntil: number }; + /** 被勸退(名字仍在選票上,但不再競選) */ + withdrawn: boolean; + /** 公開發過誓(斬雞頭、切結書):之後奧步被踢爆會加重 */ + oath: boolean; + /** 這週待回應的事件 id */ + event: string | null; + /** 已經抽過的事件(同一場不重複) */ + seenEvents: string[]; + /** 這場的目標:選情領先的人要當選;小候選人只要得票率超過 target 就算雖敗猶榮 */ + goal: CandidateGoal; + /** 待回應的記者提問(只有玩家有) */ + press: PendingPress[]; + /** 幕僚情報:各區的平均知名度、好感(這週與上週),只有玩家有 */ + intel: { aw: number[]; fv: number[]; prevAw: number[]; prevFv: number[] } | null; +} + +export interface CandidateGoal { + kind: "win" | "share"; + target: number; +} + +export interface MatchState { + matchId: string; + scenarioId: string; + seed: number; + week: number; + phase: "campaign" | "eve" | "finished"; + weather: "sunny" | "rain" | "typhoon"; + playerId: string; + mood: Record; + /** 候選人 × 選民群(候選人為外層) */ + awareness: Float32Array; + favor: Float32Array; + heat: Float32Array; + /** 候選人 × 區 */ + machine: Float32Array; + /** 開局值:知名度與地方組織往這裡衰退(不會被修改) */ + baseline: { awareness: Float32Array; machine: Float32Array }; + momentum: number[]; + candidates: CandidateState[]; + news: NewsItem[]; + /** owner 為 null 表示公開民調 */ + polls: (Poll & { owner: string | null })[]; + reports: Record; + result: ElectionResult | null; + log: { week: number; orders: Record }[]; +} diff --git a/backend/packages/engine/src/validate.ts b/backend/packages/engine/src/validate.ts new file mode 100644 index 0000000..aa1ec47 --- /dev/null +++ b/backend/packages/engine/src/validate.ts @@ -0,0 +1,167 @@ +import { SLOTS, type Order, type Slot } from "@election2026/protocol"; +import type { PackData } from "./pack.ts"; +import type { ActionDef, Content, MatchState, Scenario } from "./types.ts"; + +export interface Validated { + orders: Order[]; + errors: string[]; +} + +const SLOT_NAMES: Record = { + weekdayMorning: "平日早上", + weekdayAfternoon: "平日下午", + weekdayEvening: "平日晚上", + weekendMorning: "週末早上", + weekendAfternoon: "週末下午", + weekendEvening: "週末晚上", + midnight: "午夜", +}; + +/** 這筆指令的金額:固定成本 + 規模 × 單價 */ +export function orderCost(action: ActionDef, order: Order): number { + const per = action.amount ? (order.amount ?? 0) * action.amount.moneyPerUnit : 0; + return action.cost.money + Math.round(per); +} + +/** 佔用的時段:兩個時段的行動同時佔用前一個時段(例如造勢晚會佔週末下午與晚上) */ +export function occupiedSlots(action: ActionDef, slot: Slot): Slot[] { + if (action.duration === 1) return [slot]; + const i = SLOTS.indexOf(slot); + return i > 0 ? [SLOTS[i - 1], slot] : [slot]; +} + +/** + * 驗證一位候選人本週的指令。不合法的指令剔除並說明原因;合法的依原順序保留。 + * 錢、體力、法定經費上限依序累計檢查。 + */ +export function validateOrders( + state: MatchState, + scenario: Scenario, + pack: PackData, + content: Content, + candidateId: string, + orders: readonly Order[], +): Validated { + const ci = scenario.candidates.findIndex((c) => c.id === candidateId); + if (ci < 0) return { orders: [], errors: [`找不到候選人 ${candidateId}`] }; + const self = state.candidates[ci]; + const actions = new Map(content.actions.map((a) => [a.id, a])); + const towns = new Set(pack.towns.map((t) => t.code)); + const issues = new Set(content.issues.map((i) => i.id)); + const phase = state.phase === "eve" ? "eve" : "campaign"; + // 每個執行者(候選人本人、每位幕僚)各自的已佔用時段 + const used = new Map>(); + const staffById = new Map(self.staff.map((m) => [m.id, m])); + const ok: Order[] = []; + const errors: string[] = []; + let money = self.money; + let spent = self.spent; + let stamina = self.stamina; + + for (const order of orders) { + const action = actions.get(order.actionId); + const label = action ? `「${action.name}」(${SLOT_NAMES[order.slot]})` : `「${order.actionId}」`; + const reject = (why: string) => errors.push(`${label}:${why}`); + if (!action) { + reject("沒有這個行動"); + continue; + } + if (state.phase === "finished") { + reject("選舉已經結束"); + continue; + } + if (action.phase !== phase) { + reject(phase === "eve" ? "選前之夜只能做選前之夜的行動" : "這是選前之夜才能做的行動"); + continue; + } + if (!actionAvailable(action, scenario, ci)) { + reject(action.needsParty && !scenario.candidates[ci].party ? "無黨籍不能做這件事" : "這場選舉不能做這件事"); + continue; + } + if (!action.actors.includes(order.actor)) { + reject(order.actor === "candidate" ? "候選人本人不能做這件事" : "幕僚不能代替候選人做這件事"); + continue; + } + const member = order.staffId === null ? undefined : staffById.get(order.staffId); + if (order.actor === "candidate" ? order.staffId !== null : !member) { + reject(order.actor === "candidate" ? "候選人本人的行程不能指定幕僚" : "要指定一位團隊裡的幕僚"); + continue; + } + const performer = member?.id ?? "candidate"; + const busy = used.get(performer) ?? new Set(); + if (!action.slots.includes(order.slot)) { + reject("這個時段不能做"); + continue; + } + const slots = occupiedSlots(action, order.slot); + if (slots.some((s) => busy.has(s))) { + reject(`${member?.name ?? "候選人"}這個時段已經有行程`); + continue; + } + if (action.target === "town" && (!order.target || !towns.has(order.target))) { + reject("要選擇一個行政區"); + continue; + } + if (action.target !== "town" && order.target !== null) { + reject("這個行動不需要指定行政區"); + continue; + } + if (action.target === "opponent") { + const valid = scenario.candidates.some((c) => c.id === order.opponentId && c.id !== candidateId); + if (!valid) { + reject("要選擇一位對手"); + continue; + } + } + if (action.amount) { + const a = order.amount; + if (a === null || a < action.amount.min || a > action.amount.max || (a - action.amount.min) % action.amount.step) { + reject(`${action.amount.label}要在 ${action.amount.min}–${action.amount.max} 之間`); + continue; + } + } else if (order.amount !== null) { + reject("這個行動不需要設定規模"); + continue; + } + if (action.special === "policy") { + const ids = order.issueIds ?? []; + if (ids.length === 0 || ids.some((id) => !issues.has(id))) { + reject("要選擇 1–3 個議題"); + continue; + } + } + if (action.special === "selfFund" && (order.amount ?? 0) > self.wealth) { + reject(`個人財力只剩 ${self.wealth.toLocaleString()} 元`); + continue; + } + const cost = orderCost(action, order); + if (cost > money) { + reject(`錢不夠(需要 ${cost.toLocaleString()} 元,剩 ${money.toLocaleString()} 元)`); + continue; + } + if (spent + cost > scenario.spendingCap) { + reject("會超過法定競選經費上限(選罷法第 41 條)"); + continue; + } + if (order.actor === "candidate" && action.cost.stamina > stamina) { + reject(`候選人體力不夠(需要 ${action.cost.stamina},剩 ${stamina})`); + continue; + } + for (const s of slots) busy.add(s); + used.set(performer, busy); + money -= cost; + spent += cost; + if (order.actor === "candidate") stamina -= action.cost.stamina; + ok.push(order); + } + return { orders: ok, errors }; +} + +/** 這個行動在這場選舉、對這位候選人能不能用(選舉種類、要不要有政黨) */ +export function actionAvailable(action: ActionDef, scenario: Scenario, candidateIndex: number): boolean { + const kind = scenario.region.kind ?? "mayor"; + if (action.kinds && !action.kinds.includes(kind)) return false; + if (action.needsParty && !scenario.candidates[candidateIndex]?.party) return false; + if (scenario.rules?.noDark && action.category === "dark") return false; + return true; +} diff --git a/backend/packages/engine/src/view.ts b/backend/packages/engine/src/view.ts new file mode 100644 index 0000000..fdcdcb7 --- /dev/null +++ b/backend/packages/engine/src/view.ts @@ -0,0 +1,148 @@ +import { fillPress } from "./press.ts"; +import { intelView } from "./intel.ts"; +import { PROTOCOL_VERSION, type ActionInfo, type PlayerView } from "@election2026/protocol"; +import { weeklyUpkeep } from "./economy.ts"; +import { historicalShares } from "./pack.ts"; +import { actionAvailable } from "./validate.ts"; +import { staffRole } from "./staff.ts"; +import { lastWeekVisits, mainRival } from "./tactics.ts"; +import type { World } from "./turn.ts"; +import type { ActionDef, MatchState } from "./types.ts"; + +export function actionInfo(a: ActionDef): ActionInfo { + return { + id: a.id, + name: a.name, + category: a.category, + description: a.description, + slots: [...a.slots], + duration: a.duration, + actors: [...a.actors], + target: a.target, + cost: { ...a.cost }, + amount: a.amount ? { ...a.amount } : null, + visibility: a.visibility, + risk: a.risk, + phase: a.phase, + }; +} + +/** + * 從完整狀態切出某位候選人看得到的部分(docs/07)。 + * 不包含:其他陣營的資金細節、祕密行動、內參民調、把柄、選民模型的真實數值。 + */ +export function viewFor(state: MatchState, world: World, candidateId: string): PlayerView { + const { scenario, pack, content } = world; + const ci = scenario.candidates.findIndex((c) => c.id === candidateId); + if (ci < 0) throw new Error(`找不到候選人 ${candidateId}`); + const self = state.candidates[ci]; + const phase = state.phase === "eve" ? "eve" : "campaign"; + return { + protocolVersion: PROTOCOL_VERSION, + matchId: state.matchId, + scenarioId: scenario.id, + scenarioName: scenario.name, + // 劇本引用資料包的名稱(伺服器用它找地圖);含快照日期的完整 packId 在資料包 manifest 裡 + packId: scenario.packId, + week: Math.min(state.week, scenario.weeks + 1), + totalWeeks: scenario.weeks, + region: { + countyCode: scenario.region.countyCode, + countyName: scenario.region.countyName, + office: scenario.region.office, + kind: scenario.region.kind ?? "mayor", + area: scenario.region.area ?? scenario.region.countyName, + regionLevel: scenario.region.regionLevel ?? "town", + scope: scenario.region.scope ?? "", + }, + electionDate: scenario.electionDate, + phase: state.phase, + pollBlackout: state.week >= scenario.blackoutFromWeek, + weather: state.weather, + self: { + candidateId, + money: Math.round(self.money), + stamina: Math.round(self.stamina), + staminaMax: self.staminaMax, + volunteers: self.volunteers, + flyers: self.flyers, + officeTowns: self.offices.map((t) => pack.towns[t].code), + issueIds: [...self.issueIds], + leverage: { ...self.leverage }, + secretActions: self.secrets.length, + spendingCap: scenario.spendingCap, + spent: Math.round(self.spent), + staff: self.staff.map((m) => ({ ...m, specialty: staffRole(m.id).specialty, deck: [...staffRole(m.id).deck] })), + upkeep: weeklyUpkeep(self), + goal: { ...self.goal }, + bonus: { eloquence: self.bonus.eloquence, gaffe: self.bonus.gaffe }, + }, + candidates: scenario.candidates.map((c, i) => ({ + id: c.id, + name: c.name, + party: c.party, + slot: c.slot, + number: c.number, + isPlayer: c.id === candidateId, + description: c.description, + issueIds: [...state.candidates[i].issueIds], + tags: [...state.candidates[i].tags], + avatar: c.avatar ?? null, + runningMate: c.runningMate ?? null, + gender: c.gender ?? null, + slogan: c.slogan ?? null, + sloganSource: c.sloganSource ?? null, + })), + towns: pack.towns.map((t, ti) => ({ + code: t.code, + name: t.name, + adults: t.adults, + electors: t.electors, + lastShares: historicalShares(pack, scenario.publicHistoryElection, t.villages), + hakkaShare: t.hakkaShare, + hasOffice: self.offices.includes(ti), + })), + actions: content.actions.filter((a) => a.phase === phase && actionAvailable(a, scenario, ci)).map(actionInfo), + issues: content.issues.map((i) => ({ id: i.id, name: i.name, description: i.description })), + news: state.news.slice(-60), + polls: state.polls + .filter((p) => p.owner === null || p.owner === candidateId) + .map(({ owner: _owner, ...poll }) => poll), + report: [...(state.reports[candidateId] ?? [])], + result: state.result, + event: eventCard(world, self.event), + press: self.press.flatMap((q) => { + const def = world.content.press?.find((d) => d.id === q.defId); + if (!def) return []; + return [ + { + key: q.key, + trigger: q.trigger, + question: fillPress(def.question, q.vars), + headline: q.headline, + options: def.options.map((o) => ({ id: o.id, label: fillPress(o.label, q.vars), hint: fillPress(o.hint, q.vars), risky: o.roll !== undefined })), + fallback: def.fallback, + }, + ]; + }), + intel: intelView(state, pack, ci), + // 主要對手上週本人公開跑過的區(打對台用;公開行程本來就會上新聞,不算洩密) + rivalTrail: lastWeekVisits(state, scenario, new Map(content.actions.map((a) => [a.id, a]))) + .filter((v) => v.ci === mainRival(state, scenario, ci)) + .map((v) => ({ candidateId: scenario.candidates[v.ci]!.id, townCode: v.townCode, actionId: v.actionId })), + }; +} + +/** 待回應的事件:只給選項名稱,不透露效果(docs/12 玩家視角) */ +function eventCard(world: World, id: string | null): PlayerView["event"] { + const e = id ? world.content.events?.find((x) => x.id === id) : undefined; + if (!e) return null; + return { + id: e.id, + title: e.title, + body: e.body, + art: e.art, + options: e.options.map((o) => ({ id: o.id, label: o.label, risky: o.roll !== undefined })), + fallback: e.fallback, + }; +} diff --git a/backend/packages/engine/src/voter.ts b/backend/packages/engine/src/voter.ts new file mode 100644 index 0000000..3ade189 --- /dev/null +++ b/backend/packages/engine/src/voter.ts @@ -0,0 +1,135 @@ +import { LEANS } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, N_LEANS, type PackData } from "./pack.ts"; +import type { ModelParams } from "./params.ts"; +import type { MatchState, Scenario } from "./types.ts"; + +export interface VoteModel { + /** 候選人 × 選民群的投票機率(候選人為外層) */ + probs: Float32Array; + /** 每個選民群的投票率 */ + turnout: Float32Array; +} + +const sigmoid = (x: number): number => 1 / (1 + Math.exp(-x)); + +/** 每個村里的年齡層投票率係數,正規化成村里平均 = 1(保留歷史投票率) */ +function ageFactors(pack: PackData, params: ModelParams): Float32Array { + const out = new Float32Array(pack.cells.length); + for (let v = 0; v < pack.villages.length; v++) { + const base = v * CELLS_PER_VILLAGE; + let n = 0; + let weighted = 0; + for (let k = 0; k < CELLS_PER_VILLAGE; k++) { + const a = Math.floor(k / N_LEANS); + n += pack.cells[base + k]; + weighted += pack.cells[base + k] * params.ageTurnout[a]; + } + const norm = n > 0 ? weighted / n : 1; + for (let k = 0; k < CELLS_PER_VILLAGE; k++) { + out[base + k] = params.ageTurnout[Math.floor(k / N_LEANS)] / norm; + } + } + return out; +} + +const ageFactorCache = new WeakMap(); + +function cachedAgeFactors(pack: PackData, params: ModelParams): Float32Array { + const key = params.ageTurnout.join(","); + const hit = ageFactorCache.get(pack); + if (hit && hit.key === key) return hit.factors; + const factors = ageFactors(pack, params); + ageFactorCache.set(pack, { key, factors }); + return factors; +} + +/** + * 計算投票機率與投票率(docs/03 的投票公式)。 + * viability:被認知的勝選機率(來自最近一次公開民調),沒有時為 null(不計棄保)。 + */ +export function computeVoteModel( + state: MatchState, + scenario: Scenario, + pack: PackData, + params: ModelParams, + viability: readonly number[] | null, + weatherFactor = 1, +): VoteModel { + const nCand = scenario.candidates.length; + const nCells = pack.cells.length; + const probs = new Float32Array(nCand * nCells); + const turnout = new Float32Array(nCells); + const factors = cachedAgeFactors(pack, params); + const nTowns = pack.towns.length; + // 被勸退的候選人名字還在選票上,但支持者大多跑票 + const fixed = scenario.candidates.map( + (c, ci) => params.betaMomentum * state.momentum[ci] + params.betaMood * state.mood[c.slot] + (c.appeal ?? 0) - (state.candidates[ci]?.withdrawn ? 2.5 : 0), + ); + const logViability = viability?.map((v) => Math.log(Math.max(v, 0.02))) ?? null; + const sincere = new Float64Array(nCand); + const strategic = new Float64Array(nCand); + + for (let i = 0; i < nCells; i++) { + const v = Math.floor(i / CELLS_PER_VILLAGE); + const lean = i % N_LEANS; + const village = pack.villages[v]; + let sumS = 0; + let sumT = 0; + for (let c = 0; c < nCand; c++) { + const idx = c * nCells + i; + const slot = scenario.candidates[c].slot; + const u = + params.betaParty * params.partyMatch[slot][lean] + + params.betaFavor * state.favor[idx] + + params.betaMachine * state.machine[c * nTowns + village.townIndex] + + fixed[c]; + const w = sigmoid((state.awareness[idx] - params.considerA0) / params.considerSlope); + sincere[c] = w * Math.exp(u / params.tau); + strategic[c] = logViability ? w * Math.exp((u + params.betaViability * logViability[c]) / params.tau) : sincere[c]; + sumS += sincere[c]; + sumT += strategic[c]; + } + const sigma = params.strategicShare[LEANS[lean]]; + let heat = 0; + for (let c = 0; c < nCand; c++) { + const p = (1 - sigma) * (sincere[c] / sumS) + sigma * (strategic[c] / sumT); + probs[c * nCells + i] = p; + heat += p * state.heat[c * nCells + i]; + } + const t = + village.baseTurnout * scenario.turnoutScale * factors[i] * (1 + params.kappa * (heat - params.heatBaseline)) * weatherFactor; + turnout[i] = Math.min(0.97, Math.max(0.15, t)); + } + return { probs, turnout }; +} + +export interface Aggregate { + /** 候選人的預期得票 */ + votes: number[]; + voters: number; + /** 區 × 候選人 */ + byTown: number[][]; +} + +export function aggregate(model: VoteModel, pack: PackData, nCand: number): Aggregate { + const nCells = pack.cells.length; + const votes = new Array(nCand).fill(0); + const byTown = pack.towns.map(() => new Array(nCand).fill(0)); + let voters = 0; + for (let i = 0; i < nCells; i++) { + const t = pack.villages[Math.floor(i / CELLS_PER_VILLAGE)].townIndex; + const casting = pack.cells[i] * model.turnout[i]; + voters += casting; + for (let c = 0; c < nCand; c++) { + const n = casting * model.probs[c * nCells + i]; + votes[c] += n; + byTown[t][c] += n; + } + } + return { votes, voters, byTown }; +} + +export const shares = (votes: readonly number[]): number[] => { + const total = votes.reduce((a, b) => a + b, 0) || 1; + return votes.map((v) => v / total); +}; diff --git a/backend/packages/engine/test/engine.test.ts b/backend/packages/engine/test/engine.test.ts new file mode 100644 index 0000000..e7fac58 --- /dev/null +++ b/backend/packages/engine/test/engine.test.ts @@ -0,0 +1,278 @@ +import { PlayerView, type Order } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { + aiOrders, + autoplay, + createMatch, + playWeek, + resolveTurn, + validateOrders, + viewFor, + weeklyLeakChance, + mergeSimilar, + type MatchState, + type SecretRecord, + type World, +} from "../src/index.ts"; +import { TEST_SCENARIO, tinyWorld } from "./fixtures.ts"; + +const order = (o: Partial & Pick): Order => ({ + actor: "candidate", + staffId: o.actor === "team" ? "staff-1" : null, + target: null, + amount: null, + opponentId: null, + issueIds: null, + ...o, +}); + +function snapshot(state: MatchState): string { + return JSON.stringify(state, (_, v) => (v instanceof Float32Array ? Array.from(v) : v)); +} + +function playToEnd(world: World, seed: number, given: (state: MatchState) => Record = () => ({})) { + let state = createMatch(world, "m", seed, "alice"); + const errors: string[] = []; + while (state.phase !== "finished") { + const out = playWeek(state, world, given(state)); + Object.values(out.errors).forEach((e) => errors.push(...e)); + state = out.state; + } + return { state, errors }; +} + +describe("決定性與不可變", () => { + it("同樣的種子打出完全一樣的結果", () => { + const world = tinyWorld(); + expect(snapshot(autoplay(world, "m", 42))).toBe(snapshot(autoplay(world, "m", 42))); + }); + + it("不同種子會有不同的開票結果", () => { + const world = tinyWorld(); + expect(autoplay(world, "m", 1).result?.votes).not.toEqual(autoplay(world, "m", 2).result?.votes); + }); + + it("resolveTurn 不修改輸入的狀態", () => { + const world = tinyWorld(); + const state = createMatch(world, "m", 7, "alice"); + const before = snapshot(state); + const orders = { alice: aiOrders(state, world, "alice"), bob: aiOrders(state, world, "bob") }; + resolveTurn(state, world, orders); + expect(snapshot(state)).toBe(before); + }); +}); + +describe("指令驗證", () => { + const world = tinyWorld(); + const state = createMatch(world, "m", 1, "alice"); + const check = (orders: Order[]) => + validateOrders(state, world.scenario, world.pack, world.content, "alice", orders); + + it("接受合法的指令", () => { + const v = check([ + order({ actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }), + order({ actionId: "rally", slot: "weekendEvening", target: "68000020", amount: 3_000_000 }), + order({ actor: "team", actionId: "street_canvass", slot: "weekendAfternoon", target: "68000010" }), + ]); + expect(v.errors).toEqual([]); + expect(v.orders).toHaveLength(3); + }); + + it("剔除不合法的指令並說明原因", () => { + const v = check([ + order({ actionId: "no_such_action", slot: "weekdayMorning" }), + order({ actionId: "street_canvass", slot: "weekdayEvening", target: "68000010" }), + order({ actionId: "street_canvass", slot: "weekdayMorning", target: null }), + order({ actionId: "eve_rally", slot: "weekendEvening", target: "68000010", amount: 5_000_000 }), + order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 3_100_000 }), + order({ actor: "team", actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 3_000_000 }), + ]); + expect(v.orders).toEqual([]); + expect(v.errors).toHaveLength(6); + }); + + it("兩個時段的行動會佔用前一個時段", () => { + const v = check([ + order({ actionId: "street_canvass", slot: "weekendAfternoon", target: "68000010" }), + order({ actionId: "rally", slot: "weekendEvening", target: "68000020", amount: 3_000_000 }), + ]); + expect(v.orders).toHaveLength(1); + expect(v.errors[0]).toContain("已經有行程"); + }); + + it("錢不夠時剔除", () => { + const poor = { ...state, candidates: state.candidates.map((c) => ({ ...c, money: 1_500_000 })) }; + const v = validateOrders(poor, world.scenario, world.pack, world.content, "alice", [ + order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 1_000_000 }), + order({ actionId: "rally", slot: "weekdayEvening", target: "68000010", amount: 1_000_000 }), + ]); + expect(v.orders).toHaveLength(1); + expect(v.errors[0]).toContain("錢不夠"); + }); +}); + +describe("幕僚", () => { + const world = tinyWorld(); + const state = createMatch(world, "m", 1, "alice"); + const check = (orders: Order[]) => validateOrders(state, world.scenario, world.pack, world.content, "alice", orders); + + it("開局有劇本設定的幕僚人數,每位各有一排行程", () => { + expect(state.candidates[0].staff.map((m) => m.id)).toEqual(["staff-1", "staff-2"]); + const v = check([ + order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }), + order({ actor: "team", staffId: "staff-2", actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }), + order({ actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }), + ]); + expect(v.errors).toEqual([]); + }); + + it("同一位幕僚不能同時段兩個行程;團隊行動要指定存在的幕僚,候選人本人不能指定", () => { + const v = check([ + order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }), + order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }), + order({ actor: "team", staffId: "staff-9", actionId: "street_canvass", slot: "weekdayAfternoon", target: "68000020" }), + order({ actor: "team", staffId: null, actionId: "street_canvass", slot: "weekdayAfternoon", target: "68000020" }), + order({ staffId: "staff-1", actionId: "street_canvass", slot: "weekendMorning", target: "68000020" }), + ]); + expect(v.orders).toHaveLength(1); + expect(v.errors).toHaveLength(4); + }); + + it("找幕僚之後下週多一排行程,薪水算進每週固定支出", () => { + const next = resolveTurn(state, world, { alice: [order({ actionId: "hire_staff", slot: "weekdayMorning" })], bob: [] }).state; + expect(next.candidates[0].staff).toHaveLength(3); + const view = viewFor(next, world, "alice"); + expect(view.self.staff).toHaveLength(3); + expect(view.self.upkeep).toBe(3 * 15_000); + }); + + it("每週先付固定支出,再用剩下的錢驗證指令", () => { + const poor = { ...state, candidates: state.candidates.map((c) => ({ ...c, money: 1_020_000 })) }; + const rally = order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 1_000_000 }); + const out = resolveTurn(poor, world, { alice: [rally], bob: [] }); + expect(out.errors.alice?.[0]).toContain("錢不夠"); + expect(out.state.candidates[0].money).toBeGreaterThanOrEqual(0); + }); +}); + +describe("整場比賽", () => { + it("AI 對打可以跑完,AI 的指令全部合法", () => { + const { state, errors } = playToEnd(tinyWorld(), 3); + expect(state.phase).toBe("finished"); + expect(state.result).not.toBeNull(); + expect(errors).toEqual([]); + }); + + it("錢不會變負數,花費不超過法定上限", () => { + for (const seed of [1, 2, 3, 4, 5]) { + const end = autoplay(tinyWorld(), "m", seed); + for (const c of end.candidates) { + expect(c.money).toBeGreaterThanOrEqual(0); + expect(c.spent).toBeLessThanOrEqual(TEST_SCENARIO.spendingCap); + } + } + }); + + it("開票數字前後一致", () => { + const world = tinyWorld(); + const r = autoplay(world, "m", 9).result!; + const total = Object.values(r.votes).reduce((a, b) => a + b, 0); + expect(total).toBe(r.valid); + expect(r.ballots).toBeGreaterThanOrEqual(r.valid); + for (const id of Object.keys(r.votes)) { + const fromVillages = Object.values(r.byVillage).reduce((s, row) => s + row[id], 0); + const fromTowns = Object.values(r.byTown).reduce((s, row) => s + row[id], 0); + expect(fromVillages).toBe(r.votes[id]); + expect(fromTowns).toBe(r.votes[id]); + } + expect(r.votes[r.winnerId]).toBe(Math.max(...Object.values(r.votes))); + expect(r.countingOrder).toHaveLength(world.pack.villages.length); + }); + + it("階段依序推進:選戰 → 選前之夜 → 開票,結束後不再變動", () => { + const world = tinyWorld(); + let state = createMatch(world, "m", 5, "alice"); + for (let w = 1; w <= TEST_SCENARIO.weeks; w++) { + expect(state.phase).toBe("campaign"); + state = playWeek(state, world).state; + } + expect(state.phase).toBe("eve"); + state = playWeek(state, world).state; + expect(state.phase).toBe("finished"); + expect(resolveTurn(state, world, {}).state).toBe(state); + }); + + it("沒人檢舉時,買票確實會多拿票", () => { + const world = { ...tinyWorld(), scenario: { ...TEST_SCENARIO, bountyMultiplier: 0 } }; + const buy = (s: MatchState): Record => + s.phase === "campaign" && s.week === TEST_SCENARIO.weeks + ? { alice: [order({ actor: "team", actionId: "vote_buying", slot: "midnight", target: "68000010", amount: 2_000 })] } + : {}; + const clean = playToEnd(world, 11).state.result!; + const dirty = playToEnd(world, 11, buy).state.result!; + expect(dirty.votes.alice).toBeGreaterThan(clean.votes.alice + 1_000); + }); +}); + +describe("玩家視角", () => { + it("符合協定,且看不到別人的祕密與內參", () => { + const world = tinyWorld(); + let state = createMatch(world, "m", 13, "alice"); + const bobOrders: Order[] = [ + order({ actor: "team", actionId: "internal_poll", slot: "weekdayMorning" }), + order({ actor: "team", actionId: "vote_buying", slot: "midnight", target: "68000020", amount: 500 }), + ]; + state = resolveTurn(state, world, { alice: [], bob: bobOrders }).state; + const alice = viewFor(state, world, "alice"); + const bob = viewFor(state, world, "bob"); + expect(PlayerView.safeParse(alice).success).toBe(true); + expect(alice.polls.filter((p) => p.kind === "internal")).toEqual([]); + expect(bob.polls.filter((p) => p.kind === "internal")).toHaveLength(1); + expect(bob.polls[0].byTown).not.toBeNull(); + expect(bob.self.secretActions).toBe(1); + expect(alice.self.secretActions).toBe(0); + const text = JSON.stringify(alice); + for (const hidden of ["favor", "awareness", "boughtVotes", "secrets", "machine"]) expect(text).not.toContain(`"${hidden}"`); + expect(alice.report.some((r) => r.text.includes("買"))).toBe(false); + }); +}); + +describe("新聞", () => { + it("同一週、同一種行動的新聞合併成一則", () => { + const draft = (name: string, value: number) => ({ + title: `${name}發表主打政見`, + value, + candidateId: name, + townCode: null, + tone: "positive" as const, + topic: "announce_policy", + merge: { key: "announce_policy|", template: "{name}發表主打政見", vars: { name, town: "", opponent: "" } }, + }); + const merged = mergeSimilar([draft("甲", 4), { title: "颱風", value: 7, candidateId: null, townCode: null, tone: "neutral", topic: "typhoon" }, draft("乙", 4), draft("丙", 3)]); + expect(merged.map((d) => d.title)).toEqual(["甲、乙、丙發表主打政見", "颱風"]); + expect(merged[0].value).toBe(5); + expect(merged[0].candidateId).toBeNull(); + }); +}); + +describe("通風報信機率", () => { + const record = (recipients: number, machines: number): SecretRecord => ({ + id: "x", + week: 1, + kind: "voteBuying", + townIndex: 0, + recipients, + machines, + candidateKnows: false, + exposed: false, + }); + + it("買越多票越容易被檢舉", () => { + expect(weeklyLeakChance(record(5_000, 13), 3, 10, 1)).toBeGreaterThan(weeklyLeakChance(record(500, 2), 3, 10, 1)); + }); + + it("越接近投票日越危險,且有上限", () => { + expect(weeklyLeakChance(record(1_000, 3), 10, 10, 1)).toBeGreaterThan(weeklyLeakChance(record(1_000, 3), 3, 10, 1)); + expect(weeklyLeakChance(record(1_000_000, 3_000), 10, 10, 5)).toBeLessThanOrEqual(0.95); + }); +}); diff --git a/backend/packages/engine/test/events.test.ts b/backend/packages/engine/test/events.test.ts new file mode 100644 index 0000000..8ced422 --- /dev/null +++ b/backend/packages/engine/test/events.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { createMatch, playWeek, viewFor, type EventDef, type World } from "../src/index.ts"; +import { tinyWorld } from "./fixtures.ts"; + +const EVENTS: EventDef[] = [ + { + id: "rain", + title: "下雨", + body: "要不要出門?", + art: "x", + weight: 1, + fallback: "stay", + options: [ + { id: "go", label: "出門", outcome: { text: "淋濕了但很有誠意。", effects: [{ stat: "favor", base: 0.05, scope: "city" }], momentum: 0.05, news: { title: "{name}冒雨拜票", tone: "positive" } } }, + { id: "stay", label: "在家", outcome: { text: "沒事。" } }, + ], + }, + { id: "two", title: "第二個", body: "", art: "x", weight: 1, fallback: "a", options: [{ id: "a", label: "甲", outcome: { text: "甲。" } }, { id: "b", label: "乙", outcome: { text: "乙。", money: -10_000 } }] }, + { id: "three", title: "第三個", body: "", art: "x", weight: 1, fallback: "a", options: [{ id: "a", label: "甲", outcome: { text: "甲。" } }] }, +]; + +const world = (): World => { + const w = tinyWorld(); + return { ...w, content: { ...w.content, events: EVENTS } }; +}; + +describe("表態事件", () => { + it("開局就替每位候選人抽一張,玩家視角只看得到選項名稱", () => { + const w = world(); + const state = createMatch(w, "m", 1, "alice"); + expect(state.candidates.every((c) => c.event !== null)).toBe(true); + const view = viewFor(state, w, "alice"); + expect(view.event?.options.length).toBeGreaterThan(0); + expect(JSON.stringify(view.event)).not.toContain("effects"); + }); + + it("玩家的選擇會生效並寫進戰報;沒選就套用預設", () => { + const w = world(); + let state = createMatch(w, "m", 2, "alice"); + // 讓玩家這週拿到「下雨」 + state = { ...state, candidates: state.candidates.map((c) => (c.id === "alice" ? { ...c, event: "rain" } : c)) }; + const go = playWeek(state, w, { alice: [] }, { alice: "go" }).state; + const stay = playWeek(state, w, { alice: [] }, {}).state; + const report = (s: typeof go) => s.reports.alice!.find((r) => r.kind === "event")?.text ?? ""; + expect(report(go)).toContain("你選了「出門」"); + expect(report(stay)).toContain("你選了「在家」"); + expect(go.momentum[0]!).toBeGreaterThan(stay.momentum[0]!); + expect(go.news.some((n) => n.title.endsWith("冒雨拜票"))).toBe(true); + }); + + it("AI 候選人的表態不上新聞(不替真人捏造立場),但效果照算", () => { + const w = world(); + let state = createMatch(w, "m", 5, "alice"); + state = { ...state, candidates: state.candidates.map((c) => ({ ...c, event: "rain" })) }; + const out = playWeek(state, w, {}, { alice: "stay" }).state; + const others = state.candidates.filter((c) => c.id !== "alice").map((c) => c.id); + expect(out.news.some((n) => n.title.endsWith("冒雨拜票"))).toBe(false); + expect(others.every((id) => out.reports[id]!.some((r) => r.kind === "event"))).toBe(true); + }); + + it("同一場比賽不會抽到重複的事件;抽完就不再有事件", () => { + const w = world(); + let state = createMatch(w, "m", 3, "alice"); + const seen: string[] = []; + while (state.phase === "campaign") { + const id = state.candidates[0]!.event; + if (id) seen.push(id); + state = playWeek(state, w).state; + } + expect(new Set(seen).size).toBe(seen.length); + expect(seen.length).toBe(EVENTS.length); + }); + + it("不修改輸入的狀態", () => { + const w = world(); + const state = createMatch(w, "m", 4, "alice"); + const before = JSON.stringify(state.candidates); + playWeek(state, w, {}, { alice: "go" }); + expect(JSON.stringify(state.candidates)).toBe(before); + }); +}); diff --git a/backend/packages/engine/test/fixtures.ts b/backend/packages/engine/test/fixtures.ts new file mode 100644 index 0000000..7e1efd6 --- /dev/null +++ b/backend/packages/engine/test/fixtures.ts @@ -0,0 +1,201 @@ +import { CELLS_PER_VILLAGE, DEFAULT_PARAMS, type ActionDef, type Content, type PackData, type Scenario, type World } from "../src/index.ts"; + +/** 測試用的小資料包:兩個區、四個里,每個選民群 100 人 */ +export function tinyPack(): PackData { + const villages = [0, 1, 2, 3].map((i) => ({ + code: `680000${i < 2 ? "10" : "20"}00${i}`, + name: `第${i + 1}里`, + townIndex: i < 2 ? 0 : 1, + adults: 100 * CELLS_PER_VILLAGE, + electors: 100 * CELLS_PER_VILLAGE, + baseTurnout: 0.6, + density: 1_000 * (i + 1), + templesPer1000: 0.2 * (i + 1), + })); + const history = { + elections: [{ id: "prior", name: "上一次", date: "2020-01-11", office: "president" as const, weight: 1 }], + byVillage: Object.fromEntries( + villages.map((v, i) => [ + v.code, + { prior: { electors: 3_000, ballots: 1_800, valid: 1_780, votes: { 甲黨: 900 + 50 * i, 乙黨: 880 - 50 * i }, allocated: false } }, + ]), + ), + reconciliation: [], + }; + return { + packId: "tiny", + countyCode: "68000", + partySlots: { a: "甲黨", b: "乙黨", c: "丙黨" }, + villages, + towns: [ + { code: "68000010", name: "東區", adults: 6_000, electors: 6_000, villages: [0, 1], hakkaShare: null }, + { code: "68000020", name: "西區", adults: 6_000, electors: 6_000, villages: [2, 3], hakkaShare: 0.3 }, + ], + cells: new Float32Array(villages.length * CELLS_PER_VILLAGE).fill(100), + history, + meanTemples: 0.5, + meanDensity: 2_500, + }; +} + +const base = { + duration: 1 as const, + visibility: "public" as const, + risk: null, + phase: "campaign" as const, + amount: null, +}; + +export const TEST_ACTIONS: ActionDef[] = [ + { + ...base, + id: "street_canvass", + name: "掃街", + category: "ground", + description: "", + slots: ["weekdayMorning", "weekdayAfternoon", "weekendMorning", "weekendAfternoon"], + actors: ["candidate", "team"], + target: "town", + cost: { money: 30_000, stamina: 12 }, + effects: [ + { stat: "awareness", base: 0.05, scope: "target" }, + { stat: "favor", base: 0.01, scope: "target" }, + ], + }, + { + ...base, + id: "rally", + name: "造勢", + category: "ground", + description: "", + slots: ["weekdayEvening", "weekendEvening"], + duration: 2, + actors: ["candidate"], + target: "town", + cost: { money: 0, stamina: 20 }, + amount: { label: "規模", unit: "元", min: 1_000_000, max: 10_000_000, step: 500_000, default: 3_000_000, moneyPerUnit: 1 }, + special: "rally", + effects: [{ stat: "heat", base: 0.15, scope: "target", supportersOnly: true }], + }, + { + ...base, + id: "announce_policy", + name: "政見", + category: "policy", + description: "", + slots: ["weekdayMorning", "weekendMorning"], + actors: ["candidate"], + target: "city", + cost: { money: 100_000, stamina: 8 }, + special: "policy", + effects: [], + }, + { + ...base, + id: "internal_poll", + name: "內參", + category: "logistics", + description: "", + slots: ["weekdayMorning", "weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"], + actors: ["team"], + target: "city", + visibility: "secret", + cost: { money: 600_000, stamina: 0 }, + special: "internalPoll", + effects: [], + }, + { + ...base, + id: "investigate", + name: "打探", + category: "offense", + description: "", + slots: ["weekdayMorning", "weekdayAfternoon", "weekdayEvening", "weekendMorning", "weekendAfternoon", "weekendEvening"], + actors: ["team"], + target: "opponent", + visibility: "secret", + cost: { money: 500_000, stamina: 0 }, + special: "intel", + effects: [], + }, + { + ...base, + id: "vote_buying", + name: "買票", + category: "dark", + description: "", + slots: ["midnight"], + actors: ["team"], + target: "town", + visibility: "secret", + cost: { money: 0, stamina: 0 }, + amount: { label: "票數", unit: "票", min: 100, max: 20_000, step: 100, default: 1_000, moneyPerUnit: 1_000 }, + special: "voteBuying", + effects: [], + }, + { + ...base, + id: "hire_staff", + name: "找幕僚", + category: "logistics", + description: "", + slots: ["weekdayMorning", "weekdayAfternoon"], + actors: ["candidate", "team"], + target: "city", + visibility: "local", + cost: { money: 100_000, stamina: 4 }, + special: "hireStaff", + effects: [], + }, + { + ...base, + id: "eve_rally", + name: "選前之夜", + category: "ground", + description: "", + slots: ["weekendEvening"], + actors: ["candidate"], + target: "town", + phase: "eve", + cost: { money: 0, stamina: 0 }, + amount: { label: "規模", unit: "元", min: 1_000_000, max: 15_000_000, step: 500_000, default: 5_000_000, moneyPerUnit: 1 }, + special: "rally", + effects: [{ stat: "heat", base: 0.12, scope: "city", supportersOnly: true }], + }, +]; + +export const TEST_CONTENT: Content = { + actions: TEST_ACTIONS, + issues: [ + { id: "transport", name: "交通", description: "", appeal: { "20-29": 0.6, "30-39": 0.7, "40-49": 0.6, "50-64": 0.5, "65+": 0.4 } }, + { id: "housing", name: "居住", description: "", appeal: { "20-29": 0.9, "30-39": 0.8, "40-49": 0.5, "50-64": 0.3, "65+": 0.2 } }, + ], +}; + +export const TEST_SCENARIO: Scenario = { + id: "tiny-mayor", + name: "測試市長", + description: "", + packId: "tiny", + weeks: 4, + electionDate: "2022-11-26", + region: { countyCode: "68000", countyName: "測試市", office: "市長" }, + blackoutFromWeek: 4, + publicPollWeeks: [2], + spendingCap: 50_000_000, + mood: { a: 0, b: 0, c: 0, other: 0 }, + publicHistoryElection: "prior", + bountyMultiplier: 1, + turnoutScale: 1, + notes: [], + sources: [], + actual: { electionId: "prior", partyToCandidate: { 甲黨: "alice", 乙黨: "bob" } }, + candidates: [ + { id: "alice", name: "甲", personId: null, party: "甲黨", slot: "a", number: 1, description: "", awareness: 0.6, eloquence: 60, strategy: 60, startingMoney: 20_000_000, wealth: 5_000_000, machine: 0.2, staff: 2, fundraising: 2_000_000, realFinance: null, aiStyle: "balanced" }, + { id: "bob", name: "乙", personId: null, party: "乙黨", slot: "b", number: 2, description: "", awareness: 0.6, eloquence: 50, strategy: 50, startingMoney: 20_000_000, wealth: 5_000_000, machine: 0.2, staff: 2, fundraising: 2_000_000, realFinance: null, aiStyle: "ground" }, + ], +}; + +export function tinyWorld(): World { + return { scenario: TEST_SCENARIO, pack: tinyPack(), content: TEST_CONTENT, params: DEFAULT_PARAMS }; +} diff --git a/backend/packages/engine/test/press.test.ts b/backend/packages/engine/test/press.test.ts new file mode 100644 index 0000000..e8f44a8 --- /dev/null +++ b/backend/packages/engine/test/press.test.ts @@ -0,0 +1,32 @@ +import type { NewsItem, Poll } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { drawPress, pressHits, type PressDef } from "../src/press.ts"; +import type { MatchState, Scenario } from "../src/types.ts"; + +const scenario = { weeks: 10, candidates: [{ id: "me", name: "我" }, { id: "rival", name: "對手" }] } as unknown as Scenario; +const state = { seed: 1, week: 3, candidates: [{ id: "me", withdrawn: false }, { id: "rival", withdrawn: false }] } as unknown as MatchState; +const news = (n: Partial): NewsItem => ({ id: "n", week: 3, tier: "main", title: "標題", candidateId: null, townCode: null, tone: "neutral", topic: null, targetId: null, art: null, ...n }); +const poll = (shares: Record): Poll => ({ id: "p", week: 3, kind: "public", pollster: "x", sampleSize: 1000, marginOfError: 3, shares, undecided: 0.1, byTown: null }); +const def = (id: string, trigger: PressDef["trigger"]): PressDef => ({ id, trigger, question: "{opponent}?", fallback: "a", options: [{ id: "a", label: "A", hint: "", outcome: { text: "" } }] }); + +describe("記者堵麥", () => { + it("依新聞判斷記者會追問什麼", () => { + const hits = pressHits(scenario, state, "me", [ + news({ candidateId: "rival", targetId: "me", title: "對手攻擊我" }), + news({ candidateId: "me", tone: "negative", title: "我出包" }), + news({ candidateId: "rival", tone: "negative", title: "對手出包" }), + news({ candidateId: "me", tone: "positive", tier: "headline", title: "我造勢成功" }), + news({ candidateId: "me", tone: "negative", topic: "press:attacked", title: "我回應記者被批" }), + ], poll({ me: 0.3, rival: 0.5 })); + expect(hits.map((h) => h.trigger)).toEqual(["attacked", "own_scandal", "opp_scandal", "my_win", "poll_behind"]); + expect(hits[0]!.opponent).toBe("rival"); + }); + + it("最多兩題、依優先順序;沒事就問平靜週的題目", () => { + const defs = [def("x", "attacked"), def("y", "own_scandal"), def("z", "my_win"), def("q", "quiet")]; + const busy = drawPress(defs, scenario, state, "me", [news({ candidateId: "me", tone: "positive", tier: "headline" }), news({ candidateId: "rival", targetId: "me" }), news({ candidateId: "me", tone: "negative" })], null); + expect(busy.map((q) => q.trigger)).toEqual(["own_scandal", "attacked"]); + expect(busy[1]!.vars.opponent).toBe("對手"); + expect(drawPress(defs, scenario, state, "me", [], null).map((q) => q.trigger)).toEqual(["quiet"]); + }); +}); diff --git a/backend/packages/engine/test/tactics.test.ts b/backend/packages/engine/test/tactics.test.ts new file mode 100644 index 0000000..210621f --- /dev/null +++ b/backend/packages/engine/test/tactics.test.ts @@ -0,0 +1,75 @@ +import type { Order } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { comboBonus, COMBO_MAX, COMBO_STEP, COUNTER_BONUS, lastWeekVisits, mainRival, planTactics } from "../src/tactics.ts"; +import type { ActionDef, MatchState, Scenario } from "../src/types.ts"; + +const scenario = { candidates: [{ id: "me", name: "我", slot: "a" }, { id: "rival", name: "對手", slot: "b" }, { id: "minor", name: "小黨", slot: "c" }] } as unknown as Scenario; +const action = (id: string, category: ActionDef["category"], visibility: ActionDef["visibility"] = "public") => ({ id, category, visibility }) as ActionDef; +const actions = new Map( + [action("street_canvass", "ground"), action("market_visit", "ground"), action("temple_visit", "ritual"), action("tv_ad", "media"), action("vote_buying", "dark", "secret")].map((a) => [a.id, a]), +); +const order = (actionId: string, target: string | null, o: Partial = {}): Order => ({ + actor: "candidate", + staffId: null, + slot: "weekdayMorning", + actionId, + target, + amount: null, + opponentId: null, + issueIds: null, + ...o, +}); +const state = (lastWeek: Record, week = 3) => + ({ week, polls: [], log: [{ week: week - 1, orders: lastWeek }], candidates: [{ withdrawn: false }, { withdrawn: false }, { withdrawn: false }] }) as unknown as MatchState; + +describe("組合拳", () => { + it("同一區不同的行程越多,加成越大,有上限", () => { + expect(comboBonus(1)).toBe(0); + expect(comboBonus(2)).toBeCloseTo(COMBO_STEP); + expect(comboBonus(9)).toBeCloseTo(COMBO_MAX); + }); + + it("只算公開、打在同一區的不同行程;同一張牌打兩次不算", () => { + const mine = [order("street_canvass", "A"), order("street_canvass", "A"), order("market_visit", "A"), order("tv_ad", null), order("street_canvass", "B")]; + const t = planTactics(state({}), scenario, actions, [mine, [], []]); + expect(t.multiplier(0, mine[0]!)).toBeCloseTo(1 + COMBO_STEP); + expect(t.multiplier(0, mine[4]!)).toBe(1); + expect(t.multiplier(0, mine[3]!)).toBe(1); + expect(t.notes).toEqual([{ ci: 0, kind: "combo", townCode: "A", bonus: comboBonus(2), kinds: 2 }]); + }); +}); + +describe("打對台", () => { + it("到對手上週公開去過的區跑地面行程才有加成", () => { + const last = { rival: [order("street_canvass", "A"), order("vote_buying", "B", { actor: "team", staffId: "staff-1", slot: "midnight" })] }; + const mine = [order("market_visit", "A"), order("market_visit", "B"), order("tv_ad", null)]; + const t = planTactics(state(last), scenario, actions, [mine, [], []]); + expect(t.multiplier(0, mine[0]!)).toBeCloseTo(1 + COUNTER_BONUS); + // 對手在 B 是午夜祕密行動,不算公開去過 + expect(t.multiplier(0, mine[1]!)).toBe(1); + expect(t.notes.filter((n) => n.kind === "counter")).toEqual([{ ci: 0, kind: "counter", townCode: "A", bonus: COUNTER_BONUS, rival: 1, byCandidate: true }]); + }); + + it("自己上週去過的區不算打對台", () => { + const mine = [order("market_visit", "A")]; + const t = planTactics(state({ me: [order("street_canvass", "A")] }), scenario, actions, [mine, [], []]); + expect(t.multiplier(0, mine[0]!)).toBe(1); + }); + + it("上週足跡:只算候選人本人,每人每區一筆", () => { + const last = { rival: [order("street_canvass", "A", { actor: "team", staffId: "staff-1" }), order("temple_visit", "A"), order("market_visit", "A")] }; + expect(lastWeekVisits(state(last), scenario, actions)).toEqual([{ ci: 1, townCode: "A", actionId: "temple_visit" }]); + // 只看上一週:兩週前的足跡不算 + expect(lastWeekVisits({ ...state(last), week: 4 }, scenario, actions)).toEqual([]); + }); + + it("只對主要對手打對台:沒有民調時看兩大黨,有民調時看民調最高的對手", () => { + const last = { minor: [order("street_canvass", "A")] }; + const mine = [order("market_visit", "A")]; + expect(mainRival(state(last), scenario, 0)).toBe(1); + expect(planTactics(state(last), scenario, actions, [mine, [], []]).multiplier(0, mine[0]!)).toBe(1); + const polled = { ...state(last), polls: [{ kind: "public", shares: { me: 0.4, rival: 0.1, minor: 0.3 } }] } as unknown as MatchState; + expect(mainRival(polled, scenario, 0)).toBe(2); + expect(planTactics(polled, scenario, actions, [mine, [], []]).multiplier(0, mine[0]!)).toBeCloseTo(1 + COUNTER_BONUS); + }); +}); diff --git a/backend/packages/engine/tsconfig.json b/backend/packages/engine/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/packages/engine/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/packages/engine/vitest.config.ts b/backend/packages/engine/vitest.config.ts new file mode 100644 index 0000000..5539adc --- /dev/null +++ b/backend/packages/engine/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ test: { include: ["test/**/*.test.ts"] } }); diff --git a/backend/packages/pack-loader/package.json b/backend/packages/pack-loader/package.json new file mode 100644 index 0000000..bbb7a2d --- /dev/null +++ b/backend/packages/pack-loader/package.json @@ -0,0 +1,19 @@ +{ + "name": "@election2026/pack-loader", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "從磁碟讀取並驗證資料包(伺服器與模擬工具共用;引擎本身不讀檔)", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "@election2026/engine": "workspace:*", + "@election2026/protocol": "workspace:*", + "zod": "^4.6.7" + } +} diff --git a/backend/packages/pack-loader/src/index.ts b/backend/packages/pack-loader/src/index.ts new file mode 100644 index 0000000..89a2d27 --- /dev/null +++ b/backend/packages/pack-loader/src/index.ts @@ -0,0 +1,113 @@ +import { readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { buildPackData, type PackData, type PackFiles, type PackOptions } from "@election2026/engine"; +import { + CellsFile, + DataPackManifest, + HistoryFile, + LocalCalibration, + LocalElectionSpec, + TownsFile, + VillagesFile, +} from "@election2026/protocol"; +import type { z } from "zod"; + +/** 預設的資料包目錄:backend/data/build/packs */ +export const DEFAULT_PACKS_ROOT = fileURLToPath(new URL("../../../data/build/packs/", import.meta.url)); + +async function readJson(path: string, schema: T): Promise> { + const text = await readFile(path, "utf-8"); + const parsed = schema.safeParse(JSON.parse(text)); + if (!parsed.success) throw new Error(`${path} 不符合協定:${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join(".")} ${i.message}`).join(";")}`); + return parsed.data; +} + +/** 讀取並驗證一個資料包目錄的所有檔案 */ +export async function loadPackFiles(dir: string): Promise { + const manifest = await readJson(join(dir, "manifest.json"), DataPackManifest); + const [villages, towns, cells, history] = await Promise.all([ + readJson(join(dir, manifest.files.villages), VillagesFile), + readJson(join(dir, manifest.files.towns), TownsFile), + readJson(join(dir, manifest.files.cells), CellsFile), + readJson(join(dir, manifest.files.history), HistoryFile), + ]); + return { manifest, villages: villages.villages, towns: towns.towns, cells: cells.cells, history: history.history }; +} + +/** name:資料包目錄名稱,例如 68000-before-2022-11-26 */ +export async function loadPack(name: string, root = DEFAULT_PACKS_ROOT, options: PackOptions = {}): Promise { + if (!/^[\w-]+$/.test(name)) throw new Error(`資料包名稱不合法:${name}`); + return buildPackData(await loadPackFiles(join(root, name)), options); +} + +/** 劇本資料的各個目錄(data/build/scenarios/<名稱>) */ +export const DEFAULT_SCENARIOS_ROOT = fileURLToPath(new URL("../../../data/build/scenarios/", import.meta.url)); +export const SCENARIO_SETS = [ + "2022-local", + "2024-legislator", + "2024-president", + "2018-local", + "2020-legislator", + "2020-president", + "2014-local", + "2016-president", + "2012-president", + "2008-president", + "2004-president", + "2000-president", + "1996-president", +] as const; + +/** 讀取所有劇本資料:回傳 [資料檔名(不含 .json), 內容, 所屬目錄] */ +export async function loadAllSpecs(root = DEFAULT_SCENARIOS_ROOT): Promise<{ key: string; set: string; spec: LocalElectionSpec }[]> { + const out: { key: string; set: string; spec: LocalElectionSpec }[] = []; + for (const set of SCENARIO_SETS) { + let files: string[]; + try { + files = (await readdir(join(root, set))).filter((f) => /^\d{5}(-\d{2})?\.json$/.test(f)).sort(); + } catch { + continue; + } + for (const f of files) out.push({ key: f.replace(/\.json$/, ""), set, spec: await readJson(join(root, set, f), LocalElectionSpec) }); + } + return out; +} + +export async function loadCalibration(set: string, root = DEFAULT_SCENARIOS_ROOT): Promise { + try { + return await readJson(join(root, set, "calibration.json"), LocalCalibration); + } catch { + return null; + } +} + +export async function listPacks(root = DEFAULT_PACKS_ROOT): Promise { + const entries = await readdir(root, { withFileTypes: true }); + return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort(); +} + +export const DEFAULT_SLOGANS_FILE = fileURLToPath(new URL("../../../data/build/people/slogans.json", import.meta.url)); + +/** 查證過的競選標語(docs/20-campaign-slogans.md):鍵是「姓名|年份」;檔案不存在時回傳空的 */ +export async function loadSlogans(file = DEFAULT_SLOGANS_FILE): Promise> { + try { + const data = JSON.parse(await readFile(file, "utf-8")) as { entries: { name: string; year: number; slogans: string[]; sources: { url: string }[] }[] }; + return Object.fromEntries( + data.entries.filter((e) => e.slogans.length).map((e) => [`${e.name}|${e.year}`, { slogan: e.slogans[0]!, source: e.sources[0]?.url ?? null }]), + ); + } catch { + return {}; + } +} + +export const DEFAULT_GENDERS_FILE = fileURLToPath(new URL("../../../data/build/people/genders.json", import.meta.url)); + +/** 候選人性別(python -m election_data.genders):姓名 → m/f,給 Q 版頭像挑男女;檔案不存在時回傳空的 */ +export async function loadGenders(file = DEFAULT_GENDERS_FILE): Promise> { + try { + return JSON.parse(await readFile(file, "utf-8")) as Record; + } catch { + return {}; + } +} diff --git a/backend/packages/pack-loader/test/loader.test.ts b/backend/packages/pack-loader/test/loader.test.ts new file mode 100644 index 0000000..d1a2166 --- /dev/null +++ b/backend/packages/pack-loader/test/loader.test.ts @@ -0,0 +1,21 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { DEFAULT_PACKS_ROOT, listPacks, loadPack } from "../src/index.ts"; + +describe("資料包讀取", () => { + it("拒絕不合法的名稱(避免讀到資料包目錄以外的檔案)", async () => { + await expect(loadPack("../secrets")).rejects.toThrow("不合法"); + await expect(loadPack("a/b")).rejects.toThrow("不合法"); + }); + + const name = "68000-before-2022-11-26"; + it.skipIf(!existsSync(join(DEFAULT_PACKS_ROOT, name, "manifest.json")))("讀取並驗證已建置的資料包", async () => { + expect(await listPacks()).toContain(name); + const pack = await loadPack(name); + expect(pack.villages.length).toBeGreaterThan(500); + expect(pack.towns).toHaveLength(13); + expect(pack.cells.length).toBe(pack.villages.length * 30); + expect(pack.towns.reduce((s, t) => s + t.villages.length, 0)).toBe(pack.villages.length); + }); +}); diff --git a/backend/packages/pack-loader/tsconfig.json b/backend/packages/pack-loader/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/packages/pack-loader/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/packages/pack-loader/vitest.config.ts b/backend/packages/pack-loader/vitest.config.ts new file mode 100644 index 0000000..5539adc --- /dev/null +++ b/backend/packages/pack-loader/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ test: { include: ["test/**/*.test.ts"] } }); diff --git a/backend/packages/protocol/art/avatar/README.md b/backend/packages/protocol/art/avatar/README.md new file mode 100644 index 0000000..9d09141 --- /dev/null +++ b/backend/packages/protocol/art/avatar/README.md @@ -0,0 +1,10 @@ +# 頭像部件原圖(docs/24) + +每張圖都畫在同一個 200×220 的標準畫布、標準臉(鵝蛋臉、臉寬臉長 1)上,原創,授權見 web/public/assets/LICENSES.md。 + +- **魔術色**(程式會換成玩家選的顏色):`#ff00ff` 主色、`#800080` 主色暗面、`#00ffff` 副色、`#008080` 副色暗面、 + `#ffff00` 膚色、`#808000` 膚色暗面、`#0000ff` 衣服色、`#000080` 衣服暗面、`#00ff00` 襯衫色。其他顏色照原樣畫。 +- **只能用**:`svg g path circle ellipse rect polygon polyline line`,屬性只能是形狀、顏色、線寬、透明度、transform。 + 不准有 script、style、外部連結、文字;不能超出畫布。字(號次、名字)寫在目錄的 `text` 欄位,由程式印。 +- 要分前後兩層時用 ``(畫在頭和身體後面)、``。 +- 改完跑 `pnpm avatar:build`(在 backend/ 底下):檢查+轉成 `src/avatar/*.generated.ts`。 diff --git a/backend/packages/protocol/art/avatar/chest/corsage.svg b/backend/packages/protocol/art/avatar/chest/corsage.svg new file mode 100644 index 0000000..a68c5d4 --- /dev/null +++ b/backend/packages/protocol/art/avatar/chest/corsage.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/chest/name-tag.svg b/backend/packages/protocol/art/avatar/chest/name-tag.svg new file mode 100644 index 0000000..8950548 --- /dev/null +++ b/backend/packages/protocol/art/avatar/chest/name-tag.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/backend/packages/protocol/art/avatar/frame/billboard.svg b/backend/packages/protocol/art/avatar/frame/billboard.svg new file mode 100644 index 0000000..fc9866e --- /dev/null +++ b/backend/packages/protocol/art/avatar/frame/billboard.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/frame/gazette.svg b/backend/packages/protocol/art/avatar/frame/gazette.svg new file mode 100644 index 0000000..d2fb80d --- /dev/null +++ b/backend/packages/protocol/art/avatar/frame/gazette.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/backend/packages/protocol/art/avatar/frame/gold.svg b/backend/packages/protocol/art/avatar/frame/gold.svg new file mode 100644 index 0000000..49c8e1a --- /dev/null +++ b/backend/packages/protocol/art/avatar/frame/gold.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/frame/neon.svg b/backend/packages/protocol/art/avatar/frame/neon.svg new file mode 100644 index 0000000..9d1dea3 --- /dev/null +++ b/backend/packages/protocol/art/avatar/frame/neon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/frame/newspaper.svg b/backend/packages/protocol/art/avatar/frame/newspaper.svg new file mode 100644 index 0000000..d6e5dd5 --- /dev/null +++ b/backend/packages/protocol/art/avatar/frame/newspaper.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/hat/bamboo.svg b/backend/packages/protocol/art/avatar/hat/bamboo.svg new file mode 100644 index 0000000..d60ac13 --- /dev/null +++ b/backend/packages/protocol/art/avatar/hat/bamboo.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/hat/bucket.svg b/backend/packages/protocol/art/avatar/hat/bucket.svg new file mode 100644 index 0000000..96a85c6 --- /dev/null +++ b/backend/packages/protocol/art/avatar/hat/bucket.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/hat/campaign-cap.svg b/backend/packages/protocol/art/avatar/hat/campaign-cap.svg new file mode 100644 index 0000000..78da80a --- /dev/null +++ b/backend/packages/protocol/art/avatar/hat/campaign-cap.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/hat/helmet.svg b/backend/packages/protocol/art/avatar/hat/helmet.svg new file mode 100644 index 0000000..eff0b99 --- /dev/null +++ b/backend/packages/protocol/art/avatar/hat/helmet.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/hat/victory-band.svg b/backend/packages/protocol/art/avatar/hat/victory-band.svg new file mode 100644 index 0000000..bc2c582 --- /dev/null +++ b/backend/packages/protocol/art/avatar/hat/victory-band.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/fan.svg b/backend/packages/protocol/art/avatar/held/fan.svg new file mode 100644 index 0000000..a210c3e --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/fan.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/flag.svg b/backend/packages/protocol/art/avatar/held/flag.svg new file mode 100644 index 0000000..5909fec --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/flag.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/megaphone.svg b/backend/packages/protocol/art/avatar/held/megaphone.svg new file mode 100644 index 0000000..58f4e61 --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/megaphone.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/mic.svg b/backend/packages/protocol/art/avatar/held/mic.svg new file mode 100644 index 0000000..7a3c16d --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/mic.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/thermos.svg b/backend/packages/protocol/art/avatar/held/thermos.svg new file mode 100644 index 0000000..b0b4c7e --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/thermos.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/held/tissue.svg b/backend/packages/protocol/art/avatar/held/tissue.svg new file mode 100644 index 0000000..5db52b8 --- /dev/null +++ b/backend/packages/protocol/art/avatar/held/tissue.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/mask/number.svg b/backend/packages/protocol/art/avatar/mask/number.svg new file mode 100644 index 0000000..0ed3d44 --- /dev/null +++ b/backend/packages/protocol/art/avatar/mask/number.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/mask/plain.svg b/backend/packages/protocol/art/avatar/mask/plain.svg new file mode 100644 index 0000000..5b75c2e --- /dev/null +++ b/backend/packages/protocol/art/avatar/mask/plain.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/backend/packages/protocol/art/avatar/outer/campaign-vest.svg b/backend/packages/protocol/art/avatar/outer/campaign-vest.svg new file mode 100644 index 0000000..96c75e3 --- /dev/null +++ b/backend/packages/protocol/art/avatar/outer/campaign-vest.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/outer/hivis.svg b/backend/packages/protocol/art/avatar/outer/hivis.svg new file mode 100644 index 0000000..d06e9b5 --- /dev/null +++ b/backend/packages/protocol/art/avatar/outer/hivis.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/outer/raincoat.svg b/backend/packages/protocol/art/avatar/outer/raincoat.svg new file mode 100644 index 0000000..549bb5b --- /dev/null +++ b/backend/packages/protocol/art/avatar/outer/raincoat.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/outer/volunteer-vest.svg b/backend/packages/protocol/art/avatar/outer/volunteer-vest.svg new file mode 100644 index 0000000..405f293 --- /dev/null +++ b/backend/packages/protocol/art/avatar/outer/volunteer-vest.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/backend/packages/protocol/art/avatar/sash/gold.svg b/backend/packages/protocol/art/avatar/sash/gold.svg new file mode 100644 index 0000000..052af9a --- /dev/null +++ b/backend/packages/protocol/art/avatar/sash/gold.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/backend/packages/protocol/art/avatar/sash/red.svg b/backend/packages/protocol/art/avatar/sash/red.svg new file mode 100644 index 0000000..aad7615 --- /dev/null +++ b/backend/packages/protocol/art/avatar/sash/red.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/backend/packages/protocol/art/avatar/sash/thanks.svg b/backend/packages/protocol/art/avatar/sash/thanks.svg new file mode 100644 index 0000000..a5d4838 --- /dev/null +++ b/backend/packages/protocol/art/avatar/sash/thanks.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/backend/packages/protocol/data/avatar-catalog.json b/backend/packages/protocol/data/avatar-catalog.json new file mode 100644 index 0000000..048bbf3 --- /dev/null +++ b/backend/packages/protocol/data/avatar-catalog.json @@ -0,0 +1,1526 @@ +{ + "catalogVersion": 3, + "styles": [ + { + "id": "comic", + "name": "海報漫畫", + "note": "競選海報風:粗墨線、平塗色塊、大圖加網點陰影" + }, + { + "id": "chibi", + "name": "Q 版大頭", + "note": "頭大身體小、大眼睛加反光點、腮紅深一點" + }, + { + "id": "pixel", + "name": "復刻像素", + "note": "致敬 1994 年原作:縮成小點陣、16 色、方塊放大" + }, + { + "id": "sticker", + "name": "平面貼紙", + "note": "粗白邊、去掉陰影,像一張貼紙" + } + ], + "slots": [ + { + "id": "face", + "name": "臉型", + "tab": "face", + "field": "face", + "optional": true, + "default": "oval", + "small": "show" + }, + { + "id": "eyes", + "name": "眼睛", + "tab": "face", + "field": "eyes", + "optional": true, + "default": "round", + "small": "show" + }, + { + "id": "brows", + "name": "眉毛", + "tab": "face", + "field": "brows", + "optional": true, + "default": "normal", + "small": "show" + }, + { + "id": "mouth", + "name": "表情", + "tab": "face", + "field": "mouth", + "optional": true, + "default": "smile", + "small": "show" + }, + { + "id": "nose", + "name": "鼻子", + "tab": "face", + "field": "nose", + "optional": true, + "default": "normal", + "small": "show", + "ui": false + }, + { + "id": "ears", + "name": "耳朵", + "tab": "face", + "field": "ears", + "optional": true, + "default": "normal", + "small": "show", + "ui": false + }, + { + "id": "hair", + "name": "髮型", + "tab": "hair", + "field": "hair", + "optional": false, + "default": "short", + "small": "show" + }, + { + "id": "outfit", + "name": "服裝", + "tab": "outfit", + "field": "outfit", + "optional": false, + "default": "suit", + "small": "show" + }, + { + "id": "glasses", + "name": "眼鏡", + "tab": "extra", + "field": "glassesStyle", + "optional": true, + "default": "black", + "small": "show" + }, + { + "id": "mask", + "name": "口罩", + "tab": "extra", + "optional": true, + "default": null, + "small": "show", + "layer": "face" + }, + { + "id": "hat", + "name": "帽子", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "layer": "head" + }, + { + "id": "outer", + "name": "背心外套", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "layer": "body" + }, + { + "id": "sash", + "name": "彩帶", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "layer": "body" + }, + { + "id": "chest", + "name": "胸前", + "tab": "gear", + "optional": true, + "default": null, + "small": "hide", + "layer": "body" + }, + { + "id": "held", + "name": "手持物", + "tab": "props", + "optional": true, + "default": null, + "small": "hide", + "layer": "hand" + }, + { + "id": "frame", + "name": "頭像外框", + "tab": "props", + "optional": true, + "default": null, + "small": "hide", + "layer": "canvas" + } + ], + "palettes": { + "campaign": { + "colors": [ + "party", + "#d61f2c", + "#ffd23f", + "#1b9431", + "#2349b8", + "#16a3a6", + "#ff7a1a", + "#7a5cc4", + "#111419", + "#f4f1ea" + ] + }, + "soft": { + "colors": [ + "#eef3f7", + "#bfe3ff", + "#ffe27a", + "#ffc2d1", + "#c8f0c4", + "#e8dcc0", + "#b8c2cc", + "#2b2f36" + ] + }, + "hivis": { + "colors": [ + "#ff7a1a", + "#c8f03c", + "#ffd23f" + ] + }, + "gold": { + "colors": [ + "#e8b923", + "#f2d36b", + "#d61f2c" + ] + } + }, + "items": [ + { + "id": "oval", + "slot": "face", + "name": "鵝蛋臉", + "art": "builtin:oval", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "round", + "slot": "face", + "name": "圓臉", + "art": "builtin:round", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "long", + "slot": "face", + "name": "長臉", + "art": "builtin:long", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "square", + "slot": "face", + "name": "方臉", + "art": "builtin:square", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "heart", + "slot": "face", + "name": "瓜子臉", + "art": "builtin:heart", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "jowl", + "slot": "face", + "name": "大下巴", + "art": "builtin:jowl", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "round", + "slot": "eyes", + "name": "圓眼", + "art": "builtin:round", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "narrow", + "slot": "eyes", + "name": "細長眼", + "art": "builtin:narrow", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "dot", + "slot": "eyes", + "name": "豆豆眼", + "art": "builtin:dot", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "smile", + "slot": "eyes", + "name": "瞇瞇眼", + "art": "builtin:smile", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "droopy", + "slot": "eyes", + "name": "下垂眼", + "art": "builtin:droopy", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "wide", + "slot": "eyes", + "name": "大眼", + "art": "builtin:wide", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "thin", + "slot": "brows", + "name": "細眉", + "art": "builtin:thin", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "normal", + "slot": "brows", + "name": "一般", + "art": "builtin:normal", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "thick", + "slot": "brows", + "name": "濃眉", + "art": "builtin:thick", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "bushy", + "slot": "brows", + "name": "粗濃眉", + "art": "builtin:bushy", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "smile", + "slot": "mouth", + "name": "微笑", + "art": "builtin:smile", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "grin", + "slot": "mouth", + "name": "開心笑", + "art": "builtin:grin", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "closed", + "slot": "mouth", + "name": "抿嘴", + "art": "builtin:closed", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "teeth", + "slot": "mouth", + "name": "露齒笑", + "art": "builtin:teeth", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "smirk", + "slot": "mouth", + "name": "嘴角上揚", + "art": "builtin:smirk", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "laugh", + "slot": "mouth", + "name": "開懷大笑", + "art": "builtin:laugh", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "small", + "slot": "nose", + "name": "小鼻子", + "art": "builtin:small", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "normal", + "slot": "nose", + "name": "一般", + "art": "builtin:normal", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "big", + "slot": "nose", + "name": "大鼻子", + "art": "builtin:big", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "round", + "slot": "nose", + "name": "圓鼻頭", + "art": "builtin:round", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "small", + "slot": "ears", + "name": "小耳朵", + "art": "builtin:small", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "normal", + "slot": "ears", + "name": "一般", + "art": "builtin:normal", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "big", + "slot": "ears", + "name": "招風耳", + "art": "builtin:big", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "short", + "slot": "hair", + "name": "短髮", + "art": "builtin:short", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "side", + "slot": "hair", + "name": "旁分", + "art": "builtin:side", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true + }, + { + "id": "crew", + "slot": "hair", + "name": "小平頭", + "art": "builtin:crew", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "buzz", + "slot": "hair", + "name": "平頭", + "art": "builtin:buzz", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "slick", + "slot": "hair", + "name": "油頭", + "art": "builtin:slick", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "volume", + "slot": "hair", + "name": "蓬鬆旁分", + "art": "builtin:volume", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true + }, + { + "id": "receding", + "slot": "hair", + "name": "髮線後退", + "art": "builtin:receding", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "bald", + "slot": "hair", + "name": "光頭", + "art": "builtin:bald", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "bob", + "slot": "hair", + "name": "鮑伯頭", + "art": "builtin:bob", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "bobSide", + "slot": "hair", + "name": "側分鮑伯", + "art": "builtin:bobSide", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true + }, + { + "id": "shortBob", + "slot": "hair", + "name": "耳下短髮", + "art": "builtin:shortBob", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true + }, + { + "id": "long", + "slot": "hair", + "name": "長髮", + "art": "builtin:long", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true + }, + { + "id": "bun", + "slot": "hair", + "name": "包頭", + "art": "builtin:bun", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "curly", + "slot": "hair", + "name": "捲髮", + "art": "builtin:curly", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "perm", + "slot": "hair", + "name": "燙髮", + "art": "builtin:perm", + "zoom": "head", + "realPersonOk": true + }, + { + "id": "flatTop", + "slot": "hair", + "name": "平頭板寸", + "art": "builtin:flatTop", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "middle", + "slot": "hair", + "name": "中分", + "art": "builtin:middle", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "combover", + "slot": "hair", + "name": "側梳地中海", + "art": "builtin:combover", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true, + "since": 3 + }, + { + "id": "spiky", + "slot": "hair", + "name": "抓立短髮", + "art": "builtin:spiky", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "pompadour", + "slot": "hair", + "name": "高聳背頭", + "art": "builtin:pompadour", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "longMiddle", + "slot": "hair", + "name": "長髮中分", + "art": "builtin:longMiddle", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "longWavy", + "slot": "hair", + "name": "長波浪", + "art": "builtin:longWavy", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true, + "since": 3 + }, + { + "id": "ponytail", + "slot": "hair", + "name": "馬尾", + "art": "builtin:ponytail", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true, + "since": 3 + }, + { + "id": "pixie", + "slot": "hair", + "name": "露耳短髮", + "art": "builtin:pixie", + "zoom": "head", + "flags": [ + "parted" + ], + "realPersonOk": true, + "since": 3 + }, + { + "id": "fringe", + "slot": "hair", + "name": "瀏海短髮", + "art": "builtin:fringe", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "longBangs", + "slot": "hair", + "name": "齊瀏海長髮", + "art": "builtin:longBangs", + "zoom": "head", + "realPersonOk": true, + "since": 3 + }, + { + "id": "suit", + "slot": "outfit", + "name": "西裝領帶", + "art": "builtin:suit", + "flags": [ + "tie" + ], + "realPersonOk": true + }, + { + "id": "blouse", + "slot": "outfit", + "name": "套裝", + "art": "builtin:blouse", + "realPersonOk": true + }, + { + "id": "vest", + "slot": "outfit", + "name": "西裝背心", + "art": "builtin:vest", + "realPersonOk": true + }, + { + "id": "polo", + "slot": "outfit", + "name": "競選 Polo 衫", + "art": "builtin:polo", + "flags": [ + "collar" + ], + "realPersonOk": true + }, + { + "id": "shirt", + "slot": "outfit", + "name": "襯衫", + "art": "builtin:shirt", + "flags": [ + "collar" + ], + "realPersonOk": true, + "since": 3 + }, + { + "id": "black", + "slot": "glasses", + "name": "黑粗框", + "art": "builtin:black", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "metal", + "slot": "glasses", + "name": "金屬框", + "art": "builtin:metal", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "round", + "slot": "glasses", + "name": "圓框", + "art": "builtin:round", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "halfRim", + "slot": "glasses", + "name": "半框", + "art": "builtin:halfRim", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "rimless", + "slot": "glasses", + "name": "無框", + "art": "builtin:rimless", + "zoom": "face", + "realPersonOk": true + }, + { + "id": "browline", + "slot": "glasses", + "name": "眉框眼鏡", + "art": "builtin:browline", + "zoom": "face", + "realPersonOk": true, + "since": 3 + }, + { + "id": "hat-campaign-cap", + "slot": "hat", + "name": "競選鴨舌帽", + "desc": "掃街標配,前面印號次,顏色跟政黨走。", + "art": "hat/campaign-cap.svg", + "anchor": "headTop", + "hideHairAbove": 60, + "zoom": "head", + "tints": [ + { + "key": "main", + "name": "帽子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 100, + "y": 40.5, + "size": 15, + "fill": "main", + "width": 18 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "hat-victory-band", + "slot": "hat", + "name": "必勝頭帶", + "desc": "造勢晚會最後衝刺,綁上就停不下來。", + "art": "hat/victory-band.svg", + "anchor": "headTop", + "zoom": "head", + "text": [ + { + "kind": "fixed", + "value": "必勝", + "x": 100, + "y": 53, + "size": 10, + "fill": "#d61f2c", + "width": 26 + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8 + }, + "since": 2 + }, + { + "id": "hat-bamboo", + "slot": "hat", + "name": "斗笠", + "desc": "下鄉掃街、田埂拜票,遮陽又親切。", + "art": "hat/bamboo.svg", + "anchor": "headTop", + "hideHairAbove": 64, + "zoom": "head", + "rarity": "rare", + "get": { + "type": "shop", + "price": 20 + }, + "since": 2 + }, + { + "id": "hat-helmet", + "slot": "hat", + "name": "機車安全帽", + "desc": "騎機車掃街,安全第一。", + "art": "hat/helmet.svg", + "anchor": "headTop", + "hideHairAbove": 66, + "zoom": "head", + "tints": [ + { + "key": "main", + "name": "帽殼", + "palette": "campaign", + "default": "#f4f1ea" + }, + { + "key": "accent", + "name": "條紋", + "palette": "campaign", + "default": "party" + } + ], + "rarity": "rare", + "get": { + "type": "shop", + "price": 24 + }, + "since": 2 + }, + { + "id": "hat-bucket", + "slot": "hat", + "name": "漁夫帽", + "desc": "夏天菜市場拜票的好朋友。", + "art": "hat/bucket.svg", + "anchor": "headTop", + "hideHairAbove": 56, + "zoom": "head", + "tints": [ + { + "key": "main", + "name": "帽子顏色", + "palette": "soft", + "default": "#e8dcc0" + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "always" + }, + "since": 2 + }, + { + "id": "mask-plain", + "slot": "mask", + "name": "素色口罩", + "desc": "流感季節照樣拜票。", + "art": "mask/plain.svg", + "anchor": "face", + "zoom": "face", + "tints": [ + { + "key": "main", + "name": "口罩顏色", + "palette": "soft", + "default": "#eef3f7" + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "mask-number", + "slot": "mask", + "name": "號次口罩", + "desc": "口罩也要印號次,選民才記得住。", + "art": "mask/number.svg", + "anchor": "face", + "zoom": "face", + "tints": [ + { + "key": "main", + "name": "口罩顏色", + "palette": "soft", + "default": "#eef3f7" + }, + { + "key": "accent", + "name": "號次顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 100, + "y": 126, + "size": 17, + "fill": "accent", + "width": 26 + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6, + "shelf": "always" + }, + "since": 2 + }, + { + "id": "outer-campaign-vest", + "slot": "outer", + "name": "競選背心", + "desc": "候選人和志工的制服,印號次和名字。", + "art": "outer/campaign-vest.svg", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 70, + "y": 194, + "size": 15, + "fill": "main", + "width": 18 + }, + { + "kind": "name", + "x": 127, + "y": 198, + "size": 9, + "fill": "white", + "width": 34 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "outer-volunteer-vest", + "slot": "outer", + "name": "志工背心", + "desc": "黃背心一穿,就是選戰的一份子。", + "art": "outer/volunteer-vest.svg", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "campaign", + "default": "#ffd23f" + } + ], + "text": [ + { + "kind": "fixed", + "value": "志工", + "x": 127, + "y": 192, + "size": 10, + "fill": "ink", + "width": 22 + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "always" + }, + "since": 2 + }, + { + "id": "outer-hivis", + "slot": "outer", + "name": "工地反光背心", + "desc": "視察工程進度的必備行頭。", + "art": "outer/hivis.svg", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "hivis", + "default": "#ff7a1a" + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 10 + }, + "since": 2 + }, + { + "id": "outer-raincoat", + "slot": "outer", + "name": "輕便雨衣", + "desc": "雨中造勢,越淋越有聲勢。", + "art": "outer/raincoat.svg", + "tints": [ + { + "key": "main", + "name": "雨衣顏色", + "palette": "soft", + "default": "#bfe3ff" + } + ], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "comeback", + "text": "拿到成就「逆轉勝」" + }, + "since": 2 + }, + { + "id": "sash-red", + "slot": "sash", + "name": "候選人紅布條", + "desc": "斜背的紅布條,印上號次和名字。", + "art": "sash/red.svg", + "tints": [ + { + "key": "main", + "name": "布條顏色", + "palette": "campaign", + "default": "#d61f2c" + } + ], + "text": [ + { + "kind": "numberName", + "x": 115, + "y": 194, + "size": 10, + "rotate": 27, + "fill": "gold", + "width": 84 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "sash-thanks", + "slot": "sash", + "name": "感謝鄉親謝票帶", + "desc": "選完不管輸贏,都要上街謝票。", + "art": "sash/thanks.svg", + "text": [ + { + "kind": "fixed", + "value": "感謝鄉親", + "x": 115, + "y": 194, + "size": 10, + "rotate": 27, + "fill": "#d61f2c", + "width": 70 + } + ], + "rarity": "common", + "get": { + "type": "stat", + "stat": "losses", + "min": 1, + "text": "落選也打完一局" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "sash-gold", + "slot": "sash", + "name": "金色當選帶", + "desc": "大勝的人才拿得到的金布條。", + "art": "sash/gold.svg", + "text": [ + { + "kind": "fixed", + "value": "當選", + "x": 115, + "y": 194, + "size": 11, + "rotate": 27, + "fill": "#d61f2c", + "width": 40 + } + ], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "landslide", + "text": "拿到成就「壓倒性勝利」" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "chest-corsage", + "slot": "chest", + "name": "當選紅胸花", + "desc": "開票夜別上的大紅花。", + "art": "chest/corsage.svg", + "rarity": "rare", + "get": { + "type": "feat", + "feat": "win", + "text": "當選一次" + }, + "realPersonOk": true, + "since": 2 + }, + { + "id": "chest-name-tag", + "slot": "chest", + "name": "名牌", + "desc": "座談會、政見會都要別的名牌。", + "art": "chest/name-tag.svg", + "tints": [ + { + "key": "main", + "name": "色條", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "name", + "x": 138, + "y": 189, + "size": 7.5, + "fill": "ink", + "width": 28 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "since": 2 + }, + { + "id": "held-megaphone", + "slot": "held", + "name": "大聲公", + "desc": "掃街喊話,整條街都聽得到。", + "art": "held/megaphone.svg", + "rarity": "common", + "get": { + "type": "free" + }, + "since": 2 + }, + { + "id": "held-flag", + "slot": "held", + "name": "三角競選旗", + "desc": "插在宣傳車上、拿在手上揮。", + "art": "held/flag.svg", + "tints": [ + { + "key": "main", + "name": "旗子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 177, + "y": 79, + "size": 11, + "fill": "main", + "width": 12 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "since": 2 + }, + { + "id": "held-tissue", + "slot": "held", + "name": "面紙包", + "desc": "最受歡迎的文宣品,人人都收。", + "art": "held/tissue.svg", + "tints": [ + { + "key": "main", + "name": "包裝顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 165, + "y": 172, + "size": 10, + "rotate": -10, + "fill": "main", + "width": 16 + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6, + "shelf": "always" + }, + "since": 2 + }, + { + "id": "held-fan", + "slot": "held", + "name": "團扇", + "desc": "夏天造勢場合一人一支。", + "art": "held/fan.svg", + "tints": [ + { + "key": "main", + "name": "扇子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 170, + "y": 140, + "size": 15, + "fill": "main", + "width": 20 + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6 + }, + "since": 2 + }, + { + "id": "held-mic", + "slot": "held", + "name": "麥克風", + "desc": "政見發表會上,換你說了。", + "art": "held/mic.svg", + "rarity": "rare", + "get": { + "type": "feat", + "feat": "debate_sweep", + "text": "拿到成就「辯論三戰全勝」" + }, + "since": 2 + }, + { + "id": "held-thermos", + "slot": "held", + "name": "保溫杯", + "desc": "一天講幾十場,喉嚨要顧好。", + "art": "held/thermos.svg", + "tints": [ + { + "key": "main", + "name": "杯子顏色", + "palette": "soft", + "default": "#b8c2cc" + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8 + }, + "since": 2 + }, + { + "id": "frame-gazette", + "slot": "frame", + "name": "選舉公報框", + "desc": "像選舉公報上的候選人欄。", + "art": "frame/gazette.svg", + "text": [ + { + "kind": "number", + "x": 25, + "y": 204, + "size": 15, + "fill": "white", + "width": 22 + }, + { + "kind": "name", + "x": 102, + "y": 204, + "size": 14, + "fill": "ink", + "width": 96 + }, + { + "kind": "fixed", + "value": "選舉公報", + "x": 171, + "y": 204, + "size": 7.5, + "fill": "#5d646e", + "width": 30 + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "since": 2 + }, + { + "id": "frame-billboard", + "slot": "frame", + "name": "看板框", + "desc": "路口大看板,請支持幾號一目了然。", + "art": "frame/billboard.svg", + "tints": [ + { + "key": "main", + "name": "看板顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "plea", + "x": 100, + "y": 203, + "size": 14, + "fill": "ink", + "width": 168 + } + ], + "rarity": "rare", + "get": { + "type": "shop", + "price": 20 + }, + "since": 2 + }, + { + "id": "frame-newspaper", + "slot": "frame", + "name": "報紙頭版框", + "desc": "號外號外!上了頭版。", + "art": "frame/newspaper.svg", + "text": [ + { + "kind": "fixed", + "value": "號外", + "x": 36, + "y": 202, + "size": 15, + "fill": "white", + "width": 40 + } + ], + "rarity": "rare", + "get": { + "type": "shop", + "price": 24 + }, + "since": 2 + }, + { + "id": "frame-gold", + "slot": "frame", + "name": "金色當選框", + "desc": "選上縣市長以上才有的金框。", + "art": "frame/gold.svg", + "text": [ + { + "kind": "fixed", + "value": "當選", + "x": 100, + "y": 206, + "size": 13, + "fill": "white", + "width": 40 + } + ], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "career_mayor", + "text": "政治生涯選上縣市長" + }, + "since": 2 + }, + { + "id": "frame-neon", + "slot": "frame", + "name": "霓虹宣傳車框", + "desc": "選舉季限定:宣傳車上一圈閃亮燈泡。每年 11、12 月回來。", + "art": "frame/neon.svg", + "text": [ + { + "kind": "plea", + "x": 100, + "y": 202, + "size": 14, + "fill": "#ffd23f", + "width": 168 + } + ], + "rarity": "limited", + "get": { + "type": "shop", + "price": 36 + }, + "available": { + "months": [ + 11, + 12 + ] + }, + "since": 2 + } + ] +} diff --git a/backend/packages/protocol/package.json b/backend/packages/protocol/package.json new file mode 100644 index 0000000..e01306c --- /dev/null +++ b/backend/packages/protocol/package.json @@ -0,0 +1,27 @@ +{ + "name": "@election2026/protocol", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "前後端契約:資料包、人物、評分的結構定義(v1)", + "exports": { + ".": "./src/index.ts", + "./avatar-art": "./src/avatar/art.generated.ts", + "./schema/*": "./schema/*" + }, + "scripts": { + "schema": "node scripts/build-schema.ts", + "avatar:build": "node scripts/build-avatar-catalog.ts", + "avatar:check": "node scripts/build-avatar-catalog.ts --check", + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "zod": "^4.6.7" + }, + "devDependencies": { + "@types/node": "^26.6.5", + "typescript": "^7.0.2", + "vitest": "^5.0.5" + } +} diff --git a/backend/packages/protocol/scripts/build-avatar-catalog.ts b/backend/packages/protocol/scripts/build-avatar-catalog.ts new file mode 100644 index 0000000..ab02e16 --- /dev/null +++ b/backend/packages/protocol/scripts/build-avatar-catalog.ts @@ -0,0 +1,79 @@ +/** + * 頭像部件目錄的建置工具(docs/24):檢查 data/avatar-catalog.json 和 art/avatar 底下的 SVG, + * 轉成前後端共用的 src/avatar/catalog.generated.ts(目錄)和 src/avatar/art.generated.ts(部件圖,只有形狀和顏色)。 + * 執行:pnpm avatar:build(在 backend/ 底下),或 node scripts/build-avatar-catalog.ts。 + * 加 --check 只檢查、不寫檔(產生的檔和原始檔對不上就失敗)。 + */ +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { AvatarCatalogSchema, lintCatalog } from "../src/avatar/schema.ts"; +import { convertSvgArt, type PartArt } from "../src/avatar/svg.ts"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +export const CATALOG_FILE = join(ROOT, "data", "avatar-catalog.json"); +export const ART_DIR = join(ROOT, "art", "avatar"); +export const CATALOG_OUT = join(ROOT, "src", "avatar", "catalog.generated.ts"); +export const ART_OUT = join(ROOT, "src", "avatar", "art.generated.ts"); + +const HEADER = "// 這個檔是 scripts/build-avatar-catalog.ts 產生的,不要手改:改 data/avatar-catalog.json 或 art/avatar/*.svg 之後跑 pnpm avatar:build\n"; + +function listSvgs(dir: string): string[] { + if (!existsSync(dir)) return []; + return readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? listSvgs(join(dir, e.name)) : e.name.endsWith(".svg") ? [join(dir, e.name)] : [])); +} + +/** 讀原始檔、檢查、轉換;回傳要寫的兩個檔的內容。有問題就丟錯(訊息列出全部問題) */ +export function buildAvatarCatalog(): { catalog: string; art: string; items: number; parts: number } { + const raw: unknown = JSON.parse(readFileSync(CATALOG_FILE, "utf-8")); + const parsed = AvatarCatalogSchema.safeParse(raw); + if (!parsed.success) throw new Error(`avatar-catalog.json 格式不對:\n${parsed.error.issues.map((i) => `- ${i.path.join(".")}: ${i.message}`).join("\n")}`); + const catalog = parsed.data; + const problems = lintCatalog(catalog); + + const art: Record = {}; + for (const item of catalog.items) { + if (item.art.startsWith("builtin:")) continue; + const file = join(ART_DIR, item.art); + if (!existsSync(file)) { + problems.push(`${item.id}:找不到部件圖 art/avatar/${item.art}`); + continue; + } + try { + art[item.art] = convertSvgArt(readFileSync(file, "utf-8"), item.art); + } catch (e) { + problems.push((e as Error).message); + } + } + const used = new Set(catalog.items.map((i) => i.art)); + for (const f of listSvgs(ART_DIR)) { + const rel = relative(ART_DIR, f).split("\\").join("/"); + if (!used.has(rel)) problems.push(`art/avatar/${rel} 沒有任何部件用到(要嘛加進目錄,要嘛刪掉)`); + } + if (problems.length) throw new Error(`頭像部件目錄有問題:\n${problems.map((p) => `- ${p}`).join("\n")}`); + + const catalogTs = `${HEADER}import type { AvatarCatalog } from "./schema.ts";\n\nexport const AVATAR_CATALOG: AvatarCatalog = ${JSON.stringify(catalog, null, 1)};\n`; + const artTs = `${HEADER}import type { PartArt } from "./svg.ts";\n\nexport const AVATAR_ART: Readonly> = ${JSON.stringify(art)};\n`; + return { catalog: catalogTs, art: artTs, items: catalog.items.length, parts: Object.keys(art).length }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + const out = buildAvatarCatalog(); + if (process.argv.includes("--check")) { + const stale = [ + [CATALOG_OUT, out.catalog], + [ART_OUT, out.art], + ].filter(([file, text]) => !existsSync(file!) || readFileSync(file!, "utf-8") !== text); + if (stale.length) throw new Error(`產生的檔和原始檔對不上,請跑 pnpm avatar:build:${stale.map(([f]) => relative(ROOT, f!)).join("、")}`); + process.stdout.write(`頭像部件目錄檢查通過:${out.items} 件部件、${out.parts} 張部件圖\n`); + } else { + writeFileSync(CATALOG_OUT, out.catalog); + writeFileSync(ART_OUT, out.art); + process.stdout.write(`已產生頭像部件目錄:${out.items} 件部件、${out.parts} 張部件圖\n`); + } + } catch (e) { + process.stderr.write(`${(e as Error).message}\n`); + process.exit(1); + } +} diff --git a/backend/packages/protocol/scripts/build-schema.ts b/backend/packages/protocol/scripts/build-schema.ts new file mode 100644 index 0000000..430795c --- /dev/null +++ b/backend/packages/protocol/scripts/build-schema.ts @@ -0,0 +1,53 @@ +/** + * 由 Zod 定義產生 JSON Schema,給 Python 管線與其他語言的前端使用。 + * 執行:pnpm schema + */ +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { z } from "zod"; +import { + ApiError, + CellsFile, + CreateMatchRequest, + CreateMatchResponse, + DataPackManifest, + HistoryFile, + PeopleFile, + PlayerView, + ScenarioSummary, + SourceList, + SuggestResult, + TownsFile, + TurnResult, + TurnSubmission, + VillagesFile, +} from "../src/index.ts"; + +const outDir = join(dirname(fileURLToPath(import.meta.url)), "..", "schema"); +mkdirSync(outDir, { recursive: true }); + +const schemas: Record = { + "manifest.schema.json": DataPackManifest, + "villages.schema.json": VillagesFile, + "towns.schema.json": TownsFile, + "cells.schema.json": CellsFile, + "history.schema.json": HistoryFile, + "sources.schema.json": SourceList, + "people.schema.json": PeopleFile, + "player-view.schema.json": PlayerView, + "turn-submission.schema.json": TurnSubmission, + "scenario-summary.schema.json": ScenarioSummary, + "create-match.schema.json": CreateMatchRequest, + "create-match-response.schema.json": CreateMatchResponse, + "turn-result.schema.json": TurnResult, + "suggest-result.schema.json": SuggestResult, + "api-error.schema.json": ApiError, +}; + +for (const [file, schema] of Object.entries(schemas)) { + const json = z.toJSONSchema(schema, { target: "draft-2020-12" }); + writeFileSync(join(outDir, file), `${JSON.stringify(json, null, 2)}\n`); +} + +process.stdout.write(`已產生 ${Object.keys(schemas).length} 份 JSON Schema 到 ${outDir}\n`); diff --git a/backend/packages/protocol/src/area.ts b/backend/packages/protocol/src/area.ts new file mode 100644 index 0000000..20fab1f --- /dev/null +++ b/backend/packages/protocol/src/area.ts @@ -0,0 +1,153 @@ +import { z } from "zod"; +import { CountyCode, IsoDate, NonNegative, Share, TownCode, VillageCode } from "./common.ts"; + +/** 選民群的兩個核心維度(docs/03) */ +export const AGE_BANDS = ["20-29", "30-39", "40-49", "50-64", "65+"] as const; +export const LEANS = ["a_core", "a_lean", "middle", "b_lean", "b_core", "c_lean"] as const; +export const AgeBand = z.enum(AGE_BANDS); +export const Lean = z.enum(LEANS); +export type AgeBand = z.infer; +export type Lean = z.infer; + +const AgeCounts = z.object(Object.fromEntries(AGE_BANDS.map((a) => [a, NonNegative])) as Record); +const LeanShares = z.object(Object.fromEntries(LEANS.map((l) => [l, Share])) as Record); + +/** 政黨槽位與真實政黨的對應,由劇本決定(docs/03、docs/14) */ +export const PartySlots = z.object({ + a: z.string().min(1), + b: z.string().min(1), + c: z.string().min(1), +}); + +export const VillagePopulation = z.object({ + total: NonNegative, + adults: NonNegative, + byAgeBand: AgeCounts, + indigenousLowland: NonNegative, + indigenousHighland: NonNegative, +}); + +export const VillageAttributes = z.object({ + areaKm2: NonNegative, + densityPerKm2: NonNegative, + templeCount: NonNegative, + churchCount: NonNegative, + templesPer1000: NonNegative, + hakkaShare: Share.nullable(), + incomeMedian: NonNegative.nullable(), + incomeMean: NonNegative.nullable(), + /** 地方派系強度:沒有開放資料,為設計值(docs/10) */ + factionStrength: Share, +}); + +export const VillageRecord = z.object({ + code: VillageCode, + name: z.string().min(1), + townCode: TownCode, + townName: z.string().min(1), + countyCode: CountyCode, + countyName: z.string().min(1), + population: VillagePopulation, + /** 最近一次選舉的選舉人數 */ + electors: NonNegative.nullable(), + /** 基本投票率(0–1),多屆加權 */ + baseTurnout: Share.nullable(), + /** 6 種政黨傾向的人口比例,總和為 1 */ + lean: LeanShares.nullable(), + attributes: VillageAttributes, + /** 資料品質旗標,例如「無選舉資料」「所得以名稱比對失敗」 */ + flags: z.array(z.string()), +}); +export type VillageRecord = z.infer; + +export const TownRecord = z.object({ + code: TownCode, + name: z.string().min(1), + countyCode: CountyCode, + population: NonNegative, + villageCodes: z.array(VillageCode), + /** 普查常住人口(2020) */ + residentPopulation: NonNegative.nullable(), + /** 戶籍外流比例 = max(0, 1 - 常住 / 戶籍),以普查同月的戶籍人口計算 */ + outflowRatio: Share.nullable(), + /** 家庭使用語言比例(普查表 6,可複選,所以總和可能大於 1) */ + languageShares: z.record(z.string(), Share), + /** 15 歲以上教育程度比例(普查) */ + educationShares: z.record(z.string(), Share), + hakkaShare: Share.nullable(), +}); +export type TownRecord = z.infer; + +/** 每個村里 30 個選民群的人數,順序 = ages × leans(年齡為外層) */ +export const CellsBlock = z.object({ + ages: z.array(AgeBand).length(AGE_BANDS.length), + leans: z.array(Lean).length(LEANS.length), + values: z.record(VillageCode, z.array(NonNegative).length(AGE_BANDS.length * LEANS.length)), +}); +export type CellsBlock = z.infer; + +export const ElectionMeta = z.object({ + id: z.string().min(1), + name: z.string().min(1), + date: IsoDate, + office: z.enum(["president", "party_list", "mayor", "councilor", "legislator"]), + weight: Share, +}); + +export const VillageElectionResult = z.object({ + electors: NonNegative, + ballots: NonNegative, + valid: NonNegative, + /** 依政黨名稱加總的得票;無黨籍與其他小黨合併為「其他」 */ + votes: z.record(z.string(), NonNegative), + /** 是否含有依選舉人數比例分配的跨村里投開票所票數 */ + allocated: z.boolean(), +}); + +export const HistoryBlock = z.object({ + elections: z.array(ElectionMeta), + byVillage: z.record(VillageCode, z.record(z.string(), VillageElectionResult)), + /** 與中選會縣市總數的核對結果 */ + reconciliation: z.array( + z.object({ + electionId: z.string(), + cecValid: NonNegative, + packValid: NonNegative, + diff: z.number(), + }), + ), +}); +export type HistoryBlock = z.infer; + +export const DataPackManifest = z.object({ + protocolVersion: z.string(), + packId: z.string().min(1), + createdAt: z.string().min(1), + scope: z.object({ countyCode: CountyCode, countyName: z.string().min(1) }), + snapshot: z.object({ + population: z.string().regex(/^\d{4}-\d{2}$/), + boundaries: z.string().min(1), + }), + partySlots: PartySlots, + files: z.object({ + villages: z.string(), + towns: z.string(), + cells: z.string(), + history: z.string(), + topology: z.string(), + sources: z.string(), + }), + /** 把歷史得票轉成政黨傾向、投票率的參數(初始值,M1 回測時校準) */ + parameters: z.record(z.string(), z.unknown()), + counts: z.object({ + villages: z.number().int().nonnegative(), + towns: z.number().int().nonnegative(), + villagesWithFlags: z.number().int().nonnegative(), + }), +}); +export type DataPackManifest = z.infer; + +export const VillagesFile = z.object({ protocolVersion: z.string(), villages: z.array(VillageRecord) }); +export const TownsFile = z.object({ protocolVersion: z.string(), towns: z.array(TownRecord) }); +export const CellsFile = z.object({ protocolVersion: z.string(), cells: CellsBlock }); +export const HistoryFile = z.object({ protocolVersion: z.string(), history: HistoryBlock }); diff --git a/backend/packages/protocol/src/avatar/art.generated.ts b/backend/packages/protocol/src/avatar/art.generated.ts new file mode 100644 index 0000000..0cf03cd --- /dev/null +++ b/backend/packages/protocol/src/avatar/art.generated.ts @@ -0,0 +1,4 @@ +// 這個檔是 scripts/build-avatar-catalog.ts 產生的,不要手改:改 data/avatar-catalog.json 或 art/avatar/*.svg 之後跑 pnpm avatar:build +import type { PartArt } from "./svg.ts"; + +export const AVATAR_ART: Readonly> = {"hat/campaign-cap.svg":{"front":[{"t":"path","a":{"d":"M52 62 C50 33 72 15 100 15 C128 15 150 33 148 62 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M100 15 C128 15 150 33 148 62 L124 62 C126 40 118 22 100 15 Z","fill":"#800080","opacity":"0.35"}},{"t":"path","a":{"d":"M100 17 L100 27 M100 53 L100 60","stroke":"#800080","strokeWidth":"1.6","fill":"none","opacity":"0.6"}},{"t":"circle","a":{"cx":"100","cy":"40","r":"12.5","fill":"#ffffff"}},{"t":"circle","a":{"cx":"100","cy":"40","r":"12.5","fill":"none","stroke":"#800080","strokeWidth":"2"}},{"t":"circle","a":{"cx":"100","cy":"16","r":"3.6","fill":"#800080"}},{"t":"path","a":{"d":"M50 60 C70 54 130 54 150 60 C152 68 146 74 136 75 C112 70 88 70 64 75 C54 74 48 68 50 60 Z","fill":"#800080"}},{"t":"path","a":{"d":"M60 62 C80 58 120 58 140 62","stroke":"#ffffff","strokeWidth":"1.6","fill":"none","opacity":"0.35"}}]},"hat/victory-band.svg":{"front":[{"t":"path","a":{"d":"M145 55 L166 46 L163 59 Z","fill":"#f4f1ea"}},{"t":"path","a":{"d":"M160 48.5 L166 46 L165 51.5 Z","fill":"#d61f2c"}},{"t":"path","a":{"d":"M145 61 L167 71 L157 76 Z","fill":"#f4f1ea"}},{"t":"path","a":{"d":"M161 73.2 L167 71 L162.5 75.5 Z","fill":"#d61f2c"}},{"t":"path","a":{"d":"M53 52 C76 44 124 44 147 52 L148 66 C124 58 76 58 52 66 Z","fill":"#f4f1ea"}},{"t":"path","a":{"d":"M53 52 C76 44 124 44 147 52 L147.2 55 C124 47 76 47 52.8 55 Z","fill":"#d61f2c"}},{"t":"path","a":{"d":"M52.2 63 C76 55 124 55 147.8 63 L148 66 C124 58 76 58 52 66 Z","fill":"#d61f2c"}},{"t":"path","a":{"d":"M120 49 C130 50 140 52 147 55 L147.8 63 C140 60 130 58 120 57 Z","fill":"#000000","opacity":"0.08"}},{"t":"circle","a":{"cx":"148","cy":"59","r":"5.5","fill":"#e3ddd0"}},{"t":"circle","a":{"cx":"148","cy":"59","r":"5.5","fill":"none","stroke":"#d61f2c","strokeWidth":"1.2"}}]},"hat/bamboo.svg":{"front":[{"t":"path","a":{"d":"M12 64 C40 44 74 18 100 8 C126 18 160 44 188 64 C150 74 50 74 12 64 Z","fill":"#d9b56a"}},{"t":"path","a":{"d":"M100 8 C126 18 160 44 188 64 C170 68 150 70 128 71 C130 50 118 24 100 8 Z","fill":"#b8913f","opacity":"0.35"}},{"t":"path","a":{"d":"M100 10 L40 66 M100 10 L64 70 M100 10 L88 72 M100 10 L112 72 M100 10 L136 70 M100 10 L160 66","stroke":"#a5822f","strokeWidth":"1.3","fill":"none","opacity":"0.6"}},{"t":"path","a":{"d":"M38 47 C70 55 130 55 162 47 M66 28 C84 34 116 34 134 28","stroke":"#a5822f","strokeWidth":"1.3","fill":"none","opacity":"0.55"}},{"t":"path","a":{"d":"M12 64 C50 74 150 74 188 64 C186 70 176 74 160 76 C120 80 80 80 40 76 C24 74 14 70 12 64 Z","fill":"#b8913f"}},{"t":"path","a":{"d":"M98 14 C84 24 64 40 44 54","stroke":"#ffffff","strokeWidth":"2.4","opacity":"0.3","fill":"none","strokeLinecap":"round"}},{"t":"circle","a":{"cx":"100","cy":"9","r":"3.2","fill":"#8a6a2a"}}]},"hat/helmet.svg":{"front":[{"t":"path","a":{"d":"M46 96 C40 42 64 14 100 14 C136 14 160 42 154 96 L144 100 C146 72 128 60 100 60 C72 60 54 72 56 100 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M94 14.6 C98 14.2 102 14.2 106 14.6 L106 60.3 C102 60.1 98 60.1 94 60.3 Z","fill":"#00ffff"}},{"t":"path","a":{"d":"M100 14 C136 14 160 42 154 96 L144 100 C146 76 136 64 122 61 C128 40 118 20 100 14 Z","fill":"#000000","opacity":"0.12"}},{"t":"path","a":{"d":"M46 96 C40 42 64 14 100 14 C136 14 160 42 154 96 L144 100 C146 72 128 60 100 60 C72 60 54 72 56 100 Z","fill":"none","stroke":"#800080","strokeWidth":"1.6","opacity":"0.5"}},{"t":"path","a":{"d":"M58 66 C78 56 122 56 142 66 L140 72 C120 63 80 63 60 72 Z","fill":"#2b2f36"}},{"t":"ellipse","a":{"cx":"76","cy":"32","rx":"12","ry":"5.5","fill":"#ffffff","opacity":"0.4","transform":"rotate(-32 76 32)"}},{"t":"path","a":{"d":"M57 99 C62 124 76 142 92 150 M143 99 C138 124 124 142 108 150","stroke":"#2b2f36","strokeWidth":"2.4","fill":"none","strokeLinecap":"round","opacity":"0.85"}}]},"hat/bucket.svg":{"front":[{"t":"path","a":{"d":"M58 54 C56 26 74 15 100 15 C126 15 144 26 142 54 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M100 15 C126 15 144 26 142 54 L124 54 C126 34 116 19 100 15 Z","fill":"#800080","opacity":"0.3"}},{"t":"path","a":{"d":"M57.6 46 L142.4 46 L142 54 L58 54 Z","fill":"#800080"}},{"t":"path","a":{"d":"M36 70 C42 56 68 51 100 51 C132 51 158 56 164 70 C150 75 126 69 100 69 C74 69 50 75 36 70 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M40 68 C58 60 142 60 160 68","stroke":"#800080","strokeWidth":"1.4","fill":"none","opacity":"0.6"}},{"t":"path","a":{"d":"M36 70 C50 75 74 69 100 69 C126 69 150 75 164 70 C160 74 150 77 140 76 C120 73 80 73 60 76 C50 77 40 74 36 70 Z","fill":"#800080","opacity":"0.55"}}]},"mask/plain.svg":{"front":[{"t":"path","a":{"d":"M64 108 C55 104 53 96 57 91 M136 108 C145 104 147 96 143 91","stroke":"#c4ccd6","strokeWidth":"2.2","fill":"none","strokeLinecap":"round"}},{"t":"path","a":{"d":"M63 106 C80 100 120 100 137 106 L135 128 C127 145 113 150 100 150 C87 150 73 145 65 128 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M118 102 C126 103 132 104 137 106 L135 128 C129 141 120 147 110 149 C120 138 124 122 118 102 Z","fill":"#800080","opacity":"0.2"}},{"t":"path","a":{"d":"M67 114 Q100 109 133 114 M67 122 Q100 117 133 122 M70 130 Q100 126 130 130","stroke":"#800080","strokeWidth":"1.5","fill":"none","opacity":"0.45"}},{"t":"path","a":{"d":"M84 103.5 Q100 100.5 116 103.5","stroke":"#ffffff","strokeWidth":"2","fill":"none","opacity":"0.7","strokeLinecap":"round"}}]},"mask/number.svg":{"front":[{"t":"path","a":{"d":"M64 108 C55 104 53 96 57 91 M136 108 C145 104 147 96 143 91","stroke":"#c4ccd6","strokeWidth":"2.2","fill":"none","strokeLinecap":"round"}},{"t":"path","a":{"d":"M63 106 C80 100 120 100 137 106 L135 128 C127 145 113 150 100 150 C87 150 73 145 65 128 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M118 102 C126 103 132 104 137 106 L135 128 C129 141 120 147 110 149 C120 138 124 122 118 102 Z","fill":"#800080","opacity":"0.2"}},{"t":"path","a":{"d":"M65 140 C76 147 88 150 100 150 C112 150 124 147 135 140 L134 132 C124 139 112 142 100 142 C88 142 76 139 66 132 Z","fill":"#00ffff"}},{"t":"path","a":{"d":"M67 113 Q100 108 133 113","stroke":"#800080","strokeWidth":"1.5","fill":"none","opacity":"0.45"}},{"t":"path","a":{"d":"M84 103.5 Q100 100.5 116 103.5","stroke":"#ffffff","strokeWidth":"2","fill":"none","opacity":"0.7","strokeLinecap":"round"}}]},"outer/campaign-vest.svg":{"front":[{"t":"path","a":{"d":"M84 165 C74 165 62 167 53 171 C58 182 56 196 46 204 L43 220 L99 220 L99 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M116 165 C126 165 138 167 147 171 C142 182 144 196 154 204 L157 220 L101 220 L101 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M130 166 C138 167 143 169 147 171 C142 182 144 196 154 204 L157 220 L136 220 C140 200 138 180 130 166 Z","fill":"#800080","opacity":"0.35"}},{"t":"path","a":{"d":"M84 165 L99 208 L99 220 M116 165 L101 208 L101 220 M53 171 C58 182 56 196 46 204 M147 171 C142 182 144 196 154 204","stroke":"#800080","strokeWidth":"2","fill":"none"}},{"t":"circle","a":{"cx":"70","cy":"194","r":"11","fill":"#ffffff"}},{"t":"path","a":{"d":"M110 210 L144 210","stroke":"#800080","strokeWidth":"1.6","fill":"none","opacity":"0.7"}}]},"outer/volunteer-vest.svg":{"front":[{"t":"path","a":{"d":"M84 165 C74 165 62 167 53 171 C58 182 56 196 46 204 L43 220 L99 220 L99 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M116 165 C126 165 138 167 147 171 C142 182 144 196 154 204 L157 220 L101 220 L101 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M130 166 C138 167 143 169 147 171 C142 182 144 196 154 204 L157 220 L136 220 C140 200 138 180 130 166 Z","fill":"#800080","opacity":"0.3"}},{"t":"g","a":{"fill":"#800080","opacity":"0.28"},"c":[{"t":"circle","a":{"cx":"62","cy":"182","r":"1.4"}},{"t":"circle","a":{"cx":"70","cy":"186","r":"1.4"}},{"t":"circle","a":{"cx":"78","cy":"182","r":"1.4"}},{"t":"circle","a":{"cx":"62","cy":"206","r":"1.4"}},{"t":"circle","a":{"cx":"74","cy":"210","r":"1.4"}},{"t":"circle","a":{"cx":"86","cy":"206","r":"1.4"}},{"t":"circle","a":{"cx":"54","cy":"214","r":"1.4"}},{"t":"circle","a":{"cx":"88","cy":"190","r":"1.4"}},{"t":"circle","a":{"cx":"140","cy":"208","r":"1.4"}},{"t":"circle","a":{"cx":"128","cy":"212","r":"1.4"}},{"t":"circle","a":{"cx":"114","cy":"206","r":"1.4"}},{"t":"circle","a":{"cx":"146","cy":"214","r":"1.4"}}]},{"t":"path","a":{"d":"M84 165 L99 208 L99 220 M116 165 L101 208 L101 220 M53 171 C58 182 56 196 46 204 M147 171 C142 182 144 196 154 204","stroke":"#800080","strokeWidth":"2","fill":"none"}},{"t":"rect","a":{"x":"113","y":"184","width":"28","height":"16","rx":"2.5","fill":"#ffffff"}}]},"outer/hivis.svg":{"front":[{"t":"path","a":{"d":"M84 165 C74 165 62 167 53 171 C58 182 56 196 46 204 L43 220 L99 220 L99 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M116 165 C126 165 138 167 147 171 C142 182 144 196 154 204 L157 220 L101 220 L101 208 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M130 166 C138 167 143 169 147 171 C142 182 144 196 154 204 L157 220 L136 220 C140 200 138 180 130 166 Z","fill":"#800080","opacity":"0.3"}},{"t":"path","a":{"d":"M55.6 186 L92.5 186 L94.6 192 L55.2 192 Z M45.6 206 L99 206 L99 212 L44.5 212 Z M144.4 186 L107.5 186 L105.4 192 L144.8 192 Z M154.4 206 L101 206 L101 212 L155.5 212 Z","fill":"#d9dee5"}},{"t":"path","a":{"d":"M55.4 189 L93.5 189 M45 209 L99 209 M144.6 189 L106.5 189 M155 209 L101 209","stroke":"#ffffff","strokeWidth":"1.4","opacity":"0.8","fill":"none"}},{"t":"path","a":{"d":"M84 165 L99 208 L99 220 M116 165 L101 208 L101 220 M53 171 C58 182 56 196 46 204 M147 171 C142 182 144 196 154 204","stroke":"#800080","strokeWidth":"2","fill":"none"}}]},"outer/raincoat.svg":{"front":[{"t":"path","a":{"d":"M12 220 C16 180 50 161 100 159 C150 161 184 180 188 220 Z","fill":"#ff00ff","opacity":"0.6"}},{"t":"path","a":{"d":"M100 159 C150 161 184 180 188 220 L152 220 C154 196 142 172 100 159 Z","fill":"#800080","opacity":"0.15"}},{"t":"path","a":{"d":"M76 166 C82 154 118 154 124 166 C118 173 82 173 76 166 Z","fill":"#ff00ff","opacity":"0.9"}},{"t":"path","a":{"d":"M80 165 C88 159 112 159 120 165","stroke":"#800080","strokeWidth":"1.4","fill":"none","opacity":"0.6"}},{"t":"path","a":{"d":"M100 172 L100 220","stroke":"#800080","strokeWidth":"1.6","opacity":"0.55","fill":"none"}},{"t":"circle","a":{"cx":"100","cy":"182","r":"2.4","fill":"#800080"}},{"t":"circle","a":{"cx":"100","cy":"198","r":"2.4","fill":"#800080"}},{"t":"circle","a":{"cx":"100","cy":"214","r":"2.4","fill":"#800080"}},{"t":"path","a":{"d":"M34 202 C38 189 48 181 60 176 M150 178 C160 182 168 190 172 200","stroke":"#ffffff","strokeWidth":"3","opacity":"0.55","fill":"none","strokeLinecap":"round"}},{"t":"path","a":{"d":"M70 196 L74 206 M128 192 L131 200 M56 212 L58 218","stroke":"#ffffff","strokeWidth":"1.8","opacity":"0.6","fill":"none","strokeLinecap":"round"}}]},"sash/red.svg":{"front":[{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L177 220 L151 220 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L83 169.3 Q70 171 61 178.2 Z","fill":"#800080"}},{"t":"path","a":{"d":"M79.5 168.8 L174 220 M58 177.6 L153 220","stroke":"#ffd23f","strokeWidth":"1.8","fill":"none"}}]},"sash/thanks.svg":{"front":[{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L177 220 L151 220 Z","fill":"#ffd23f"}},{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L83 169.3 Q70 171 61 178.2 Z","fill":"#d9a514"}},{"t":"path","a":{"d":"M79.5 168.8 L174 220 M58 177.6 L153 220","stroke":"#d61f2c","strokeWidth":"1.8","fill":"none"}}]},"sash/gold.svg":{"front":[{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L177 220 L151 220 Z","fill":"#e8b923"}},{"t":"path","a":{"d":"M66 170 L170 220 L160 220 L60 173 Z","fill":"#fff3b0","opacity":"0.45"}},{"t":"path","a":{"d":"M55 175 Q64 168 77 166 L83 169.3 Q70 171 61 178.2 Z","fill":"#b8860b"}},{"t":"path","a":{"d":"M79.5 168.8 L174 220 M58 177.6 L153 220","stroke":"#fff6c8","strokeWidth":"1.8","fill":"none"}},{"t":"path","a":{"d":"M86 176 L88 180 L92 181 L88 182 L86 186 L84 182 L80 181 L84 180 Z M150 206 L151.6 209 L155 210 L151.6 211 L150 214 L148.4 211 L145 210 L148.4 209 Z","fill":"#ffffff"}}]},"chest/corsage.svg":{"front":[{"t":"path","a":{"d":"M134 186 L127 210 L132 206 L135 212 L138 188 Z M142 186 L149 210 L144 206 L141 212 L138 188 Z","fill":"#b3121d"}},{"t":"g","a":{"fill":"#d61f2c"},"c":[{"t":"circle","a":{"cx":"145","cy":"182","r":"5.6"}},{"t":"circle","a":{"cx":"142.95","cy":"186.95","r":"5.6"}},{"t":"circle","a":{"cx":"138","cy":"189","r":"5.6"}},{"t":"circle","a":{"cx":"133.05","cy":"186.95","r":"5.6"}},{"t":"circle","a":{"cx":"131","cy":"182","r":"5.6"}},{"t":"circle","a":{"cx":"133.05","cy":"177.05","r":"5.6"}},{"t":"circle","a":{"cx":"138","cy":"175","r":"5.6"}},{"t":"circle","a":{"cx":"142.95","cy":"177.05","r":"5.6"}}]},{"t":"g","a":{"fill":"#ef3b48"},"c":[{"t":"circle","a":{"cx":"141.5","cy":"182","r":"3.8"}},{"t":"circle","a":{"cx":"139.75","cy":"185.03","r":"3.8"}},{"t":"circle","a":{"cx":"136.25","cy":"185.03","r":"3.8"}},{"t":"circle","a":{"cx":"134.5","cy":"182","r":"3.8"}},{"t":"circle","a":{"cx":"136.25","cy":"178.97","r":"3.8"}},{"t":"circle","a":{"cx":"139.75","cy":"178.97","r":"3.8"}}]},{"t":"circle","a":{"cx":"138","cy":"182","r":"3.6","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"136.8","cy":"180.8","r":"1.2","fill":"#ffffff","opacity":"0.7"}}]},"chest/name-tag.svg":{"front":[{"t":"rect","a":{"x":"134","y":"175","width":"8","height":"5","rx":"1.2","fill":"#9aa3ad"}},{"t":"rect","a":{"x":"122","y":"178","width":"32","height":"17","rx":"2","fill":"#ffffff"}},{"t":"rect","a":{"x":"122","y":"178","width":"32","height":"17","rx":"2","fill":"none","stroke":"#c4ccd6","strokeWidth":"1"}},{"t":"rect","a":{"x":"122","y":"178","width":"32","height":"5","rx":"1.5","fill":"#ff00ff"}}]},"held/megaphone.svg":{"front":[{"t":"circle","a":{"cx":"150","cy":"176","r":"5.5","fill":"#2b2f36"}},{"t":"path","a":{"d":"M145.8 171.8 L172.7 130.7 L195.3 153.3 L154.2 180.2 Z","fill":"#f4f1ea"}},{"t":"path","a":{"d":"M154.2 180.2 L195.3 153.3 L184 142 L150 176 Z","fill":"#000000","opacity":"0.1"}},{"t":"path","a":{"d":"M160.6 149.2 L164.6 143 L183 161.4 L176.8 165.4 Z","fill":"#d61f2c"}},{"t":"ellipse","a":{"cx":"184","cy":"142","rx":"16","ry":"6","transform":"rotate(45 184 142)","fill":"#3a3f47"}},{"t":"ellipse","a":{"cx":"184","cy":"142","rx":"16","ry":"6","transform":"rotate(45 184 142)","fill":"none","stroke":"#f4f1ea","strokeWidth":"2.4"}},{"t":"path","a":{"d":"M140 220 L148 199 C152 195 168 195 172 199 L182 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M164 197 C168 197 170 197 172 199 L182 220 L170 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M147 200 C152 195 168 195 173 200 L172 204 C167 200 153 200 148 204 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"160","cy":"188","rx":"13","ry":"11","fill":"#ffff00"}},{"t":"path","a":{"d":"M153 182 Q151 188 153 194 M159 181 Q157 188 159 195 M165 182 Q163 188 165 194","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"held/flag.svg":{"front":[{"t":"path","a":{"d":"M166 60 L198 79 L166 98 Z","fill":"#ff00ff"}},{"t":"path","a":{"d":"M166 79 L198 79 L166 98 Z","fill":"#800080","opacity":"0.3"}},{"t":"path","a":{"d":"M166 60 L198 79 L166 98","stroke":"#ffffff","strokeWidth":"1.6","fill":"none","opacity":"0.7"}},{"t":"circle","a":{"cx":"177","cy":"79","r":"7.5","fill":"#ffffff"}},{"t":"path","a":{"d":"M164 58 L164 196","stroke":"#6b4a2b","strokeWidth":"4","fill":"none","strokeLinecap":"round"}},{"t":"circle","a":{"cx":"164","cy":"56","r":"3.6","fill":"#ffd23f"}},{"t":"path","a":{"d":"M144 220 L152 199 C156 195 172 195 176 199 L186 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M168 197 C172 197 174 197 176 199 L186 220 L174 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M151 200 C156 195 172 195 177 200 L176 204 C171 200 157 200 152 204 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"164","cy":"186","rx":"13","ry":"11","fill":"#ffff00"}},{"t":"path","a":{"d":"M157 180 Q155 186 157 192 M163 179 Q161 186 163 193 M169 180 Q167 186 169 192","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"153","cy":"180","rx":"5.5","ry":"4.2","transform":"rotate(-30 153 180)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"153","cy":"180","rx":"5.5","ry":"4.2","transform":"rotate(-30 153 180)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"held/tissue.svg":{"front":[{"t":"g","a":{"transform":"rotate(-10 165 170)"},"c":[{"t":"rect","a":{"x":"147","y":"157","width":"36","height":"26","rx":"6","fill":"#ffffff"}},{"t":"rect","a":{"x":"147","y":"157","width":"36","height":"9","rx":"4","fill":"#ff00ff"}},{"t":"rect","a":{"x":"147","y":"162","width":"36","height":"4","fill":"#ff00ff"}},{"t":"path","a":{"d":"M155 160.5 Q165 154 175 160.5","stroke":"#ffffff","strokeWidth":"2.2","fill":"none","strokeLinecap":"round"}},{"t":"rect","a":{"x":"147","y":"157","width":"36","height":"26","rx":"6","fill":"none","stroke":"#c4ccd6","strokeWidth":"1"}}]},{"t":"path","a":{"d":"M140 220 L148 199 C152 195 168 195 172 199 L182 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M164 197 C168 197 170 197 172 199 L182 220 L170 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M147 200 C152 195 168 195 173 200 L172 204 C167 200 153 200 148 204 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"160","cy":"188","rx":"13","ry":"11","fill":"#ffff00"}},{"t":"path","a":{"d":"M153 182 Q151 188 153 194 M159 181 Q157 188 159 195 M165 182 Q163 188 165 194","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"held/fan.svg":{"front":[{"t":"path","a":{"d":"M162 196 L168 162","stroke":"#6b4a2b","strokeWidth":"4.5","fill":"none","strokeLinecap":"round"}},{"t":"circle","a":{"cx":"170","cy":"140","r":"24","fill":"#ff00ff"}},{"t":"path","a":{"d":"M170 116 A24 24 0 0 1 170 164 Z","fill":"#800080","opacity":"0.25"}},{"t":"path","a":{"d":"M152 124 L188 156 M150 140 L190 140 M152 156 L188 124","stroke":"#ffffff","strokeWidth":"1.2","opacity":"0.25","fill":"none"}},{"t":"circle","a":{"cx":"170","cy":"140","r":"14","fill":"#ffffff"}},{"t":"circle","a":{"cx":"170","cy":"140","r":"24","fill":"none","stroke":"#800080","strokeWidth":"2"}},{"t":"path","a":{"d":"M140 220 L148 199 C152 195 168 195 172 199 L182 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M164 197 C168 197 170 197 172 199 L182 220 L170 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M147 200 C152 195 168 195 173 200 L172 204 C167 200 153 200 148 204 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"160","cy":"188","rx":"13","ry":"11","fill":"#ffff00"}},{"t":"path","a":{"d":"M153 182 Q151 188 153 194 M159 181 Q157 188 159 195 M165 182 Q163 188 165 194","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"held/mic.svg":{"front":[{"t":"path","a":{"d":"M146.5 190 L131 161 L139 156.4 L153.5 186 Z","fill":"#2b2f36"}},{"t":"path","a":{"d":"M131 161 L139 156.4 L141.4 160.5 L133.4 165.1 Z","fill":"#9aa3ad"}},{"t":"circle","a":{"cx":"131","cy":"151","r":"10","fill":"#5a6370"}},{"t":"path","a":{"d":"M123 146 L137 156 M121 151 L135 160 M126 143 L140 151 M128 141 L122 156 M134 142 L127 159 M139 146 L133 160","stroke":"#2b2f36","strokeWidth":"1.1","fill":"none","opacity":"0.7"}},{"t":"circle","a":{"cx":"127","cy":"147","r":"3","fill":"#ffffff","opacity":"0.4"}},{"t":"path","a":{"d":"M136 220 L144 201 C148 197 164 197 168 201 L178 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M160 199 C164 199 166 199 168 201 L178 220 L166 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M143 202 C148 197 164 197 169 202 L168 206 C163 202 149 202 144 206 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"156","cy":"191","rx":"12.5","ry":"10.5","fill":"#ffff00"}},{"t":"path","a":{"d":"M150 185 Q148 191 150 197 M156 184 Q154 191 156 198 M162 185 Q160 191 162 197","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"146","cy":"185","rx":"5.2","ry":"4","transform":"rotate(-30 146 185)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"146","cy":"185","rx":"5.2","ry":"4","transform":"rotate(-30 146 185)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"held/thermos.svg":{"front":[{"t":"rect","a":{"x":"148","y":"140","width":"26","height":"58","rx":"5","fill":"#ff00ff"}},{"t":"path","a":{"d":"M164 140 L169 140 A5 5 0 0 1 174 145 L174 193 A5 5 0 0 1 169 198 L164 198 Z","fill":"#800080","opacity":"0.35"}},{"t":"rect","a":{"x":"152","y":"146","width":"4","height":"44","rx":"2","fill":"#ffffff","opacity":"0.55"}},{"t":"rect","a":{"x":"146","y":"131","width":"30","height":"12","rx":"3.5","fill":"#2b2f36"}},{"t":"rect","a":{"x":"150","y":"133","width":"22","height":"2.5","rx":"1.2","fill":"#ffffff","opacity":"0.25"}},{"t":"path","a":{"d":"M140 220 L148 199 C152 195 168 195 172 199 L182 220 Z","fill":"#0000ff"}},{"t":"path","a":{"d":"M164 197 C168 197 170 197 172 199 L182 220 L170 220 Z","fill":"#000080","opacity":"0.5"}},{"t":"path","a":{"d":"M147 200 C152 195 168 195 173 200 L172 204 C167 200 153 200 148 204 Z","fill":"#00ff00"}},{"t":"ellipse","a":{"cx":"160","cy":"188","rx":"13","ry":"11","fill":"#ffff00"}},{"t":"path","a":{"d":"M153 182 Q151 188 153 194 M159 181 Q157 188 159 195 M165 182 Q163 188 165 194","stroke":"#808000","strokeWidth":"1.6","fill":"none","opacity":"0.6","strokeLinecap":"round"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"#ffff00"}},{"t":"ellipse","a":{"cx":"149","cy":"182","rx":"5.5","ry":"4.2","transform":"rotate(-30 149 182)","fill":"none","stroke":"#808000","strokeWidth":"1.2","opacity":"0.6"}}]},"frame/gazette.svg":{"front":[{"t":"path","a":{"d":"M24 0 H176 A24 24 0 0 1 200 24 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 V24 A24 24 0 0 1 24 0 Z M13 9 H187 A4 4 0 0 1 191 13 V186 A4 4 0 0 1 187 190 H13 A4 4 0 0 1 9 186 V13 A4 4 0 0 1 13 9 Z","fill":"#f8f4ea","fillRule":"evenodd"}},{"t":"path","a":{"d":"M13 9 H187 A4 4 0 0 1 191 13 V186 A4 4 0 0 1 187 190 H13 A4 4 0 0 1 9 186 V13 A4 4 0 0 1 13 9 Z","fill":"none","stroke":"#111419","strokeWidth":"2"}},{"t":"rect","a":{"x":"12","y":"194","width":"26","height":"20","rx":"3","fill":"#111419"}},{"t":"path","a":{"d":"M44 196 L44 212 M150 196 L150 212","stroke":"#c9c3b0","strokeWidth":"1.4","fill":"none"}}]},"frame/billboard.svg":{"front":[{"t":"path","a":{"d":"M24 0 H176 A24 24 0 0 1 200 24 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 V24 A24 24 0 0 1 24 0 Z M16 13 H184 A3 3 0 0 1 187 16 V183 A3 3 0 0 1 184 186 H16 A3 3 0 0 1 13 183 V16 A3 3 0 0 1 16 13 Z","fill":"#ff00ff","fillRule":"evenodd"}},{"t":"path","a":{"d":"M34 0 L42 0 L35 13 L27 13 Z M54 0 L62 0 L55 13 L47 13 Z M74 0 L82 0 L75 13 L67 13 Z M94 0 L102 0 L95 13 L87 13 Z M114 0 L122 0 L115 13 L107 13 Z M134 0 L142 0 L135 13 L127 13 Z M154 0 L162 0 L155 13 L147 13 Z","fill":"#ffffff","opacity":"0.2"}},{"t":"path","a":{"d":"M16 13 H184 A3 3 0 0 1 187 16 V183 A3 3 0 0 1 184 186 H16 A3 3 0 0 1 13 183 V16 A3 3 0 0 1 16 13 Z","fill":"none","stroke":"#111419","strokeWidth":"2.5"}},{"t":"path","a":{"d":"M0 186 H200 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 Z","fill":"#ffd23f"}},{"t":"path","a":{"d":"M0 186 H200","stroke":"#111419","strokeWidth":"2.5","fill":"none"}},{"t":"circle","a":{"cx":"6.5","cy":"100","r":"2.6","fill":"#9aa3ad"}},{"t":"circle","a":{"cx":"193.5","cy":"100","r":"2.6","fill":"#9aa3ad"}},{"t":"circle","a":{"cx":"100","cy":"6.5","r":"2.6","fill":"#9aa3ad"}}]},"frame/newspaper.svg":{"front":[{"t":"path","a":{"d":"M24 0 H176 A24 24 0 0 1 200 24 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 V24 A24 24 0 0 1 24 0 Z M12 10 H188 A2 2 0 0 1 190 12 V182 A2 2 0 0 1 188 184 H12 A2 2 0 0 1 10 182 V12 A2 2 0 0 1 12 10 Z","fill":"#efe9d8","fillRule":"evenodd"}},{"t":"path","a":{"d":"M12 10 H188 A2 2 0 0 1 190 12 V182 A2 2 0 0 1 188 184 H12 A2 2 0 0 1 10 182 V12 A2 2 0 0 1 12 10 Z","fill":"none","stroke":"#3a3a3a","strokeWidth":"1.4"}},{"t":"path","a":{"d":"M30 5 H170","stroke":"#3a3a3a","strokeWidth":"1","fill":"none"}},{"t":"rect","a":{"x":"12","y":"190","width":"48","height":"24","rx":"3","fill":"#d61f2c"}},{"t":"g","a":{"fill":"#8a8577","opacity":"0.75"},"c":[{"t":"rect","a":{"x":"68","y":"190","width":"118","height":"3.2","rx":"1"}},{"t":"rect","a":{"x":"68","y":"197","width":"108","height":"3.2","rx":"1"}},{"t":"rect","a":{"x":"68","y":"204","width":"116","height":"3.2","rx":"1"}},{"t":"rect","a":{"x":"68","y":"211","width":"88","height":"3.2","rx":"1"}}]}]},"frame/gold.svg":{"front":[{"t":"path","a":{"d":"M24 0 H176 A24 24 0 0 1 200 24 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 V24 A24 24 0 0 1 24 0 Z M14 10 H186 A4 4 0 0 1 190 14 V188 A4 4 0 0 1 186 192 H14 A4 4 0 0 1 10 188 V14 A4 4 0 0 1 14 10 Z","fill":"#e8b923","fillRule":"evenodd"}},{"t":"path","a":{"d":"M14 10 H186 A4 4 0 0 1 190 14 V188 A4 4 0 0 1 186 192 H14 A4 4 0 0 1 10 188 V14 A4 4 0 0 1 14 10 Z","fill":"none","stroke":"#b8860b","strokeWidth":"2.5"}},{"t":"path","a":{"d":"M24 2.5 H176 A21.5 21.5 0 0 1 197.5 24 V196 A21.5 21.5 0 0 1 176 217.5 H24 A21.5 21.5 0 0 1 2.5 196 V24 A21.5 21.5 0 0 1 24 2.5 Z","fill":"none","stroke":"#fff6c8","strokeWidth":"1.4","opacity":"0.8"}},{"t":"path","a":{"d":"M12 5 L14.5 9.5 L19 12 L14.5 14.5 L12 19 L9.5 14.5 L5 12 L9.5 9.5 Z M188 5 L190.5 9.5 L195 12 L190.5 14.5 L188 19 L185.5 14.5 L181 12 L185.5 9.5 Z","fill":"#fff6c8"}},{"t":"g","a":{"fill":"#b8860b"},"c":[{"t":"ellipse","a":{"cx":"22","cy":"180","rx":"6","ry":"2.6","transform":"rotate(-62 22 180)"}},{"t":"ellipse","a":{"cx":"27","cy":"190","rx":"6","ry":"2.6","transform":"rotate(-38 27 190)"}},{"t":"ellipse","a":{"cx":"36","cy":"197","rx":"6","ry":"2.6","transform":"rotate(-14 36 197)"}},{"t":"ellipse","a":{"cx":"178","cy":"180","rx":"6","ry":"2.6","transform":"rotate(62 178 180)"}},{"t":"ellipse","a":{"cx":"173","cy":"190","rx":"6","ry":"2.6","transform":"rotate(38 173 190)"}},{"t":"ellipse","a":{"cx":"164","cy":"197","rx":"6","ry":"2.6","transform":"rotate(14 164 197)"}}]},{"t":"path","a":{"d":"M54 196 H146 L154 206 L146 216 H54 L46 206 Z","fill":"#d61f2c"}},{"t":"path","a":{"d":"M54 196 H146 L150 201 H50 Z","fill":"#ffffff","opacity":"0.2"}}]},"frame/neon.svg":{"front":[{"t":"path","a":{"d":"M24 0 H176 A24 24 0 0 1 200 24 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 V24 A24 24 0 0 1 24 0 Z M19 13 H181 A6 6 0 0 1 187 19 V178 A6 6 0 0 1 181 184 H19 A6 6 0 0 1 13 178 V19 A6 6 0 0 1 19 13 Z","fill":"#1a2440","fillRule":"evenodd"}},{"t":"path","a":{"d":"M19 13 H181 A6 6 0 0 1 187 19 V178 A6 6 0 0 1 181 184 H19 A6 6 0 0 1 13 178 V19 A6 6 0 0 1 19 13 Z","fill":"none","stroke":"#ff4d9a","strokeWidth":"6","opacity":"0.3"}},{"t":"path","a":{"d":"M19 13 H181 A6 6 0 0 1 187 19 V178 A6 6 0 0 1 181 184 H19 A6 6 0 0 1 13 178 V19 A6 6 0 0 1 19 13 Z","fill":"none","stroke":"#ff4d9a","strokeWidth":"2.4"}},{"t":"path","a":{"d":"M0 184 H200 V196 A24 24 0 0 1 176 220 H24 A24 24 0 0 1 0 196 Z","fill":"#111a30"}},{"t":"path","a":{"d":"M8 186 H192","stroke":"#4ad6ff","strokeWidth":"2","fill":"none"}},{"t":"circle","a":{"cx":"30","cy":"6.5","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"29.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"44","cy":"6.5","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"43.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"58","cy":"6.5","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"57.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"72","cy":"6.5","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"71.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"86","cy":"6.5","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"85.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"100","cy":"6.5","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"99.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"114","cy":"6.5","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"113.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"128","cy":"6.5","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"127.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"142","cy":"6.5","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"141.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"156","cy":"6.5","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"155.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"170","cy":"6.5","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"169.2","cy":"5.7","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"30","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"5.7","cy":"29.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"44","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"5.7","cy":"43.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"58","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"5.7","cy":"57.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"72","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"5.7","cy":"71.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"86","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"5.7","cy":"85.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"100","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"5.7","cy":"99.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"114","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"5.7","cy":"113.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"128","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"5.7","cy":"127.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"142","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"5.7","cy":"141.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"156","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"5.7","cy":"155.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"6.5","cy":"170","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"5.7","cy":"169.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"30","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"192.7","cy":"29.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"44","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"192.7","cy":"43.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"58","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"192.7","cy":"57.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"72","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"192.7","cy":"71.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"86","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"192.7","cy":"85.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"100","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"192.7","cy":"99.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"114","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"192.7","cy":"113.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"128","r":"3.2","fill":"#ff4d5a"}},{"t":"circle","a":{"cx":"192.7","cy":"127.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"142","r":"3.2","fill":"#4ad6ff"}},{"t":"circle","a":{"cx":"192.7","cy":"141.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"156","r":"3.2","fill":"#7dff7a"}},{"t":"circle","a":{"cx":"192.7","cy":"155.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}},{"t":"circle","a":{"cx":"193.5","cy":"170","r":"3.2","fill":"#ffd23f"}},{"t":"circle","a":{"cx":"192.7","cy":"169.2","r":"1.1","fill":"#ffffff","opacity":"0.8"}}]}}; diff --git a/backend/packages/protocol/src/avatar/catalog.generated.ts b/backend/packages/protocol/src/avatar/catalog.generated.ts new file mode 100644 index 0000000..6289fd8 --- /dev/null +++ b/backend/packages/protocol/src/avatar/catalog.generated.ts @@ -0,0 +1,2453 @@ +// 這個檔是 scripts/build-avatar-catalog.ts 產生的,不要手改:改 data/avatar-catalog.json 或 art/avatar/*.svg 之後跑 pnpm avatar:build +import type { AvatarCatalog } from "./schema.ts"; + +export const AVATAR_CATALOG: AvatarCatalog = { + "catalogVersion": 3, + "styles": [ + { + "id": "comic", + "name": "海報漫畫", + "note": "競選海報風:粗墨線、平塗色塊、大圖加網點陰影" + }, + { + "id": "chibi", + "name": "Q 版大頭", + "note": "頭大身體小、大眼睛加反光點、腮紅深一點" + }, + { + "id": "pixel", + "name": "復刻像素", + "note": "致敬 1994 年原作:縮成小點陣、16 色、方塊放大" + }, + { + "id": "sticker", + "name": "平面貼紙", + "note": "粗白邊、去掉陰影,像一張貼紙" + } + ], + "slots": [ + { + "id": "face", + "name": "臉型", + "tab": "face", + "field": "face", + "optional": true, + "default": "oval", + "small": "show", + "ui": true + }, + { + "id": "eyes", + "name": "眼睛", + "tab": "face", + "field": "eyes", + "optional": true, + "default": "round", + "small": "show", + "ui": true + }, + { + "id": "brows", + "name": "眉毛", + "tab": "face", + "field": "brows", + "optional": true, + "default": "normal", + "small": "show", + "ui": true + }, + { + "id": "mouth", + "name": "表情", + "tab": "face", + "field": "mouth", + "optional": true, + "default": "smile", + "small": "show", + "ui": true + }, + { + "id": "nose", + "name": "鼻子", + "tab": "face", + "field": "nose", + "optional": true, + "default": "normal", + "small": "show", + "ui": false + }, + { + "id": "ears", + "name": "耳朵", + "tab": "face", + "field": "ears", + "optional": true, + "default": "normal", + "small": "show", + "ui": false + }, + { + "id": "hair", + "name": "髮型", + "tab": "hair", + "field": "hair", + "optional": false, + "default": "short", + "small": "show", + "ui": true + }, + { + "id": "outfit", + "name": "服裝", + "tab": "outfit", + "field": "outfit", + "optional": false, + "default": "suit", + "small": "show", + "ui": true + }, + { + "id": "glasses", + "name": "眼鏡", + "tab": "extra", + "field": "glassesStyle", + "optional": true, + "default": "black", + "small": "show", + "ui": true + }, + { + "id": "mask", + "name": "口罩", + "tab": "extra", + "optional": true, + "default": null, + "small": "show", + "ui": true, + "layer": "face" + }, + { + "id": "hat", + "name": "帽子", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "ui": true, + "layer": "head" + }, + { + "id": "outer", + "name": "背心外套", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "ui": true, + "layer": "body" + }, + { + "id": "sash", + "name": "彩帶", + "tab": "gear", + "optional": true, + "default": null, + "small": "show", + "ui": true, + "layer": "body" + }, + { + "id": "chest", + "name": "胸前", + "tab": "gear", + "optional": true, + "default": null, + "small": "hide", + "ui": true, + "layer": "body" + }, + { + "id": "held", + "name": "手持物", + "tab": "props", + "optional": true, + "default": null, + "small": "hide", + "ui": true, + "layer": "hand" + }, + { + "id": "frame", + "name": "頭像外框", + "tab": "props", + "optional": true, + "default": null, + "small": "hide", + "ui": true, + "layer": "canvas" + } + ], + "palettes": { + "campaign": { + "strict": false, + "colors": [ + "party", + "#d61f2c", + "#ffd23f", + "#1b9431", + "#2349b8", + "#16a3a6", + "#ff7a1a", + "#7a5cc4", + "#111419", + "#f4f1ea" + ] + }, + "soft": { + "strict": false, + "colors": [ + "#eef3f7", + "#bfe3ff", + "#ffe27a", + "#ffc2d1", + "#c8f0c4", + "#e8dcc0", + "#b8c2cc", + "#2b2f36" + ] + }, + "hivis": { + "strict": false, + "colors": [ + "#ff7a1a", + "#c8f03c", + "#ffd23f" + ] + }, + "gold": { + "strict": false, + "colors": [ + "#e8b923", + "#f2d36b", + "#d61f2c" + ] + } + }, + "items": [ + { + "id": "oval", + "slot": "face", + "name": "鵝蛋臉", + "art": "builtin:oval", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "round", + "slot": "face", + "name": "圓臉", + "art": "builtin:round", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "long", + "slot": "face", + "name": "長臉", + "art": "builtin:long", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "square", + "slot": "face", + "name": "方臉", + "art": "builtin:square", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "heart", + "slot": "face", + "name": "瓜子臉", + "art": "builtin:heart", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "jowl", + "slot": "face", + "name": "大下巴", + "art": "builtin:jowl", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "round", + "slot": "eyes", + "name": "圓眼", + "art": "builtin:round", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "narrow", + "slot": "eyes", + "name": "細長眼", + "art": "builtin:narrow", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "dot", + "slot": "eyes", + "name": "豆豆眼", + "art": "builtin:dot", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "smile", + "slot": "eyes", + "name": "瞇瞇眼", + "art": "builtin:smile", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "droopy", + "slot": "eyes", + "name": "下垂眼", + "art": "builtin:droopy", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "wide", + "slot": "eyes", + "name": "大眼", + "art": "builtin:wide", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "thin", + "slot": "brows", + "name": "細眉", + "art": "builtin:thin", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "normal", + "slot": "brows", + "name": "一般", + "art": "builtin:normal", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "thick", + "slot": "brows", + "name": "濃眉", + "art": "builtin:thick", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "bushy", + "slot": "brows", + "name": "粗濃眉", + "art": "builtin:bushy", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "smile", + "slot": "mouth", + "name": "微笑", + "art": "builtin:smile", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "grin", + "slot": "mouth", + "name": "開心笑", + "art": "builtin:grin", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "closed", + "slot": "mouth", + "name": "抿嘴", + "art": "builtin:closed", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "teeth", + "slot": "mouth", + "name": "露齒笑", + "art": "builtin:teeth", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "smirk", + "slot": "mouth", + "name": "嘴角上揚", + "art": "builtin:smirk", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "laugh", + "slot": "mouth", + "name": "開懷大笑", + "art": "builtin:laugh", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "small", + "slot": "nose", + "name": "小鼻子", + "art": "builtin:small", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "normal", + "slot": "nose", + "name": "一般", + "art": "builtin:normal", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "big", + "slot": "nose", + "name": "大鼻子", + "art": "builtin:big", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "round", + "slot": "nose", + "name": "圓鼻頭", + "art": "builtin:round", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "small", + "slot": "ears", + "name": "小耳朵", + "art": "builtin:small", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "normal", + "slot": "ears", + "name": "一般", + "art": "builtin:normal", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "big", + "slot": "ears", + "name": "招風耳", + "art": "builtin:big", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "short", + "slot": "hair", + "name": "短髮", + "art": "builtin:short", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "side", + "slot": "hair", + "name": "旁分", + "art": "builtin:side", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "crew", + "slot": "hair", + "name": "小平頭", + "art": "builtin:crew", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "buzz", + "slot": "hair", + "name": "平頭", + "art": "builtin:buzz", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "slick", + "slot": "hair", + "name": "油頭", + "art": "builtin:slick", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "volume", + "slot": "hair", + "name": "蓬鬆旁分", + "art": "builtin:volume", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "receding", + "slot": "hair", + "name": "髮線後退", + "art": "builtin:receding", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "bald", + "slot": "hair", + "name": "光頭", + "art": "builtin:bald", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "bob", + "slot": "hair", + "name": "鮑伯頭", + "art": "builtin:bob", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "bobSide", + "slot": "hair", + "name": "側分鮑伯", + "art": "builtin:bobSide", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "shortBob", + "slot": "hair", + "name": "耳下短髮", + "art": "builtin:shortBob", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "long", + "slot": "hair", + "name": "長髮", + "art": "builtin:long", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "bun", + "slot": "hair", + "name": "包頭", + "art": "builtin:bun", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "curly", + "slot": "hair", + "name": "捲髮", + "art": "builtin:curly", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "perm", + "slot": "hair", + "name": "燙髮", + "art": "builtin:perm", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "flatTop", + "slot": "hair", + "name": "平頭板寸", + "art": "builtin:flatTop", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "middle", + "slot": "hair", + "name": "中分", + "art": "builtin:middle", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "combover", + "slot": "hair", + "name": "側梳地中海", + "art": "builtin:combover", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "spiky", + "slot": "hair", + "name": "抓立短髮", + "art": "builtin:spiky", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "pompadour", + "slot": "hair", + "name": "高聳背頭", + "art": "builtin:pompadour", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "longMiddle", + "slot": "hair", + "name": "長髮中分", + "art": "builtin:longMiddle", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "longWavy", + "slot": "hair", + "name": "長波浪", + "art": "builtin:longWavy", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "ponytail", + "slot": "hair", + "name": "馬尾", + "art": "builtin:ponytail", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "pixie", + "slot": "hair", + "name": "露耳短髮", + "art": "builtin:pixie", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "parted" + ], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "fringe", + "slot": "hair", + "name": "瀏海短髮", + "art": "builtin:fringe", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "longBangs", + "slot": "hair", + "name": "齊瀏海長髮", + "art": "builtin:longBangs", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "suit", + "slot": "outfit", + "name": "西裝領帶", + "art": "builtin:suit", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "tie" + ], + "zoom": "none", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "blouse", + "slot": "outfit", + "name": "套裝", + "art": "builtin:blouse", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "vest", + "slot": "outfit", + "name": "西裝背心", + "art": "builtin:vest", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "polo", + "slot": "outfit", + "name": "競選 Polo 衫", + "art": "builtin:polo", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "collar" + ], + "zoom": "none", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "shirt", + "slot": "outfit", + "name": "襯衫", + "art": "builtin:shirt", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [ + "collar" + ], + "zoom": "none", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "black", + "slot": "glasses", + "name": "黑粗框", + "art": "builtin:black", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "metal", + "slot": "glasses", + "name": "金屬框", + "art": "builtin:metal", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "round", + "slot": "glasses", + "name": "圓框", + "art": "builtin:round", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "halfRim", + "slot": "glasses", + "name": "半框", + "art": "builtin:halfRim", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "rimless", + "slot": "glasses", + "name": "無框", + "art": "builtin:rimless", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 1, + "credit": "原創(選舉小鎮)" + }, + { + "id": "browline", + "slot": "glasses", + "name": "眉框眼鏡", + "art": "builtin:browline", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 3, + "credit": "原創(選舉小鎮)" + }, + { + "id": "hat-campaign-cap", + "slot": "hat", + "name": "競選鴨舌帽", + "desc": "掃街標配,前面印號次,顏色跟政黨走。", + "art": "hat/campaign-cap.svg", + "anchor": "headTop", + "hideHairAbove": 60, + "tints": [ + { + "key": "main", + "name": "帽子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 100, + "y": 40.5, + "size": 15, + "rotate": 0, + "fill": "main", + "width": 18, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "head", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "hat-victory-band", + "slot": "hat", + "name": "必勝頭帶", + "desc": "造勢晚會最後衝刺,綁上就停不下來。", + "art": "hat/victory-band.svg", + "anchor": "headTop", + "tints": [], + "text": [ + { + "kind": "fixed", + "value": "必勝", + "x": 100, + "y": 53, + "size": 10, + "rotate": 0, + "fill": "#d61f2c", + "width": 26, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "head", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "hat-bamboo", + "slot": "hat", + "name": "斗笠", + "desc": "下鄉掃街、田埂拜票,遮陽又親切。", + "art": "hat/bamboo.svg", + "anchor": "headTop", + "hideHairAbove": 64, + "tints": [], + "text": [], + "rarity": "rare", + "get": { + "type": "shop", + "price": 20, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "head", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "hat-helmet", + "slot": "hat", + "name": "機車安全帽", + "desc": "騎機車掃街,安全第一。", + "art": "hat/helmet.svg", + "anchor": "headTop", + "hideHairAbove": 66, + "tints": [ + { + "key": "main", + "name": "帽殼", + "palette": "campaign", + "default": "#f4f1ea" + }, + { + "key": "accent", + "name": "條紋", + "palette": "campaign", + "default": "party" + } + ], + "text": [], + "rarity": "rare", + "get": { + "type": "shop", + "price": 24, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "head", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "hat-bucket", + "slot": "hat", + "name": "漁夫帽", + "desc": "夏天菜市場拜票的好朋友。", + "art": "hat/bucket.svg", + "anchor": "headTop", + "hideHairAbove": 56, + "tints": [ + { + "key": "main", + "name": "帽子顏色", + "palette": "soft", + "default": "#e8dcc0" + } + ], + "text": [], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "always" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "head", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "mask-plain", + "slot": "mask", + "name": "素色口罩", + "desc": "流感季節照樣拜票。", + "art": "mask/plain.svg", + "anchor": "face", + "tints": [ + { + "key": "main", + "name": "口罩顏色", + "palette": "soft", + "default": "#eef3f7" + } + ], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "face", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "mask-number", + "slot": "mask", + "name": "號次口罩", + "desc": "口罩也要印號次,選民才記得住。", + "art": "mask/number.svg", + "anchor": "face", + "tints": [ + { + "key": "main", + "name": "口罩顏色", + "palette": "soft", + "default": "#eef3f7" + }, + { + "key": "accent", + "name": "號次顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 100, + "y": 126, + "size": 17, + "rotate": 0, + "fill": "accent", + "width": 26, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6, + "shelf": "always" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "face", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "outer-campaign-vest", + "slot": "outer", + "name": "競選背心", + "desc": "候選人和志工的制服,印號次和名字。", + "art": "outer/campaign-vest.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 70, + "y": 194, + "size": 15, + "rotate": 0, + "fill": "main", + "width": 18, + "vertical": false + }, + { + "kind": "name", + "x": 127, + "y": 198, + "size": 9, + "rotate": 0, + "fill": "white", + "width": 34, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "outer-volunteer-vest", + "slot": "outer", + "name": "志工背心", + "desc": "黃背心一穿,就是選戰的一份子。", + "art": "outer/volunteer-vest.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "campaign", + "default": "#ffd23f" + } + ], + "text": [ + { + "kind": "fixed", + "value": "志工", + "x": 127, + "y": 192, + "size": 10, + "rotate": 0, + "fill": "ink", + "width": 22, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "always" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "outer-hivis", + "slot": "outer", + "name": "工地反光背心", + "desc": "視察工程進度的必備行頭。", + "art": "outer/hivis.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "背心顏色", + "palette": "hivis", + "default": "#ff7a1a" + } + ], + "text": [], + "rarity": "common", + "get": { + "type": "shop", + "price": 10, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "outer-raincoat", + "slot": "outer", + "name": "輕便雨衣", + "desc": "雨中造勢,越淋越有聲勢。", + "art": "outer/raincoat.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "雨衣顏色", + "palette": "soft", + "default": "#bfe3ff" + } + ], + "text": [], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "comeback", + "text": "拿到成就「逆轉勝」" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "sash-red", + "slot": "sash", + "name": "候選人紅布條", + "desc": "斜背的紅布條,印上號次和名字。", + "art": "sash/red.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "布條顏色", + "palette": "campaign", + "default": "#d61f2c" + } + ], + "text": [ + { + "kind": "numberName", + "x": 115, + "y": 194, + "size": 10, + "rotate": 27, + "fill": "gold", + "width": 84, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "sash-thanks", + "slot": "sash", + "name": "感謝鄉親謝票帶", + "desc": "選完不管輸贏,都要上街謝票。", + "art": "sash/thanks.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "fixed", + "value": "感謝鄉親", + "x": 115, + "y": 194, + "size": 10, + "rotate": 27, + "fill": "#d61f2c", + "width": 70, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "stat", + "stat": "losses", + "min": 1, + "text": "落選也打完一局" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "sash-gold", + "slot": "sash", + "name": "金色當選帶", + "desc": "大勝的人才拿得到的金布條。", + "art": "sash/gold.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "fixed", + "value": "當選", + "x": 115, + "y": 194, + "size": 11, + "rotate": 27, + "fill": "#d61f2c", + "width": 40, + "vertical": false + } + ], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "landslide", + "text": "拿到成就「壓倒性勝利」" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "chest-corsage", + "slot": "chest", + "name": "當選紅胸花", + "desc": "開票夜別上的大紅花。", + "art": "chest/corsage.svg", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "win", + "text": "當選一次" + }, + "status": "active", + "realPersonOk": true, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "chest-name-tag", + "slot": "chest", + "name": "名牌", + "desc": "座談會、政見會都要別的名牌。", + "art": "chest/name-tag.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "色條", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "name", + "x": 138, + "y": 189, + "size": 7.5, + "rotate": 0, + "fill": "ink", + "width": 28, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-megaphone", + "slot": "held", + "name": "大聲公", + "desc": "掃街喊話,整條街都聽得到。", + "art": "held/megaphone.svg", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-flag", + "slot": "held", + "name": "三角競選旗", + "desc": "插在宣傳車上、拿在手上揮。", + "art": "held/flag.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "旗子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 177, + "y": 79, + "size": 11, + "rotate": 0, + "fill": "main", + "width": 12, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-tissue", + "slot": "held", + "name": "面紙包", + "desc": "最受歡迎的文宣品,人人都收。", + "art": "held/tissue.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "包裝顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 165, + "y": 172, + "size": 10, + "rotate": -10, + "fill": "main", + "width": 16, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6, + "shelf": "always" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-fan", + "slot": "held", + "name": "團扇", + "desc": "夏天造勢場合一人一支。", + "art": "held/fan.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "扇子顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "number", + "x": 170, + "y": 140, + "size": 15, + "rotate": 0, + "fill": "main", + "width": 20, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "shop", + "price": 6, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-mic", + "slot": "held", + "name": "麥克風", + "desc": "政見發表會上,換你說了。", + "art": "held/mic.svg", + "anchor": "none", + "tints": [], + "text": [], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "debate_sweep", + "text": "拿到成就「辯論三戰全勝」" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "held-thermos", + "slot": "held", + "name": "保溫杯", + "desc": "一天講幾十場,喉嚨要顧好。", + "art": "held/thermos.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "杯子顏色", + "palette": "soft", + "default": "#b8c2cc" + } + ], + "text": [], + "rarity": "common", + "get": { + "type": "shop", + "price": 8, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "frame-gazette", + "slot": "frame", + "name": "選舉公報框", + "desc": "像選舉公報上的候選人欄。", + "art": "frame/gazette.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "number", + "x": 25, + "y": 204, + "size": 15, + "rotate": 0, + "fill": "white", + "width": 22, + "vertical": false + }, + { + "kind": "name", + "x": 102, + "y": 204, + "size": 14, + "rotate": 0, + "fill": "ink", + "width": 96, + "vertical": false + }, + { + "kind": "fixed", + "value": "選舉公報", + "x": 171, + "y": 204, + "size": 7.5, + "rotate": 0, + "fill": "#5d646e", + "width": 30, + "vertical": false + } + ], + "rarity": "common", + "get": { + "type": "free" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "frame-billboard", + "slot": "frame", + "name": "看板框", + "desc": "路口大看板,請支持幾號一目了然。", + "art": "frame/billboard.svg", + "anchor": "none", + "tints": [ + { + "key": "main", + "name": "看板顏色", + "palette": "campaign", + "default": "party" + } + ], + "text": [ + { + "kind": "plea", + "x": 100, + "y": 203, + "size": 14, + "rotate": 0, + "fill": "ink", + "width": 168, + "vertical": false + } + ], + "rarity": "rare", + "get": { + "type": "shop", + "price": 20, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "frame-newspaper", + "slot": "frame", + "name": "報紙頭版框", + "desc": "號外號外!上了頭版。", + "art": "frame/newspaper.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "fixed", + "value": "號外", + "x": 36, + "y": 202, + "size": 15, + "rotate": 0, + "fill": "white", + "width": 40, + "vertical": false + } + ], + "rarity": "rare", + "get": { + "type": "shop", + "price": 24, + "shelf": "rotate" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "frame-gold", + "slot": "frame", + "name": "金色當選框", + "desc": "選上縣市長以上才有的金框。", + "art": "frame/gold.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "fixed", + "value": "當選", + "x": 100, + "y": 206, + "size": 13, + "rotate": 0, + "fill": "white", + "width": 40, + "vertical": false + } + ], + "rarity": "rare", + "get": { + "type": "feat", + "feat": "career_mayor", + "text": "政治生涯選上縣市長" + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + }, + { + "id": "frame-neon", + "slot": "frame", + "name": "霓虹宣傳車框", + "desc": "選舉季限定:宣傳車上一圈閃亮燈泡。每年 11、12 月回來。", + "art": "frame/neon.svg", + "anchor": "none", + "tints": [], + "text": [ + { + "kind": "plea", + "x": 100, + "y": 202, + "size": 14, + "rotate": 0, + "fill": "#ffd23f", + "width": 168, + "vertical": false + } + ], + "rarity": "limited", + "get": { + "type": "shop", + "price": 36, + "shelf": "rotate" + }, + "available": { + "months": [ + 11, + 12 + ] + }, + "status": "active", + "realPersonOk": false, + "flags": [], + "zoom": "none", + "since": 2, + "credit": "原創(選舉小鎮)" + } + ] +}; diff --git a/backend/packages/protocol/src/avatar/catalog.ts b/backend/packages/protocol/src/avatar/catalog.ts new file mode 100644 index 0000000..50cb495 --- /dev/null +++ b/backend/packages/protocol/src/avatar/catalog.ts @@ -0,0 +1,266 @@ +import { AVATAR_SPEC_VERSION, AvatarSpecSchema, type AvatarSpecData } from "../game.ts"; +import { AVATAR_CATALOG } from "./catalog.generated.ts"; +import type { AvatarCatalog, AvatarItemDef, AvatarSlotDef } from "./schema.ts"; + +/** + * 頭像部件目錄(docs/24):前端照目錄列選項、疊圖;伺服器照同一份目錄檢查玩家送來的頭像。 + * 目錄原始檔是 data/avatar-catalog.json,改完跑 pnpm avatar:build。 + * 部件代號永不刪除、永不改名(停售改 status: "retired",舊存檔照樣能穿)。 + */ +export * from "./schema.ts"; +export { MAGIC_COLORS, type ArtShape, type MagicRole, type PartArt } from "./svg.ts"; +export { AVATAR_CATALOG }; + +export type AvatarItem = AvatarItemDef; + +const slotIndex = new WeakMap>(); +const itemIndex = new WeakMap>(); +const wearIndex = new WeakMap>(); + +function slotsOf(c: AvatarCatalog): Map { + let m = slotIndex.get(c); + if (!m) slotIndex.set(c, (m = new Map(c.slots.map((s) => [s.id, s])))); + return m; +} +function itemsOf(c: AvatarCatalog): Map { + let m = itemIndex.get(c); + if (!m) itemIndex.set(c, (m = new Map(c.items.map((i) => [`${i.slot}:${i.id}`, i])))); + return m; +} +function wearOf(c: AvatarCatalog): Map { + let m = wearIndex.get(c); + if (!m) wearIndex.set(c, (m = new Map(c.items.filter((i) => !i.art.startsWith("builtin:")).map((i) => [i.id, i])))); + return m; +} + +export const avatarSlot = (slot: string, c: AvatarCatalog = AVATAR_CATALOG): AvatarSlotDef | undefined => slotsOf(c).get(slot); +/** 某個部位的某件部件(舊部件代號只在同一個部位裡唯一,例如 round 同時是臉型、眼睛、眼鏡) */ +export const avatarItem = (slot: string, id: string, c: AvatarCatalog = AVATAR_CATALOG): AvatarItemDef | undefined => itemsOf(c).get(`${slot}:${id}`); +/** 新部件(帽子、彩帶…)用代號找:新部件的代號全目錄唯一 */ +export const wearItem = (id: string, c: AvatarCatalog = AVATAR_CATALOG): AvatarItemDef | undefined => wearOf(c).get(id); +/** 某個部位列在清單上的部件(hidden 不列;retired 停售的也不列,舊存檔照樣能穿) */ +export const slotItems = (slot: string, c: AvatarCatalog = AVATAR_CATALOG): AvatarItemDef[] => c.items.filter((i) => i.slot === slot && i.status === "active"); +/** 新部位(存在頭像資料的 wear 裡) */ +export const wearSlots = (c: AvatarCatalog = AVATAR_CATALOG): AvatarSlotDef[] => c.slots.filter((s) => !s.field); +export const avatarStyles = (c: AvatarCatalog = AVATAR_CATALOG) => c.styles; +export const isAvatarStyle = (id: string | undefined, c: AvatarCatalog = AVATAR_CATALOG): boolean => !!id && c.styles.some((s) => s.id === id); + +export interface AvatarCheckOptions { + /** 真實政治人物的頭像:只能穿 realPersonOk 的部件,也不放付費部件 */ + realPerson?: boolean; + catalog?: AvatarCatalog; +} + +export interface AvatarIssue { + /** 哪個欄位:hair、wear.hat、tint.hat.main… */ + field: string; + value: string; + problem: "unknown" | "wrongSlot" | "notForRealPerson" | "badTint"; +} + +const BUILTIN_FIELDS = (c: AvatarCatalog) => c.slots.filter((s): s is AvatarSlotDef & { field: string } => Boolean(s.field)); + +/** 一件新部件能不能穿在這個頭像上 */ +function wearProblem(slot: string, id: string, opts: AvatarCheckOptions): AvatarIssue["problem"] | null { + const c = opts.catalog ?? AVATAR_CATALOG; + const s = slotsOf(c).get(slot); + if (!s || s.field) return "unknown"; + const item = wearOf(c).get(id); + if (!item) return "unknown"; + if (item.slot !== slot) return "wrongSlot"; + if (opts.realPerson && (!item.realPersonOk || item.get.type === "shop")) return "notForRealPerson"; + return null; +} + +/** 照目錄檢查頭像(不改東西):每個代號都在目錄裡、部位對得上、真實人物沒穿不該穿的、換色合規定 */ +export function checkAvatar(spec: AvatarSpecData, opts: AvatarCheckOptions = {}): AvatarIssue[] { + const c = opts.catalog ?? AVATAR_CATALOG; + const issues: AvatarIssue[] = []; + for (const s of BUILTIN_FIELDS(c)) { + const v = (spec as Record)[s.field]; + if (typeof v === "string" && !itemsOf(c).has(`${s.id}:${v}`)) issues.push({ field: s.field, value: v, problem: "unknown" }); + } + if (spec.style !== undefined && !isAvatarStyle(spec.style, c)) issues.push({ field: "style", value: spec.style, problem: "unknown" }); + for (const [slot, id] of Object.entries(spec.wear ?? {})) { + const p = wearProblem(slot, id, opts); + if (p) issues.push({ field: `wear.${slot}`, value: id, problem: p }); + } + for (const [key, color] of Object.entries(spec.tint ?? {})) { + if (!tintAllowed(spec, key, color, c)) issues.push({ field: `tint.${key}`, value: color, problem: "badTint" }); + } + return issues; +} + +function tintAllowed(spec: AvatarSpecData, key: string, color: string, c: AvatarCatalog): boolean { + const [slot = "", tintKey = ""] = key.split("."); + const id = spec.wear?.[slot]; + const item = id ? wearOf(c).get(id) : undefined; + const def = item?.tints.find((t) => t.key === tintKey); + if (!item || item.slot !== slot || !def) return false; + const palette = c.palettes[def.palette]; + if (palette?.strict) return palette.colors.some((p) => p.toLowerCase() === color.toLowerCase()); + return true; +} + +/** + * 清洗頭像:看不懂的代號換成預設值(不能不穿的部位)或拿掉(可以不穿的),真實人物拿掉不能穿的部件, + * 沒穿的部件的換色拿掉。合法的頭像原封不動(舊存檔一個字都不用改)。notes 是換掉了什麼,給伺服器記紀錄。 + */ +export function cleanAvatar(spec: AvatarSpecData, opts: AvatarCheckOptions = {}): { spec: AvatarSpecData; notes: string[] } { + const c = opts.catalog ?? AVATAR_CATALOG; + const issues = checkAvatar(spec, opts); + if (issues.length === 0) return { spec, notes: [] }; + const next: Record = { ...spec }; + const notes: string[] = []; + const wear: Record = { ...(spec.wear ?? {}) }; + const tint: Record = { ...(spec.tint ?? {}) }; + for (const i of issues) { + if (i.field.startsWith("wear.")) { + delete wear[i.field.slice(5)]; + notes.push(`${i.field}「${i.value}」${i.problem === "notForRealPerson" ? "真實人物不能穿,拿掉" : "看不懂,拿掉"}`); + } else if (i.field.startsWith("tint.")) { + delete tint[i.field.slice(5)]; + } else if (i.field === "style") { + delete next.style; + notes.push(`畫風「${i.value}」看不懂,改用預設`); + } else { + const slot = BUILTIN_FIELDS(c).find((s) => s.field === i.field); + if (slot && !slot.optional && slot.default) next[i.field] = slot.default; + else delete next[i.field]; + notes.push(`${i.field}「${i.value}」看不懂,換成預設`); + } + } + // 拿掉部件之後,它的換色也不要了 + for (const key of Object.keys(tint)) if (!tintAllowed({ ...spec, wear }, key, tint[key]!, c)) delete tint[key]; + if (Object.keys(wear).length) next.wear = wear; + else delete next.wear; + if (Object.keys(tint).length) next.tint = tint; + else delete next.tint; + return { spec: next as AvatarSpecData, notes }; +} + +/** 舊版缺欄位時用的預設頭像(跟前端隨機產生的範圍一樣) */ +export const DEFAULT_AVATAR_SPEC: AvatarSpecData = { + skin: "#eebd98", + hair: "short", + hairColor: "#2f2520", + outfit: "suit", + suit: "#24324a", + shirt: "#f7f5f0", + tie: "#b3262d", + glasses: false, + beard: false, + bg: "#dfe8f0", +}; + +/** + * 讀玩家瀏覽器裡的頭像存檔:格式壞掉的欄位丟掉(必填的換成預設),再照目錄清洗。 + * 完全不是頭像(不是物件)回 null。存檔壞掉也不會當機。 + */ +export function parseAvatarLoose(raw: unknown, opts: AvatarCheckOptions = {}): AvatarSpecData | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + let candidate: Record = { ...(raw as Record) }; + for (let tries = 0; tries < 4; tries++) { + const r = AvatarSpecSchema.safeParse(candidate); + if (r.success) return cleanAvatar(r.data, opts).spec; + const bad = new Set(r.error.issues.map((i) => String(i.path[0] ?? ""))); + const fixed: Record = { ...candidate }; + for (const k of bad) { + if (k in DEFAULT_AVATAR_SPEC) fixed[k] = DEFAULT_AVATAR_SPEC[k as keyof AvatarSpecData]; + else delete fixed[k]; + } + candidate = fixed; + } + return null; +} + +/** 新做的頭像(有用到新部位或畫風)標上第 2 版 */ +export function stampAvatarVersion(spec: AvatarSpecData): AvatarSpecData { + const modern = spec.style !== undefined || (spec.wear && Object.keys(spec.wear).length > 0) || spec.tint !== undefined; + return modern ? { ...spec, v: AVATAR_SPEC_VERSION } : spec; +} + +// ── 服裝店:每週上架(用週數當亂數,所有人看到一樣,不需要伺服器) ── + +const DAY = 86_400_000; +const WEEK = 7 * DAY; +/** 第 0 週:2026-01-05(星期一)台灣時間 0 點 */ +export const SHOP_EPOCH = Date.UTC(2026, 0, 5) - 8 * 3_600_000; +export const SHOP_WEEKLY = 6; + +/** 現在是第幾週(台灣時間,星期一換週) */ +export const shopWeek = (now: Date | number = Date.now()): number => Math.floor((+now - SHOP_EPOCH) / WEEK); +/** 某一週的星期一(台灣時間)的日期 YYYY-MM-DD */ +export function shopWeekStart(week: number): string { + return taiwanDate(SHOP_EPOCH + week * WEEK); +} +/** 台灣時間的日期 YYYY-MM-DD */ +export function taiwanDate(t: Date | number): string { + return new Date(+t + 8 * 3_600_000).toISOString().slice(0, 10); +} + +function rng(seed: number): () => number { + let a = (seed * 2654435761) >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), a | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** 這件部件在某一天能不能買(上架時間、每年固定月份) */ +export function onSale(item: AvatarItemDef, date: string): boolean { + if (item.status !== "active" || item.get.type !== "shop") return false; + const a = item.available; + if (!a) return true; + if (a.from && date < a.from) return false; + if (a.until && date > a.until) return false; + if (a.months && !a.months.includes(Number(date.slice(5, 7)))) return false; + return true; +} + +export interface ShopShelf { + week: number; + /** 本週上架(輪替的 6 件;新品第一週一定上) */ + weekly: AvatarItemDef[]; + /** 基本款,一直都在 */ + always: AvatarItemDef[]; + /** 限定(活動期間才有,每年同一個時候回來) */ + limited: AvatarItemDef[]; +} + +/** + * 某一週服裝店上架的東西。輪替的部件洗牌後每週拿 6 件,一輪(ceil(件數/6) 週)每件都會上一次; + * 所以每件最久 2 輪就會再上架(測試保證一年內一定會再上)。新品(available.from 在這一週)第一週一定上。 + */ +export function shopShelf(now: Date | number = Date.now(), c: AvatarCatalog = AVATAR_CATALOG): ShopShelf { + const week = shopWeek(now); + const date = taiwanDate(now); + const start = shopWeekStart(week); + const end = shopWeekStart(week + 1); + const forSale = c.items.filter((i) => onSale(i, date)); + const always = forSale.filter((i) => i.get.type === "shop" && i.get.shelf === "always" && !i.available?.months); + const limited = forSale.filter((i) => Boolean(i.available?.months) || i.rarity === "limited"); + const pool = forSale.filter((i) => !always.includes(i) && !limited.includes(i)).sort((a, b) => (a.id < b.id ? -1 : 1)); + const fresh = pool.filter((i) => i.available?.from && i.available.from >= start && i.available.from < end); + const rotating = pool.filter((i) => !fresh.includes(i)); + const picks: AvatarItemDef[] = [...fresh]; + if (rotating.length <= SHOP_WEEKLY) picks.push(...rotating); + else { + const rounds = Math.ceil(rotating.length / SHOP_WEEKLY); + const round = Math.floor(week / rounds); + const r = rng(round + 1); + const deck = [...rotating]; + for (let i = deck.length - 1; i > 0; i--) { + const j = Math.floor(r() * (i + 1)); + [deck[i], deck[j]] = [deck[j]!, deck[i]!]; + } + const at = (((week % rounds) + rounds) % rounds) * SHOP_WEEKLY; + const slice = deck.slice(at, at + SHOP_WEEKLY); + // 最後一週不滿 6 件:從這一輪的開頭補(不重複) + for (const it of deck) if (slice.length < SHOP_WEEKLY && !slice.includes(it)) slice.push(it); + picks.push(...slice.filter((i) => !picks.includes(i))); + } + return { week, weekly: picks.slice(0, Math.max(SHOP_WEEKLY, fresh.length)), always, limited }; +} diff --git a/backend/packages/protocol/src/avatar/schema.ts b/backend/packages/protocol/src/avatar/schema.ts new file mode 100644 index 0000000..dfcf6d5 --- /dev/null +++ b/backend/packages/protocol/src/avatar/schema.ts @@ -0,0 +1,181 @@ +import { z } from "zod"; +import { AvatarCode } from "../game.ts"; + +/** + * 頭像部件目錄的格式(docs/24 第 1 節)。目錄本身在 data/avatar-catalog.json, + * 由 scripts/build-avatar-catalog.ts 檢查後轉成 catalog.generated.ts(前後端共用同一份)。 + * + * 版本規則(以後照做): + * - 部件代號永不刪除、永不改名。不想賣了改 status: "retired"(舊存檔照樣能穿,只是不能再拿);畫錯了換圖,代號不變。 + * - 目錄每次更新 catalogVersion +1,每件部件記 since(第幾版加進來的)。 + */ + +const HexColor = z.string().regex(/^#[0-9a-fA-F]{6}$/); +/** 顏色:#RRGGBB,或 party(跟角色的政黨色) */ +const TintColor = z.union([z.literal("party"), HexColor]); + +/** 畫風:同一套部件換畫法,所有部件自動支援(docs/24 第 3 節做法 A) */ +export const AvatarStyleDef = z.object({ + id: AvatarCode, + name: z.string().min(1).max(8), + note: z.string().max(60), +}); + +/** 部位:放在哪個分頁、第幾層、64 像素以下的小圖要不要畫 */ +export const AvatarSlotDef = z.object({ + id: AvatarCode, + name: z.string().min(1).max(8), + /** 捏人物畫面的哪個分頁 */ + tab: z.string(), + /** 舊部位存在頭像資料的哪個欄位(hair、outfit、glassesStyle…);新部位存在 wear 裡 */ + field: z.string().optional(), + /** 可以不穿(帽子、彩帶…);不能不穿的(髮型、服裝)看不懂時換成 default */ + optional: z.boolean(), + default: AvatarCode.nullable(), + /** 64 像素以下的小圖:show 照畫、hide 省略 */ + small: z.enum(["show", "hide"]), + /** 捏人物畫面要不要列出來(鼻子、耳朵只給政治人物特徵用) */ + ui: z.boolean().default(true), + /** + * 新部位畫在哪一層(由後到前):body 衣服上面(外套、彩帶、胸前)、face 嘴巴上面(口罩)、 + * head 頭的最上面(帽子)、hand 頭的前面(手持物)、canvas 整張最上面(外框)。同一層照 slots 的順序。 + */ + layer: z.enum(["body", "face", "head", "hand", "canvas"]).optional(), +}); + +/** 可以換色的地方 */ +export const AvatarTintDef = z.object({ + key: z.string().regex(/^[a-z][A-Za-z0-9]{0,15}$/), + name: z.string().min(1).max(8), + /** 用哪個色盤(palettes) */ + palette: z.string(), + default: TintColor, +}); + +/** 部件上印的字(號次、名字、標語):座標是標準畫布(200×220、標準臉)上的位置 */ +export const AvatarTextDef = z.object({ + /** number 號次、name 名字、numberName「3號 王小明」、plea「請支持 3 號」、fixed 固定的字 */ + kind: z.enum(["number", "name", "numberName", "plea", "fixed"]), + value: z.string().max(8).optional(), + x: z.number(), + y: z.number(), + size: z.number().positive().max(40), + rotate: z.number().min(-90).max(90).default(0), + /** 字的顏色:main/accent(部件顏色)、ink、white、gold,或 #RRGGBB */ + fill: z.union([z.enum(["main", "accent", "ink", "white", "gold"]), HexColor]), + /** 最寬多少(太長就壓窄) */ + width: z.number().positive().max(200), + /** 直書(旗子) */ + vertical: z.boolean().default(false), +}); + +/** 怎麼拿到(沒拿到的格子寫出來,跟圖鑑灰卡一樣) */ +export const AvatarGet = z.discriminatedUnion("type", [ + z.object({ type: z.literal("free") }), + /** 服裝店用小鎮幣買;rotate=每週輪替上架,always=基本款常駐 */ + z.object({ type: z.literal("shop"), price: z.number().int().positive().max(999), shelf: z.enum(["rotate", "always"]).default("rotate") }), + /** 拿到某個成就(選戰卡牌的成就 id) */ + z.object({ type: z.literal("feat"), feat: z.string().max(40), text: z.string().max(30) }), + /** 累積成績:當選、落選、打完的局數 */ + z.object({ type: z.literal("stat"), stat: z.enum(["wins", "losses", "runs"]), min: z.number().int().positive(), text: z.string().max(30) }), +]); + +export const AvatarItemDef = z.object({ + id: AvatarCode, + slot: AvatarCode, + /** 畫面上的名字 */ + name: z.string().min(1).max(10), + desc: z.string().max(60).optional(), + /** builtin:xxx=程式畫的舊部件;其他是部件圖(art/avatar 底下的 SVG 路徑),所有畫風共用 */ + art: z.string().regex(/^(builtin:[A-Za-z0-9-]+|[a-z]+\/[a-z0-9-]+\.svg)$/), + /** 對齊哪裡:headTop 頭頂(跟著頭寬縮放)、face 臉(跟著臉寬臉長)、none 整張畫布 */ + anchor: z.enum(["none", "headTop", "face"]).default("none"), + /** 戴上後頭髮在這條線(標準畫布的 y)以上藏起來(帽子壓住頭髮) */ + hideHairAbove: z.number().optional(), + tints: z.array(AvatarTintDef).max(3).default([]), + text: z.array(AvatarTextDef).max(4).default([]), + rarity: z.enum(["common", "rare", "limited"]).default("common"), + get: AvatarGet.default({ type: "free" }), + /** 上架時間(限定品):from/until 是日期(YYYY-MM-DD,台灣時間);months 是每年固定的月份(每年都會回來) */ + available: z + .object({ + from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + until: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + months: z.array(z.number().int().min(1).max(12)).max(12).optional(), + }) + .optional(), + /** active 上架中、hidden 不在清單出現、retired 停售(舊存檔照樣能穿) */ + status: z.enum(["active", "hidden", "retired"]).default("active"), + /** 真實政治人物的頭像能不能用(只開放正式類,見 docs/24 第 2 節) */ + realPersonOk: z.boolean().default(false), + /** 舊部件的特性:parted 可以選分線方向、tie 有領帶、collar 襯衫那一塊叫「領子」(Polo 衫) */ + flags: z.array(z.enum(["parted", "tie", "collar"])).default([]), + /** 捏人物格子的小預覽要放大到哪:face 臉、head 頭、none 半身 */ + zoom: z.enum(["face", "head", "none"]).default("none"), + since: z.number().int().positive().default(1), + credit: z.string().default("原創(選舉小鎮)"), +}); + +export const AvatarCatalogSchema = z.object({ + catalogVersion: z.number().int().positive(), + styles: z.array(AvatarStyleDef).min(1), + slots: z.array(AvatarSlotDef).min(1), + palettes: z.record(z.string(), z.object({ strict: z.boolean().default(false), colors: z.array(TintColor).min(1).max(16) })), + items: z.array(AvatarItemDef), +}); + +export type AvatarStyleDef = z.infer; +export type AvatarSlotDef = z.infer; +export type AvatarTintDef = z.infer; +export type AvatarTextDef = z.infer; +export type AvatarGet = z.infer; +export type AvatarItemDef = z.infer; +export type AvatarCatalog = z.infer; + +/** 目錄內容的額外規則(Zod 管不到的):回傳問題清單,空的就是沒問題。建置工具和測試都會跑 */ +export function lintCatalog(c: AvatarCatalog): string[] { + const problems: string[] = []; + const slots = new Map(c.slots.map((s) => [s.id, s])); + const styleIds = new Set(); + for (const s of c.styles) { + if (styleIds.has(s.id)) problems.push(`畫風代號重複:${s.id}`); + styleIds.add(s.id); + } + if (slots.size !== c.slots.length) problems.push("部位代號重複"); + const seen = new Set(); + const newIds = new Set(); + for (const it of c.items) { + const key = `${it.slot}:${it.id}`; + if (seen.has(key)) problems.push(`部件重複:${key}`); + seen.add(key); + const slot = slots.get(it.slot); + if (!slot) { + problems.push(`${it.id}:沒有這個部位 ${it.slot}`); + continue; + } + const builtin = it.art.startsWith("builtin:"); + if (builtin !== Boolean(slot.field)) problems.push(`${it.id}:${builtin ? "舊部件只能放在舊部位" : "新部件要放在新部位(wear)"}`); + if (!builtin) { + // 新部件的代號全目錄唯一(擁有清單、商店用代號找部件) + if (newIds.has(it.id)) problems.push(`新部件代號重複:${it.id}`); + newIds.add(it.id); + if (!it.id.startsWith(`${it.slot}-`)) problems.push(`${it.id}:新部件代號要用部位開頭(${it.slot}-…)`); + if (!/^[a-z0-9-]+$/.test(it.id)) problems.push(`${it.id}:新部件代號只能用小寫英數和連字號`); + } + if (/凍蒜/.test(it.name)) problems.push(`${it.id}:部件名稱不用「凍蒜」`); + if (it.realPersonOk && it.get.type === "shop") problems.push(`${it.id}:真實人物能穿的部件不能是付費/商店部件`); + if (it.rarity === "limited" && !it.available) problems.push(`${it.id}:限定品要寫上架時間`); + if (it.available?.months && it.get.type !== "shop") problems.push(`${it.id}:每年固定月份上架的只能是商店部件`); + for (const t of it.tints) if (!c.palettes[t.palette]) problems.push(`${it.id}:沒有色盤 ${t.palette}`); + if (new Set(it.tints.map((t) => t.key)).size !== it.tints.length) problems.push(`${it.id}:換色名稱重複`); + if (it.text.some((t) => t.kind === "fixed" && !t.value)) problems.push(`${it.id}:固定的字要寫 value`); + } + for (const s of c.slots) { + if (s.default && !seen.has(`${s.id}:${s.default}`)) problems.push(`部位 ${s.id} 的預設 ${s.default} 不在目錄裡`); + if (!s.optional && !s.default) problems.push(`部位 ${s.id} 不能不穿,要有預設`); + const free = c.items.filter((i) => i.slot === s.id && i.status === "active" && i.get.type === "free"); + if (!s.field && free.length === 0) problems.push(`新部位 ${s.id} 至少要有 1 件免費`); + if (!s.field && !s.layer) problems.push(`新部位 ${s.id} 要寫 layer(畫在哪一層)`); + } + return problems; +} diff --git a/backend/packages/protocol/src/avatar/svg.ts b/backend/packages/protocol/src/avatar/svg.ts new file mode 100644 index 0000000..b0d7399 --- /dev/null +++ b/backend/packages/protocol/src/avatar/svg.ts @@ -0,0 +1,422 @@ +/** + * 頭像部件 SVG 的檢查與轉檔(docs/24 第 1 節「安全」)。 + * SVG 裡可以藏程式碼,所以不直接把 SVG 塞進網頁:這裡把 SVG 轉成「只有形狀和顏色」的資料, + * 順便檢查:只准白名單裡的元素和屬性(沒有 script、style、外部連結、文字)、不能超出 200×220 畫布、 + * 顏色只能是 #RGB/#RRGGBB 或 none、檔案和形狀數量有上限。檢查不過就不收。 + * 純函式(不讀檔),建置工具 scripts/build-avatar-catalog.ts 和測試共用。 + */ + +export const CANVAS_W = 200; +export const CANVAS_H = 220; +/** 線寬、反鋸齒的容許誤差 */ +const SLACK = 4; +export const MAX_SVG_BYTES = 16_000; +const MAX_NODES = 400; + +/** 魔術色:畫圖時塗這些顏色,程式換成玩家選的顏色(art/avatar/README.md) */ +export const MAGIC_COLORS = { + "#ff00ff": "main", + "#800080": "mainShade", + "#00ffff": "accent", + "#008080": "accentShade", + "#ffff00": "skin", + "#808000": "skinShade", + "#0000ff": "suit", + "#000080": "suitShade", + "#00ff00": "shirt", +} as const; +export type MagicRole = (typeof MAGIC_COLORS)[keyof typeof MAGIC_COLORS]; + +export type ArtTag = "g" | "path" | "circle" | "ellipse" | "rect" | "polygon" | "polyline" | "line"; +/** 轉好的一個形狀:屬性名稱已經是 React 的寫法(strokeWidth…),顏色已經轉成小寫 #rrggbb */ +export interface ArtShape { + t: ArtTag; + a: Record; + c?: ArtShape[]; +} +/** 一件部件的圖:back 畫在頭和身體後面、front 畫在自己的圖層 */ +export interface PartArt { + back?: ArtShape[]; + front: ArtShape[]; +} + +const SHAPE_ATTRS: Record = { + g: [], + path: ["d"], + circle: ["cx", "cy", "r"], + ellipse: ["cx", "cy", "rx", "ry"], + rect: ["x", "y", "width", "height", "rx", "ry"], + polygon: ["points"], + polyline: ["points"], + line: ["x1", "y1", "x2", "y2"], +}; +const PAINT_ATTRS = ["fill", "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin", "opacity", "fill-opacity", "stroke-opacity", "fill-rule", "transform"] as const; +const REACT_NAME: Record = { + "stroke-width": "strokeWidth", + "stroke-linecap": "strokeLinecap", + "stroke-linejoin": "strokeLinejoin", + "fill-opacity": "fillOpacity", + "stroke-opacity": "strokeOpacity", + "fill-rule": "fillRule", +}; +const ENUM_VALUES: Record = { + "stroke-linecap": ["butt", "round", "square"], + "stroke-linejoin": ["miter", "round", "bevel"], + "fill-rule": ["nonzero", "evenodd"], +}; +const NUMBER = /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i; +const NUMBER_LIST = /^[-\d.eE,\s]+$/; +const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz\d\s,.eE-]+$/; +const TRANSFORM = /^(\s*(translate|scale|rotate|matrix)\(\s*[-\d.eE,\s]+\)\s*)+$/; + +export class SvgArtError extends Error {} + +interface Tag { + name: string; + attrs: Record; + close: boolean; + selfClose: boolean; +} + +function tokenize(src: string): Tag[] { + if (src.length > MAX_SVG_BYTES) throw new SvgArtError(`檔案太大(${src.length} 字元,上限 ${MAX_SVG_BYTES})`); + if (//, "").replace(//g, ""); + if (/<\?/.test(body)) throw new SvgArtError("不准有處理指令"); + const tags: Tag[] = []; + const re = /<\s*(\/)?\s*([A-Za-z][\w:-]*)([^<>]*?)(\/)?\s*>/g; + let last = 0; + for (let m = re.exec(body); m; m = re.exec(body)) { + if (body.slice(last, m.index).trim()) throw new SvgArtError("不准有文字(字由目錄的 text 欄位印)"); + last = re.lastIndex; + const attrs: Record = {}; + const rest = (m[3] ?? "").trim(); + const attrRe = /([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g; + let consumed = rest; + for (let a = attrRe.exec(rest); a; a = attrRe.exec(rest)) { + const name = a[1]!; + if (name in attrs) throw new SvgArtError(`屬性重複:${name}`); + attrs[name] = a[2] ?? a[3] ?? ""; + consumed = consumed.replace(a[0], ""); + } + if (consumed.trim()) throw new SvgArtError(`看不懂的屬性寫法:${consumed.trim().slice(0, 40)}`); + tags.push({ name: m[2]!, attrs, close: Boolean(m[1]), selfClose: Boolean(m[4]) }); + } + if (body.slice(last).trim()) throw new SvgArtError("檔案結尾有多餘的內容"); + return tags; +} + +// ── 範圍檢查:把每個形狀的外框(含控制點,保守估計)經過 transform 換到畫布上 ── + +type Matrix = [number, number, number, number, number, number]; +const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]; +const mul = (m: Matrix, n: Matrix): Matrix => [ + m[0] * n[0] + m[2] * n[1], + m[1] * n[0] + m[3] * n[1], + m[0] * n[2] + m[2] * n[3], + m[1] * n[2] + m[3] * n[3], + m[0] * n[4] + m[2] * n[5] + m[4], + m[1] * n[4] + m[3] * n[5] + m[5], +]; +const nums = (s: string): number[] => (s.match(/-?(\d+\.?\d*|\.\d+)(e-?\d+)?/gi) ?? []).map(Number); + +function parseTransform(t: string): Matrix { + let m = IDENTITY; + for (const part of t.matchAll(/(translate|scale|rotate|matrix)\(([^)]*)\)/g)) { + const v = nums(part[2]!); + let n: Matrix; + switch (part[1]) { + case "translate": + n = [1, 0, 0, 1, v[0] ?? 0, v[1] ?? 0]; + break; + case "scale": + n = [v[0] ?? 1, 0, 0, v[1] ?? v[0] ?? 1, 0, 0]; + break; + case "rotate": { + const r = ((v[0] ?? 0) * Math.PI) / 180; + const [cx, cy] = [v[1] ?? 0, v[2] ?? 0]; + const rot: Matrix = [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0]; + n = mul(mul([1, 0, 0, 1, cx, cy], rot), [1, 0, 0, 1, -cx, -cy]); + break; + } + default: + if (v.length !== 6) throw new SvgArtError("matrix() 要 6 個數字"); + n = v as Matrix; + } + m = mul(m, n); + } + return m; +} + +/** 弧線上的點:照 SVG 規格(F.6.5)換成圓心表示法,再沿著弧取樣 */ +function arcPoints(x1: number, y1: number, rxIn: number, ryIn: number, rotDeg: number, large: boolean, sweep: boolean, x2: number, y2: number): [number, number][] { + let rx = Math.abs(rxIn); + let ry = Math.abs(ryIn); + if (rx === 0 || ry === 0) return [[x2, y2]]; + const phi = (rotDeg * Math.PI) / 180; + const [cos, sin] = [Math.cos(phi), Math.sin(phi)]; + const dx = (x1 - x2) / 2; + const dy = (y1 - y2) / 2; + const x1p = cos * dx + sin * dy; + const y1p = -sin * dx + cos * dy; + const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry); + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p; + const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p; + const co = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, num / den)); + const cxp = (co * rx * y1p) / ry; + const cyp = (-co * ry * x1p) / rx; + const cx = cos * cxp - sin * cyp + (x1 + x2) / 2; + const cy = sin * cxp + cos * cyp + (y1 + y2) / 2; + const angle = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); + const t1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry); + let dt = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry); + if (!sweep && dt > 0) dt -= 2 * Math.PI; + if (sweep && dt < 0) dt += 2 * Math.PI; + const out: [number, number][] = []; + for (let k = 0; k <= 16; k++) { + const t = t1 + (dt * k) / 16; + out.push([cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos]); + } + return out; +} + +/** 路徑經過的點(含控制點,保守估計;弧線沿著弧取樣) */ +function pathPoints(d: string): [number, number][] { + const pts: [number, number][] = []; + const tokens = d.match(/[MmLlHhVvCcSsQqTtAaZz]|-?(\d+\.?\d*|\.\d+)(e-?\d+)?/gi) ?? []; + let i = 0; + let cmd = ""; + let [x, y, sx, sy] = [0, 0, 0, 0]; + const num = () => { + const t = tokens[i++]; + if (t === undefined || /[a-z]/i.test(t)) throw new SvgArtError("路徑資料不完整"); + return Number(t); + }; + while (i < tokens.length) { + if (/[a-z]/i.test(tokens[i]!)) cmd = tokens[i++]!; + else if (!cmd) throw new SvgArtError("路徑要從指令開始"); + const rel = cmd === cmd.toLowerCase(); + const ox = rel ? x : 0; + const oy = rel ? y : 0; + switch (cmd.toUpperCase()) { + case "M": + case "L": + case "T": + x = ox + num(); + y = oy + num(); + pts.push([x, y]); + if (cmd.toUpperCase() === "M") { + [sx, sy] = [x, y]; + cmd = rel ? "l" : "L"; + } + break; + case "H": + x = ox + num(); + pts.push([x, y]); + break; + case "V": + y = oy + num(); + pts.push([x, y]); + break; + case "C": + for (let k = 0; k < 3; k++) pts.push([ox + num(), oy + num()]); + [x, y] = pts[pts.length - 1]!; + break; + case "S": + case "Q": + for (let k = 0; k < 2; k++) pts.push([ox + num(), oy + num()]); + [x, y] = pts[pts.length - 1]!; + break; + case "A": { + const rx = num(); + const ry = num(); + const rot = num(); + const large = num(); + const sweep = num(); + const [px, py] = [x, y]; + x = ox + num(); + y = oy + num(); + pts.push(...arcPoints(px, py, rx, ry, rot, large !== 0, sweep !== 0, x, y)); + break; + } + case "Z": + [x, y] = [sx, sy]; + cmd = ""; + break; + default: + throw new SvgArtError(`看不懂的路徑指令 ${cmd}`); + } + } + return pts; +} + +function localPoints(tag: ArtTag, a: Record): [number, number][] { + const n = (k: string) => Number(a[k] ?? 0); + switch (tag) { + case "path": + return pathPoints(a.d ?? ""); + case "circle": + return [ + [n("cx") - n("r"), n("cy") - n("r")], + [n("cx") + n("r"), n("cy") + n("r")], + ]; + case "ellipse": + return [ + [n("cx") - n("rx"), n("cy") - n("ry")], + [n("cx") + n("rx"), n("cy") + n("ry")], + ]; + case "rect": + return [ + [n("x"), n("y")], + [n("x") + n("width"), n("y") + n("height")], + ]; + case "line": + return [ + [n("x1"), n("y1")], + [n("x2"), n("y2")], + ]; + case "polygon": + case "polyline": { + const v = nums(a.points ?? ""); + const out: [number, number][] = []; + for (let k = 0; k + 1 < v.length; k += 2) out.push([v[k]!, v[k + 1]!]); + return out; + } + default: + return []; + } +} + +function checkBounds(tag: ArtTag, a: Record, m: Matrix, where: string) { + const pts = localPoints(tag, a); + if (pts.length === 0) return; + const xs = pts.map(([x]) => x); + const ys = pts.map(([, y]) => y); + const sw = a.stroke && a.stroke !== "none" ? Number(a["stroke-width"] ?? 1) / 2 : 0; + const [x0, x1, y0, y1] = [Math.min(...xs) - sw, Math.max(...xs) + sw, Math.min(...ys) - sw, Math.max(...ys) + sw]; + for (const [x, y] of [ + [x0, y0], + [x1, y0], + [x0, y1], + [x1, y1], + ] as const) { + const tx = m[0] * x + m[2] * y + m[4]; + const ty = m[1] * x + m[3] * y + m[5]; + if (tx < -SLACK || tx > CANVAS_W + SLACK || ty < -SLACK || ty > CANVAS_H + SLACK) + throw new SvgArtError(`${where}超出 ${CANVAS_W}×${CANVAS_H} 畫布(${tx.toFixed(1)}, ${ty.toFixed(1)})`); + } +} + +function normalizeColor(v: string, where: string): string { + const s = v.trim().toLowerCase(); + if (s === "none") return s; + const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(s); + if (short) return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`; + if (/^#[0-9a-f]{6}$/.test(s)) return s; + throw new SvgArtError(`${where}顏色只能用 #RRGGBB 或 none(看到 ${v})`); +} + +/** 檢查並轉換一張部件 SVG;不合規定就丟 SvgArtError */ +export function convertSvgArt(src: string, name = "SVG"): PartArt { + try { + return convert(src, name); + } catch (e) { + const msg = (e as Error).message; + throw new SvgArtError(msg.startsWith(`${name}:`) ? msg : `${name}:${msg}`); + } +} + +function convert(src: string, name: string): PartArt { + let tags: Tag[]; + try { + tags = tokenize(src); + } catch (e) { + throw new SvgArtError(`${name}:${(e as Error).message}`); + } + const fail = (msg: string): never => { + throw new SvgArtError(`${name}:${msg}`); + }; + const root = tags[0]; + if (!root || root.name !== "svg" || root.close) fail("最外層要是 "); + for (const k of Object.keys(root!.attrs)) if (!["xmlns", "viewBox", "width", "height"].includes(k)) fail(` 不准有屬性 ${k}`); + if (root!.attrs.xmlns && root!.attrs.xmlns !== "http://www.w3.org/2000/svg") fail("xmlns 只能是 SVG 的"); + if ((root!.attrs.viewBox ?? "").trim().split(/[\s,]+/).join(" ") !== `0 0 ${CANVAS_W} ${CANVAS_H}`) fail(`viewBox 要是 0 0 ${CANVAS_W} ${CANVAS_H}`); + if (tags.length > MAX_NODES) fail(`形狀太多(上限 ${MAX_NODES})`); + + const out: PartArt = { front: [] }; + type Frame = { tag: ArtTag | "svg"; list: ArtShape[]; m: Matrix }; + const stack: Frame[] = [{ tag: "svg", list: out.front, m: IDENTITY }]; + let count = 0; + for (const t of tags.slice(1)) { + const top = stack[stack.length - 1]!; + if (t.close) { + if (top.tag !== t.name) fail(` 對不上`); + stack.pop(); + if (t.name === "svg" && stack.length !== 0) fail(" 位置不對"); + continue; + } + if (stack.length === 0) fail(" 後面還有東西"); + if (top.tag !== "svg" && top.tag !== "g") fail(`<${top.tag}> 裡面不能再放東西`); + const tag = t.name as ArtTag; + if (!(tag in SHAPE_ATTRS)) fail(`不准用 <${t.name}>(只能用 ${Object.keys(SHAPE_ATTRS).join("、")})`); + const where = `<${tag}> `; + const a: Record = {}; + const allowed = new Set([...SHAPE_ATTRS[tag], ...PAINT_ATTRS, ...(tag === "g" ? ["id"] : [])]); + for (const [k, raw] of Object.entries(t.attrs)) { + if (!allowed.has(k)) fail(`${where}不准有屬性 ${k}`); + const v = raw.trim(); + if (/url\(|javascript:|&|<|>/i.test(v)) fail(`${where}${k} 的值不合規定`); + if (k === "fill" || k === "stroke") a[k] = normalizeColor(v, where); + else if (k === "transform") { + if (!TRANSFORM.test(v)) fail(`${where}transform 只能用 translate、scale、rotate、matrix`); + a[k] = v; + } else if (k === "d") { + if (!PATH_DATA.test(v)) fail(`${where}路徑資料有怪字元`); + a[k] = v.replace(/\s+/g, " "); + } else if (k === "points") { + if (!NUMBER_LIST.test(v)) fail(`${where}points 只能是數字`); + a[k] = v; + } else if (k === "id") { + if (v !== "back" && v !== "front") fail('群組 id 只能是 "back" 或 "front"'); + if (stack.length !== 1) fail("back/front 群組要放在最外層"); + a[k] = v; + } else if (ENUM_VALUES[k]) { + if (!ENUM_VALUES[k]!.includes(v)) fail(`${where}${k} 的值不合規定`); + a[k] = v; + } else { + if (!NUMBER.test(v)) fail(`${where}${k} 要是數字`); + if (/opacity/.test(k) && (Number(v) < 0 || Number(v) > 1)) fail(`${where}${k} 要在 0–1`); + a[k] = v; + } + } + for (const req of SHAPE_ATTRS[tag]) if (!["rx", "ry", "x", "y"].includes(req) && !(req in a)) fail(`${where}少了 ${req}`); + const m = a.transform ? mul(top.m, parseTransform(a.transform)) : top.m; + if (tag !== "g") checkBounds(tag, a, m, where); + count += 1; + const shape: ArtShape = { t: tag, a: Object.fromEntries(Object.entries(a).filter(([k]) => k !== "id").map(([k, v]) => [REACT_NAME[k] ?? k, v])) }; + if (tag === "g" && a.id) { + const list: ArtShape[] = []; + shape.c = list; + if (a.id === "back") { + if (out.back) fail("只能有一個 back 群組"); + out.back = [shape]; + } else top.list.push(shape); + if (!t.selfClose) stack.push({ tag, list, m }); + continue; + } + top.list.push(shape); + if (tag === "g" && !t.selfClose) { + shape.c = []; + stack.push({ tag, list: shape.c, m }); + } else if (!t.selfClose && tag !== "g") { + stack.push({ tag, list: [], m }); + } + } + if (stack.length !== 0) fail("標籤沒有關好"); + if (count === 0) fail("沒有任何形狀"); + return out; +} diff --git a/backend/packages/protocol/src/common.ts b/backend/packages/protocol/src/common.ts new file mode 100644 index 0000000..51a103f --- /dev/null +++ b/backend/packages/protocol/src/common.ts @@ -0,0 +1,34 @@ +import { z } from "zod"; + +/** 協定版本:破壞性變更時升版(docs/16) */ +export const PROTOCOL_VERSION = "1.0.0"; + +/** 村里代碼(= 國土測繪中心 VILLCODE = 戶政 district_code),11 碼 */ +export const VillageCode = z.string().regex(/^\d{11}$/, "村里代碼應為 11 碼數字"); +/** 鄉鎮市區代碼(TOWNCODE),8 碼 */ +export const TownCode = z.string().regex(/^\d{8}$/, "鄉鎮市區代碼應為 8 碼數字"); +/** 縣市代碼(COUNTYCODE),5 碼 */ +export const CountyCode = z.string().regex(/^\d{5}$/, "縣市代碼應為 5 碼數字"); + +export const IsoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "日期格式應為 YYYY-MM-DD"); +export const Share = z.number().min(0).max(1); +export const NonNegative = z.number().min(0); + +/** 資料來源:每個欄位都要能追到這裡(docs/10、docs/15) */ +export const SourceRef = z.object({ + id: z.string().min(1), + title: z.string().min(1), + agency: z.string().min(1), + url: z.string().url(), + license: z.string().min(1), + retrievedAt: IsoDate, + version: z.string().optional(), + note: z.string().optional(), +}); +export type SourceRef = z.infer; + +export const SourceList = z.object({ + protocolVersion: z.string(), + sources: z.array(SourceRef), +}); +export type SourceList = z.infer; diff --git a/backend/packages/protocol/src/game.ts b/backend/packages/protocol/src/game.ts new file mode 100644 index 0000000..2d9cad0 --- /dev/null +++ b/backend/packages/protocol/src/game.ts @@ -0,0 +1,538 @@ +import { z } from "zod"; +import { TownCode, VillageCode } from "./common.ts"; +import { PARTY_NAMES } from "./parties.ts"; + +const PARTY_SET = new Set(PARTY_NAMES); + +/** 一週的時段:六個公開時段加午夜(只能做祕密行動)(docs/02) */ +export const SLOTS = [ + "weekdayMorning", + "weekdayAfternoon", + "weekdayEvening", + "weekendMorning", + "weekendAfternoon", + "weekendEvening", + "midnight", +] as const; +export const Slot = z.enum(SLOTS); +export type Slot = z.infer; + +/** 候選人本人或團隊(幕僚與義工)執行(docs/02、docs/04) */ +export const Actor = z.enum(["candidate", "team"]); +export type Actor = z.infer; + +export const PartySlotKey = z.enum(["a", "b", "c", "other"]); +export type PartySlotKey = z.infer; + +/** 拜票副本:遇到的三個遭遇與玩家的選擇(候選人本人親自走一趟時才有) */ +export const EncounterPlay = z.object({ ids: z.array(z.string().max(64)).max(4), picks: z.array(z.string().max(64)).max(4) }); +export type EncounterPlay = z.infer; + +export const Order = z.object({ + actor: Actor, + /** 團隊行動由哪一位幕僚執行(SelfState.staff 的 id);候選人本人為 null */ + staffId: z.string().nullable().default(null), + slot: Slot, + actionId: z.string().min(1), + /** 目標行政區;全市性行動為 null */ + target: TownCode.nullable(), + /** 規模參數:金額(元)、票數、桌數等,依行動定義;不需要時為 null */ + amount: z.number().int().nonnegative().nullable(), + /** 攻擊類行動的對手 */ + opponentId: z.string().nullable(), + /** 提出政見時選擇的議題 */ + issueIds: z.array(z.string()).max(3).nullable(), + encounter: EncounterPlay.optional(), +}); +export type Order = z.infer; + +/** + * 幕僚方針:玩家只排自己打出的牌,其他幕僚的時段由伺服器依方針自動排。 + * style 是打法(均衡、地面戰、空戰);focus 是要多跑的區(最多 5 個),空的就由幕僚自己判斷。 + */ +export const StaffPolicy = z.object({ + style: z.enum(["balanced", "ground", "air"]), + focus: z.array(TownCode).max(5).default([]), +}); +export type StaffPolicy = z.infer; + +/** 候選人本人加最多 6 位幕僚,每人 7 個時段;有幕僚方針時,空著的幕僚時段由伺服器補上 */ +export const TurnSubmission = z.object({ + orders: z.array(Order).max(64), + staffPolicy: StaffPolicy.nullable().default(null), + /** 這週表態事件選的選項 id;沒選就套用事件的預設回應 */ + eventChoice: z.string().max(64).nullable().default(null), + /** 記者堵麥的回應:提問 key → 選項 id;沒回應的套用「不回應」 */ + pressReplies: z.record(z.string().max(64), z.string().max(64)).default({}), +}); +export type TurnSubmission = z.infer; + +/** 行動目錄:前端用來顯示與組指令,規則本身只在後端 */ +export const ActionInfo = z.object({ + id: z.string(), + name: z.string(), + category: z.enum(["ground", "media", "org", "finance", "policy", "offense", "dark", "ritual", "self", "logistics"]), + description: z.string(), + slots: z.array(Slot), + duration: z.union([z.literal(1), z.literal(2)]), + actors: z.array(Actor), + target: z.enum(["town", "city", "opponent"]), + cost: z.object({ money: z.number().int().nonnegative(), stamina: z.number().int() }), + amount: z + .object({ + label: z.string(), + unit: z.string(), + min: z.number().int().nonnegative(), + max: z.number().int().nonnegative(), + step: z.number().int().positive(), + default: z.number().int().nonnegative(), + moneyPerUnit: z.number().nonnegative(), + }) + .nullable(), + visibility: z.enum(["public", "local", "secret"]), + risk: z.string().nullable(), + phase: z.enum(["campaign", "eve"]), +}); +export type ActionInfo = z.infer; + +export const IssueInfo = z.object({ id: z.string(), name: z.string(), description: z.string() }); + +const HexColor = z.string().regex(/^#[0-9a-fA-F]{6}$/); + +/** + * 頭像部件的代號(部件目錄 data/avatar-catalog.json,docs/24):英數與連字號,最長 40 字。 + * 舊部件沿用原本的代號(short、bobSide、halfRim…),新部件用小寫加連字號(hat-campaign-cap)。 + * 代號永不刪除、永不改名。這裡只檢查格式;有沒有這個部件由 checkAvatar/cleanAvatar 依目錄判斷。 + */ +export const AvatarCode = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9-]{0,39}$/); +/** 新部位(帽子、彩帶…)最多穿幾件、可以換色的地方最多幾個 */ +export const AVATAR_WEAR_MAX = 12; +export const AVATAR_TINT_MAX = 24; +/** 頭像資料的版本:沒寫是舊版(1),有 wear/style/tint 的是 2 */ +export const AVATAR_SPEC_VERSION = 2; + +/** + * 自創角色的捏臉設定(前端畫頭像用);真實人物為 null。 + * 髮型、服裝、眼鏡、五官等從「寫死的選項」改成「目錄裡的代號」:格式不對才回錯誤, + * 看不懂的代號由 cleanAvatar 換成預設值,不擋開局。舊存檔一個字都不用改就合法。 + */ +export const AvatarSpecSchema = z.object({ + skin: HexColor, + hair: AvatarCode, + hairColor: HexColor, + outfit: AvatarCode, + suit: HexColor, + shirt: HexColor, + tie: HexColor, + glasses: z.boolean(), + beard: z.boolean(), + bg: HexColor, + // ── 漫畫肖像的細節(都可以省略,省略時用預設) ── + face: AvatarCode.optional(), + /** 臉寬、臉長的倍率 */ + faceW: z.number().min(0.8).max(1.25).optional(), + faceH: z.number().min(0.85).max(1.25).optional(), + ears: AvatarCode.optional(), + brows: AvatarCode.optional(), + /** 眉毛角度:負的是八字眉(溫和),正的是劍眉 */ + browAngle: z.number().min(-1).max(1).optional(), + eyes: AvatarCode.optional(), + glassesStyle: AvatarCode.optional(), + glassesColor: HexColor.optional(), + nose: AvatarCode.optional(), + mouth: AvatarCode.optional(), + /** 法令紋、皺紋(0–2) */ + lines: z.number().int().min(0).max(2).optional(), + /** 旁分的方向 */ + part: z.enum(["left", "right"]).optional(), + mustache: z.boolean().optional(), + // ── 第 2 版(docs/24):畫風與新部位,都可以省略 ── + v: z.number().int().min(1).max(99).optional(), + /** 這個角色自己的畫風(comic、chibi、pixel、sticker);沒寫就跟全遊戲設定 */ + style: AvatarCode.optional(), + /** 新部位穿的部件:部位 → 部件代號(hat → hat-campaign-cap) */ + wear: z + .record(AvatarCode, AvatarCode) + .refine((w) => Object.keys(w).length <= AVATAR_WEAR_MAX, { message: `最多穿 ${AVATAR_WEAR_MAX} 件` }) + .optional(), + /** 部件換色:「部位.顏色名」→ 顏色(hat.main → #c0392b);沒寫用部件的預設色(常常是政黨色) */ + tint: z + .record(z.string().regex(/^[A-Za-z0-9-]{1,40}\.[A-Za-z0-9]{1,16}$/), HexColor) + .refine((t) => Object.keys(t).length <= AVATAR_TINT_MAX, { message: `最多 ${AVATAR_TINT_MAX} 個顏色` }) + .optional(), +}); +export type AvatarSpecData = z.infer; + +/** 選舉的地區與職位,例如 桃園市/市長 */ +export const Region = z.object({ + countyCode: z.string(), + countyName: z.string(), + office: z.string(), + /** 選舉種類與選舉區名稱(例如「臺北市第 1 選舉區」) */ + kind: z.enum(["mayor", "legislator", "president"]).default("mayor"), + area: z.string().default(""), + /** 「區」的層級:鄉鎮市區或縣市(總統選舉) */ + regionLevel: z.enum(["town", "county"]).default("town"), + /** 立委選區涵蓋的鄉鎮市區,例如「北投區、士林區(部分)」;其他選舉為空字串 */ + scope: z.string().default(""), +}); +export type Region = z.infer; + +export const CandidatePublic = z.object({ + id: z.string(), + name: z.string(), + party: z.string().nullable(), + slot: PartySlotKey, + number: z.number().int().positive(), + isPlayer: z.boolean(), + description: z.string(), + /** 公開可見的主打政見 */ + issueIds: z.array(z.string()), + /** 公開可見的標籤,例如「奧步」「檢調約談」 */ + tags: z.array(z.string()), + /** 自創角色才有 */ + avatar: AvatarSpecSchema.nullable().default(null), + /** 總統選舉的副手 */ + runningMate: z.string().nullable().default(null), + /** 性別(中選會資料),給 Q 版頭像挑男女;自創角色有自己的 avatar */ + gender: z.enum(["m", "f"]).nullable().default(null), + /** 當年查證過的競選標語與出處;查不到是 null(不替真人編標語) */ + slogan: z.string().nullable().default(null), + sloganSource: z.string().nullable().default(null), +}); +export type CandidatePublic = z.infer; + +/** 開始畫面比較候選人用的能力值,各 0–10 */ +export const CandidateStats = z.object({ + fame: z.number().int().min(0).max(10), + eloquence: z.number().int().min(0).max(10), + wealth: z.number().int().min(0).max(10), + network: z.number().int().min(0).max(10), + charisma: z.number().int().min(0).max(10), +}); +export type CandidateStats = z.infer; + +/** 總統選舉可以換的虛構副手類型(不配對真實人物,docs/14) */ +export const RUNNING_MATE_TYPES = ["real", "scholar", "local", "tycoon", "influencer"] as const; + +export const TownPublic = z.object({ + code: TownCode, + name: z.string(), + adults: z.number().int().nonnegative(), + electors: z.number().int().nonnegative(), + /** 上一次可比較的選舉中各政黨的得票率(公開歷史資料) */ + lastShares: z.record(z.string(), z.number()), + hakkaShare: z.number().nullable(), + /** 這個陣營在此區有服務處 */ + hasOffice: z.boolean(), +}); +export type TownPublic = z.infer; + +export const NewsItem = z.object({ + id: z.string(), + week: z.number().int(), + tier: z.enum(["headline", "main", "local", "online"]), + title: z.string(), + candidateId: z.string().nullable(), + townCode: TownCode.nullable(), + tone: z.enum(["positive", "neutral", "negative"]), + /** 新聞的主題,畫面用來挑配圖:行動 id(例如 rally)或事件種類(typhoon、investigation…) */ + topic: z.string().nullable().default(null), + /** 被攻擊、被點名的候選人(攻擊文宣、爆料的對象) */ + targetId: z.string().nullable().default(null), + /** 配圖(卡牌插圖名稱);沒有就依 topic 挑 */ + art: z.string().nullable().default(null), +}); +export type NewsItem = z.infer; + +export const Poll = z.object({ + id: z.string(), + week: z.number().int(), + kind: z.enum(["public", "internal"]), + pollster: z.string(), + sampleSize: z.number().int().positive(), + marginOfError: z.number().nonnegative(), + /** 候選人 id → 支持率(0–1) */ + shares: z.record(z.string(), z.number()), + undecided: z.number(), + /** 內參民調才有:行政區代碼 → 候選人 id → 支持率 */ + byTown: z.record(z.string(), z.record(z.string(), z.number())).nullable(), +}); +export type Poll = z.infer; + +export const ReportItem = z.object({ + /** tactic:組合拳、打對台的加成 */ + kind: z.enum(["action", "cancelled", "event", "leak", "intel", "money", "tactic"]), + text: z.string(), + week: z.number().int(), +}); +export type ReportItem = z.infer; + +/** 幕僚:每位都有自己的一排行程格;skill 是代替候選人執行時的效果倍率 */ +export const StaffInfo = z.object({ + id: z.string(), + name: z.string(), + skill: z.number().min(0).max(1), + /** 每週薪水(元) */ + salary: z.number().int().nonnegative(), + /** 專長(卡牌角落顯示,例如「組織」) */ + specialty: z.string().default(""), + /** 每週帶進手牌的專長牌(行動 id) */ + deck: z.array(z.string()).default([]), +}); +export type StaffInfo = z.infer; + +export const SelfState = z.object({ + candidateId: z.string(), + money: z.number().int(), + stamina: z.number().int(), + staminaMax: z.number().int(), + volunteers: z.number().int(), + flyers: z.number().int(), + officeTowns: z.array(TownCode), + issueIds: z.array(z.string()), + /** 自己手上的把柄:對手 id → 數量 */ + leverage: z.record(z.string(), z.number().int()), + /** 已執行的祕密行動數(只有自己看得到) */ + secretActions: z.number().int(), + spendingCap: z.number().int(), + spent: z.number().int(), + staff: z.array(StaffInfo), + /** 每週固定支出:服務處租金+幕僚薪水 */ + upkeep: z.number().int().nonnegative(), + /** + * 這場選舉的目標:選情領先的人要當選;小候選人的目標是得票率超過 target(雖敗猶榮)。 + * 開局依當時的選情算出來。 + */ + goal: z.object({ kind: z.enum(["win", "share"]), target: z.number().min(0).max(1) }).default({ kind: "win", target: 0.5 }), + /** 口才、失言機率的訓練加成 */ + bonus: z.object({ eloquence: z.number(), gaffe: z.number() }).default({ eloquence: 0, gaffe: 0 }), +}); +export type SelfState = z.infer; + +export const ElectionResult = z.object({ + electors: z.number().int(), + ballots: z.number().int(), + valid: z.number().int(), + /** 候選人 id → 得票數 */ + votes: z.record(z.string(), z.number().int()), + winnerId: z.string(), + byTown: z.record(TownCode, z.record(z.string(), z.number().int())), + byVillage: z.record(VillageCode, z.record(z.string(), z.number().int())), + /** 開票夜的回報順序(村里代碼),小的里先開完 */ + countingOrder: z.array(VillageCode), + /** 選後司法:當選無效等 */ + postElection: z.array(z.string()), + voided: z.boolean(), + /** 歷史劇本才有:真實結果(候選人 id → 得票率) */ + actualShares: z.record(z.string(), z.number()).nullable(), +}); +export type ElectionResult = z.infer; + +/** 這週要表態的事件(docs/08):每個選項都會讓某些人高興、某些人不高興 */ +export const EventCard = z.object({ + id: z.string(), + title: z.string(), + body: z.string(), + /** 卡牌插圖名稱(/cards/.webp) */ + art: z.string(), + options: z.array(z.object({ id: z.string(), label: z.string(), risky: z.boolean() })), + /** 不回應時套用的選項 */ + fallback: z.string(), +}); +export type EventCard = z.infer; + +/** 記者堵麥:上週跟你有關的新聞,記者追問你要怎麼回應(docs/07) */ +export const PressCard = z.object({ + key: z.string(), + /** 觸發的原因:被攻擊、自己的負面新聞、對手出包、聲勢看漲、對手造勢、民調落後/領先、平靜的一週 */ + trigger: z.enum(["attacked", "own_scandal", "opp_scandal", "my_win", "rival_win", "poll_behind", "poll_lead", "quiet"]), + question: z.string(), + /** 引發提問的那則新聞標題 */ + headline: z.string().nullable(), + options: z.array(z.object({ id: z.string(), label: z.string(), hint: z.string(), risky: z.boolean() })), + fallback: z.string(), +}); +export type PressCard = z.infer; + +/** 幕僚對各區情勢的估計:只有等級(0–4)與漲跌,不是真實數字(docs/07:玩家看不到選民模型的數字) */ +export const TownIntel = z.object({ + code: TownCode, + reach: z.number().int().min(0).max(4), + warmth: z.number().int().min(0).max(4), + reachTrend: z.number().int().min(-1).max(1), + warmthTrend: z.number().int().min(-1).max(1), +}); +export type TownIntel = z.infer; + +export const Intel = z.object({ + reach: z.number().int().min(0).max(4), + warmth: z.number().int().min(0).max(4), + reachTrend: z.number().int().min(-1).max(1), + warmthTrend: z.number().int().min(-1).max(1), + towns: z.array(TownIntel), +}); +export type Intel = z.infer; + +/** 主要對手上週本人公開跑過的區(打對台用) */ +export const RivalVisit = z.object({ + candidateId: z.string(), + townCode: TownCode, + actionId: z.string(), +}); +export type RivalVisit = z.infer; + +export const PlayerView = z.object({ + protocolVersion: z.string(), + matchId: z.string(), + scenarioId: z.string(), + scenarioName: z.string(), + packId: z.string(), + week: z.number().int(), + totalWeeks: z.number().int(), + region: Region, + /** 投票日(YYYY-MM-DD);第 w 週從投票日往前推(totalWeeks − w + 1)週 */ + electionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + phase: z.enum(["campaign", "eve", "finished"]), + /** 投票前 10 天起不得發布民調(選罷法第 53 條) */ + pollBlackout: z.boolean(), + weather: z.enum(["sunny", "rain", "typhoon"]), + self: SelfState, + candidates: z.array(CandidatePublic), + towns: z.array(TownPublic), + actions: z.array(ActionInfo), + issues: z.array(IssueInfo), + news: z.array(NewsItem), + polls: z.array(Poll), + report: z.array(ReportItem), + result: ElectionResult.nullable(), + event: EventCard.nullable().default(null), + press: z.array(PressCard).default([]), + intel: Intel.nullable().default(null), + rivalTrail: z.array(RivalVisit).default([]), +}); +export type PlayerView = z.infer; + +/** 劇本數字的出處(給玩家看的連結) */ +export const ScenarioSource = z.object({ label: z.string(), url: z.string().url() }); +export type ScenarioSource = z.infer; + +export const ScenarioSummary = z.object({ + id: z.string(), + name: z.string(), + description: z.string(), + packId: z.string(), + weeks: z.number().int(), + region: Region, + /** 假設情境(例如勢均力敵);歷史重演為 false */ + hypothetical: z.boolean(), + electionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + /** 法定競選經費上限(元) */ + spendingCap: z.number().int(), + candidates: z.array( + z.object({ + id: z.string(), + name: z.string(), + party: z.string().nullable(), + slot: PartySlotKey, + number: z.number().int().positive(), + description: z.string(), + startingMoney: z.number().int(), + staff: z.number().int(), + /** 總統選舉的副手 */ + runningMate: z.string().nullable().default(null), + gender: z.enum(["m", "f"]).nullable().default(null), + slogan: z.string().nullable().default(null), + sloganSource: z.string().nullable().default(null), + /** 給玩家比較用的能力值(0–10),由劇本數字換算 */ + stats: CandidateStats.optional(), + /** 歷史劇本:真實的政治獻金收支(元) */ + realFinance: z.object({ income: z.number().int(), spending: z.number().int() }).nullable(), + }), + ), + /** 數字的出處,以及哪些是遊戲設定 */ + notes: z.array(z.string()), + sources: z.array(ScenarioSource), +}); +export type ScenarioSummary = z.infer; + +/** 自創角色的出身(docs/04) */ +export const BACKGROUNDS = ["醫師", "律師", "教授", "前藝人", "網紅", "政二代", "基層里長", "企業家", "前官員", "社運出身"] as const; +export const STATS = ["fame", "eloquence", "strategy", "wealth", "network"] as const; +/** 能力點數:五項各 0–10,總共 25 點 */ +export const STAT_BUDGET = 25; +export const STAT_MAX = 10; + +export const CustomCandidate = z + .object({ + name: z.string().trim().min(2).max(12), + /** null 表示無黨籍;其他是台灣歷屆選舉推出過候選人的政黨(parties.ts,中選會資料) */ + party: z + .string() + .refine((p) => PARTY_SET.has(p), { message: "不是台灣歷屆選舉出現過的政黨" }) + .nullable(), + background: z.enum(BACKGROUNDS), + stats: z.object(Object.fromEntries(STATS.map((k) => [k, z.number().int().min(0).max(STAT_MAX)])) as Record<(typeof STATS)[number], z.ZodNumber>), + avatar: AvatarSpecSchema, + /** 取代劇本裡的某位候選人(沿用號次);null 表示以新候選人加入 */ + replace: z.string().nullable(), + }) + .refine((c) => STATS.reduce((sum, k) => sum + c.stats[k], 0) <= STAT_BUDGET, { message: `能力點數總共最多 ${STAT_BUDGET} 點`, path: ["stats"] }); +export type CustomCandidate = z.infer; + +export const CreateMatchRequest = z.object({ + scenarioId: z.string(), + /** 要扮演的候選人;用自創角色時忽略 */ + candidateId: z.string(), + seed: z.number().int().nonnegative().optional(), + custom: CustomCandidate.optional(), + /** 虛構對決:讓原本的候選人退選、從其他選舉找人客串(客串的人 id 是 g-0、g-1…) */ + lineup: z + .object({ + remove: z.array(z.string().max(64)).max(12).default([]), + guests: z.array(z.object({ scenarioId: z.string().max(128), candidateId: z.string().max(64) })).max(6).default([]), + }) + .optional(), + /** 總統選舉:副手類型;real 是原本的副手(自創角色沒有原本的副手,預設學者型) */ + runningMate: z.enum(RUNNING_MATE_TYPES).optional(), + /** 開局選項(規則可以調) */ + options: z + .object({ + /** 公平起跑:每位候選人的起始資金與募款能力至少有最多那位的四成 */ + fairStart: z.boolean().default(false), + /** 選戰週數(4–10);短一點的選戰從後面幾週開始 */ + weeks: z.number().int().min(4).max(10).optional(), + /** 所有人的起始資金與募款能力倍率 */ + moneyScale: z.number().min(0.25).max(3).default(1), + aiLevel: z.enum(["easy", "normal", "hard"]).default("normal"), + /** 允許黑暗面(買票、網軍、栽贓…) */ + darkSide: z.boolean().default(true), + /** 每週的表態事件 */ + events: z.boolean().default(true), + }) + .optional(), +}); +export type CreateMatchRequest = z.infer; + +export const CreateMatchResponse = z.object({ matchId: z.string(), view: PlayerView }); +export type CreateMatchResponse = z.infer; + +/** 送出一週指令的回應:新的玩家視角,以及被剔除的指令與原因 */ +export const TurnResult = z.object({ + view: PlayerView, + errors: z.array(z.string()), + /** 依幕僚方針自動排的行程(播放時用) */ + autoOrders: z.array(Order).default([]), +}); +export type TurnResult = z.infer; + +/** 幕僚建議行程:伺服器用 AI 規劃器替玩家排一週,玩家可以再改 */ +export const SuggestResult = z.object({ orders: z.array(Order) }); +export type SuggestResult = z.infer; + +/** 比賽的地圖範圍:立委選區只含縣市裡的部分村里;其他選舉為 null(整份資料包都是) */ +export const MatchArea = z.object({ villages: z.array(z.string()).nullable() }); +export type MatchArea = z.infer; + +export const ApiError = z.object({ error: z.string(), details: z.array(z.string()).optional() }); +export type ApiError = z.infer; diff --git a/backend/packages/protocol/src/index.ts b/backend/packages/protocol/src/index.ts new file mode 100644 index 0000000..2a3e97e --- /dev/null +++ b/backend/packages/protocol/src/index.ts @@ -0,0 +1,10 @@ +export * from "./common.ts"; +export * from "./area.ts"; +export * from "./people.ts"; +export * from "./game.ts"; +export * from "./scenario.ts"; +export * from "./rogue.ts"; +export * from "./records.ts"; +export * from "./parties.ts"; +export * from "./origins.ts"; +export * from "./avatar/catalog.ts"; diff --git a/backend/packages/protocol/src/origins.ts b/backend/packages/protocol/src/origins.ts new file mode 100644 index 0000000..7e0ea31 --- /dev/null +++ b/backend/packages/protocol/src/origins.ts @@ -0,0 +1,87 @@ +import type { BACKGROUNDS } from "./game.ts"; +import type { CareerAbilities } from "./rogue.ts"; + +/** + * 出身與政黨的加成(18 第 53 項,使用者選做法 B「有得有失」): + * - 出身:起始能力 +1(不同出身加不同項)+一張專屬起始牌。 + * - 政黨:「黨的資源」不能自己點。大黨(民進黨、國民黨)資金多、組織 +1、開局一張黨部動員掃街,但有黨的包袱(黨中央風波); + * 民眾黨媒體 +1;其他政黨和無黨籍資源少,但形象清新(開局得票略多、記者追問掉的票少),政治生涯經驗 ×1.2。 + * 只套在自創角色上(真實候選人照真實的資源)。數字是遊戲設定,用 apps/sim/src/party-balance.ts 模擬調過: + * 打得好的玩家各黨勝率 96–98%,隨手玩 23–35%(2026-10-27,4 個劇本 × 3 種出身 × 16 個種子)。 + */ + +export type Background = (typeof BACKGROUNDS)[number]; +export type AbilityId = keyof CareerAbilities; +export type PartyKind = "major" | "tpp" | "minor"; + +export const ABILITY_NAMES: Record = { eloquence: "口才", organization: "組織", media: "媒體", finance: "財務", integrity: "清廉" }; + +/** 每個出身:起始能力 +1 的那一項、專屬起始牌(rogue/data.ts 的 id 與名稱) */ +export const ORIGINS: Record = { + 醫師: { ability: "integrity", card: "origin_clinic", cardName: "巡迴義診" }, + 律師: { ability: "eloquence", card: "origin_legal", cardName: "法律諮詢站" }, + 教授: { ability: "eloquence", card: "origin_lecture", cardName: "公共政策講座" }, + 前藝人: { ability: "media", card: "origin_fanmeet", cardName: "粉絲見面會" }, + 網紅: { ability: "media", card: "origin_stream", cardName: "直播開箱" }, + 政二代: { ability: "organization", card: "origin_clan", cardName: "家族老樁腳" }, + 基層里長: { ability: "organization", card: "origin_assembly", cardName: "里民大會" }, + 企業家: { ability: "finance", card: "origin_donors", cardName: "企業募款餐會" }, + 前官員: { ability: "finance", card: "origin_record", cardName: "施政成績單" }, + 社運出身: { ability: "integrity", card: "origin_petition", cardName: "街頭連署" }, +}; + +const MAJOR = new Set(["民主進步黨", "中國國民黨"]); + +/** 大黨(民進黨、國民黨)、民眾黨、其他政黨與無黨籍 */ +export const partyKind = (party: string | null): PartyKind => (party && MAJOR.has(party) ? "major" : party === "台灣民眾黨" ? "tpp" : "minor"); + +/** 黨的資源(不能自己點):加哪一項能力、好處、代價;畫面上照這份寫 */ +export const PARTY_RESOURCES: Record = { + major: { + label: "大黨", + ability: "organization", + perks: ["開局資金多", "組織 +1(黨部樁腳)", "開局多一張「黨部動員掃街」(不花體力)"], + costs: ["黨的包袱:第 3 或第 4 週有一次「黨中央風波」,那週沒回應,全市掉票"], + }, + tpp: { + label: "第三大黨", + ability: "media", + perks: ["開局資金中等", "媒體 +1(網路聲量)"], + costs: ["沒有黨部動員"], + }, + minor: { + label: "小黨或無黨籍", + ability: null, + perks: ["形象清新:開局得票多 0.2 個百分點、記者追問掉的票少一成五", "政治生涯經驗 ×1.2"], + costs: ["開局資金少", "沒有黨部樁腳"], + }, +}; + +/** 小黨、無黨籍在政治生涯多拿的經驗 */ +export const MINOR_EXP_MULT = 1.2; +/** 開局各區你的得票(已表態的部分)加減幾個百分點:大黨的包袱、小黨的清新形象 */ +export const PARTY_LEAN_SHIFT: Record = { major: 0, tpp: 0, minor: 0.002 }; +/** 小黨、無黨籍沒回應記者追問時掉的票 */ +export const MINOR_REPORTER_MULT = 0.85; + +const clampLevel = (n: number) => Math.max(0, Math.min(5, n)); + +/** + * 自創角色的起始能力(0–5):捏人物點數換算(0–2 級)+出身那一項 +1+黨的資源那一項 +1。 + * 點數換算:(點數 − 3) ÷ 3 四捨五入,最多 2 級;口才看口才、組織看人脈、媒體看知名度、財務看財力;清廉沒有點數,只看出身。 + */ +export function originAbilities(c: { stats: { fame: number; eloquence: number; wealth: number; network: number }; background: Background; party: string | null }): CareerAbilities { + const lv = (n: number) => Math.max(0, Math.min(2, Math.round((n - 3) / 3))); + const out: CareerAbilities = { eloquence: lv(c.stats.eloquence), organization: lv(c.stats.network), media: lv(c.stats.fame), finance: lv(c.stats.wealth), integrity: 0 }; + const origin = ORIGINS[c.background]; + if (origin) out[origin.ability] = clampLevel(out[origin.ability] + 1); + const party = PARTY_RESOURCES[partyKind(c.party)].ability; + if (party) out[party] = clampLevel(out[party] + 1); + return out; +} + +/** 「律師:口才 +1,專屬牌「法律諮詢站」」 */ +export function originBonusText(background: Background): string { + const o = ORIGINS[background]; + return o ? `${ABILITY_NAMES[o.ability]} +1,專屬牌「${o.cardName}」` : ""; +} diff --git a/backend/packages/protocol/src/parties.ts b/backend/packages/protocol/src/parties.ts new file mode 100644 index 0000000..b8db5e7 --- /dev/null +++ b/backend/packages/protocol/src/parties.ts @@ -0,0 +1,159 @@ +/** + * 台灣歷屆選舉推出過候選人的政黨(中選會選舉資料庫 1994–2024,依推出的候選人數排序)。 + * 由 backend/data/pipeline 的 `election-data parties` 產生,不要手改。 + * candidates:推出的候選人數;elected:當選人數;first、last:第一次、最近一次推人參選的年份。 + */ +export interface PartyRecord { + name: string; + candidates: number; + elected: number; + first: number | null; + last: number | null; +} + +export const PARTY_RECORDS: readonly PartyRecord[] = [ + {"name": "中國國民黨", "candidates": 19147, "elected": 12832, "first": 1994, "last": 2024}, + {"name": "民主進步黨", "candidates": 7377, "elected": 4230, "first": 1994, "last": 2024}, + {"name": "親民黨", "candidates": 562, "elected": 203, "first": 2001, "last": 2024}, + {"name": "新黨", "candidates": 420, "elected": 118, "first": 1994, "last": 2024}, + {"name": "台灣團結聯盟", "candidates": 305, "elected": 66, "first": 2002, "last": 2024}, + {"name": "台灣民眾黨", "candidates": 179, "elected": 27, "first": 2020, "last": 2024}, + {"name": "時代力量", "candidates": 115, "elected": 25, "first": 2018, "last": 2024}, + {"name": "綠黨", "candidates": 77, "elected": 9, "first": 2001, "last": 2022}, + {"name": "建國黨", "candidates": 72, "elected": 3, "first": 1997, "last": 2005}, + {"name": "無黨團結聯盟", "candidates": 65, "elected": 28, "first": 2002, "last": 2022}, + {"name": "中華統一促進黨", "candidates": 54, "elected": 9, "first": 2009, "last": 2024}, + {"name": "台灣基進", "candidates": 38, "elected": 3, "first": 2020, "last": 2024}, + {"name": "人民民主陣線", "candidates": 37, "elected": 1, "first": 2012, "last": 2014}, + {"name": "樹黨", "candidates": 36, "elected": 3, "first": 2014, "last": 2018}, + {"name": "台灣維新", "candidates": 31, "elected": 0, "first": 2020, "last": 2024}, + {"name": "勞動黨", "candidates": 29, "elected": 7, "first": 1994, "last": 2024}, + {"name": "小民參政歐巴桑聯盟", "candidates": 26, "elected": 0, "first": 2022, "last": 2024}, + {"name": "人民最大黨", "candidates": 24, "elected": 1, "first": 2012, "last": 2024}, + {"name": "綠色本土清新黨", "candidates": 22, "elected": 1, "first": 1996, "last": 1998}, + {"name": "民主聯盟", "candidates": 21, "elected": 4, "first": null, "last": null}, + {"name": "青年陽光黨", "candidates": 21, "elected": 2, "first": 2018, "last": 2022}, + {"name": "新國家連線", "candidates": 17, "elected": 1, "first": 1998, "last": 1998}, + {"name": "臺灣慧行志工黨", "candidates": 17, "elected": 0, "first": 2002, "last": 2004}, + {"name": "公民黨", "candidates": 16, "elected": 2, "first": 2005, "last": 2022}, + {"name": "制憲聯盟", "candidates": 14, "elected": 1, "first": 2008, "last": 2010}, + {"name": "台灣主義黨", "candidates": 14, "elected": 1, "first": 2012, "last": 2014}, + {"name": "合一行動聯盟", "candidates": 14, "elected": 0, "first": 2020, "last": 2024}, + {"name": "喜樂島聯盟", "candidates": 14, "elected": 0, "first": 2020, "last": 2024}, + {"name": "國會政黨聯盟", "candidates": 14, "elected": 0, "first": 2020, "last": 2020}, + {"name": "人民民主黨", "candidates": 13, "elected": 3, "first": 2018, "last": 2024}, + {"name": "制度救世島", "candidates": 13, "elected": 0, "first": 2024, "last": 2024}, + {"name": "宗教聯盟", "candidates": 13, "elected": 0, "first": 2020, "last": 2020}, + {"name": "一邊一國行動黨", "candidates": 12, "elected": 0, "first": 2020, "last": 2020}, + {"name": "中華民國臺灣基本法連線", "candidates": 12, "elected": 1, "first": 2012, "last": 2012}, + {"name": "中華民族致公黨", "candidates": 12, "elected": 4, "first": 2018, "last": 2022}, + {"name": "台澎黨", "candidates": 12, "elected": 0, "first": 2020, "last": 2022}, + {"name": "司法改革黨", "candidates": 12, "elected": 0, "first": 2024, "last": 2024}, + {"name": "基進黨", "candidates": 12, "elected": 0, "first": 2018, "last": 2018}, + {"name": "安定力量", "candidates": 12, "elected": 0, "first": 2020, "last": 2020}, + {"name": "客家黨", "candidates": 12, "elected": 1, "first": 2008, "last": 2009}, + {"name": "紅黨", "candidates": 12, "elected": 1, "first": 2008, "last": 2008}, + {"name": "健保免費連線", "candidates": 11, "elected": 1, "first": 2012, "last": 2012}, + {"name": "台灣國民會議", "candidates": 11, "elected": 1, "first": 2012, "last": 2012}, + {"name": "台灣農民黨", "candidates": 11, "elected": 1, "first": 2008, "last": 2008}, + {"name": "第三社會黨", "candidates": 11, "elected": 1, "first": 2008, "last": 2008}, + {"name": "臺灣雙語無法黨", "candidates": 11, "elected": 0, "first": 2024, "last": 2024}, + {"name": "大道慈悲濟世黨", "candidates": 10, "elected": 0, "first": 2008, "last": 2010}, + {"name": "保護台灣大聯盟", "candidates": 7, "elected": 0, "first": 2005, "last": 2006}, + {"name": "社會民主黨", "candidates": 7, "elected": 2, "first": 2018, "last": 2024}, + {"name": "中國台灣原住民黨", "candidates": 6, "elected": 1, "first": 1996, "last": 1998}, + {"name": "台灣第一民族黨", "candidates": 6, "elected": 3, "first": 2014, "last": 2014}, + {"name": "天宙和平統一家庭黨", "candidates": 6, "elected": 1, "first": 2014, "last": 2022}, + {"name": "民國黨", "candidates": 6, "elected": 3, "first": 2018, "last": 2018}, + {"name": "台灣工黨", "candidates": 5, "elected": 0, "first": 2020, "last": 2022}, + {"name": "民主自由黨", "candidates": 5, "elected": 0, "first": 2008, "last": 2008}, + {"name": "信心希望聯盟", "candidates": 4, "elected": 0, "first": 2018, "last": 2018}, + {"name": "台灣動物保護黨", "candidates": 4, "elected": 0, "first": 2020, "last": 2022}, + {"name": "台灣整復師聯盟工黨", "candidates": 4, "elected": 0, "first": 2018, "last": 2024}, + {"name": "左翼聯盟", "candidates": 4, "elected": 0, "first": 2018, "last": 2022}, + {"name": "復康聯盟黨", "candidates": 4, "elected": 0, "first": 2024, "last": 2024}, + {"name": "正黨", "candidates": 4, "elected": 0, "first": 2012, "last": 2022}, + {"name": "臺灣前進黨", "candidates": 4, "elected": 0, "first": 2018, "last": 2020}, + {"name": "中國民眾黨", "candidates": 3, "elected": 1, "first": 2005, "last": 2022}, + {"name": "先進黨", "candidates": 3, "elected": 0, "first": 1996, "last": 1996}, + {"name": "共和黨", "candidates": 3, "elected": 0, "first": 2022, "last": 2022}, + {"name": "台灣吾黨", "candidates": 3, "elected": 1, "first": null, "last": null}, + {"name": "台灣澎友黨", "candidates": 3, "elected": 1, "first": 2022, "last": 2022}, + {"name": "工教聯盟", "candidates": 3, "elected": 1, "first": 2004, "last": 2005}, + {"name": "社會改革黨", "candidates": 3, "elected": 0, "first": 1997, "last": 1998}, + {"name": "統一聯盟黨", "candidates": 3, "elected": 1, "first": 2022, "last": 2022}, + {"name": "經濟黨", "candidates": 3, "elected": 0, "first": 2018, "last": 2024}, + {"name": "軍公教聯盟黨", "candidates": 3, "elected": 0, "first": 2018, "last": 2018}, + {"name": "中國和平統一黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2022}, + {"name": "中國國家社會主義勞工黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "中國青年黨", "candidates": 2, "elected": 0, "first": 1996, "last": 1996}, + {"name": "中華婦女黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "中華愛國同心黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "中華文化復興在理黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2022}, + {"name": "中華聯合黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "全國人民黨", "candidates": 2, "elected": 1, "first": 2018, "last": 2022}, + {"name": "前進黨", "candidates": 2, "elected": 0, "first": 2022, "last": 2022}, + {"name": "台灣國民黨", "candidates": 2, "elected": 0, "first": 2009, "last": 2024}, + {"name": "台灣學習黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "台灣建國聯盟", "candidates": 2, "elected": 0, "first": 2006, "last": 2006}, + {"name": "台灣民意黨", "candidates": 2, "elected": 0, "first": 2010, "last": 2020}, + {"name": "台灣民族黨", "candidates": 2, "elected": 0, "first": 2014, "last": 2014}, + {"name": "台灣綠黨", "candidates": 2, "elected": 0, "first": 2024, "last": 2024}, + {"name": "台灣進步黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "台灣革命黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "台灣麻將最大黨", "candidates": 2, "elected": 0, "first": 2024, "last": 2024}, + {"name": "司法正義黨", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "天一黨", "candidates": 2, "elected": 0, "first": 2022, "last": 2022}, + {"name": "教科文預算保障e聯盟", "candidates": 2, "elected": 0, "first": 2014, "last": 2018}, + {"name": "新生黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "新華勞動黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "皇君人民政黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2018}, + {"name": "聾國黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2020}, + {"name": "臺灣人民共產黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2022}, + {"name": "興中同盟會", "candidates": 2, "elected": 0, "first": 2020, "last": 2024}, + {"name": "華裔和合黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2018}, + {"name": "農民黨", "candidates": 2, "elected": 1, "first": 2005, "last": 2018}, + {"name": "金門高粱黨", "candidates": 2, "elected": 0, "first": 2018, "last": 2020}, + {"name": "三等國民公義人權自救黨", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "世界和平黨", "candidates": 1, "elected": 0, "first": 2008, "last": 2008}, + {"name": "世界大同黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "中國婦女黨", "candidates": 1, "elected": 0, "first": 1998, "last": 1998}, + {"name": "中國忠義黨", "candidates": 1, "elected": 0, "first": 1994, "last": 1994}, + {"name": "中國民主進步黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "中國生產黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "中華台商愛國黨", "candidates": 1, "elected": 0, "first": 2012, "last": 2012}, + {"name": "中華文化共和黨", "candidates": 1, "elected": 0, "first": 2024, "last": 2024}, + {"name": "中華文化民主黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "中華新住民黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "中華民主向日葵憲政改革聯盟", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "中華民國國政監督聯盟", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "中華照生黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "全民生活政策黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "全民的黨", "candidates": 1, "elected": 0, "first": null, "last": null}, + {"name": "勞工黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "台灣君民黨", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, + {"name": "台灣新住民黨", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, + {"name": "台灣獨立黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "台灣經濟發展黨", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, + {"name": "國家民主黨", "candidates": 1, "elected": 0, "first": null, "last": null}, + {"name": "圓黨", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "夏潮聯合會", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, + {"name": "大中華統一陣線", "candidates": 1, "elected": 0, "first": null, "last": null}, + {"name": "大道人民黨", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "家庭基本收入", "candidates": 1, "elected": 0, "first": 2024, "last": 2024}, + {"name": "愛心黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "新政世紀黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "正神名黨", "candidates": 1, "elected": 1, "first": 2022, "last": 2022}, + {"name": "正義聯盟", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "民生公益", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "洪運忠義黨", "candidates": 1, "elected": 0, "first": 2008, "last": 2008}, + {"name": "聯合黨", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "自由台灣黨", "candidates": 1, "elected": 0, "first": 2018, "last": 2018}, + {"name": "臺灣建國黨", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "華聲黨", "candidates": 1, "elected": 0, "first": 2014, "last": 2014}, + {"name": "言論自由聯盟", "candidates": 1, "elected": 0, "first": 2020, "last": 2020}, + {"name": "金色力量黨", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, + {"name": "龍黨", "candidates": 1, "elected": 0, "first": 2022, "last": 2022}, +]; + +export const PARTY_NAMES: readonly string[] = PARTY_RECORDS.map((p) => p.name); diff --git a/backend/packages/protocol/src/people.ts b/backend/packages/protocol/src/people.ts new file mode 100644 index 0000000..bf53df2 --- /dev/null +++ b/backend/packages/protocol/src/people.ts @@ -0,0 +1,103 @@ +import { z } from "zod"; +import { IsoDate } from "./common.ts"; + +/** 人物類別:所有具名人物都是真實人物;custom 只來自玩家捏臉(docs/15) */ +export const PersonCategory = z.enum([ + "politician", + "official", + "business", + "entertainer", + "pundit", + "influencer", + "village_chief", + "custom", +]); + +export const STAT_KEYS = [ + "awareness", + "network", + "affinity", + "eloquence", + "strategy", + "online", + "image", + "wealth", + "stamina", +] as const; +export const StatKey = z.enum(STAT_KEYS); +export type StatKey = z.infer; + +/** 遊戲屬性 0–100;null 代表尚未評分 */ +export const Stats = z.object( + Object.fromEntries(STAT_KEYS.map((k) => [k, z.number().int().min(0).max(100).nullable()])) as Record< + StatKey, + z.ZodNullable + >, +); + +export const Position = z.object({ + title: z.string().min(1), + org: z.string().min(1), + from: IsoDate.nullable(), + to: IsoDate.nullable(), + sourceIds: z.array(z.string()).min(1), +}); + +export const Education = z.object({ + degree: z.string().min(1), + school: z.string().nullable(), + sourceIds: z.array(z.string()).min(1), +}); + +export const ElectionRecord = z.object({ + election: z.string().min(1), + district: z.string().nullable(), + party: z.string().nullable(), + votes: z.number().int().nonnegative().nullable(), + share: z.number().min(0).max(1).nullable(), + elected: z.boolean(), + sourceIds: z.array(z.string()).min(1), +}); + +/** 每個屬性的評分紀錄:沒有出處的 AI 分數一律作廢(docs/15) */ +export const ScoringRecord = z.object({ + stat: StatKey, + value: z.number().int().min(0).max(100), + method: z.enum(["derived", "ai", "manual", "default"]), + rationale: z.string().nullable(), + /** 出處:資料來源 id(見 sources.json)或公開網頁網址 */ + citations: z.array(z.string()), + confidence: z.enum(["high", "medium", "low"]), + model: z.string().nullable(), + rubricVersion: z.string(), + scoredAt: z.string().min(1), + reviewed: z.boolean(), +}); +export type ScoringRecord = z.infer; + +export const Person = z.object({ + id: z.string().min(1), + kind: z.enum(["real", "custom"]), + category: PersonCategory, + name: z.string().min(1), + gender: z.enum(["M", "F", "X"]).nullable(), + birthDate: IsoDate.nullable(), + party: z.string().nullable(), + wikidataId: z.string().regex(/^Q\d+$/).nullable(), + positions: z.array(Position), + education: z.array(Education), + electionHistory: z.array(ElectionRecord), + stats: Stats, + scoring: z.array(ScoringRecord), + /** 欄位名稱 → 出處 id;姓名、性別、生日、政黨等純量欄位的出處 */ + fieldSources: z.record(z.string(), z.array(z.string()).min(1)), + asOf: IsoDate, +}); +export type Person = z.infer; + +export const PeopleFile = z.object({ + protocolVersion: z.string(), + asOf: IsoDate, + people: z.array(Person), +}); +export type PeopleFile = z.infer; diff --git a/backend/packages/protocol/src/records.ts b/backend/packages/protocol/src/records.ts new file mode 100644 index 0000000..1a30746 --- /dev/null +++ b/backend/packages/protocol/src/records.ts @@ -0,0 +1,227 @@ +import { z } from "zod"; +import { CountyCode, IsoDate, Share, TownCode, VillageCode } from "./common.ts"; + +/** + * 歷屆參選人資料庫(data/build/people/records.json,由 election-data records 產生): + * 縣市長、議員,加上總統副總統、立法委員(區域、原住民、不分區)。 + * 只用中選會選舉資料庫的公開紀錄計算資歷分數;分數是遊戲數值,不代表對個人的評價。 + * 檔名叫 records 是為了和 people.ts(具名人物名單 people.json)分開。 + */ + +/** mayor:首長(縣市長、直轄市長、臺灣省長);councilor:議員;president:總統、副總統;legislator:立法委員 */ +export const ElectionOffice = z.enum(["mayor", "councilor", "president", "legislator"]); +export type ElectionOffice = z.infer; + +export const RECORD_SCORE_KEYS = ["fame", "organization", "seniority", "strength", "finance"] as const; +export const RecordScoreKey = z.enum(RECORD_SCORE_KEYS); +export type RecordScoreKey = z.infer; + +/** 一次參選 */ +export const ElectionRun = z.object({ + year: z.number().int(), + date: IsoDate, + /** 臺灣省長、直轄市長、縣市長、臺灣省議員、直轄市議員、縣市議員、總統、副總統、立法委員、不分區立法委員 */ + election: z.string().min(1), + office: ElectionOffice, + /** 平地原住民、山地原住民、原住民(1994–2006 北高);區域選舉是 null */ + indigenous: z.string().nullable(), + /** 當年的縣市名稱(臺北縣、臺灣省……);總統副總統、原住民立委、不分區立委是「全國」 */ + county: z.string(), + /** 對到目前的縣市代碼(臺北縣 → 65000);臺灣省、全國是 null */ + countyCode: CountyCode.nullable(), + /** 第 3 選區;首長選舉或整個縣市一個選區是 null */ + district: z.string().nullable(), + /** 號次;不分區立委是政黨的號次 */ + number: z.number().int().nullable(), + /** 政黨(總統副總統是推薦的政黨);無黨籍是 null */ + party: z.string().nullable(), + /** 得票;副總統是同一組正副總統的票;不分區立委沒有個人得票,是 null */ + votes: z.number().int().nonnegative().nullable(), + share: Share.nullable(), + elected: z.boolean(), + /** 中選會候選人檔的「現任」欄;舊資料沒有填就是 null */ + incumbent: z.boolean().nullable(), + /** 總統副總統選舉同一組的搭檔:總統候選人這裡是副總統,副總統候選人這裡是總統候選人 */ + runningMate: z.string().min(1).optional(), + /** 不分區立委:政黨名單上的排名(第 1 名……) */ + listRank: z.number().int().positive().optional(), + /** 不分區立委:所屬政黨的全國政黨票與得票率 */ + partyVotes: z.number().int().nonnegative().optional(), + partyShare: Share.optional(), +}); +export type ElectionRun = z.infer; + +/** 一項資歷分數:value 0–10(null 是無資料),basis 是代入公式的數字 */ +export const RecordScore = z.object({ + key: RecordScoreKey, + value: z.number().min(0).max(10).nullable(), + basis: z.string(), +}); +export type RecordScore = z.infer; + +/** 分數的算法與出處(全部人共用) */ +export const RecordScoreDef = z.object({ + key: RecordScoreKey, + label: z.string().min(1), + formula: z.string().min(1), + source: z.string().min(1), +}); +export type RecordScoreDef = z.infer; + +export const RecordStats = z.object({ + runs: z.number().int().positive(), + wins: z.number().int().nonnegative(), + firstYear: z.number().int(), + lastYear: z.number().int(), + maxVotes: z.number().int().nonnegative(), +}); + +/** records.json 裡的一個人 */ +export const PersonRecord = z.object({ + id: z.string().regex(/^r-[0-9a-f]{10}$/), + name: z.string().min(1), + gender: z.enum(["M", "F"]).nullable(), + birthYear: z.number().int().nullable(), + /** high:同名+出生年對上;low:有一筆沒有出生年、用同名+同縣市對的,或出生年差 1 年串起來的(比對信心:低) */ + confidence: z.enum(["high", "low"]), + /** 比對信心低的原因(例如出生年差 1 年串起來的);沒有就是一般的「沒有出生年」 */ + matchNote: z.string().optional(), + counties: z.array(CountyCode), + /** 參選過的政黨,最近的排前面;null 是無黨籍 */ + parties: z.array(z.string().nullable()), + stats: RecordStats, + runs: z.array(ElectionRun).min(1), + scores: z.array(RecordScore), +}); +export type PersonRecord = z.infer; + +export const RecordSource = z.object({ + title: z.string().min(1), + url: z.string(), + retrievedAt: IsoDate.nullish(), + sha256: z.string().nullish(), + license: z.string().optional(), + note: z.string().optional(), +}); + +export const RecordElection = z.object({ + folder: z.string(), + year: z.number().int(), + date: IsoDate, + election: z.string(), + office: ElectionOffice, + indigenous: z.string().nullable(), + candidates: z.number().int().nonnegative(), + elected: z.number().int().nonnegative(), + noVotes: z.number().int().nonnegative(), +}); + +/** data/build/people/records.json 整個檔案 */ +export const RecordsFile = z.object({ + protocolVersion: z.string(), + generatedAt: IsoDate, + note: z.string(), + sources: z.array(RecordSource), + scoreDefs: z.array(RecordScoreDef), + elections: z.array(RecordElection), + people: z.array(PersonRecord), +}); +export type RecordsFile = z.infer; + +// ── API:GET /api/people、GET /api/people/:id ── + +export const PEOPLE_PAGE_SIZE = 50; + +export const PeopleListQuery = z.object({ + county: CountyCode.optional(), + office: ElectionOffice.optional(), + year: z.coerce.number().int().min(1900).max(2100).optional(), + q: z.string().trim().max(40).optional(), + page: z.coerce.number().int().min(1).max(10_000).default(1), +}); +export type PeopleListQuery = z.infer; + +/** 列表的一列 */ +export const PersonRecordSummary = z.object({ + id: z.string(), + name: z.string(), + /** 最近一次參選的政黨;無黨籍是 null */ + party: z.string().nullable(), + runs: z.number().int(), + wins: z.number().int(), + firstYear: z.number().int(), + lastYear: z.number().int(), + /** 最近一次參選:「2022 臺北市第3選區 直轄市議員」「2024 全國 副總統」 */ + latest: z.string(), + confidence: z.enum(["high", "low"]), +}); +export type PersonRecordSummary = z.infer; + +export const PeopleListResponse = z.object({ + total: z.number().int().nonnegative(), + page: z.number().int().positive(), + pageSize: z.number().int().positive(), + people: z.array(PersonRecordSummary), + /** 資料庫有收的年份(篩選用) */ + years: z.array(z.number().int()), + note: z.string(), +}); +export type PeopleListResponse = z.infer; + +/** 個人頁:分數附上算法與出處 */ +export const PersonRecordResponse = z.object({ + person: PersonRecord.omit({ scores: true }).extend({ + scores: z.array(RecordScore.extend({ label: z.string(), formula: z.string(), source: z.string() })), + }), + sources: z.array(RecordSource), + note: z.string(), +}); +export type PersonRecordResponse = z.infer; + +// ── 議員選區檔:data/build/council/<年>.json(政治生涯的議員關用) ── + +export const CouncilCandidate = z.object({ + number: z.number().int().nullable(), + name: z.string(), + party: z.string().nullable(), + votes: z.number().int().nullable(), + share: Share.nullable(), + elected: z.boolean(), + incumbent: z.boolean().nullable(), + /** records.json 的人物 id */ + personId: z.string().nullable(), +}); + +export const CouncilDistrict = z.object({ + /** 縣市代碼-中選會選區代碼,例如 63000-03 */ + id: z.string(), + countyCode: CountyCode, + countyName: z.string(), + election: z.string(), + indigenous: z.string().nullable(), + district: z.string().nullable(), + districtCode: z.string(), + /** 應選席次(當選人數,含婦女保障名額) */ + seats: z.number().int().nonnegative(), + electors: z.number().int().nullable(), + validVotes: z.number().int().nullable(), + towns: z.array(TownCode), + villages: z.array(VillageCode), + candidates: z.array(CouncilCandidate), + /** 當選門檻:得票最少的當選者 */ + threshold: z.object({ name: z.string(), votes: z.number().int().nullable(), share: Share.nullable() }).nullable(), +}); +export type CouncilDistrict = z.infer; + +export const CouncilFile = z.object({ + protocolVersion: z.string(), + year: z.number().int(), + date: IsoDate, + source: RecordSource, + districts: z.array(CouncilDistrict), + /** 選舉當時的村里代碼對不上目前資料包的(選後合併、改名) */ + unmatchedVillages: z.array(z.object({ district: z.string(), code: z.string(), reason: z.string() })), + /** 目前資料包有、但不在任何區域議員選區內的村里(選後新設) */ + uncoveredVillages: z.record(z.string(), z.array(z.string())), +}); +export type CouncilFile = z.infer; diff --git a/backend/packages/protocol/src/rogue.ts b/backend/packages/protocol/src/rogue.ts new file mode 100644 index 0000000..4a0e41d --- /dev/null +++ b/backend/packages/protocol/src/rogue.ts @@ -0,0 +1,495 @@ +import { z } from "zod"; +import { CandidatePublic, CustomCandidate } from "./game.ts"; + +/** + * 選戰卡牌(新玩法,docs/21、22)的前後端契約。 + * 規則在後端 @election2026/rogue;前端只拿到畫面要用的狀態,連「選了這張牌打在哪一區會加多少」都由伺服器先算好。 + */ + +export const RogueTrait = z.enum(["young", "old", "temples", "dense", "rural", "hakka"]); +export type RogueTrait = z.infer; + +export const RogueOwner = z.enum(["you", "rival"]).nullable(); + +export const RogueTown = z.object({ + code: z.string(), + name: z.string(), + /** 預計投票人數(依真實投票率推估) */ + voters: z.number().int().nonnegative(), + /** 已經表態支持的票數;undecided 是還沒表態的人 */ + you: z.number().int().nonnegative(), + rival: z.number().int().nonnegative(), + others: z.number().int().nonnegative(), + undecided: z.number().int().nonnegative(), + traits: z.array(RogueTrait), + /** 相鄰的區(造勢、宣傳車會擴散過去) */ + neighbors: z.array(z.string()), + /** 你在這區的樁腳(擋對手本週在這區的行動) */ + shield: z.number().int().nonnegative(), + /** 對手在這區的樁腳(擋你本週在這區的牌) */ + rivalShield: z.number().int().nonnegative(), + /** 有服務處或看板:每週自動加票 */ + office: z.boolean(), + /** 這週已經打在這區的牌(不重複) */ + played: z.array(z.object({ id: z.string(), name: z.string(), art: z.string() })), + /** 插旗:已表態的票裡領先 8 個百分點以上 */ + flag: RogueOwner, +}); +export type RogueTown = z.infer; + +export const RogueIntentKind = z.enum(["canvass", "rally", "tv", "online", "attack", "smear", "stake"]); +export type RogueIntentKind = z.infer; + +/** 對手這週要做的事:週初就亮在地圖上,週末才執行 */ +export const RogueIntent = z.object({ + id: z.string(), + kind: RogueIntentKind, + label: z.string(), + /** 打在哪一區;全市的是 null */ + town: z.string().nullable(), + /** 預計的票數(批評是你會被拉走的票,佈樁是盾的大小) */ + amount: z.number().int().nonnegative(), + /** 被你打對台、澄清之後剩下的比例(1 是原封不動) */ + cut: z.number().min(0).max(1), + /** 預告過的大型造勢 */ + big: z.boolean(), +}); +export type RogueIntent = z.infer; + +export const RogueCardTarget = z.enum(["town", "city", "intent", "attack", "none"]); +export const RogueRarity = z.enum(["basic", "common", "rare", "status"]); +export type RogueRarity = z.infer; + +export const RogueCard = z.object({ + uid: z.string(), + id: z.string(), + name: z.string(), + /** 卡牌插圖(沿用 /cards/*.webp) */ + art: z.string(), + cost: z.number().int().nonnegative(), + /** 花費(萬元) */ + money: z.number().int().nonnegative(), + rarity: RogueRarity, + tags: z.array(z.string()), + target: RogueCardTarget, + /** 牌面大字:主要數字(例如 +1,500),沒有就是 null */ + value: z.string().nullable(), + /** 牌面小字:一句話 */ + text: z.string(), + /** 關鍵字:消耗、保留、虛無、不能打 */ + keywords: z.array(z.string()), + /** 升級過(+版) */ + up: z.boolean(), + /** 不能打的原因;能打是 null */ + blocked: z.string().nullable(), +}); +export type RogueCard = z.infer; + +/** 選起一張牌時,打在每個目標的預估效果 */ +export const RoguePreview = z.object({ + /** 區代碼、對手意圖 id,或 "city"(不用選目標的牌) */ + target: z.string(), + /** 預估加的票(負數是被拉走) */ + votes: z.number().int(), + /** 加成說明,例如「宮廟多 ×2・組合拳 +15%」 */ + note: z.string(), +}); +export type RoguePreview = z.infer; + +export const RogueAdvisor = z.object({ + id: z.string(), + name: z.string(), + text: z.string(), + art: z.string(), + school: z.string(), + /** 圖鑑:怎麼拿到 */ + how: z.string().optional(), +}); +export type RogueAdvisor = z.infer; + +export const RogueEvent = z.object({ id: z.string(), title: z.string(), text: z.string(), how: z.string().optional() }); + +/** 結算時發生的事,前端照順序演出 */ +export const RogueLog = z.object({ + side: z.enum(["you", "rival", "system"]), + text: z.string(), + town: z.string().nullable(), + /** 對你的票數影響(正的是你多了、負的是你少了或對手多了) */ + votes: z.number().int(), + /** 你擋下的票(樁腳、打對台、澄清讓對手少拉的票;不是實際變化) */ + blocked: z.number().int().nonnegative().optional(), +}); +export type RogueLog = z.infer; + +/** 劇情、地方抉擇的一個選項 */ +export const RogueChoice = z.object({ + label: z.string(), + hint: z.string(), + /** 不能選的原因(資金不夠…);能選是 null */ + blocked: z.string().nullable(), + /** 要看運氣 */ + risky: z.boolean(), +}); +export type RogueChoice = z.infer; + +export const DebateMove = z.enum(["policy", "emotion", "question"]); +export type DebateMove = z.infer; + +/** 每週開場的劇情 */ +export const RogueScene = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("press"), question: z.string(), choices: z.array(RogueChoice) }), + z.object({ + kind: z.literal("debate"), + round: z.number().int(), + rounds: z.number().int(), + /** 這回合的題目與對手的質疑 */ + topic: z.string().nullable(), + challenge: z.string().nullable(), + /** 看得出最好的回應(辯論教練、口才 5 級):best 是 hand 裡那張的位置 */ + sure: z.boolean(), + best: z.number().int().nullable(), + /** 你手上的論點;用掉就沒了 */ + hand: z.array(z.object({ kind: DebateMove, label: z.string(), text: z.string(), policy: z.boolean() })), + /** 三種論點的說明 */ + moves: z.array(z.object({ id: DebateMove, label: z.string(), counters: z.string() })), + history: z.array( + z.object({ + topic: z.string(), + challenge: z.string(), + you: DebateMove, + text: z.string(), + result: z.enum(["win", "lose", "tie"]), + combo: z.number().int(), + votes: z.number().int(), + }), + ), + combo: z.number().int(), + wins: z.number().int(), + losses: z.number().int(), + }), + z.object({ kind: z.literal("crisis"), amount: z.number().int(), choices: z.array(RogueChoice) }), + z.object({ kind: z.literal("poll"), you: z.number(), rival: z.number(), lead: z.boolean() }), +]); +export type RogueScene = z.infer; + +/** 政策工坊:玩家自己組合的政策(對象 × 做法 × 財源),每一局可以帶進牌組 */ +export const PolicyTarget = z.enum(["old", "young", "workers", "farmers", "hakka", "believers", "families"]); +export const PolicyMethod = z.enum(["subsidy", "build", "law", "tax_cut"]); +export const PolicyFunding = z.enum(["tax", "debt", "cut", "invest"]); +export const PolicySpec = z.object({ + name: z.string().trim().min(1).max(20), + target: PolicyTarget, + method: PolicyMethod, + funding: PolicyFunding, +}); +export type PolicySpec = z.infer; + +/** 政策島的建築等級(跨局成長;存在玩家的瀏覽器,開局時帶給伺服器) */ +export const IslandPerk = z.object({ id: z.string().min(1).max(30), level: z.number().int().min(1).max(3) }); +export type IslandPerk = z.infer; + +/** 政治生涯的角色能力(0–5 級) */ +export const CareerAbilities = z.object({ + eloquence: z.number().int().min(0).max(5), + organization: z.number().int().min(0).max(5), + media: z.number().int().min(0).max(5), + finance: z.number().int().min(0).max(5), + integrity: z.number().int().min(0).max(5), +}); +export type CareerAbilities = z.infer; + +/** 選戰小遊戲的種類(下一站「小遊戲」) */ +export const MiniGameKind = z.enum(["handshake", "rally", "billboard"]); +export type MiniGameKind = z.infer; + +/** 放大絕招:哪一招、小遊戲分數、掃街馬拉松挑的區(最多 3 區) */ +export const RogueUltimateRequest = z.object({ + kind: MiniGameKind, + score: z.number().min(0).max(100), + towns: z.array(z.string().max(40)).max(3).optional(), +}); +export type RogueUltimateRequest = z.infer; + +/** 政策島的建築(圖鑑資料) */ +export const IslandBuilding = z.object({ + id: z.string(), + name: z.string(), + art: z.string(), + /** 每一級的效果說明 */ + levels: z.array(z.string()), + /** 蓋到第 1、2、3 級要的政績點 */ + cost: z.array(z.number().int()), +}); +export type IslandBuilding = z.infer; + +export const RogueStopKind = z.enum(["card", "advisor", "upgrade", "remove", "shop", "encounter", "event", "minigame"]); +export type RogueStopKind = z.infer; + +/** 獎勵、商店上的一個選項(牌或幕僚) */ +export const RogueOffer = z.object({ + /** 圖鑑:怎麼拿到(只有圖鑑的清單有) */ + how: z.string().optional(), + kind: z.enum(["card", "advisor", "remove"]), + id: z.string(), + name: z.string(), + text: z.string(), + art: z.string(), + rarity: z.string(), + /** 牌的標籤(決定類型色條);幕僚是空的 */ + tags: z.array(z.string()), + /** 牌的關鍵字(消耗、保留…) */ + keywords: z.array(z.string()), + /** 牌的體力、花費、大字(幕僚沒有) */ + cost: z.number().int().nullable(), + money: z.number().int().nullable(), + value: z.string().nullable(), + /** 商店價格與是否已賣出 */ + price: z.number().int().nullable(), + sold: z.boolean(), +}); +export type RogueOffer = z.infer; + +export const RogueStop = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("card"), options: z.array(RogueOffer) }), + z.object({ kind: z.literal("advisor"), options: z.array(RogueOffer) }), + z.object({ kind: z.literal("upgrade") }), + z.object({ kind: z.literal("remove") }), + z.object({ kind: z.literal("shop"), items: z.array(RogueOffer) }), + z.object({ + kind: z.literal("encounter"), + town: z.string(), + townName: z.string(), + step: z.number().int(), + total: z.number().int(), + score: z.number().int(), + /** 目前遇到的人;三個都遇完是 null */ + current: z.object({ who: z.string(), line: z.string(), options: z.array(z.object({ label: z.string(), risky: z.boolean() })) }).nullable(), + notes: z.array(z.string()), + }), + z.object({ kind: z.literal("event"), title: z.string(), text: z.string(), art: z.string(), choices: z.array(RogueChoice) }), + z.object({ + kind: z.literal("minigame"), + game: MiniGameKind, + title: z.string(), + text: z.string(), + /** 在哪一區玩(掃街、看板);造勢是全市 */ + town: z.string().nullable(), + townName: z.string().nullable(), + /** 難度 0–1(越後面越難) */ + level: z.number(), + seed: z.number().int(), + }), +]); +export type RogueStop = z.infer; + +export const RogueRoute = z.object({ + kind: RogueStopKind, + title: z.string(), + text: z.string(), + /** 門上直接攤開的內容(拜會地方、招募幕僚、地方抉擇);其他門是 null,要進門 */ + preview: RogueStop.nullable(), +}); +export type RogueRoute = z.infer; + +/** 牌組裡的一張牌(看牌組、升級、拿掉用);plus 是升級後的樣子 */ +export const RogueDeckCard = RogueCard.omit({ blocked: true }).extend({ + pile: z.enum(["draw", "hand", "discard"]), + plus: z.object({ name: z.string(), cost: z.number().int(), value: z.string().nullable(), text: z.string() }).nullable(), +}); +export type RogueDeckCard = z.infer; + +export const RogueResult = z.object({ + won: z.boolean(), + you: z.number().int(), + rival: z.number().int(), + others: z.number().int(), + /** 得票率(0–1) */ + youShare: z.number(), + rivalShare: z.number(), + grade: z.enum(["S", "A", "B", "C", "D"]), + /** 各區:你、對手的得票 */ + byTown: z.array(z.object({ code: z.string(), you: z.number().int(), rival: z.number().int(), others: z.number().int() })), + /** 這局拿到的成就 id */ + feats: z.array(z.string()), +}); +export type RogueResult = z.infer; + +export const RogueView = z.object({ + runId: z.string(), + seed: z.number().int(), + scenarioId: z.string(), + scenarioName: z.string(), + packId: z.string(), + countyCode: z.string(), + countyName: z.string(), + /** 選區名稱(立委是「高雄市第 4 選舉區」,縣市長是縣市名稱) */ + area: z.string(), + /** 選幾席(議員是多席次:贏過最後一席就當選);threshold 是最後一席的得票率(真實資料) */ + seats: z.number().int(), + threshold: z.number().nullable(), + office: z.string(), + options: z.object({ + ascension: z.number().int(), + tutorial: z.boolean(), + daily: z.string().nullable(), + even: z.boolean(), + /** 政治生涯的第幾關(里長 → 議員 → 立委 → 縣市長 → 總統);不是政治生涯是 null */ + career: z.object({ stage: z.number().int(), total: z.number().int() }).nullable(), + /** 角色能力(政治生涯;或玩真實候選人時依公開選舉紀錄換算);abilitiesBasis 是換算的依據 */ + abilities: CareerAbilities.nullable(), + abilitiesBasis: z.string().nullable(), + /** 自創角色的出身與政黨(專屬起始牌、黨的資源);真實候選人是 null */ + origin: z.object({ background: z.string(), party: z.string().nullable(), kind: z.enum(["major", "tpp", "minor"]) }).nullable().default(null), + }), + week: z.number().int(), + totalWeeks: z.number().int(), + phase: z.enum(["scene", "plan", "route", "stop", "finished"]), + energy: z.number().int(), + energyMax: z.number().int(), + /** 資金(萬元) */ + money: z.number().int(), + momentum: z.number().int(), + rivalMomentum: z.number().int(), + momentumMax: z.number().int(), + /** 把柄:爆料要用 */ + leverage: z.number().int(), + you: CandidatePublic, + rival: CandidatePublic, + others: z.array(CandidatePublic), + /** 雙方的代表色(政黨色;同一個顏色或教學關卡用別的顏色區分) */ + colors: z.object({ you: z.string(), rival: z.string() }), + /** 對手性格 */ + rivalTrait: z.object({ name: z.string(), text: z.string() }), + towns: z.array(RogueTown), + intents: z.array(RogueIntent), + /** 對手預告的大型造勢(第幾週、哪一區、預計多少) */ + nextBig: z.object({ week: z.number().int(), town: z.string(), label: z.string(), amount: z.number().int() }).nullable(), + event: RogueEvent, + hand: z.array(RogueCard), + drawCount: z.number().int(), + discardCount: z.number().int(), + exhaustedCount: z.number().int(), + /** 整副牌(看牌組、升級、拿掉用) */ + deck: z.array(RogueDeckCard), + advisors: z.array(RogueAdvisor), + advisorSlots: z.number().int(), + /** 整局有效的能力、這週的加成 */ + powers: z.array(z.string()), + buffs: z.array(z.string()), + /** 手上每張牌打在各目標的預估效果(uid → 預估) */ + previews: z.record(z.string(), z.array(RoguePreview)), + scene: RogueScene.nullable(), + route: z.array(RogueRoute).nullable(), + /** 最近一次民調(第 4 週自動公布) */ + poll: z.object({ week: z.number().int(), you: z.number(), rival: z.number(), lead: z.boolean() }).nullable(), + /** 大絕招(18 第 57 項):集氣 0–100、能不能放、放過幾次/最多幾次、落後倍率、落後幾個百分點、三招、掃街馬拉松建議的區 */ + ultimate: z + .object({ + charge: z.number(), + ready: z.boolean(), + used: z.number().int(), + max: z.number().int(), + mult: z.number(), + deficit: z.number(), + options: z.array(z.object({ kind: MiniGameKind, name: z.string(), game: z.string(), text: z.string() })), + suggest: z.array(z.string()), + }) + .nullable() + .default(null), + stop: RogueStop.nullable(), + /** 不去下一站改拿的資金(萬元) */ + skipMoney: z.number().int(), + /** 剛剛發生的事(出牌、劇情或週末結算),前端拿來演出 */ + log: z.array(RogueLog), + /** 這週的戰果:你拉到的票、被拉走的票、擋下的票,以及這週開始時的全市支持度 */ + tally: z.object({ gained: z.number().int(), lost: z.number().int(), blocked: z.number().int(), startYou: z.number(), startRival: z.number() }), + /** 如果今天開票(含聲勢帶出的未表態):雙方得票率 */ + forecast: z.object({ you: z.number(), rival: z.number() }), + /** 剛打出的那張牌的加成說明(實際結果,例如「爆紅!」);只有出牌的回應才有 */ + notes: z.array(z.string()).default([]), + /** 每週結束時的全市支持度(畫走勢) */ + history: z.array(z.object({ week: z.number().int(), you: z.number(), rival: z.number() })), + result: RogueResult.nullable(), +}); +export type RogueView = z.infer; + +/** 圖鑑:全部的牌、幕僚、成就、逆風難度說明 */ +export const RogueCatalog = z.object({ + cards: z.array(RogueOffer), + buildings: z.array(IslandBuilding), + /** 政策落地:每種政策對象的「家」是哪一棟建築(那棟每級讓政策牌 +10%) */ + policyHome: z.record(PolicyTarget, z.string()), + /** 政治生涯的五項能力:名稱、每一級的效果 */ + abilities: z.array(z.object({ id: z.enum(["eloquence", "organization", "media", "finance", "integrity"]), label: z.string(), effect: z.string() })), + advisors: z.array(RogueAdvisor), + feats: z.array(z.object({ id: z.string(), name: z.string(), text: z.string() })), + ascension: z.array(z.string()), + events: z.array(RogueEvent), +}); +export type RogueCatalog = z.infer; + +/** 選區範圍:立委選區內的村里代碼;縣市長、總統是 null(整份資料包) */ +export const RogueArea = z.object({ + villages: z.array(z.string()).nullable(), + /** 議員選區把村里分群時:村里 → 遊戲裡的區代碼 */ + groups: z.record(z.string(), z.string()).nullable().default(null), +}); +export type RogueArea = z.infer; + +/** 政治生涯里長關:這個縣市的區和里(自己挑要選哪一里,18 第 56 項);選舉人數是現在的戶籍 20 歲以上人口 × 0.9987 */ +export const RogueVillageList = z.object({ + towns: z.array(z.object({ name: z.string(), villages: z.array(z.object({ code: z.string(), name: z.string(), electors: z.number().int() })) })), +}); +export type RogueVillageList = z.infer; + +export const CreateRogueRequest = z.object({ + scenarioId: z.string().min(1).max(80), + candidateId: z.string().min(1).max(80), + seed: z.number().int().nonnegative().optional(), + /** 逆風難度 0–10 */ + ascension: z.number().int().min(0).max(10).default(0), + /** 勢均力敵:雙方開局底盤拉平(劇本 id 結尾是 -even 的一定拉平) */ + even: z.boolean().default(false), + /** 每日一戰的日期(YYYY-MM-DD) */ + daily: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + /** 政治生涯:用自創角色參選(取代同黨的候選人,或以新候選人加入) */ + custom: CustomCandidate.optional(), + /** 政治生涯的角色能力 */ + abilities: CareerAbilities.optional(), + /** 政策島的建築加成 */ + perks: z.array(IslandPerk).max(20).default([]), + /** 帶進這一局的政策(最多 3 份) */ + policies: z.array(PolicySpec).max(3).default([]), + career: z.object({ stage: z.number().int().min(1).max(5) }).optional(), + /** 政治生涯的地方選舉:里長(不指定里就隨機挑)、議員(那個里所在的議員選區);scenarioId 用那個縣市的縣市長劇本 */ + local: z + .discriminatedUnion("kind", [ + z.object({ kind: z.literal("village"), village: z.string().regex(/^\d{11}$/).nullable().default(null) }), + z.object({ kind: z.literal("council"), village: z.string().regex(/^\d{11}$/) }), + ]) + .optional(), + /** 政治生涯帶到下一場的幕僚(最多 2 位)和牌(最多 3 張) */ + carry: z + .object({ + advisors: z.array(z.string().max(40)).max(2).default([]), + cards: z.array(z.object({ id: z.string().max(40), up: z.boolean().default(false) })).max(3).default([]), + /** 前幾場累積的聲望換成的起始資金(萬元) */ + money: z.number().int().min(0).max(1000).default(0), + /** 任期表現好:開局聲勢 */ + momentum: z.number().int().min(0).max(2).default(0), + }) + .optional(), +}); +export const RoguePlayRequest = z.object({ + uid: z.string().min(1).max(40), + /** 區代碼、對手意圖 id;不用選目標的牌是 null */ + target: z.string().max(40).nullable().default(null), +}); +export const RogueChooseRequest = z.object({ + /** 選第幾個(從 0 開始),或 "skip"(不選、離開);小遊戲送分數 0–100 */ + pick: z.union([z.number().int().min(0).max(100), z.literal("skip")]), + /** 下一站:門上直接選的選項(拜會地方、招募幕僚、地方抉擇),選門+選項一次完成 */ + option: z.number().int().min(0).max(10).optional(), + /** 要升級、拿掉的牌(uid) */ + target: z.string().max(40).nullable().default(null), +}); diff --git a/backend/packages/protocol/src/scenario.ts b/backend/packages/protocol/src/scenario.ts new file mode 100644 index 0000000..4ba7861 --- /dev/null +++ b/backend/packages/protocol/src/scenario.ts @@ -0,0 +1,72 @@ +import { z } from "zod"; +import { CountyCode, VillageCode } from "./common.ts"; + +/** + * 管線產生的選舉劇本資料(data/build/scenarios/2022-local/<縣市>.json): + * 只有可查證的事實(候選人、各里得票、經費上限、政治獻金)。能力值與規則在 content。 + */ +export const ElectionKind = z.enum(["mayor", "legislator", "president"]); +export type ElectionKind = z.infer; + +export const LocalElectionSpec = z.object({ + electionId: z.string(), + electionDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + kind: ElectionKind, + /** 全國為 00000 */ + countyCode: CountyCode, + countyName: z.string(), + /** 選舉區名稱:縣市名、「臺北市第 1 選舉區」或「全國」 */ + areaName: z.string(), + districtCode: z.string().optional(), + /** 立委選區涵蓋的鄉鎮市區;partial 表示只涵蓋其中部分里 */ + towns: z.array(z.object({ code: z.string(), name: z.string(), partial: z.boolean() })).optional(), + office: z.string(), + /** 遊戲裡的「區」:鄉鎮市區,或(總統選舉)縣市 */ + regionLevel: z.enum(["town", "county"]), + packId: z.string(), + spendingCap: z.number().int().positive(), + capPopulation: z.number().int().positive(), + candidates: z + .array( + z.object({ + number: z.number().int().positive(), + name: z.string().min(1), + party: z.string().nullable(), + runningMate: z.string().nullable().optional(), + finance: z.object({ income: z.number().int(), spending: z.number().int() }).nullable(), + }), + ) + .min(1), + /** 村里代碼 → 選舉人數、投票數、有效票、各號次得票(鍵為 "#3") */ + byVillage: z.record( + VillageCode, + z.object({ + electors: z.number().int().nonnegative(), + ballots: z.number().int().nonnegative(), + valid: z.number().int().nonnegative(), + votes: z.record(z.string().regex(/^#\d+$/), z.number().int().nonnegative()), + }), + ), + cecValid: z.number().int().nullable(), + sources: z.record(z.string(), z.unknown()), +}); +export type LocalElectionSpec = z.infer; + +/** 回測校準的結果(apps/sim calibrate-local):每位候選人的個人魅力加分與投票率倍率 */ +export const LocalCalibration = z.object({ + generatedAt: z.string(), + /** 鍵是劇本資料檔名:縣市代碼,或「縣市代碼-選區」 */ + counties: z.record( + z.string(), + z.object({ + turnoutScale: z.number().positive(), + /** 號次 → 個人魅力(歷史重演) */ + appeal: z.record(z.string(), z.number()), + /** 號次 → 個人魅力(勢均力敵:前兩名打平) */ + evenAppeal: z.record(z.string(), z.number()).nullable(), + /** 回測誤差(百分點):全市、各區、各里 */ + error: z.object({ county: z.number(), town: z.number(), village: z.number() }), + }), + ), +}); +export type LocalCalibration = z.infer; diff --git a/backend/packages/protocol/test/avatar.test.ts b/backend/packages/protocol/test/avatar.test.ts new file mode 100644 index 0000000..4292d72 --- /dev/null +++ b/backend/packages/protocol/test/avatar.test.ts @@ -0,0 +1,269 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { ART_OUT, CATALOG_OUT, buildAvatarCatalog } from "../scripts/build-avatar-catalog.ts"; +import { + AVATAR_CATALOG, + AvatarSpecSchema, + CustomCandidate, + checkAvatar, + cleanAvatar, + lintCatalog, + onSale, + parseAvatarLoose, + shopShelf, + shopWeek, + slotItems, + stampAvatarVersion, + wearItem, + wearSlots, + type AvatarSpecData, +} from "../src/index.ts"; +import { convertSvgArt, SvgArtError } from "../src/avatar/svg.ts"; + +/** 改版前(寫死選項那一版)存下來的頭像:每個舊選項都要照樣合法、清洗後一個字都不變 */ +const legacy: AvatarSpecData = { + skin: "#f6d3b7", + hair: "bobSide", + hairColor: "#2f2520", + outfit: "blouse", + suit: "#5a2d34", + shirt: "#f3e6d8", + tie: "#2c5aa0", + glasses: true, + beard: false, + bg: "#efe0e6", + face: "heart", + faceW: 0.95, + faceH: 1.06, + ears: "small", + brows: "thin", + browAngle: -0.3, + eyes: "narrow", + glassesStyle: "halfRim", + glassesColor: "#a8874f", + nose: "small", + mouth: "teeth", + lines: 1, + part: "right", + mustache: false, +}; + +const OLD_OPTIONS = { + hair: ["short", "side", "buzz", "bob", "long", "bun", "curly", "bald", "receding", "slick", "bobSide", "shortBob", "perm", "crew", "volume"], + outfit: ["suit", "blouse", "vest", "polo"], + face: ["oval", "round", "long", "square", "heart"], + ears: ["small", "normal", "big"], + brows: ["thin", "normal", "thick"], + eyes: ["round", "narrow", "dot", "smile"], + glassesStyle: ["metal", "rimless", "black", "round", "halfRim"], + nose: ["small", "normal", "big"], + mouth: ["smile", "grin", "closed", "teeth"], +} as const; + +describe("頭像資料:舊存檔照樣過", () => { + it("改版前的完整頭像:格式合法、目錄檢查沒問題、清洗後是同一個物件", () => { + const parsed = AvatarSpecSchema.parse(legacy); + expect(parsed).toEqual(legacy); + expect(checkAvatar(parsed)).toEqual([]); + expect(cleanAvatar(parsed).spec).toBe(parsed); + }); + + it("每一個舊選項都在目錄裡(代號沿用)", () => { + for (const [field, values] of Object.entries(OLD_OPTIONS)) { + for (const v of values) { + const spec = { ...legacy, [field]: v }; + expect(checkAvatar(AvatarSpecSchema.parse(spec)), `${field}=${v}`).toEqual([]); + } + } + }); + + it("只有必填欄位的最舊存檔也合法;自創角色照樣能開局", () => { + const minimal = { skin: "#eebd98", hair: "short", hairColor: "#1f1b18", outfit: "suit", suit: "#24324a", shirt: "#f7f5f0", tie: "#b3262d", glasses: false, beard: false, bg: "#dfe8f0" }; + expect(cleanAvatar(AvatarSpecSchema.parse(minimal)).notes).toEqual([]); + const custom = CustomCandidate.parse({ name: "測試人", party: null, background: "律師", stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: legacy, replace: null }); + expect(custom.avatar).toEqual(legacy); + }); + + it("新欄位(畫風、新部位、換色)也合法", () => { + const spec = AvatarSpecSchema.parse({ ...legacy, v: 2, style: "chibi", wear: { hat: "hat-campaign-cap", sash: "sash-red" }, tint: { "hat.main": "#c0392b" } }); + expect(checkAvatar(spec)).toEqual([]); + expect(cleanAvatar(spec).spec).toBe(spec); + }); +}); + +describe("頭像資料:看不懂的代號換預設、格式壞掉才擋", () => { + it("看不懂的髮型、服裝換成預設值;看不懂的五官拿掉(畫的時候用預設)", () => { + const spec = AvatarSpecSchema.parse({ ...legacy, hair: "mohawk-2099", outfit: "spacesuit", eyes: "laser", glassesStyle: "monocle" }); + const { spec: out, notes } = cleanAvatar(spec); + expect(out.hair).toBe("short"); + expect(out.outfit).toBe("suit"); + expect(out.eyes).toBeUndefined(); + expect(out.glassesStyle).toBeUndefined(); + expect(notes.length).toBe(4); + expect(checkAvatar(out)).toEqual([]); + }); + + it("看不懂的部件、部位、畫風拿掉;穿錯部位的拿掉;沒穿的部件的換色也拿掉", () => { + const spec = AvatarSpecSchema.parse({ + ...legacy, + style: "oil-painting", + wear: { hat: "hat-from-the-future", pet: "pet-cat", sash: "hat-campaign-cap", outer: "outer-campaign-vest" }, + tint: { "hat.main": "#123456", "outer.main": "#654321", "outer.glitter": "#ffffff" }, + }); + const { spec: out } = cleanAvatar(spec); + expect(out.style).toBeUndefined(); + expect(out.wear).toEqual({ outer: "outer-campaign-vest" }); + expect(out.tint).toEqual({ "outer.main": "#654321" }); + }); + + it("格式壞掉才回錯誤:代號有怪字元、穿太多件、顏色不是 #RRGGBB", () => { + expect(AvatarSpecSchema.safeParse({ ...legacy, hair: "")], + ["事件屬性", bad('')], + ["外部連結", bad('')], + ["use 連結", bad('')], + ["style", bad("")], + ["style 屬性", bad('')], + ["url() 填色", bad('')], + ["文字", bad("凍蒜")], + ["超出畫布", bad('')], + ["transform 移出畫布", bad('')], + ["顏色名稱", bad('')], + ["DOCTYPE", `]>${ok}`], + ["viewBox 不對", ok.replace("0 0 200 220", "0 0 400 400")], + ["foreignObject", bad("")], + ])("擋掉:%s", (_name, src) => { + expect(() => convertSvgArt(src)).toThrow(SvgArtError); + }); +}); + +describe("服裝店每週上架", () => { + const monday = new Date("2026-10-26T00:00:00+08:00"); + it("台灣時間星期一換週;同一週所有人看到一樣", () => { + expect(shopWeek(new Date("2026-10-25T23:59:00+08:00"))).toBe(shopWeek(monday) - 1); + expect(shopShelf(monday).weekly.map((i) => i.id)).toEqual(shopShelf(new Date("2026-11-01T20:00:00+08:00")).weekly.map((i) => i.id)); + }); + + it("每週 6 件;基本款常駐;本週和常駐不重複", () => { + const s = shopShelf(monday); + expect(s.weekly).toHaveLength(6); + expect(s.always.map((i) => i.id).sort()).toEqual(["hat-bucket", "held-tissue", "mask-number", "outer-volunteer-vest"]); + expect(s.weekly.some((i) => s.always.includes(i))).toBe(false); + }); + + it("每件輪替的部件一年內一定會再上架", () => { + const rotating = AVATAR_CATALOG.items.filter((i) => i.get.type === "shop" && i.get.shelf === "rotate" && !i.available); + const last = new Map(); + let maxGap = 0; + const w0 = shopWeek(monday); + for (let w = w0; w < w0 + 156; w++) { + for (const it of shopShelf(new Date(+monday + (w - w0) * 7 * 86_400_000)).weekly) { + const prev = last.get(it.id); + if (prev !== undefined) maxGap = Math.max(maxGap, w - prev); + last.set(it.id, w); + } + } + for (const it of rotating) expect(last.has(it.id), it.id).toBe(true); + expect(maxGap).toBeLessThanOrEqual(52); + }); + + it("限定品只在每年選舉季(11、12 月)上架,隔年同一個時候回來", () => { + const neon = wearItem("frame-neon")!; + expect(onSale(neon, "2026-11-15")).toBe(true); + expect(onSale(neon, "2027-01-02")).toBe(false); + expect(onSale(neon, "2027-12-01")).toBe(true); + expect(shopShelf(new Date("2026-11-16T12:00:00+08:00")).limited.map((i) => i.id)).toEqual(["frame-neon"]); + expect(shopShelf(new Date("2027-03-16T12:00:00+08:00")).limited).toEqual([]); + }); +}); diff --git a/backend/packages/protocol/test/built-packs.test.ts b/backend/packages/protocol/test/built-packs.test.ts new file mode 100644 index 0000000..57362f7 --- /dev/null +++ b/backend/packages/protocol/test/built-packs.test.ts @@ -0,0 +1,58 @@ +/** + * 契約測試:Python 管線產出的資料包,必須能被 TypeScript 端的 Zod 定義解析。 + * 沒有產出時略過(CI 先跑管線再跑這個測試)。 + */ +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { CellsFile, DataPackManifest, HistoryFile, PeopleFile, TownsFile, VillagesFile } from "../src/index.ts"; + +const buildDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "data", "build"); +const packsDir = join(buildDir, "packs"); +const packs = existsSync(packsDir) ? readdirSync(packsDir) : []; +const read = (path: string): unknown => JSON.parse(readFileSync(path, "utf-8")); + +describe.skipIf(packs.length === 0)("已產出的資料包", () => { + for (const pack of packs) { + describe(pack, () => { + const dir = join(packsDir, pack); + const manifest = DataPackManifest.parse(read(join(dir, "manifest.json"))); + + it("每個檔案都符合協定", () => { + expect(VillagesFile.safeParse(read(join(dir, manifest.files.villages))).success).toBe(true); + expect(TownsFile.safeParse(read(join(dir, manifest.files.towns))).success).toBe(true); + expect(CellsFile.safeParse(read(join(dir, manifest.files.cells))).success).toBe(true); + expect(HistoryFile.safeParse(read(join(dir, manifest.files.history))).success).toBe(true); + }); + + it("每個村里都有 30 個選民群,總和等於成年人口", () => { + const villages = VillagesFile.parse(read(join(dir, manifest.files.villages))).villages; + const cells = CellsFile.parse(read(join(dir, manifest.files.cells))).cells.values; + expect(Object.keys(cells).length).toBe(villages.length); + for (const v of villages) { + const sum = (cells[v.code] ?? []).reduce((a, b) => a + b, 0); + expect(Math.abs(sum - v.population.adults)).toBeLessThan(1); + } + }); + + it("歷屆得票與中選會總數一致", () => { + const { reconciliation } = HistoryFile.parse(read(join(dir, manifest.files.history))).history; + // 2016 年臺南有一個跨村里投開票所(大仁里、大山里)涵蓋的里在 2018 年前就合併了,對不到現在的里(883 票,千分之一以下) + const tolerance = (r: { electionId: string; cecValid: number }) => (r.electionId.startsWith("2016-") ? r.cecValid * 1e-3 : 0); + expect(reconciliation.filter((r) => Math.abs(r.diff) > tolerance(r))).toEqual([]); + }); + }); + } +}); + +const peopleFiles = ["people.json", "people_scored.json"].map((f) => join(buildDir, "people", f)).filter(existsSync); + +describe.skipIf(peopleFiles.length === 0)("已產出的人物資料", () => { + for (const file of peopleFiles) { + it(`${file.split("/").pop()} 符合協定`, () => { + const result = PeopleFile.safeParse(read(file)); + expect(result.success, result.success ? "" : JSON.stringify(result.error.issues.slice(0, 3))).toBe(true); + }); + } +}); diff --git a/backend/packages/protocol/test/protocol.test.ts b/backend/packages/protocol/test/protocol.test.ts new file mode 100644 index 0000000..435e40b --- /dev/null +++ b/backend/packages/protocol/test/protocol.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; +import { AGE_BANDS, CellsBlock, LEANS, Person, VillageCode, VillageRecord } from "../src/index.ts"; + +const village = { + code: "68000010001", + name: "示例里", + townCode: "68000010", + townName: "桃園區", + countyCode: "68000", + countyName: "桃園市", + population: { + total: 3000, + adults: 2400, + byAgeBand: { "20-29": 400, "30-39": 500, "40-49": 500, "50-64": 600, "65+": 400 }, + indigenousLowland: 10, + indigenousHighland: 5, + }, + electors: 2380, + baseTurnout: 0.68, + lean: { a_core: 0.2, a_lean: 0.15, middle: 0.2, b_lean: 0.15, b_core: 0.2, c_lean: 0.1 }, + attributes: { + areaKm2: 0.8, + densityPerKm2: 3750, + templeCount: 2, + churchCount: 1, + templesPer1000: 0.67, + hakkaShare: null, + incomeMedian: 650, + incomeMean: 900, + factionStrength: 0.5, + }, + flags: [], +}; + +describe("村里代碼", () => { + it("接受 11 碼數字", () => { + expect(VillageCode.safeParse("68000010001").success).toBe(true); + }); + it("拒絕中選會的 4 碼村里段與字母代碼", () => { + expect(VillageCode.safeParse("0001").success).toBe(false); + expect(VillageCode.safeParse("680000100A1").success).toBe(false); + }); +}); + +describe("VillageRecord", () => { + it("接受完整的村里紀錄", () => { + expect(VillageRecord.safeParse(village).success).toBe(true); + }); + it("拒絕超出 0–1 的比例", () => { + const bad = { ...village, baseTurnout: 1.2 }; + expect(VillageRecord.safeParse(bad).success).toBe(false); + }); +}); + +describe("CellsBlock", () => { + it("每個村里必須剛好 30 格", () => { + const ok = { ages: [...AGE_BANDS], leans: [...LEANS], values: { "68000010001": new Array(30).fill(1) } }; + const bad = { ...ok, values: { "68000010001": new Array(29).fill(1) } }; + expect(CellsBlock.safeParse(ok).success).toBe(true); + expect(CellsBlock.safeParse(bad).success).toBe(false); + }); +}); + +describe("Person", () => { + const nullStats = { + awareness: null, + network: null, + affinity: null, + eloquence: null, + strategy: null, + online: null, + image: null, + wealth: null, + stamina: null, + }; + const person = { + id: "ly-11-001", + kind: "real", + category: "politician", + name: "示例", + gender: "F", + birthDate: null, + party: "某政黨", + wikidataId: null, + positions: [{ title: "立法委員", org: "立法院", from: "2024-02-01", to: null, sourceIds: ["ly-id9"] }], + education: [], + electionHistory: [], + stats: nullStats, + scoring: [], + fieldSources: { name: ["ly-id9"] }, + asOf: "2026-10-25", + }; + it("接受合法人物", () => { + expect(Person.safeParse(person).success).toBe(true); + }); + it("職位必須附出處", () => { + const bad = { ...person, positions: [{ ...person.positions[0], sourceIds: [] }] }; + expect(Person.safeParse(bad).success).toBe(false); + }); +}); diff --git a/backend/packages/protocol/tsconfig.json b/backend/packages/protocol/tsconfig.json new file mode 100644 index 0000000..195695e --- /dev/null +++ b/backend/packages/protocol/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"] }, + "include": ["src", "scripts", "test"] +} diff --git a/backend/packages/protocol/vitest.config.ts b/backend/packages/protocol/vitest.config.ts new file mode 100644 index 0000000..8b5840a --- /dev/null +++ b/backend/packages/protocol/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["test/**/*.test.ts"], + }, +}); diff --git a/backend/packages/rogue/package.json b/backend/packages/rogue/package.json new file mode 100644 index 0000000..0511691 --- /dev/null +++ b/backend/packages/rogue/package.json @@ -0,0 +1,21 @@ +{ + "name": "@election2026/rogue", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "選戰卡牌(新玩法,docs/21、22)的規則:純函式,狀態可序列化、可重現(同一個種子同一局)", + "exports": { + ".": "./src/index.ts", + "./setup": "./src/setup.ts", + "./local": "./src/local.ts" + }, + "scripts": { + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "@election2026/content": "workspace:*", + "@election2026/engine": "workspace:*", + "@election2026/protocol": "workspace:*" + } +} diff --git a/backend/packages/rogue/src/advisors.ts b/backend/packages/rogue/src/advisors.ts new file mode 100644 index 0000000..39666ff --- /dev/null +++ b/backend/packages/rogue/src/advisors.ts @@ -0,0 +1,54 @@ +/** + * 幕僚:被動能力,最多帶 5 位(docs/21、22)。都是虛構的職位,不對應真實人物。 + * 規則裡用 has(s, id) 查有沒有這位幕僚;倍率類的集中在 cards.ts 的 boost。 + */ +export interface AdvisorDef { + id: string; + name: string; + art: string; + text: string; + /** 偏哪一派(模擬玩家挑幕僚、畫面分類用) */ + school: "ground" | "air" | "org" | "money" | "defend" | "any"; +} + +export const ADVISORS: readonly AdvisorDef[] = [ + { id: "temple_master", name: "宮廟通", art: "temple_visit", text: "宮廟牌效果 +60%", school: "ground" }, + { id: "market_auntie", name: "菜市場阿姨", art: "market_visit", text: "市場、夜市牌效果 +50%", school: "ground" }, + { id: "rally_king", name: "造勢天王", art: "rally", text: "造勢牌效果 +50%,聲勢上限 +2", school: "ground" }, + { id: "hakka_director", name: "客家事務主任", art: "visit_associations", text: "打在客家庄的牌 +50%", school: "ground" }, + { id: "farm_ally", name: "農會總幹事", art: "homecoming", text: "打在地廣人稀的區的牌 +50%", school: "ground" }, + { id: "student_leader", name: "學生會長", art: "forum", text: "打在年輕人多的區的牌 +40%", school: "ground" }, + { id: "truck_captain", name: "宣傳車隊長", art: "sound_truck", text: "打在某區的地面牌,隔壁每一區也有兩成效果", school: "ground" }, + + { id: "social_editor", name: "網路小編", art: "online_ad", text: "每週第一張網路牌不花體力", school: "air" }, + { id: "ad_planner", name: "媒體企劃", art: "tv_ad", text: "電視、網路廣告效果 +40%,花費打七折", school: "air" }, + { id: "debate_coach", name: "辯論教練", art: "debate_training", text: "辯論時看穿對手的出招;記者會、座談類的牌 +30%", school: "air" }, + { id: "influencer", name: "網紅朋友", art: "influencer_live", text: "直播、短影音爆紅的機率加倍", school: "air" }, + + { id: "old_stake", name: "老樁腳", art: "recruit_machine", text: "佈樁的盾加倍", school: "org" }, + { id: "combo_coach", name: "組合拳教練", art: "debate_training", text: "組合拳加成加倍", school: "org" }, + { id: "councilors", name: "議員聯盟", art: "councilor_allies", text: "你插旗的區每週自動加票", school: "org" }, + { id: "iron_base", name: "鐵票部隊", art: "flags_billboards", text: "你插旗的區,對手的行動只剩一半", school: "org" }, + { id: "party_org", name: "黨部組織部", art: "party_fund", text: "每週開始多一張「徒步掃街」(消耗)", school: "org" }, + { id: "volunteer_lead", name: "志工隊長", art: "recruit_volunteers", text: "每週第 3 張牌打完,退回 1 點體力", school: "org" }, + + { id: "tycoon", name: "金主", art: "big_donor", text: "每週資金 +150 萬", school: "money" }, + { id: "fundraiser", name: "募款高手", art: "fundraiser_dinner", text: "募款牌 +50%", school: "money" }, + { id: "cfo", name: "財務長", art: "party_fund", text: "週末每點沒用完的體力換 60 萬", school: "money" }, + + { id: "spin_doctor", name: "公關高手", art: "crisis_pr", text: "對手批評你的效果減半", school: "defend" }, + { id: "muckraker", name: "調查記者出身", art: "expose_press", text: "爆料不用把柄也有全額效果", school: "defend" }, + { id: "lawyer", name: "法律顧問", art: "lawsuit", text: "黑函危機的損失減半;爆料沒把柄不會反傷", school: "defend" }, + { id: "crisis_team", name: "危機處理小組", art: "crisis_pr", text: "「記者追問」不花體力,留在手上也不會掉票", school: "defend" }, + + { id: "youth_corps", name: "青年軍", art: "influencer_live", text: "每週多抽 1 張牌", school: "any" }, + { id: "chief", name: "競選總幹事", art: "hire_staff", text: "每週體力 +1", school: "any" }, + { id: "scheduler", name: "行程秘書", art: "study", text: "每週體力 +1,但少抽 1 張牌", school: "any" }, + { id: "mascot", name: "競選吉祥物", art: "concert", text: "每週開始聲勢至少 1", school: "any" }, + { id: "pollster", name: "民調專家", art: "internal_poll", text: "開票時聲勢帶出來投票的人 +50%", school: "any" }, + { id: "speechwriter", name: "文膽", art: "white_paper", text: "週末保留手上最貴的 1 張牌", school: "any" }, + { id: "opener", name: "開場哥", art: "press_conference", text: "每週第一張牌效果 +50%", school: "any" }, + { id: "night_owl", name: "夜貓子", art: "eve_phone_bank", text: "用掉最後一點體力的那張牌效果 +50%", school: "any" }, +]; + +export const ADVISOR_BY_ID = new Map(ADVISORS.map((a) => [a.id, a])); diff --git a/backend/packages/rogue/src/bots.ts b/backend/packages/rogue/src/bots.ts new file mode 100644 index 0000000..faaff55 --- /dev/null +++ b/backend/packages/rogue/src/bots.ts @@ -0,0 +1,349 @@ +import { ADVISOR_BY_ID } from "./advisors.ts"; +import { attackable, blockedReason, counterable, defOf, playCard } from "./cards.ts"; +import { PRESS_BY_ID, STOP_EVENT_BY_ID, type Choice, type Outcome } from "./content.ts"; +import { cardDef, findCard, upgradable } from "./data.ts"; +import { encounterById } from "./route.ts"; +import { choose, createRun, endWeek, ultimate, type CreateOptions } from "./rules.ts"; +import { bestArg, choiceBlocked } from "./scenes.ts"; +import { nextRandom, type RogueSetup, type RunState, type StopKind } from "./state.ts"; +import { ultReady } from "./ultimate.ts"; +import { previewsFor } from "./view.ts"; + +/** + * 模擬玩家(平衡報告用,apps/sim rogue-balance): + * - idle:什麼都不做;random:亂出牌、亂選;naive:牌都打在人最多的區、不理對手; + * - casual:照手牌順序出,每張打在畫面推薦的第一名(隨手玩、但會看星號的玩家); + * - greedy:每次挑「每點體力換最多票」的牌和區(看得懂預估數字的玩家),劇情和下一站也挑划算的; + * - ground/air/attack:greedy 出牌,但獎勵只拿某一派的牌,檢查有沒有一招通吃。 + */ +export type BotName = "idle" | "random" | "naive" | "casual" | "greedy" | "ground" | "air" | "attack"; + +interface Dice { + next: () => number; +} + +function dice(seed: number): Dice { + let state = (seed ^ 0x5bd1e995) >>> 0 || 1; + return { + next: () => { + const [x, n] = nextRandom(state); + state = n; + return x; + }, + }; +} + +function targetsOf(s: RunState, uid: string): (string | null)[] { + const card = defOf(s.hand.find((c) => c.uid === uid)!); + if (card.target === "town") return s.towns.map((t) => t.code); + if (card.target === "intent") return counterable(s).map((i) => i.id); + if (card.target === "attack") return attackable(s).map((i) => i.id); + return [null]; +} + +const playable = (s: RunState) => s.hand.filter((c) => !blockedReason(s, defOf(c))); + +function playRandom(s: RunState, d: Dice): RunState { + for (let k = 0; k < 14; k++) { + const cards = playable(s); + if (cards.length === 0 || d.next() < 0.1) break; + const card = cards[Math.floor(d.next() * cards.length)]!; + const targets = targetsOf(s, card.uid); + const r = playCard(s, card.uid, targets[Math.floor(d.next() * targets.length)] ?? null); + if ("error" in r) break; + s = r.state; + } + return s; +} + +function playNaive(s: RunState): RunState { + const biggest = [...s.towns].sort((a, b) => b.voters - a.voters)[0]!.code; + for (let k = 0; k < 14; k++) { + const card = playable(s).find((c) => { + const t = defOf(c).target; + return t !== "intent" && t !== "attack"; + }); + if (!card) break; + const r = playCard(s, card.uid, defOf(card).target === "town" ? biggest : null); + if ("error" in r) break; + s = r.state; + } + return s; +} + +const SPECIAL = new Set(["money", "probe", "draw", "rush", "power", "answer"]); + +/** 照手牌順序,每張打在預估最高的目標;預估是負的就跳過(募款、抽牌照打) */ +function playCasual(s: RunState): RunState { + for (let k = 0; k < 14; k++) { + const previews = previewsFor(s); + const next = s.hand + .map((c) => ({ c, best: [...(previews[c.uid] ?? [])].sort((a, b) => b.votes - a.votes)[0] })) + .find(({ c, best }) => best && (best.votes > 0 || SPECIAL.has(defOf(c).effect.kind))); + if (!next?.best) break; + const r = playCard(s, next.c.uid, next.best.target === "city" ? null : next.best.target); + if ("error" in r) break; + s = r.state; + } + return s; +} + +/** 每點體力換多少票;錢不夠時募款牌加分,沒有把柄時打探加分 */ +function playGreedy(s: RunState): RunState { + for (let k = 0; k < 14; k++) { + const previews = previewsFor(s); + let best: { uid: string; target: string | null; value: number } | null = null; + for (const c of s.hand) { + const card = defOf(c); + for (const p of previews[c.uid] ?? []) { + let value = p.votes; + const kind = card.effect.kind; + if (kind === "money") value = s.money < 500 ? 4000 * s.scale : 300 * s.scale; + if (kind === "probe") value = s.leverage === 0 ? 2500 * s.scale : 0; + if (kind === "draw") value = 2600 * s.scale; + if (kind === "rush") value = s.hand.length > 1 ? 3000 * s.scale : 0; + if (kind === "power") value = (s.totalWeeks - s.week + 1) * 900 * s.scale; + if (kind === "answer") value = 3000 * s.scale; + const per = value / Math.max(0.5, card.cost); + if (per > 0 && (!best || per > best.value)) best = { uid: c.uid, target: p.target === "city" ? null : p.target, value: per }; + } + } + if (!best) break; + const r = playCard(s, best.uid, best.target); + if ("error" in r) break; + s = r.state; + } + return s; +} + +/** 拿牌的偏好:數字越大越想要 */ +const CARD_TASTE: Record = { + rally: 5, pilgrimage: 5, celebrity: 4.5, door: 4, tv: 4, counter: 4, office: 4, online: 3.5, oath: 3.5, kneel: 4, night: 3, calls: 3, clarify: 3, expose: 2.5, probe: 2.5, live: 3, talk: 2.5, + walk: 2.5, small: 2, breakfast: 3.5, park: 3, campus: 3, hakka: 2.5, weddings: 3, truck: 4, banquet: 3.5, endorse: 3.5, billboard: 3, volunteers: 3.5, phonebank: 3.5, mobilize: 3, allnighter: 3, + shorts: 3, line: 3.5, radio: 3, flyers: 3, policy: 3.5, whitepaper: 3, mediatraining: 3.5, fieldwork: 3.5, factcheck: 3, contrast: 3, selffund: 2.5, tycoon: 2, elder: 4, +}; +const ADVISOR_TASTE: Record = { + chief: 5, youth_corps: 4.5, scheduler: 4, combo_coach: 4, rally_king: 3.5, temple_master: 3, market_auntie: 3.5, ad_planner: 3, tycoon: 3, old_stake: 2.5, spin_doctor: 3, social_editor: 2.5, + muckraker: 2.5, opener: 4, night_owl: 3.5, truck_captain: 3.5, councilors: 3, iron_base: 3, party_org: 3.5, volunteer_lead: 3.5, mascot: 3, pollster: 3, fundraiser: 2.5, cfo: 2.5, lawyer: 2.5, + crisis_team: 2.5, debate_coach: 3, influencer: 2.5, speechwriter: 3, hakka_director: 2, farm_ally: 2, student_leader: 2.5, +}; +const ARCHETYPE_TAGS: Partial> = { ground: ["ground", "rally", "org"], air: ["media", "online", "tv", "press"], attack: ["attack", "intel", "press", "defend"] }; +const ARCHETYPE_SCHOOL: Partial> = { ground: ["ground", "org", "any"], air: ["air", "any", "money"], attack: ["defend", "any", "air"] }; + +const cardScore = (bot: BotName, id: string): number => { + const card = findCard(id)!; + const tags = ARCHETYPE_TAGS[bot]; + if (tags && !card.tags.some((t) => tags.includes(t))) return 0; + return CARD_TASTE[id] ?? 1; +}; +const advisorScore = (bot: BotName, id: string): number => { + const schools = ARCHETYPE_SCHOOL[bot]; + if (schools && !schools.includes(ADVISOR_BY_ID.get(id)?.school ?? "any")) return 0.5; + return ADVISOR_TASTE[id] ?? 1; +}; + +/** 劇情結果大概值多少票(greedy 挑選項用) */ +function outcomeValue(s: RunState, o: Outcome): number { + return ( + (o.votes ?? 0) + + (o.rivalVotes ?? 0) * 0.8 + + (o.momentum ?? 0) * 1800 - + (o.rivalMomentum ?? 0) * 1500 + + (o.money ?? 0) * (s.money < 400 ? 8 : 3) + + (o.energy ?? 0) * 1700 + + (o.card ? 1800 : 0) + + (o.upgrade ? 1500 : 0) + + (o.advisor ? 2500 : 0) - + (o.status ?? []).reduce((a, x) => a + (x === "favor" ? 2500 : x === "reporter" || x === "storm" ? 1200 : 600), 0) + ); +} +const choiceValue = (s: RunState, c: Choice): number => (c.roll ? c.roll.chance * outcomeValue(s, c.outcome) + (1 - c.roll.chance) * outcomeValue(s, c.roll.fail) : outcomeValue(s, c.outcome)); + +function bestChoice(s: RunState, choices: readonly Choice[]): number { + let best = 0; + let value = -Infinity; + choices.forEach((c, i) => { + if (choiceBlocked(s, c)) return; + const v = choiceValue(s, c); + if (v > value) { + value = v; + best = i; + } + }); + return best; +} + +const smart = (bot: BotName) => bot === "greedy" || bot === "ground" || bot === "air" || bot === "attack"; + +function pickScene(s: RunState, bot: BotName, d: Dice): number { + const scene = s.scene!; + if (scene.kind === "poll") return 0; + if (scene.kind === "debate") { + if (scene.round >= scene.topics.length) return 0; + if (!smart(bot) && bot !== "casual") return Math.floor(d.next() * scene.hand.length); + // 看懂質疑:挑手上最好的論點;隨手玩的三成看錯 + if (bot === "casual" && d.next() < 0.3) return Math.floor(d.next() * scene.hand.length); + return bestArg(scene.hand, scene.needs[scene.round]!); + } + if (scene.kind === "crisis") { + if (!smart(bot)) return 1; + if (s.money >= 450) return 0; + return s.hand.length > 0 ? 2 : 3; + } + const def = PRESS_BY_ID.get(scene.id)!; + if (!smart(bot)) { + const ok = def.choices.map((c, i) => (choiceBlocked(s, c) ? -1 : i)).filter((i) => i >= 0); + return ok[Math.floor(d.next() * ok.length)] ?? 0; + } + return bestChoice(s, def.choices); +} + +const deck = (s: RunState) => [...s.draw, ...s.discard, ...s.hand]; + +/** 下一站的偏好 */ +function routeScore(s: RunState, bot: BotName, kind: StopKind): number { + const basics = deck(s).filter((c) => ["canvass", "market", "temple", "dinner", "favor", "tired", "reporter", "storm"].includes(c.id)).length; + const scores: Record = { + card: 3, + advisor: 4, + upgrade: 2.6, + remove: basics >= 4 ? 2.5 : 1, + shop: s.money >= 500 ? 3.2 : 0.5, + encounter: 2.4, + event: 2.2, + minigame: 2.3, + }; + if (bot === "attack" && kind === "encounter") return 1; + return scores[kind]; +} + +/** 要拿掉的牌:先人情包袱,再來是開局的弱牌 */ +function removeTarget(s: RunState): string | null { + const order = ["favor", "tired", "reporter", "storm", "temple", "dinner", "market", "canvass"]; + for (const id of order) { + const c = deck(s).find((x) => x.id === id && !x.up); + if (c) return c.uid; + } + return null; +} + +/** 要升級的牌:效果大、常打的 */ +function upgradeTarget(s: RunState): string | null { + const order = ["rally", "office", "counter", "pilgrimage", "celebrity", "volunteers", "door", "truck", "tv", "canvass", "market", "stake", "temple"]; + for (const id of order) { + const c = deck(s).find((x) => x.id === id && upgradable(x.id, x.up)); + if (c) return c.uid; + } + const any = deck(s).find((x) => upgradable(x.id, x.up)); + return any?.uid ?? null; +} + +function pickRouteFor(s: RunState, bot: BotName, d: Dice): number | "skip" { + const route = s.route!; + if (bot === "idle") return "skip"; + if (bot === "random" || bot === "naive") return Math.floor(d.next() * route.length); + if (bot === "casual") return route.indexOf("card") >= 0 ? route.indexOf("card") : 0; + const ranked = route.map((k, i) => ({ i, v: routeScore(s, bot, k) })).sort((a, b) => b.v - a.v); + return ranked[0]!.i; +} + +function pickStopFor(s: RunState, bot: BotName, d: Dice): { pick: number | "skip"; target: string | null } { + const stop = s.stop!; + const randomish = !smart(bot); + switch (stop.kind) { + case "card": { + if (randomish) return { pick: Math.floor(d.next() * stop.options.length), target: null }; + const ranked = stop.options.map((id, i) => ({ i, v: cardScore(bot, id) })).sort((a, b) => b.v - a.v); + return ranked[0] && ranked[0].v > 0 ? { pick: ranked[0].i, target: null } : { pick: "skip", target: null }; + } + case "advisor": { + if (randomish) return { pick: Math.floor(d.next() * stop.options.length), target: null }; + const ranked = stop.options.map((id, i) => ({ i, v: advisorScore(bot, id) })).sort((a, b) => b.v - a.v); + return { pick: ranked[0]!.i, target: null }; + } + case "upgrade": { + const target = randomish ? (deck(s).find((c) => upgradable(c.id, c.up))?.uid ?? null) : upgradeTarget(s); + return target ? { pick: 0, target } : { pick: "skip", target: null }; + } + case "remove": { + const target = removeTarget(s); + return target ? { pick: 0, target } : { pick: "skip", target: null }; + } + case "shop": { + if (randomish) return { pick: "skip", target: null }; + const reserve = 250; + const favor = deck(s).some((c) => c.id === "favor"); + const options = stop.items + .map((item, i) => ({ item, i })) + .filter(({ item }) => !item.sold && s.money - item.price >= reserve) + .map(({ item, i }) => ({ i, item, v: item.kind === "card" ? cardScore(bot, item.id) : item.kind === "advisor" ? advisorScore(bot, item.id) + 1 : favor ? 5 : 2 })) + .filter((x) => x.v >= 3) + .sort((a, b) => b.v - a.v); + const top = options[0]; + if (!top) return { pick: "skip", target: null }; + return { pick: top.i, target: top.item.kind === "remove" ? removeTarget(s) : null }; + } + case "encounter": { + if (stop.step >= stop.encounters.length) return { pick: "skip", target: null }; + const e = encounterById(stop.encounters[stop.step]!)!; + if (randomish) return { pick: Math.floor(d.next() * e.options.length), target: null }; + const value = (o: (typeof e.options)[number]) => (o.roll ? o.roll.chance * o.roll.success.score + (1 - o.roll.chance) * o.roll.failure.score : o.score); + const ranked = e.options.map((o, i) => ({ i, v: value(o) })).sort((a, b) => b.v - a.v); + return { pick: ranked[0]!.i, target: null }; + } + case "minigame": + // 打得好的玩家大約 75 分、隨手玩 40–70 分 + return { pick: Math.round(randomish ? 40 + d.next() * 30 : 65 + d.next() * 20), target: null }; + case "event": { + const def = STOP_EVENT_BY_ID.get(stop.id)!; + if (randomish) { + const ok = def.choices.map((c, i) => (choiceBlocked(s, c) ? -1 : i)).filter((i) => i >= 0); + return { pick: ok[Math.floor(d.next() * ok.length)] ?? 0, target: null }; + } + return { pick: bestChoice(s, def.choices), target: null }; + } + } +} + +/** 讓模擬玩家打完整場;watch 每做完一步呼叫一次(平衡分析用:看這一步的 log) */ +export function runBot(setup: RogueSetup, seed: number, bot: BotName, opts: CreateOptions = {}, watch?: (s: RunState, step: "week" | "scene" | "stop") => void): RunState { + let s = createRun(setup, `bot-${seed}`, seed, opts); + const d = dice(seed); + for (let guard = 0; s.phase !== "finished" && guard < 200; guard++) { + let next: RunState | { error: string }; + if (s.phase === "plan" && s.scene?.kind === "press") { + // 記者堵麥:這週內要回答(先回答再出牌) + next = choose(s, bot === "idle" ? 0 : pickScene(s, bot, d)); + for (let k = 0; "error" in next && k < 4; k++) next = choose(s, k); + } else if (s.phase === "plan") { + // 大絕招集滿就放(小遊戲分數模擬:打得好 75–95、其他 40–70) + if (bot !== "idle" && ultReady(s)) { + const score = bot === "greedy" ? 75 + d.next() * 20 : 40 + d.next() * 30; + const r = ultimate(s, "rally", score); + if (!("error" in r)) s = r; + } + if (bot === "random") s = playRandom(s, d); + else if (bot === "naive") s = playNaive(s); + else if (bot === "casual") s = playCasual(s); + else if (bot !== "idle") s = playGreedy(s); + next = endWeek(s); + } else if (s.phase === "scene") { + next = choose(s, bot === "idle" ? 0 : pickScene(s, bot, d)); + // 選不了(例如錢不夠提告)就照順序換一個 + for (let k = 0; "error" in next && k < 4; k++) next = choose(s, k); + } + else if (s.phase === "route") next = choose(s, pickRouteFor(s, bot, d)); + else { + const p = bot === "idle" ? { pick: "skip" as const, target: null } : pickStopFor(s, bot, d); + next = choose(s, p.pick, p.target); + // 選不了(例如錢不夠)就離開這一站 + if ("error" in next) next = choose(s, "skip"); + } + if ("error" in next) throw new Error(`${bot} 第 ${s.week} 週 ${s.phase}:${next.error}`); + watch?.(next, s.phase === "plan" && !s.scene ? "week" : s.phase === "scene" || s.scene ? "scene" : "stop"); + s = next; + } + return s; +} + +export const cardName = (id: string, up = false) => cardDef(id, up)?.name ?? id; diff --git a/backend/packages/rogue/src/cards.ts b/backend/packages/rogue/src/cards.ts new file mode 100644 index 0000000..25e4877 --- /dev/null +++ b/backend/packages/rogue/src/cards.ts @@ -0,0 +1,392 @@ +import { ADVISOR_BY_ID } from "./advisors.ts"; +import { POWERS, TRAIT_LABELS, cardDef, hasKeyword, type CardDef } from "./data.ts"; +import { BUILDING_BY_ID, POLICY_HOME, POLICY_HOME_STEP, policyTargetOf } from "./meta.ts"; +import { addMomentum, asc, cityVotes, drawCards, eventMult, eventOf, has, loseVotes, moveVotes, spread, updateFlags } from "./mechanics.ts"; +import { addTally, cloneState, newCard, rand, type CardInst, type Intent, type RunState, type TownState } from "./state.ts"; + +/** 組合拳:同一週同一區打出第 n 種不同的牌,這張牌的加成 */ +export const COMBO_STEP = 0.15; +export const COMBO_MAX = 0.4; +export const comboBonus = (n: number): number => Math.min(COMBO_MAX, COMBO_STEP * Math.max(0, n - 1)); +/** 每一點聲勢讓你的牌效果 +8% */ +export const MOMENTUM_STEP = 0.08; +/** 選前之夜:造勢牌效果 */ +export const EVE_RALLY = 1.3; + +export const defOf = (c: CardInst): CardDef => cardDef(c.id, c.up)!; + +export function cardCost(s: RunState, card: CardDef): { energy: number; money: number } { + if ((card.id === "reporter" || card.id === "storm") && has(s, "crisis_team")) return { energy: 0, money: 0 }; + const freeOnline = has(s, "social_editor") && card.tags.includes("online") && s.onlinePlayed === 0; + const ads = has(s, "ad_planner") && (card.id === "tv" || card.id === "online"); + return { energy: freeOnline ? 0 : card.cost, money: Math.round(card.money * (ads ? 0.7 : 1)) }; +} + +/** 對手這週可以打對台的行動:打在某一區、還沒被打對台過 */ +export const counterable = (s: RunState): Intent[] => s.intents.filter((i) => i.town !== null && i.cut >= 1 && ["canvass", "rally", "smear", "stake"].includes(i.kind)); +/** 對手這週全市的批評(事實查核可以讓它失效) */ +export const attackable = (s: RunState): Intent[] => s.intents.filter((i) => i.kind === "attack" && i.cut > 0); + +export function blockedReason(s: RunState, card: CardDef): string | null { + if (s.phase !== "plan") return "現在不能出牌"; + if (hasKeyword(card, "unplayable")) return "這張牌不能打"; + const cost = cardCost(s, card); + if (cost.energy > s.energy) return "體力不夠"; + if (cost.money > s.money) return "資金不夠"; + if (card.effect.kind === "kneel" && s.week !== s.totalWeeks) return "最後一週才能打"; + if (card.oncePerWeek && (s.weekCards ?? []).includes(card.id)) return "這週已經打過了"; + if (card.target === "intent" && counterable(s).length === 0) return "對手這週沒有區域行動"; + if (card.target === "attack" && attackable(s).length === 0) return "對手這週沒有批評你"; + return null; +} + +const traitWeight = (trait: string | undefined) => (t: TownState) => t.voters * (trait && t.traits.includes(trait as TownState["traits"][number]) ? 1.5 : 1); + +interface Boost { + mult: number; + notes: string[]; +} + +/** 地區特色類的幕僚:打在有這種特色的區加成 */ +const TOWN_ADVISORS = [ + { id: "hakka_director", trait: "hakka", m: 1.5 }, + { id: "farm_ally", trait: "rural", m: 1.5 }, + { id: "student_leader", trait: "young", m: 1.4 }, +] as const; + +/** 牌類的幕僚 */ +const CARD_ADVISORS = [ + { id: "temple_master", ok: (c: CardDef) => c.tags.includes("temple"), m: 1.6 }, + { id: "market_auntie", ok: (c: CardDef) => c.tags.includes("market"), m: 1.5 }, + { id: "rally_king", ok: (c: CardDef) => c.tags.includes("rally"), m: 1.5 }, + { id: "ad_planner", ok: (c: CardDef) => c.id === "tv" || c.id === "online", m: 1.4 }, + { id: "debate_coach", ok: (c: CardDef) => c.tags.includes("press"), m: 1.3 }, +] as const; + +/** 一張牌的倍率:比例尺 × 區的大小 × 地區特色 × 幕僚 × 能力 × 每週事件 × 聲勢 */ +export function boost(s: RunState, card: CardDef, town: TownState | null): Boost { + let mult = s.scale; + const notes: string[] = []; + const apply = (m: number, note: string) => { + if (Math.abs(m - 1) < 0.001) return; + mult *= m; + notes.push(note); + }; + if (town && Math.abs(town.reach - 1) >= 0.05) apply(town.reach, `${town.reach > 1 ? "人多" : "人少"} ×${town.reach.toFixed(1)}`); + for (const b of card.bonus ?? []) if (town?.traits.includes(b.trait)) apply(b.mult, `${TRAIT_LABELS[b.trait]} ×${b.mult}`); + if (town) for (const a of TOWN_ADVISORS) if (has(s, a.id) && town.traits.includes(a.trait)) apply(a.m, `${ADVISOR_BY_ID.get(a.id)!.name} ×${a.m}`); + for (const a of CARD_ADVISORS) if (has(s, a.id) && a.ok(card)) apply(a.m, `${ADVISOR_BY_ID.get(a.id)!.name} ×${a.m}`); + for (const p of s.powers) { + const power = POWERS[p]; + if (power && card.tags.includes(power.tag)) apply(power.mult, `${power.label} ×${power.mult}`); + } + for (const b of s.buffs) if (card.tags.includes(b.tag)) apply(b.mult, `這週加成 ×${b.mult}`); + // 政策島的建築 + const perk = (id: string) => s.options.perks?.[id] ?? 0; + if (town?.traits.includes("old") && perk("care")) apply(1 + 0.08 * perk("care"), `長照中心 ×${(1 + 0.08 * perk("care")).toFixed(2)}`); + if (town?.traits.includes("young") && perk("nursery")) apply(1 + 0.08 * perk("nursery"), `托育園 ×${(1 + 0.08 * perk("nursery")).toFixed(2)}`); + if (card.tags.includes("online") && perk("techpark")) apply(1 + 0.1 * perk("techpark"), `科技園區 ×${(1 + 0.1 * perk("techpark")).toFixed(1)}`); + if (card.tags.includes("market") && perk("nightmarket")) apply(1 + 0.1 * perk("nightmarket"), `觀光夜市 ×${(1 + 0.1 * perk("nightmarket")).toFixed(1)}`); + if (card.tags.includes("temple") && perk("plaza")) apply(1 + 0.1 * perk("plaza"), `宮廟廣場 ×${(1 + 0.1 * perk("plaza")).toFixed(1)}`); + if (card.tags.includes("media") && perk("media")) apply(1 + 0.06 * perk("media"), `媒體中心 ×${(1 + 0.06 * perk("media")).toFixed(2)}`); + if (card.tags.includes("policy") && perk("library") >= 3) apply(1.15, "政策研究院 ×1.15"); + // 政策落地:這份政策的「家」蓋越高越強 + const target = card.tags.includes("policy") ? policyTargetOf(card.id) : null; + const home = target ? POLICY_HOME[target] : null; + if (home && perk(home)) apply(1 + POLICY_HOME_STEP * perk(home), `${BUILDING_BY_ID.get(home)?.name ?? "小島"}落地 ×${(1 + POLICY_HOME_STEP * perk(home)).toFixed(1)}`); + // 政治生涯的角色能力 + const ability = (k: keyof NonNullable) => s.options.abilities?.[k] ?? 0; + if (card.tags.includes("press") && ability("eloquence")) apply(1 + 0.04 * ability("eloquence"), `口才 ${ability("eloquence")} 級`); + if (card.tags.includes("ground") && ability("organization")) apply(1 + 0.03 * ability("organization"), `組織 ${ability("organization")} 級`); + if (card.tags.includes("media") && ability("media")) apply(1 + 0.05 * ability("media"), `媒體 ${ability("media")} 級`); + const ev = eventMult(s, card.tags); + apply(ev, `${eventOf(s).title} ×${ev}`); + if (s.week === s.totalWeeks && card.tags.includes("rally")) apply(EVE_RALLY, `選前之夜 ×${EVE_RALLY}`); + if (has(s, "opener") && s.playedThisWeek === 0) apply(1.5, "開場哥 ×1.5"); + if (has(s, "night_owl") && s.energy === 0 && (s.paying ?? 0) > 0) apply(1.5, "夜貓子 ×1.5"); + if (asc(s, 8)) apply(0.92, "逆風 ×0.92"); + if (s.momentum > 0) apply(1 + MOMENTUM_STEP * s.momentum, `聲勢 +${Math.round(MOMENTUM_STEP * s.momentum * 100)}%`); + return { mult, notes }; +} + +/** 組合拳:這張牌是這週這區的第幾種牌 */ +function comboOf(s: RunState, card: CardDef, town: TownState): number { + if (town.played.includes(card.id)) return 0; + return comboBonus(town.played.length + 1) * (has(s, "combo_coach") ? 2 : 1); +} + +interface Played { + log: RunState["log"]; + notes: string[]; +} + +/** 你在某一區加票:先被對手樁腳擋掉一部分。spill 是擴散到隔壁區(不算組合拳) */ +function gainAt(s: RunState, card: CardDef, t: TownState, base: number, out: Played, spill = false): number { + const b = boost(s, card, t); + const combo = spill ? 0 : comboOf(s, card, t); + if (combo > 0) b.notes.push(`組合拳 +${Math.round(combo * 100)}%`); + const raw = base * b.mult * (1 + combo); + const blocked = Math.min(t.rivalShield, raw); + t.rivalShield -= blocked; + if (blocked > 0) b.notes.push(`被對手樁腳擋掉 ${Math.round(blocked).toLocaleString("en-US")}`); + const net = moveVotes(t, raw - blocked, "you"); + if (!spill) out.notes.push(...b.notes); + out.log.push({ side: "you", text: `${card.name}・${t.name}${spill ? "(擴散)" : ""}`, town: t.code, votes: Math.round(net) }); + s.stats.bigHit = Math.max(s.stats.bigHit, net / s.scale); + return net; +} + +/** 擴散到隔壁每一區 */ +function spillTo(s: RunState, card: CardDef, t: TownState, base: number, ratio: number, out: Played): void { + if (ratio <= 0) return; + for (const code of t.neighbors) { + const n = s.towns.find((x) => x.code === code); + if (n) gainAt(s, card, n, base * ratio, out, true); + } +} + +/** 全市加票(空戰不會被樁腳擋) */ +function gainCity(s: RunState, card: CardDef, total: number, weightTrait: string | undefined, out: Played, label = card.name): void { + const net = cityVotes(s, total, "you", traitWeight(weightTrait)); + out.log.push({ side: "you", text: `${label}・全市`, town: null, votes: Math.round(net) }); +} + +/** 對手全市掉票(依對手支持者分布) */ +function hurtRival(s: RunState, amount: number, out: Played, text: string): void { + const parts = spread(s.towns, amount, (t) => t.rival); + const hurt = s.towns.reduce((a, t, i) => a + loseVotes(t, parts[i]!, "rival"), 0); + out.log.push({ side: "you", text, town: null, votes: Math.round(hurt) }); +} + +/** 一次打好幾區的牌:每一區都算打過(同一週再打同一張不算組合拳) */ +function markPlayed(towns: readonly TownState[], card: CardDef): void { + for (const t of towns) if (!t.played.includes(card.id)) t.played.push(card.id); +} + +const truckSpill = (s: RunState, card: CardDef): number => (has(s, "truck_captain") && card.tags.includes("ground") ? 0.2 : 0); + +function resolve(s: RunState, card: CardDef, town: TownState | null, intent: Intent | null, expect: boolean, out: Played): void { + const e = card.effect; + switch (e.kind) { + case "gain": + gainAt(s, card, town!, e.base, out); + spillTo(s, card, town!, e.base, truckSpill(s, card), out); + break; + case "rally": + gainAt(s, card, town!, e.base, out); + spillTo(s, card, town!, e.base, (e.spill ?? 0) + truckSpill(s, card), out); + addMomentum(s, e.momentum); + out.notes.push(`聲勢 +${e.momentum}`); + break; + case "spread": + gainAt(s, card, town!, e.base, out); + spillTo(s, card, town!, e.base, e.spill + truckSpill(s, card), out); + break; + case "shield": { + const shield = e.base * s.scale * (has(s, "old_stake") ? 2 : 1) * (1 + 0.1 * (s.options.abilities?.organization ?? 0)); + town!.shield += shield; + out.notes.push(`樁腳 ${Math.round(shield).toLocaleString("en-US")}`); + gainAt(s, card, town!, e.gain, out); + break; + } + case "city": { + const b = boost(s, card, null); + out.notes.push(...b.notes); + gainCity(s, card, e.base * b.mult, e.weight, out); + if (e.momentum) { + addMomentum(s, e.momentum); + out.notes.push(`聲勢 +${e.momentum}`); + } + break; + } + case "gamble": { + const b = boost(s, card, null); + const chance = Math.min(0.9, e.chance * (has(s, "influencer") && e.hit > 1 ? 2 : 1) + (e.hit > 1 ? 0.03 * (s.options.abilities?.media ?? 0) : 0)); + const hit = expect ? false : rand(s) < chance; + const mult = expect ? chance * e.hit + (1 - chance) * e.miss : hit ? e.hit : e.miss; + out.notes.push(...b.notes, expect ? `${Math.round(chance * 100)}% 機率 ×${e.hit}(預估取平均)` : hit ? (e.hit > 1 ? "爆紅!" : "失言!") : ""); + gainCity(s, card, e.base * b.mult * mult, undefined, out, hit ? `${card.name}${e.hit > 1 ? "爆紅" : "失言"}` : card.name); + break; + } + case "counter": { + const t = s.towns.find((x) => x.code === intent!.town)!; + intent!.cut = Math.min(intent!.cut, e.cut); + if (intent!.kind === "stake") t.rivalShield *= e.cut; + out.notes.push(`對手${t.name}的行動剩 ${Math.round(e.cut * 100)}%`); + gainAt(s, card, t, e.base, out); + break; + } + case "clarify": { + for (const i of s.intents) if (i.kind === "attack") i.cut = Math.min(i.cut, e.cut); + if (e.momentum) addMomentum(s, e.momentum); + out.notes.push(e.cut === 0 ? "對手這週的批評全部無效" : `對手這週的批評剩 ${Math.round(e.cut * 100)}%`); + if (e.base > 0) gainCity(s, card, e.base * boost(s, card, null).mult, undefined, out); + else out.log.push({ side: "you", text: card.name, town: null, votes: 0 }); + break; + } + case "nullify": { + intent!.cut = 0; + out.notes.push("這個批評失效"); + gainCity(s, card, e.base * boost(s, card, null).mult, undefined, out); + break; + } + case "probe": { + const ok = expect || rand(s) < e.chance; + if (ok) s.leverage += 1; + out.notes.push(expect ? `${Math.round(e.chance * 100)}% 拿到把柄` : ok ? "拿到一個把柄" : "沒查到東西"); + out.log.push({ side: "you", text: ok ? "打探對手:拿到一個把柄" : "打探對手:沒查到東西", town: null, votes: 0 }); + break; + } + case "expose": { + s.stats.attacks += 1; + const strong = s.leverage > 0 || has(s, "muckraker"); + if (s.leverage > 0) s.leverage -= 1; + const amount = (strong ? e.base : e.weak) * boost(s, card, null).mult; + hurtRival(s, amount, out, strong ? "爆料記者會:對手支持者動搖" : "爆料記者會:證據不足"); + if (!strong && !has(s, "lawyer")) { + const lost = cityVotes(s, -e.backlash * s.scale); + out.log.push({ side: "you", text: "被批評亂爆料", town: null, votes: Math.round(lost) }); + out.notes.push("沒有把柄:效果只剩一點,還會反傷自己"); + } + break; + } + case "contrast": + s.stats.attacks += 1; + hurtRival(s, e.base * boost(s, card, null).mult, out, `${card.name}:對手支持者動搖`); + break; + case "office": + town!.office += e.perWeek; + gainAt(s, card, town!, e.perWeek, out); + out.notes.push("之後每週自動加票"); + break; + case "money": { + const amount = Math.round((e.base + e.perMomentum * s.momentum) * eventMult(s, card.tags) * (has(s, "fundraiser") ? 1.5 : 1)); + s.money += amount; + out.notes.push(`資金 +${amount} 萬`); + out.log.push({ side: "you", text: `${card.name}:資金 +${amount} 萬`, town: null, votes: 0 }); + if (e.curse) { + s.discard.push(newCard(s, e.curse)); + out.notes.push("塞了一張「人情包袱」"); + } + break; + } + case "base": { + const best = [...s.towns].sort((a, b) => b.you - b.rival - (a.you - a.rival)).slice(0, e.towns); + for (const t of best) gainAt(s, card, t, e.base, out); + markPlayed(best, card); + break; + } + case "flags": { + const mine = s.towns.filter((t) => t.flag === "you"); + for (const t of mine) gainAt(s, card, t, e.base, out); + markPlayed(mine, card); + if (mine.length === 0) out.log.push({ side: "you", text: `${card.name}:還沒有插旗的區`, town: null, votes: 0 }); + break; + } + case "draw": + drawCards(s, e.cards); + out.notes.push(`抽 ${e.cards} 張牌`); + out.log.push({ side: "you", text: `${card.name}:抽 ${e.cards} 張牌`, town: null, votes: 0 }); + break; + case "rush": + s.energy += e.energy; + s.discard.push(newCard(s, e.curse)); + out.notes.push(`體力 +${e.energy},塞一張「疲勞」`); + out.log.push({ side: "you", text: `${card.name}:體力 +${e.energy}`, town: null, votes: 0 }); + break; + case "buff": + gainCity(s, card, e.base * boost(s, card, null).mult, undefined, out); + s.buffs.push({ tag: e.tag, mult: e.mult }); + out.notes.push(`這週之後的媒體牌 ×${e.mult}`); + break; + case "power": + if (!s.powers.includes(e.power)) s.powers.push(e.power); + out.notes.push(`${POWERS[e.power]?.label ?? card.name}:整局有效`); + out.log.push({ side: "you", text: `${card.name}:整局有效`, town: null, votes: 0 }); + break; + case "kneel": { + const b = boost(s, card, null); + out.notes.push(...b.notes); + gainCity(s, card, e.base * b.mult, "old", out); + addMomentum(s, e.momentum); + break; + } + case "answer": + gainCity(s, card, e.base * s.scale, undefined, out, "回應記者追問"); + break; + case "none": + break; + } +} + +export type PlayResult = { state: RunState; notes: string[] } | { error: string }; + +/** + * 出一張牌。target:區代碼(要選區的牌)、對手意圖 id(打對台、事實查核),其他牌是 null。 + * expect:預估模式,機率事件用期望值、不抽亂數(給畫面上的預估數字用)。 + */ +export function playCard(state: RunState, uid: string, target: string | null, expect = false): PlayResult { + const s = cloneState(state); + s.log = []; + const at = s.hand.findIndex((c) => c.uid === uid); + if (at < 0) return { error: "手上沒有這張牌" }; + const inst = s.hand[at]!; + const card = cardDef(inst.id, inst.up); + if (!card) return { error: "沒有這張牌" }; + const reason = blockedReason(s, card); + if (reason) return { error: reason }; + let town: TownState | null = null; + let intent: Intent | null = null; + if (card.target === "town") { + town = s.towns.find((t) => t.code === target) ?? null; + if (!town) return { error: "先選一區" }; + } else if (card.target === "intent") { + intent = counterable(s).find((i) => i.id === target) ?? null; + if (!intent) return { error: "選一個對手在某一區的行動" }; + } else if (card.target === "attack") { + intent = attackable(s).find((i) => i.id === target) ?? null; + if (!intent) return { error: "選一個對手的批評" }; + } + const cost = cardCost(s, card); + s.energy -= cost.energy; + s.money -= cost.money; + if (card.tags.includes("online")) s.onlinePlayed += 1; + // 打出去的牌在效果結算、抽完牌之後才進棄牌堆,抽牌時不會把自己洗回來(避免無限循環) + s.hand.splice(at, 1); + s.paying = cost.energy; + const out: Played = { log: [], notes: [] }; + s.log = out.log; + resolve(s, card, town, intent, expect, out); + const mark = town ?? (intent?.town ? s.towns.find((t) => t.code === intent!.town)! : null); + if (mark && !mark.played.includes(card.id)) { + mark.played.push(card.id); + s.stats.maxCombo = Math.max(s.stats.maxCombo, mark.played.length); + } + if (card.draw) drawCards(s, card.draw); + // 政策卡的財源:記者追問、資金、全市流失一點票 + if (card.side?.curse) s.discard.push(newCard(s, card.side.curse)); + if (card.side?.money) { + s.money = Math.max(0, s.money + card.side.money); + out.log.push({ side: "you", text: `${card.name}:招商資金 +${card.side.money} 萬`, town: null, votes: 0 }); + } + if (card.side?.backlash) { + const lost = cityVotes(s, -card.side.backlash * s.scale); + out.log.push({ side: "you", text: `${card.name}:被刪預算的人不高興`, town: null, votes: Math.round(lost) }); + } + if (hasKeyword(card, "exhaust")) s.exhausted.push(inst); + else s.discard.push(inst); + s.paying = 0; + s.weekCards = [...(s.weekCards ?? []), card.id]; + s.playedThisWeek += 1; + s.stats.played += 1; + if (card.tags.includes("rally")) s.lastWeek.rallied = true; + if (has(s, "volunteer_lead") && s.playedThisWeek === 3) { + s.energy += 1; + out.notes.push("志工隊長:體力 +1"); + } + if (!expect) { + updateFlags(s); + addTally(s, s.log); + } + return { state: s, notes: out.notes.filter(Boolean) }; +} diff --git a/backend/packages/rogue/src/content.ts b/backend/packages/rogue/src/content.ts new file mode 100644 index 0000000..0265d5b --- /dev/null +++ b/backend/packages/rogue/src/content.ts @@ -0,0 +1,560 @@ +/** + * 選戰卡牌的劇情內容(docs/22):記者堵麥、地方抉擇、電視辯論。 + * 題目只寫「記者問」「有人質疑」,不捏造真人說過的話;黑函一律是匿名的,不算在任何候選人頭上。 + * 票數一樣以「全市 100 萬人投票」為準,實際乘上比例尺。 + */ + +export interface Outcome { + text: string; + /** 全市加票(負的是你掉票) */ + votes?: number; + /** 對手全市掉票 */ + rivalVotes?: number; + momentum?: number; + rivalMomentum?: number; + /** 萬元 */ + money?: number; + leverage?: number; + /** 這週的體力(堵麥在出牌前);在週與週之間發生的是下週 */ + energy?: number; + /** 拿到一張牌:堵麥時放進手上,週與週之間放進牌組 */ + card?: string; + upCard?: boolean; + /** 塞進牌組的狀態牌 */ + status?: string[]; + /** 隨機升級牌組裡一張牌 */ + upgrade?: boolean; + /** 隨機加入一位幕僚(有空位才有) */ + advisor?: boolean; +} + +export interface Choice { + id: string; + label: string; + hint: string; + outcome: Outcome; + /** 看運氣:chance 的機率照 outcome,其他時候照 fail */ + roll?: { chance: number; fail: Outcome }; + /** 需要的資源,不夠就不能選 */ + needs?: { money?: number; leverage?: number }; +} + +export type PressTrigger = "attacked" | "leading" | "trailing" | "rallied" | "flipped" | "typhoon" | "poor" | "rich" | "any"; + +export interface PressDef { + id: string; + trigger: PressTrigger; + question: string; + choices: Choice[]; +} + +export const PRESS: readonly PressDef[] = [ + { + id: "policy_doubt", + trigger: "attacked", + question: "有人質疑你的交通政見根本做不到,財源在哪裡?", + choices: [ + { id: "table", label: "拿出財源規劃表逐條說明", hint: "這週體力 −1;全市加票", outcome: { text: "你把財源一條一條講清楚,中間選民聽進去了。", energy: -1, votes: 1840 } }, + { id: "brush", label: "「選民會自己判斷」", hint: "一半機率沒事,否則多一張記者追問", outcome: { text: "這個話題很快被其他新聞蓋過去。" }, roll: { chance: 0.5, fail: { text: "記者覺得你在閃躲,追問更多了。", status: ["reporter"] } } }, + { id: "back", label: "反問對手的政見財源", hint: "七成機率對手掉票,否則你掉票", outcome: { text: "你點出對方政見的漏洞,支持者叫好。", rivalVotes: 1380 }, roll: { chance: 0.7, fail: { text: "兩邊你來我往,選民看了很厭煩。", votes: -920 } } }, + ], + }, + { + id: "sleepy_video", + trigger: "attacked", + question: "網路流傳一段你在拜票途中打瞌睡的影片,你是不是太累了?", + choices: [ + { id: "joke", label: "自嘲「連睡覺都在想政見」", hint: "六成機率變成好梗:聲勢 +1", outcome: { text: "大家笑成一片,影片反而幫你拉了人氣。", momentum: 1, votes: 690 }, roll: { chance: 0.6, fail: { text: "這個笑話沒有人笑,記者繼續追問。", status: ["reporter"] } } }, + { id: "schedule", label: "公布一週行程表", hint: "全市小加票", outcome: { text: "密密麻麻的行程表讓人覺得你很拚。", votes: 690 } }, + { id: "silent", label: "不回應", hint: "多一張記者追問", outcome: { text: "沒有回應,話題繼續延燒。", status: ["reporter"] } }, + ], + }, + { + id: "too_early", + trigger: "leading", + question: "民調領先,會不會太早慶祝?", + choices: [ + { id: "humble", label: "「最後一票都不能放」", hint: "聲勢 +1", outcome: { text: "支持者覺得你很穩,沒有鬆懈。", momentum: 1 } }, + { id: "more", label: "宣布加碼掃街", hint: "手上多一張徒步掃街;資金 −50 萬", outcome: { text: "你宣布這週再加跑十個點。", card: "walk", money: -50 } }, + { id: "party", label: "開香檳慶祝", hint: "三成機率全市加票,否則聲勢 −1、多一張記者追問", outcome: { text: "支持者跟著一起嗨,聲量大增。", votes: 1380 }, roll: { chance: 0.3, fail: { text: "被批評太囂張,新聞標題很難看。", momentum: -1, status: ["reporter"] } } }, + ], + }, + { + id: "drop_out", + trigger: "trailing", + question: "民調落後,會不會考慮退選?", + choices: [ + { id: "never", label: "「我不會放棄任何一票」", hint: "聲勢 +1,全市小加票", outcome: { text: "你的堅持感動了不少人。", momentum: 1, votes: 460 } }, + { id: "attack", label: "宣布全面進攻", hint: "手上多一張打對台", outcome: { text: "你宣布接下來每場都要跟對手正面對決。", card: "counter" } }, + { id: "poll", label: "「民調不等於選票」", hint: "全市加票", outcome: { text: "你冷靜的態度讓中間選民放心。", votes: 920 } }, + ], + }, + { + id: "bused_in", + trigger: "rallied", + question: "上週造勢人潮很多,是不是動員來的?", + choices: [ + { id: "fans", label: "「都是自己來的鄉親」", hint: "六成機率聲勢 +1,否則多一張記者追問", outcome: { text: "現場影片證明大家是自己來的。", momentum: 1 }, roll: { chance: 0.6, fail: { text: "有人翻出遊覽車照片,記者繼續追問。", status: ["reporter"] } } }, + { id: "list", label: "公開志工報名名單", hint: "資金 −50 萬;全市加票", outcome: { text: "上千位志工的名單讓質疑消失。", money: -50, votes: 1150 } }, + { id: "invite", label: "「歡迎記者下次一起來」", hint: "全市小加票", outcome: { text: "記者真的來了,還拍了不少畫面。", votes: 460 } }, + ], + }, + { + id: "typhoon_run", + trigger: "typhoon", + question: "颱風天你還在跑行程,這樣安不安全?", + choices: [ + { id: "help", label: "改去社區幫忙防颱", hint: "這週體力 −1;全市加票,聲勢 +1", outcome: { text: "你穿著雨衣幫忙堆沙包,畫面傳遍網路。", energy: -1, votes: 1610, momentum: 1 } }, + { id: "live", label: "取消行程,改開防災直播", hint: "手上多一張臉書直播", outcome: { text: "你在總部開直播整理防災資訊。", card: "live" } }, + { id: "go", label: "照常跑行程", hint: "一半機率加票,否則被批評", outcome: { text: "風雨中拜票,鄉親很感動。", votes: 1150 }, roll: { chance: 0.5, fail: { text: "被批評不顧安全,還拖累隨行記者。", votes: -920 } } }, + ], + }, + { + id: "secret", + trigger: "flipped", + question: "你在幾個區翻盤領先,秘訣是什麼?", + choices: [ + { id: "stake", label: "感謝地方里長幫忙", hint: "手上多一張佈樁", outcome: { text: "里長們很有面子,更賣力了。", card: "stake" } }, + { id: "policy", label: "「是政見打動了大家」", hint: "聲勢 +1", outcome: { text: "支持者把這句話做成梗圖。", momentum: 1 } }, + ], + }, + { + id: "dance", + trigger: "any", + question: "網紅想跟你合拍一支短影音,你會不會跳舞?", + choices: [ + { id: "dance", label: "當場跳一段", hint: "一半機率爆紅,否則被笑", outcome: { text: "影片衝上熱門,年輕人都在轉。", votes: 2070 }, roll: { chance: 0.5, fail: { text: "舞步太僵硬,被做成迷因嘲笑。", votes: -460 } } }, + { id: "talk", label: "婉拒,改聊政見", hint: "全市小加票", outcome: { text: "你把話題拉回政見,認真的形象加分。", votes: 460 } }, + { id: "mascot", label: "請吉祥物代跳", hint: "手上多一張短影音", outcome: { text: "吉祥物跳得比你好,網友要求看本人。", card: "shorts" } }, + ], + }, + { + id: "one_line", + trigger: "any", + question: "請用一句話說出你最重要的政見。", + choices: [ + { id: "traffic", label: "交通", hint: "手上多一張政見發表會", outcome: { text: "你講了三分鐘的捷運路線圖。", card: "policy" } }, + { id: "care", label: "長照", hint: "全市加票", outcome: { text: "長輩和照顧者都聽得很認真。", votes: 1150 } }, + { id: "housing", label: "青年住宅", hint: "聲勢 +1", outcome: { text: "年輕人在網路上熱烈討論。", momentum: 1 } }, + ], + }, + { + id: "broke", + trigger: "poor", + question: "你的競選經費是不是快燒光了?", + choices: [ + { id: "donate", label: "發起小額募款", hint: "資金 +200 萬", outcome: { text: "支持者十塊、一百塊地捐,一天湧入不少錢。", money: 200 } }, + { id: "spirit", label: "「選舉靠的是理念」", hint: "全市小加票", outcome: { text: "這句話引起不少共鳴。", votes: 690 } }, + ], + }, + { + id: "ads", + trigger: "rich", + question: "你的廣告是不是下太多了?", + choices: [ + { id: "info", label: "「要讓大家知道政見」", hint: "全市小加票", outcome: { text: "大家點頭接受。", votes: 460 } }, + { id: "charity", label: "把部分經費捐給公益", hint: "資金 −300 萬;聲勢 +2", outcome: { text: "這個決定上了頭版。", money: -300, momentum: 2 }, needs: { money: 300 } }, + ], + }, + { + id: "debate_prep", + trigger: "any", + question: "最近都在忙什麼?", + choices: [ + { id: "study", label: "「在讀各區的地方需求」", hint: "隨機升級牌組裡一張牌", outcome: { text: "幕僚幫你整理了一份地方需求清單。", upgrade: true } }, + { id: "volunteer", label: "「在陪志工打電話」", hint: "手上多一張志工電話催票", outcome: { text: "志工們很受鼓舞。", card: "calls" } }, + ], + }, + { + id: "copied", + trigger: "attacked", + question: "有人說你的政見是抄別人的,你怎麼回應?", + choices: [ + { id: "compare", label: "公開原文,請大家比較", hint: "資金 −30 萬;全市加票", outcome: { text: "對照表一放出來,質疑就站不住腳了。", money: -30, votes: 1380 } }, + { id: "learn", label: "「好政策本來就該互相學習」", hint: "六成機率聲勢 +1,否則多一張記者追問", outcome: { text: "這句話讓人覺得你很大方。", momentum: 1 }, roll: { chance: 0.6, fail: { text: "被說是在狡辯,記者追著問。", status: ["reporter"] } } }, + { id: "silent", label: "不回應", hint: "多一張記者追問", outcome: { text: "話題繼續燒。", status: ["reporter"] } }, + ], + }, + { + id: "too_safe", + trigger: "leading", + question: "民調領先之後,會不會開始保守、不敢衝?", + choices: [ + { id: "night", label: "宣布加碼夜間行程", hint: "手上多一張夜市拜票+", outcome: { text: "你宣布每天晚上都要跑夜市。", card: "night", upCard: true } }, + { id: "remind", label: "請支持者別鬆懈", hint: "全市加票", outcome: { text: "支持者把「別鬆懈」做成了大字報。", votes: 690 } }, + ], + }, + { + id: "hopeless", + trigger: "trailing", + question: "有人說你已經沒希望了?", + choices: [ + { id: "live", label: "開直播跟網友聊", hint: "手上多一張臉書直播", outcome: { text: "直播湧進很多替你打氣的人。", card: "live" } }, + { id: "door", label: "跑去最難的區挨家挨戶", hint: "手上多一張挨家挨戶", outcome: { text: "你說:「票是一張一張拜來的。」", card: "door" } }, + { id: "poll", label: "拿出內部民調反擊", hint: "一半機率聲勢 +1,否則掉票", outcome: { text: "內部民調顯示差距在縮小,支持者士氣大振。", momentum: 1 }, roll: { chance: 0.5, fail: { text: "被質疑民調灌水。", votes: -460 } } }, + ], + }, + { + id: "noisy_rally", + trigger: "rallied", + question: "造勢晚會太晚結束吵到鄰居,有人抗議?", + choices: [ + { id: "sorry", label: "親自登門道歉", hint: "全市加票", outcome: { text: "鄰居收下道歉,還說會去投票。", votes: 690 } }, + { id: "fruit", label: "送水果禮盒賠罪", hint: "資金 −40 萬;聲勢 +1", outcome: { text: "禮盒送到每一戶,大家都笑了。", money: -40, momentum: 1 } }, + { id: "tolerate", label: "「選舉期間請大家包容」", hint: "四成機率沒事,否則掉票", outcome: { text: "大家想想也就算了。", votes: 230 }, roll: { chance: 0.4, fail: { text: "這句話被批評態度高傲。", votes: -690 } } }, + ], + }, + { + id: "typhoon_day_off", + trigger: "typhoon", + question: "颱風停班停課,你要發什麼訊息?", + choices: [ + { id: "kit", label: "發防災懶人包", hint: "手上多一張印文宣", outcome: { text: "懶人包被很多群組轉傳。", card: "flyers" } }, + { id: "shelter", label: "到避難中心探視", hint: "這週體力 −1;全市加票", outcome: { text: "你陪長輩聊了一下午。", energy: -1, votes: 1380 } }, + ], + }, + { + id: "unsold_tables", + trigger: "poor", + question: "募款餐會的桌數賣不完?", + choices: [ + { id: "bento", label: "改辦平價便當會", hint: "資金 +120 萬", outcome: { text: "便當會反而湧進一堆小額支持者。", money: 120 } }, + { id: "party", label: "請黨部幫忙包桌", hint: "資金 +250 萬;牌組多一張人情包袱", outcome: { text: "桌子坐滿了,但你欠了一個人情。", money: 250, status: ["favor"] } }, + ], + }, + { + id: "fancy_hq", + trigger: "rich", + question: "有人說你的競選總部太豪華?", + choices: [ + { id: "open", label: "開放民眾參觀", hint: "全市加票", outcome: { text: "參觀的人發現其實是舊倉庫改的。", votes: 690 } }, + { id: "move", label: "搬到夜市旁的小店面", hint: "資金 −100 萬;聲勢 +1", outcome: { text: "新總部人來人往,很有人氣。", money: -100, momentum: 1 }, needs: { money: 100 } }, + ], + }, + { + id: "backlash", + trigger: "flipped", + question: "你在對手的老票倉翻盤,會不會招來反撲?", + choices: [ + { id: "guard", label: "加派樁腳顧好", hint: "手上多一張佈樁", outcome: { text: "里長們說會幫你顧好。", card: "stake" } }, + { id: "push", label: "乘勝追擊", hint: "聲勢 +1", outcome: { text: "你宣布下一站繼續往對手的大本營走。", momentum: 1 } }, + ], + }, + { + id: "late_snack", + trigger: "any", + question: "有人拍到你在路邊攤吃宵夜,你最愛吃什麼?", + choices: [ + { id: "rice", label: "滷肉飯", hint: "全市加票", outcome: { text: "老闆說你每次都加一顆滷蛋。", votes: 690 } }, + { id: "tofu", label: "臭豆腐", hint: "一半機率聲勢 +1", outcome: { text: "網友說你很懂吃。", momentum: 1 }, roll: { chance: 0.5, fail: { text: "被說太刻意,大家笑笑就過了。" } } }, + { id: "all", label: "「都好吃」", hint: "全市小加票", outcome: { text: "標準答案,但很安全。", votes: 460 } }, + ], + }, + { + id: "meme", + trigger: "any", + question: "網友把你做成梗圖,你怎麼看?", + choices: [ + { id: "repost", label: "轉貼自嘲", hint: "六成機率全市大加票,否則多一張記者追問", outcome: { text: "自嘲比原圖還紅。", votes: 1380 }, roll: { chance: 0.65, fail: { text: "被說是在蹭熱度。", status: ["reporter"] } } }, + { id: "team", label: "請團隊做更好笑的回應", hint: "手上多一張短影音", outcome: { text: "團隊熬夜剪了一支回應影片。", card: "shorts" } }, + { id: "calm", label: "「請大家理性討論政策」", hint: "全市小加票", outcome: { text: "有點無聊,但沒有扣分。", votes: 230 } }, + ], + }, + { + id: "streetlight", + trigger: "any", + question: "有民眾陳情:社區的路燈壞了好幾個月?", + choices: [ + { id: "call", label: "當場打電話找人處理", hint: "全市加票", outcome: { text: "隔天路燈就亮了。", votes: 920 } }, + { id: "policy", label: "把路燈列進政見", hint: "手上多一張政見發表會", outcome: { text: "「讓每條巷子都亮起來」成了新口號。", card: "policy" } }, + ], + }, + { + id: "song", + trigger: "any", + question: "你的競選歌曲被說很洗腦?", + choices: [ + { id: "yes", label: "「洗腦就對了」", hint: "聲勢 +1", outcome: { text: "歌在夜市一直放,連小朋友都會唱。", momentum: 1 } }, + { id: "remix", label: "推出台語版", hint: "全市加票", outcome: { text: "台語版在長輩群組瘋傳。", votes: 1150 } }, + ], + }, +]; + +export const PRESS_BY_ID = new Map(PRESS.map((p) => [p.id, p])); + +export interface StopEventDef { + id: string; + title: string; + text: string; + art: string; + choices: Choice[]; +} + +/** 下一站「地方抉擇」:有代價、有風險的選擇 */ +export const STOP_EVENTS: readonly StopEventDef[] = [ + { + id: "temple_committee", + title: "廟方的邀請", + text: "地方大廟邀你擔任今年遶境的副主委,要跟著走完全程。", + art: "pilgrimage", + choices: [ + { id: "yes", label: "接下來", hint: "拿到「跟著遶境+」;下週體力 −1", outcome: { text: "你跟著神轎走了一整天,腳都起水泡。", card: "pilgrimage", upCard: true, energy: -1 } }, + { id: "no", label: "婉拒,改捐香油錢", hint: "資金 −50 萬;聲勢 +1", outcome: { text: "廟方很客氣地收下了。", money: -50, momentum: 1 }, needs: { money: 50 } }, + ], + }, + { + id: "corporate_donor", + title: "企業主的捐款", + text: "一位企業主想捐 500 萬,但希望你上任後「多關心」他的開發案。", + art: "big_donor", + choices: [ + { id: "take", label: "收下", hint: "資金 +500 萬;牌組多一張「人情包袱」", outcome: { text: "錢進來了,但你知道這不是免費的。", money: 500, status: ["favor"] } }, + { id: "refuse", label: "婉拒,公開說明", hint: "聲勢 +1", outcome: { text: "清廉的形象讓支持者更挺你。", momentum: 1 } }, + ], + }, + { + id: "influencer_ad", + title: "網紅業配", + text: "百萬訂閱的網紅想幫你拍一支影片,報價 150 萬。", + art: "influencer_live", + choices: [ + { id: "pay", label: "付錢拍", hint: "資金 −150 萬;一半機率全市大加票", outcome: { text: "影片爆紅,留言區一片支持。", money: -150, votes: 4140 }, roll: { chance: 0.5, fail: { text: "影片中規中矩,觀看數普通。", money: -150, votes: 1150 } }, needs: { money: 150 } }, + { id: "no", label: "不拍", hint: "沒事", outcome: { text: "你把錢留給更穩的行程。" } }, + ], + }, + { + id: "chef_friend", + title: "總舖師老同學", + text: "你的國中同學是有名的辦桌總舖師,說要幫你辦一場流水席。", + art: "banquet", + choices: [ + { id: "yes", label: "好啊!", hint: "拿到「流水席辦桌」", outcome: { text: "老同學拍胸脯說包在他身上。", card: "banquet" } }, + { id: "donate", label: "請他改捐給志工便當", hint: "資金 +100 萬", outcome: { text: "志工們吃得很開心。", money: 100 } }, + ], + }, + { + id: "volunteer_fair", + title: "志工園遊會", + text: "志工想在週末辦一場募款園遊會,大家都要加班。", + art: "recruit_volunteers", + choices: [ + { id: "yes", label: "辦!", hint: "資金 +250 萬;牌組多兩張「疲勞」", outcome: { text: "園遊會很成功,但大家都累壞了。", money: 250, status: ["tired", "tired"] } }, + { id: "no", label: "讓大家休息", hint: "下週體力 +1", outcome: { text: "大家休息夠了,下週衝更快。", energy: 1 } }, + ], + }, + { + id: "moms_forum", + title: "媽媽社團座談", + text: "地方媽媽社團邀你去聊托育和長照,問題都很尖銳。", + art: "forum", + choices: [ + { id: "go", label: "親自去", hint: "隨機升級牌組裡一張牌;全市小加票", outcome: { text: "你被問倒好幾次,但學到很多。", upgrade: true, votes: 460 } }, + { id: "staff", label: "派幕僚代打", hint: "全市小加票", outcome: { text: "幕僚帶回一疊問卷。", votes: 690 } }, + ], + }, + { + id: "cleanup", + title: "颱風過後", + text: "上週颱風讓好幾個社區淹水,清淤人手不夠。", + art: "scene-typhoon", + choices: [ + { id: "help", label: "捲起袖子去清淤", hint: "下週體力 −1;全市加票,聲勢 +1", outcome: { text: "你的雨鞋都是泥巴,鄉親都看在眼裡。", energy: -1, votes: 2070, momentum: 1 } }, + { id: "donate", label: "捐物資", hint: "資金 −150 萬;全市加票", outcome: { text: "物資很快送到每個社區。", money: -150, votes: 1380 }, needs: { money: 150 } }, + ], + }, + { + id: "veteran", + title: "老牌操盤手", + text: "一位退休的老牌選舉操盤手說,想在最後幾週幫你一把。", + art: "hire_staff", + choices: [ + { id: "yes", label: "請他加入", hint: "隨機一位幕僚(要有空位)", outcome: { text: "他一進總部就把行程表全部重排。", advisor: true } }, + { id: "fee", label: "請他當顧問就好", hint: "資金 −100 萬;隨機升級一張牌", outcome: { text: "他給的建議很受用。", money: -100, upgrade: true }, needs: { money: 100 } }, + ], + }, + { + id: "party_hq", + title: "黨部的要求", + text: "黨部希望你配合全國的統一文宣,地方特色要少一點。", + art: "party_fund", + choices: [ + { id: "follow", label: "配合", hint: "拿到「黨內大老站台」;資金 +150 萬", outcome: { text: "黨部很滿意,資源跟著進來。", card: "elder", money: 150 } }, + { id: "local", label: "堅持地方路線", hint: "拿到「掃街拜票+」;聲勢 +1", outcome: { text: "你決定繼續用自己的方式選。", card: "canvass", upCard: true, momentum: 1 } }, + ], + }, + { + id: "fortune", + title: "廟口算命仙", + text: "廟口的算命仙拉住你:「少年仔,你這次……」", + art: "temple_visit", + choices: [ + { id: "listen", label: "坐下來聽,添香油錢", hint: "資金 −30 萬;七成機率聲勢 +1", outcome: { text: "「穩上的啦!」你心情大好。", money: -30, momentum: 1 }, roll: { chance: 0.7, fail: { text: "「要小心身邊的人……」你有點不安。", money: -30 } }, needs: { money: 30 } }, + { id: "walk", label: "笑笑走開", hint: "沒事", outcome: { text: "選舉還是要靠自己。" } }, + ], + }, + { + id: "night_market_stall", + title: "夜市擺攤", + text: "夜市自治會長邀你來擺一晚的攤,賣烤香腸。", + art: "night_market", + choices: [ + { id: "yes", label: "穿圍裙上工", hint: "拿到「夜市拜票+」;下週體力 −1", outcome: { text: "香腸烤焦了幾條,但大家很捧場。", card: "night", upCard: true, energy: -1 } }, + { id: "no", label: "下次吧", hint: "沒事", outcome: { text: "會長說隨時歡迎。" } }, + ], + }, + { + id: "volunteer_cut", + title: "整頓行程", + text: "幕僚說有些行程效率太低,建議砍掉,把人力集中。", + art: "rest", + choices: [ + { id: "cut", label: "照幕僚說的砍", hint: "下週體力 +1", outcome: { text: "行程變少,但每一場都更紮實。", energy: 1 } }, + { id: "keep", label: "行程照跑", hint: "資金 +80 萬(地方小額捐款)", outcome: { text: "每一場都有人捐一點。", money: 80 } }, + ], + }, + { + id: "lunchbox", + title: "愛心便當", + text: "社區媽媽說要天天幫總部煮便當。", + art: "banquet", + choices: [ + { id: "yes", label: "感謝收下", hint: "資金 −20 萬(食材);下週體力 +1", outcome: { text: "吃飽了大家跑得更起勁。", money: -20, energy: 1 } }, + { id: "spread", label: "請媽媽們幫忙宣傳", hint: "全市小加票", outcome: { text: "媽媽們的群組比廣告還有效。", votes: 460 } }, + ], + }, + { + id: "village_chief", + title: "老里長的條件", + text: "一位老里長說可以幫你顧好一整個里,但希望你上任後幫忙爭取新的活動中心。", + art: "recruit_machine", + choices: [ + { id: "deal", label: "答應", hint: "拿到「拜託里長佈樁+」;牌組多一張人情包袱", outcome: { text: "里長拍拍你的肩膀:「包在我身上。」", card: "stake", upCard: true, status: ["favor"] } }, + { id: "no", label: "婉拒,說要照程序來", hint: "聲勢 +1", outcome: { text: "你的堅持被支持者傳開了。", momentum: 1 } }, + ], + }, + { + id: "students", + title: "大學生志工", + text: "一群大學生想幫你拍短影音。", + art: "short_video", + choices: [ + { id: "video", label: "交給他們拍", hint: "拿到「短影音+」", outcome: { text: "他們的剪接比專業團隊還好。", card: "shorts", upCard: true } }, + { id: "walk", label: "請他們陪你掃街", hint: "拿到「徒步掃街」;全市小加票", outcome: { text: "一整排年輕人跟在後面,很有氣勢。", card: "walk", votes: 460 } }, + ], + }, + { + id: "divination", + title: "擲筊", + text: "廟方說,擲到三個聖筊就幫你辦一場祈福。", + art: "temple_visit", + choices: [ + { id: "throw", label: "擲!", hint: "四成機率聲勢 +2 並拿到「宮廟參拜+」", outcome: { text: "連續三個聖筊!廟口一陣歡呼。", momentum: 2, card: "temple", upCard: true }, roll: { chance: 0.4, fail: { text: "擲到笑筊,大家笑成一團。", votes: 230 } } }, + { id: "pray", label: "誠心上香就好", hint: "沒事", outcome: { text: "心安最重要。" } }, + ], + }, + { + id: "late_show", + title: "通告邀約", + text: "深夜政論節目邀你上通告。", + art: "talk_show", + choices: [ + { id: "tv", label: "上電視", hint: "拿到「上政論節目+」", outcome: { text: "主持人說你很會接話。", card: "talk", upCard: true } }, + { id: "radio", label: "改上地方廣播", hint: "拿到「廣播專訪」", outcome: { text: "計程車司機都在聽。", card: "radio" } }, + ], + }, + { + id: "leaky_hq", + title: "總部漏水", + text: "一場大雨,競選總部天花板開始漏水。", + art: "rest", + choices: [ + { id: "fix", label: "花錢修好", hint: "資金 −100 萬", outcome: { text: "修好了,大家鬆一口氣。", money: -100 }, needs: { money: 100 } }, + { id: "tent", label: "搬到門口搭帳篷辦公", hint: "牌組多一張疲勞;聲勢 +1", outcome: { text: "「帳篷總部」上了新聞,大家覺得你很拚。", status: ["tired"], momentum: 1 } }, + ], + }, + { + id: "reunion", + title: "同學會", + text: "國中同學會剛好辦在這週。", + art: "banquet", + choices: [ + { id: "go", label: "抽空參加", hint: "全市小加票;資金 +80 萬", outcome: { text: "老同學們紛紛掏出小額捐款。", votes: 690, money: 80 } }, + { id: "card", label: "寄卡片致意", hint: "沒事", outcome: { text: "同學們說等你凍蒜再聚。" } }, + ], + }, + { + id: "ring_toss", + title: "夜市套圈圈", + text: "套圈圈攤老闆說,套中最遠那瓶就幫你掛一個月的看板。", + art: "night_market", + choices: [ + { id: "toss", label: "挑戰", hint: "一半機率拿到「插旗看板+」", outcome: { text: "套中了!整條夜市都在拍手。", card: "billboard", upCard: true }, roll: { chance: 0.5, fail: { text: "差一點點,老闆送你一支棉花糖。", money: -10 } } }, + { id: "watch", label: "在旁邊幫大家加油", hint: "全市小加票", outcome: { text: "大家覺得你很親切。", votes: 460 } }, + ], + }, + { + id: "village_meeting", + title: "里民大會", + text: "里民大會上,兩派人為了停車位吵起來。", + art: "forum", + choices: [ + { id: "mediate", label: "出面當和事佬", hint: "六成機率全市加票,否則掉票", outcome: { text: "你提出輪流停車的辦法,兩邊都接受了。", votes: 1150 }, roll: { chance: 0.6, fail: { text: "兩邊都覺得你偏袒對方。", votes: -460 } } }, + { id: "listen", label: "安靜聽完,記下來", hint: "隨機升級牌組裡一張牌", outcome: { text: "你的筆記本又多了好幾頁地方需求。", upgrade: true } }, + ], + }, + { + id: "platform_draw", + title: "政見發表會抽籤", + text: "電視政見發表會,你抽到第一個發言。", + art: "announce_policy", + choices: [ + { id: "prepare", label: "熬夜準備開場白", hint: "拿到「政見發表會+」;牌組多一張疲勞", outcome: { text: "開場白背得滾瓜爛熟。", card: "policy", upCard: true, status: ["tired"] } }, + { id: "improv", label: "即興發揮", hint: "一半機率聲勢 +2,否則掉票", outcome: { text: "你的即興演講被剪成精華到處轉。", momentum: 2 }, roll: { chance: 0.5, fail: { text: "講到一半忘詞,場面有點尷尬。", votes: -460 } } }, + ], + }, +]; + +export const STOP_EVENT_BY_ID = new Map(STOP_EVENTS.map((e) => [e.id, e])); + +/** 電視辯論的題目(一般性的議題,不針對真實政策) */ +export const DEBATE_TOPICS = ["交通建設", "房價與居住", "長照", "托育", "治安", "空污與能源", "經濟與就業", "觀光發展", "教育"]; + +/** + * 論點連擊辯論(docs/23):對手每回合丟出一種質疑,你從手上的論點挑一張回應。 + * 三種論點:拿數據、講故事、反問對手。每種質疑有最好、普通、不好的回應。 + * 對手是真實人物時不寫成引述,只用中性的描述(對手要你說清楚…)。 + */ +export const DEBATE_MOVES = { + policy: { label: "拿數據", counters: "對手質疑數字、預算的時候" }, + emotion: { label: "講故事", counters: "對手談感受、在地心聲的時候" }, + question: { label: "反問對手", counters: "對手翻你的紀錄、立場的時候" }, +} as const; + +/** 回應得普通的論點(剩下那種是不好的回應) */ +export const DEBATE_MID: Record = { policy: "question", question: "emotion", emotion: "policy" }; + +/** 對手的質疑,依「最好用哪種論點回應」分類;{topic} 換成這回合的題目 */ +export const DEBATE_CHALLENGES: Record = { + policy: ["對手要你說清楚{topic}政見的預算從哪裡來", "對手拿出數字,問你的{topic}方案算過了沒", "對手質疑你的{topic}政見做不到"], + emotion: ["對手分享在地居民對{topic}的心聲,請你回應", "對手談{topic}對一般家庭的影響,請你回應", "對手請你說說自己和{topic}有關的經驗"], + question: ["對手提起你過去在{topic}的立場,問你為什麼改變", "對手比較兩人在{topic}上的紀錄,請你回應", "對手問你上次承諾的{topic}政見做到幾成"], +}; + +/** 舉債的政策會被拿出來問 */ +export const DEBATE_DEBT_CHALLENGE = "對手問你的「{policy}」要舉債,之後怎麼還"; + +/** 你手上的論點 */ +export const DEBATE_ARGS: Record = { + policy: ["拿出預算表一項一項說明", "引用政府統計數字", "說明政見的時程和財源"], + emotion: ["說一段在地方上聽到的故事", "談自己家裡也遇過的難處", "請觀眾想想自己家裡的需要"], + question: ["反問對手政見的細節", "請對手說明自己的做法", "把兩人的方案放在一起比"], +}; +export const DEBATE_POLICY_ARG = "用你的政策「{policy}」說明"; + +/** 匿名黑函危機的四種回應 */ +export const CRISIS_CHOICES = [ + { id: "sue", label: "提告並開記者會", hint: "資金 −250 萬;損失剩三成,不會有記者追問", money: 250 }, + { id: "ignore", label: "冷處理", hint: "一半機率損失剩四成;否則損失 ×1.2 再多兩張記者追問" }, + { id: "sympathy", label: "悲情反擊", hint: "損失剩七成;聲勢 +2,多一張記者追問" }, + { id: "transparent", label: "公開所有資料自清", hint: "這週體力 −1;沒有損失" }, +] as const; diff --git a/backend/packages/rogue/src/data.ts b/backend/packages/rogue/src/data.ts new file mode 100644 index 0000000..35ec695 --- /dev/null +++ b/backend/packages/rogue/src/data.ts @@ -0,0 +1,342 @@ +import type { RogueTrait } from "@election2026/protocol"; +import { policyCardDef } from "./meta.ts"; + +/** + * 牌與每週事件(docs/21、22)。票數是以「全市 100 萬人投票」為準的基準值, + * 實際牌面會乘上比例尺(桃園約 1.1、嘉義市約 0.15),小縣市的數字跟著變小。 + */ + +export type CardEffect = + /** 該區加票 */ + | { kind: "gain"; base: number } + /** 該區加票,聲勢 +momentum;spill 是隔壁區各拿到幾成 */ + | { kind: "rally"; base: number; momentum: number; spill?: number } + /** 該區加票,隔壁區各拿到 spill 成 */ + | { kind: "spread"; base: number; spill: number } + /** 該區這週的樁腳(擋對手),順便加一點票 */ + | { kind: "shield"; base: number; gain: number } + /** 全市加票,依人口分配;weight 是哪種區分到比較多 */ + | { kind: "city"; base: number; weight?: RogueTrait; momentum?: number } + /** 全市加票,有 chance 的機率效果變成 hit 倍(爆紅 ×3、失言倒扣),其他時候是 miss 倍 */ + | { kind: "gamble"; base: number; chance: number; hit: number; miss: number } + /** 對手某一區的行動打對台:對手效果剩 cut,你在那區加票 */ + | { kind: "counter"; base: number; cut: number } + /** 對手這週的攻擊只剩 cut;可以加聲勢、全市加一點票 */ + | { kind: "clarify"; cut: number; base: number; momentum: number } + /** 指定對手一個全市的攻擊,讓它完全失效 */ + | { kind: "nullify"; base: number } + /** 機率拿到一個把柄 */ + | { kind: "probe"; chance: number } + /** 爆料:有把柄全額,沒把柄只有 weak 而且自己扣 backlash */ + | { kind: "expose"; base: number; weak: number; backlash: number } + /** 比較文宣:不用把柄,對手全市少一點票 */ + | { kind: "contrast"; base: number } + /** 服務處、看板:之後每週這區自動加票 */ + | { kind: "office"; perWeek: number } + /** 募款(萬元),聲勢越高募越多;curse 是附帶塞進牌組的狀態牌 */ + | { kind: "money"; base: number; perMomentum: number; curse?: string } + /** 鞏固基本盤:你領先最多的幾區各加票 */ + | { kind: "base"; base: number; towns: number } + /** 你插旗的每一區加票 */ + | { kind: "flags"; base: number } + /** 抽牌 */ + | { kind: "draw"; cards: number } + /** 多拿體力,代價是塞一張狀態牌 */ + | { kind: "rush"; energy: number; curse: string } + /** 這週之後打出的某類牌加成 */ + | { kind: "buff"; tag: string; mult: number; base: number } + /** 能力牌:整局有效 */ + | { kind: "power"; power: string } + /** 選前之夜下跪:只能在最後一週打,聲勢大增、全市加票 */ + | { kind: "kneel"; base: number; momentum: number } + /** 狀態牌:回應記者追問(全市一點點) */ + | { kind: "answer"; base: number } + /** 不能打的牌 */ + | { kind: "none" }; + +export type Keyword = "exhaust" | "retain" | "ethereal" | "unplayable"; + +export interface CardDef { + id: string; + name: string; + art: string; + cost: number; + /** 萬元 */ + money: number; + rarity: "basic" | "common" | "rare" | "status"; + tags: string[]; + target: "town" | "city" | "intent" | "attack" | "none"; + effect: CardEffect; + /** 打在有這種特色的區,效果加乘 */ + bonus?: { trait: RogueTrait; mult: number }[]; + keywords?: Keyword[]; + /** 打完再抽幾張牌 */ + draw?: number; + /** 每週只能打一次(加體力的牌,避免一週無限循環) */ + oncePerWeek?: boolean; + /** 打出後的附帶效果(政策卡的財源):塞一張狀態牌、資金增減、全市流失一點票 */ + side?: { curse?: string; money?: number; backlash?: number }; + /** 「+」版:沒寫的部分照原版,效果數字 ×1.35 */ + plus?: { cost?: number; effect?: CardEffect; keywords?: Keyword[]; text?: string }; + /** 牌面小字;{n} 換成實際票數、{m} 換成萬元 */ + text: string; +} + +export const TRAIT_LABELS: Record = { + young: "年輕人多", + old: "長輩多", + temples: "宮廟多", + dense: "人口密集", + rural: "地廣人稀", + hakka: "客家庄", +}; + +export const KEYWORD_LABELS: Record = { + exhaust: "消耗", + retain: "保留", + ethereal: "虛無", + unplayable: "不能打", +}; + +export const CARDS: readonly CardDef[] = [ + // ── 開局牌 ── + { id: "canvass", name: "掃街拜票", art: "street_canvass", cost: 1, money: 0, rarity: "basic", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1720 }, bonus: [{ trait: "dense", mult: 1.3 }], text: "該區 +{n};人口密集 ×1.3" }, + { id: "market", name: "菜市場拜票", art: "market_visit", cost: 1, money: 0, rarity: "basic", tags: ["ground", "market"], target: "town", effect: { kind: "gain", base: 1490 }, bonus: [{ trait: "old", mult: 1.5 }], text: "該區 +{n};長輩多 ×1.5" }, + { id: "temple", name: "宮廟參拜", art: "temple_visit", cost: 1, money: 0, rarity: "basic", tags: ["ground", "temple"], target: "town", effect: { kind: "gain", base: 1260 }, bonus: [{ trait: "temples", mult: 2 }], text: "該區 +{n};宮廟多 ×2" }, + { id: "stake", name: "拜託里長佈樁", art: "recruit_machine", cost: 1, money: 0, rarity: "basic", tags: ["org", "defend"], target: "town", effect: { kind: "shield", base: 2880, gain: 580 }, text: "該區樁腳 {n},擋對手這週在這區的行動" }, + { id: "dinner", name: "募款餐會", art: "fundraiser_dinner", cost: 1, money: 0, rarity: "basic", tags: ["money"], target: "none", effect: { kind: "money", base: 300, perMomentum: 30 }, text: "資金 +{m} 萬;聲勢越高募越多" }, + { id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", tags: ["ground", "rally"], target: "town", effect: { kind: "rally", base: 3450, momentum: 2, spill: 0.25 }, plus: { effect: { kind: "rally", base: 4140, momentum: 3, spill: 0.3 } }, text: "該區 +{n}、隔壁區兩成半,聲勢 +2" }, + + // ── 地面戰 ── + { id: "night", name: "夜市拜票", art: "night_market", cost: 1, money: 0, rarity: "common", tags: ["ground", "market"], target: "town", effect: { kind: "gain", base: 1490 }, bonus: [{ trait: "young", mult: 1.5 }], text: "該區 +{n};年輕人多 ×1.5" }, + { id: "walk", name: "徒步掃街", art: "grassroots_walk", cost: 0, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 690 }, text: "不花體力;該區 +{n}" }, + { id: "door", name: "挨家挨戶", art: "door_to_door", cost: 2, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 3680 }, bonus: [{ trait: "rural", mult: 1.3 }], text: "該區 +{n};地廣人稀 ×1.3" }, + { id: "breakfast", name: "早餐店拜票", art: "street_interview", cost: 1, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1150 }, bonus: [{ trait: "dense", mult: 1.3 }], draw: 1, text: "該區 +{n},再抽 1 張牌;人口密集 ×1.3" }, + { id: "park", name: "公園晨運", art: "workout", cost: 1, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1380 }, bonus: [{ trait: "old", mult: 1.7 }], text: "該區 +{n};長輩多 ×1.7" }, + { id: "campus", name: "校園座談", art: "forum", cost: 1, money: 0, rarity: "common", tags: ["ground", "press"], target: "town", effect: { kind: "gain", base: 1380 }, bonus: [{ trait: "young", mult: 1.7 }], text: "該區 +{n};年輕人多 ×1.7" }, + { id: "hakka", name: "客家庄拜會", art: "visit_associations", cost: 1, money: 0, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1260 }, bonus: [{ trait: "hakka", mult: 2.2 }], text: "該區 +{n};客家庄 ×2.2" }, + { id: "weddings", name: "跑紅白帖", art: "weddings_funerals", cost: 1, money: 30, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "gain", base: 1260 }, bonus: [{ trait: "rural", mult: 1.6 }, { trait: "old", mult: 1.2 }], text: "該區 +{n};地廣人稀 ×1.6、長輩多 ×1.2" }, + { id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", tags: ["ground"], target: "town", effect: { kind: "spread", base: 1150, spill: 0.5 }, text: "該區 +{n},隔壁每一區也有一半" }, + { id: "banquet", name: "流水席辦桌", art: "banquet", cost: 2, money: 150, rarity: "common", tags: ["ground", "org"], target: "town", effect: { kind: "shield", base: 1440, gain: 2880 }, text: "該區 +{n},樁腳 {s}" }, + { id: "pilgrimage", name: "跟著遶境", art: "pilgrimage", cost: 2, money: 50, rarity: "rare", tags: ["ground", "temple", "rally"], target: "town", effect: { kind: "rally", base: 2880, momentum: 2 }, bonus: [{ trait: "temples", mult: 2 }], text: "該區 +{n},聲勢 +2;宮廟多 ×2" }, + { id: "celebrity", name: "藝人站台", art: "concert", cost: 2, money: 250, rarity: "rare", tags: ["rally", "media"], target: "town", effect: { kind: "rally", base: 4600, momentum: 2, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n}、隔壁區兩成,聲勢 +2;年輕人多 ×1.3" }, + { id: "endorse", name: "地方仕紳背書", art: "endorsement", cost: 1, money: 0, rarity: "rare", tags: ["ground", "org"], target: "town", effect: { kind: "gain", base: 2070 }, keywords: ["retain"], text: "保留;該區 +{n}" }, + + // ── 組織 ── + { id: "counter", name: "打對台", art: "sound_truck", cost: 1, money: 0, rarity: "common", tags: ["ground", "defend"], target: "intent", effect: { kind: "counter", base: 1720, cut: 0.4 }, plus: { effect: { kind: "counter", base: 2320, cut: 0.2 } }, text: "對手在某區的行動剩四成,你在那區 +{n}" }, + { id: "office", name: "設競選服務處", art: "open_office", cost: 2, money: 200, rarity: "common", tags: ["org"], target: "town", effect: { kind: "office", perWeek: 920 }, plus: { cost: 1 }, text: "該區現在和之後每週 +{n}" }, + { id: "billboard", name: "插旗看板", art: "flags_billboards", cost: 1, money: 100, rarity: "common", tags: ["org", "media"], target: "town", effect: { kind: "office", perWeek: 520 }, text: "該區現在和之後每週 +{n}" }, + { id: "calls", name: "志工電話催票", art: "volunteer_calls", cost: 1, money: 0, rarity: "common", tags: ["org"], target: "none", effect: { kind: "base", base: 1040, towns: 3 }, text: "你領先最多的 3 區各 +{n}" }, + { id: "volunteers", name: "志工大隊", art: "recruit_volunteers", cost: 1, money: 0, rarity: "common", tags: ["org"], target: "none", effect: { kind: "draw", cards: 2 }, text: "抽 2 張牌" }, + { id: "phonebank", name: "電話拜票中心", art: "phone_banking", cost: 2, money: 100, rarity: "rare", tags: ["org"], target: "none", effect: { kind: "base", base: 1040, towns: 5 }, text: "你領先最多的 5 區各 +{n}" }, + { id: "mobilize", name: "全面動員令", art: "councilor_allies", cost: 1, money: 0, rarity: "rare", tags: ["org"], target: "none", effect: { kind: "flags", base: 920 }, text: "你插旗的每一區 +{n}" }, + { id: "allnighter", name: "熬夜跑行程", art: "rest", cost: 0, money: 0, rarity: "common", tags: ["org"], target: "none", effect: { kind: "rush", energy: 2, curse: "tired" }, oncePerWeek: true, text: "每週一次;體力 +2,塞一張「疲勞」進棄牌堆" }, + + // ── 空戰 ── + { id: "tv", name: "電視廣告", art: "tv_ad", cost: 1, money: 300, rarity: "common", tags: ["media", "tv"], target: "city", effect: { kind: "city", base: 5180, weight: "old" }, text: "全市 +{n},長輩多的區分到較多" }, + { id: "online", name: "網路廣告", art: "online_ad", cost: 1, money: 120, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 3220, weight: "young" }, text: "全市 +{n},年輕人多的區分到較多" }, + { id: "live", name: "臉書直播", art: "facebook_live", cost: 1, money: 0, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "gamble", base: 1380, chance: 0.35, hit: 3, miss: 1 }, text: "全市 +{n};35% 爆紅 ×3" }, + { id: "shorts", name: "短影音", art: "short_video", cost: 1, money: 60, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "gamble", base: 1840, chance: 0.25, hit: 3.5, miss: 1 }, text: "全市 +{n};25% 爆紅 ×3.5" }, + { id: "talk", name: "上政論節目", art: "talk_show", cost: 1, money: 0, rarity: "common", tags: ["media"], target: "city", effect: { kind: "gamble", base: 2530, chance: 0.2, hit: -0.7, miss: 1 }, plus: { effect: { kind: "gamble", base: 3220, chance: 0.1, hit: -0.7, miss: 1 }, text: "全市 +{n};10% 失言倒扣" }, text: "全市 +{n};20% 失言倒扣" }, + { id: "line", name: "長輩群組", art: "line_groups", cost: 1, money: 40, rarity: "common", tags: ["media", "online"], target: "city", effect: { kind: "city", base: 2990, weight: "old" }, text: "全市 +{n},長輩多的區分到較多" }, + { id: "radio", name: "廣播專訪", art: "radio_ad", cost: 1, money: 0, rarity: "common", tags: ["media", "press"], target: "city", effect: { kind: "city", base: 2070, weight: "rural" }, text: "全市 +{n},地廣人稀的區分到較多" }, + { id: "flyers", name: "印文宣", art: "print_flyers", cost: 0, money: 50, rarity: "common", tags: ["media"], target: "city", effect: { kind: "city", base: 1150 }, text: "不花體力;全市 +{n}" }, + { id: "policy", name: "政見發表會", art: "announce_policy", cost: 1, money: 0, rarity: "common", tags: ["press", "media"], target: "city", effect: { kind: "city", base: 1610, momentum: 1 }, text: "全市 +{n},聲勢 +1" }, + { id: "whitepaper", name: "政策白皮書", art: "white_paper", cost: 1, money: 0, rarity: "rare", tags: ["press"], target: "none", effect: { kind: "buff", tag: "media", mult: 1.5, base: 1150 }, text: "全市 +{n};這週之後的媒體牌 ×1.5" }, + { id: "mediatraining", name: "媒體訓練", art: "media_training", cost: 1, money: 100, rarity: "rare", tags: ["press"], target: "none", effect: { kind: "power", power: "media" }, keywords: ["exhaust"], plus: { cost: 0 }, text: "能力:這局之後的媒體牌 +25%" }, + { id: "fieldwork", name: "蹲點研究", art: "study", cost: 1, money: 0, rarity: "rare", tags: ["ground"], target: "none", effect: { kind: "power", power: "ground" }, keywords: ["exhaust"], plus: { cost: 0 }, text: "能力:這局之後的地面牌 +15%" }, + + // ── 攻防 ── + { id: "clarify", name: "澄清記者會", art: "rebuttal_press", cost: 1, money: 0, rarity: "common", tags: ["defend", "press"], target: "none", effect: { kind: "clarify", cut: 0.2, base: 690, momentum: 0 }, text: "對手這週的批評剩兩成;全市 +{n}" }, + { id: "factcheck", name: "事實查核", art: "fact_check", cost: 0, money: 0, rarity: "common", tags: ["defend"], target: "attack", effect: { kind: "nullify", base: 460 }, keywords: ["retain"], text: "保留;讓對手一個全市的批評失效,全市 +{n}" }, + { id: "probe", name: "打探對手", art: "investigate", cost: 1, money: 100, rarity: "common", tags: ["intel"], target: "none", effect: { kind: "probe", chance: 0.7 }, plus: { effect: { kind: "probe", chance: 1 }, text: "一定拿到一個把柄(爆料用)" }, text: "70% 拿到一個把柄(爆料用)" }, + { id: "expose", name: "爆料記者會", art: "expose_press", cost: 1, money: 50, rarity: "common", tags: ["attack", "press"], target: "none", effect: { kind: "expose", base: 4600, weak: 1150, backlash: 920 }, text: "用一個把柄:對手全市 −{n};沒把柄會反傷" }, + { id: "contrast", name: "比較文宣", art: "flags_billboards", cost: 1, money: 80, rarity: "common", tags: ["attack", "media"], target: "none", effect: { kind: "contrast", base: 2070 }, text: "列出雙方政見比較:對手全市 −{n}" }, + { id: "oath", name: "斬雞頭發誓", art: "chicken_oath", cost: 1, money: 20, rarity: "rare", tags: ["defend", "temple"], target: "none", effect: { kind: "clarify", cut: 0, base: 0, momentum: 1 }, keywords: ["exhaust"], plus: { keywords: [] , text: "對手這週的批評全部無效,聲勢 +1" }, text: "消耗;對手這週的批評全部無效,聲勢 +1" }, + + // ── 資金 ── + { id: "small", name: "網路小額募款", art: "small_donations", cost: 0, money: 0, rarity: "common", tags: ["money", "online"], target: "none", effect: { kind: "money", base: 80, perMomentum: 20 }, text: "不花體力;資金 +{m} 萬" }, + { id: "selffund", name: "自掏腰包", art: "self_fund", cost: 0, money: 0, rarity: "common", tags: ["money"], target: "none", effect: { kind: "money", base: 250, perMomentum: 0 }, keywords: ["exhaust"], text: "消耗;資金 +{m} 萬" }, + { id: "tycoon", name: "企業主餐敘", art: "big_donor", cost: 1, money: 0, rarity: "common", tags: ["money"], target: "none", effect: { kind: "money", base: 500, perMomentum: 0, curse: "favor" }, text: "資金 +{m} 萬;塞一張「人情包袱」" }, + + // ── 稀有大招 ── + { id: "elder", name: "黨內大老站台", art: "party_elder", cost: 2, money: 0, rarity: "rare", tags: ["rally", "media"], target: "city", effect: { kind: "city", base: 4600, momentum: 2 }, keywords: ["exhaust"], text: "消耗;全市 +{n},聲勢 +2" }, + { id: "kneel", name: "選前之夜下跪", art: "kneel", cost: 2, money: 0, rarity: "rare", tags: ["rally"], target: "none", effect: { kind: "kneel", base: 5750, momentum: 3 }, text: "最後一週才能打:全市 +{n},聲勢 +3" }, + + // ── 出身專屬牌(18 第 53 項):自創角色依出身開局就有一張,不會出現在獎勵裡 ── + { id: "origin_clinic", name: "巡迴義診", art: "visit_associations", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "gain", base: 1500 }, bonus: [{ trait: "old", mult: 2 }], text: "該區 +{n};長輩多 ×2" }, + { id: "origin_legal", name: "法律諮詢站", art: "open_office", cost: 1, money: 0, rarity: "rare", tags: ["defend", "press", "origin"], target: "none", effect: { kind: "clarify", cut: 0.4, base: 1380, momentum: 0 }, text: "對手這週的批評剩四成;全市 +{n}" }, + { id: "origin_lecture", name: "公共政策講座", art: "forum", cost: 1, money: 0, rarity: "rare", tags: ["press", "media", "origin"], target: "city", effect: { kind: "city", base: 1840, momentum: 1 }, text: "全市 +{n},聲勢 +1" }, + { id: "origin_fanmeet", name: "粉絲見面會", art: "concert", cost: 1, money: 100, rarity: "rare", tags: ["rally", "media", "origin"], target: "town", effect: { kind: "rally", base: 2300, momentum: 1, spill: 0.2 }, bonus: [{ trait: "young", mult: 1.3 }], text: "該區 +{n},聲勢 +1;年輕人多 ×1.3" }, + { id: "origin_stream", name: "直播開箱", art: "facebook_live", cost: 1, money: 0, rarity: "rare", tags: ["media", "online", "origin"], target: "city", effect: { kind: "gamble", base: 1840, chance: 0.4, hit: 3, miss: 1 }, text: "全市 +{n};40% 爆紅 ×3" }, + { id: "origin_clan", name: "家族老樁腳", art: "recruit_machine", cost: 1, money: 0, rarity: "rare", tags: ["org", "origin"], target: "none", effect: { kind: "base", base: 1380, towns: 3 }, text: "你領先最多的 3 區各 +{n}" }, + { id: "origin_assembly", name: "里民大會", art: "door_to_door", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "gain", base: 1840 }, bonus: [{ trait: "rural", mult: 1.3 }], text: "該區 +{n};地廣人稀 ×1.3" }, + { id: "origin_donors", name: "企業募款餐會", art: "big_donor", cost: 1, money: 0, rarity: "rare", tags: ["money", "origin"], target: "none", effect: { kind: "money", base: 450, perMomentum: 20 }, text: "資金 +{m} 萬;聲勢越高募越多" }, + { id: "origin_record", name: "施政成績單", art: "announce_policy", cost: 1, money: 0, rarity: "rare", tags: ["press", "media", "origin"], target: "city", effect: { kind: "city", base: 2530 }, text: "全市 +{n}" }, + { id: "origin_petition", name: "街頭連署", art: "grassroots_walk", cost: 1, money: 0, rarity: "rare", tags: ["ground", "origin"], target: "town", effect: { kind: "spread", base: 1380, spill: 0.5 }, text: "該區 +{n},隔壁每一區也有一半" }, + + // ── 劇情給的牌(不會出現在獎勵裡) ── + { id: "sympathy", name: "悲情催票", art: "live_pledge", cost: 1, money: 0, rarity: "status", tags: ["rally"], target: "none", effect: { kind: "city", base: 2300, momentum: 1 }, keywords: ["exhaust"], text: "消耗;全市 +{n},聲勢 +1" }, + { id: "soundbite", name: "辯論金句", art: "debate_training", cost: 1, money: 0, rarity: "status", tags: ["press", "media"], target: "city", effect: { kind: "city", base: 3450, momentum: 1 }, keywords: ["exhaust"], text: "消耗;全市 +{n},聲勢 +1" }, + { id: "walkx", name: "黨部動員掃街", art: "grassroots_walk", cost: 0, money: 0, rarity: "status", tags: ["ground"], target: "town", effect: { kind: "gain", base: 690 }, keywords: ["exhaust"], text: "消耗;不花體力,該區 +{n}" }, + { id: "reporter", name: "記者追問", art: "interview", cost: 1, money: 0, rarity: "status", tags: ["status", "press"], target: "none", effect: { kind: "answer", base: 350 }, keywords: ["exhaust"], text: "回應就移除(全市 +{n});留在手上過週末,全市 −{n2}" }, + { id: "storm", name: "黨中央風波", art: "interview", cost: 1, money: 0, rarity: "status", tags: ["status", "press"], target: "none", effect: { kind: "answer", base: 350 }, keywords: ["exhaust", "ethereal"], text: "大黨的包袱。回應就移除(全市 +{n});留在手上過週末,全市 −{n2},之後消失" }, + { id: "favor", name: "人情包袱", art: "gifts", cost: 0, money: 0, rarity: "status", tags: ["status"], target: "none", effect: { kind: "none" }, keywords: ["unplayable"], text: "不能打;要在「整頓行程」才能拿掉" }, + { id: "tired", name: "疲勞", art: "rest", cost: 0, money: 0, rarity: "status", tags: ["status"], target: "none", effect: { kind: "none" }, keywords: ["unplayable", "ethereal"], text: "不能打;週末還在手上就消失" }, +]; + +export const CARD_BY_ID = new Map(CARDS.map((c) => [c.id, c])); + +/** 記者追問留在手上過週末,全市掉多少票(基準) */ +export const REPORTER_PENALTY = 1040; + +/** 可以出現在獎勵、商店的牌 */ +export const REWARD_CARDS = CARDS.filter((c) => (c.rarity === "common" || c.rarity === "rare") && !c.tags.includes("origin")); +/** 出身專屬牌(自創角色依出身開局就有,不在獎勵裡) */ +export const ORIGIN_CARDS = CARDS.filter((c) => c.tags.includes("origin")); + +/** 開局牌組(10 張) */ +export const STARTER_DECK = ["canvass", "canvass", "canvass", "market", "market", "temple", "stake", "stake", "dinner", "rally"]; + +/** 數字效果的升級倍率 */ +export const PLUS_MULT = 1.35; + +function scaleEffect(e: CardEffect): CardEffect { + const m = (n: number) => Math.round((n * PLUS_MULT) / 10) * 10; + switch (e.kind) { + case "gain": + case "spread": + case "city": + case "gamble": + case "kneel": + case "answer": + case "flags": + case "contrast": + case "nullify": + return { ...e, base: m(e.base) }; + case "rally": + return { ...e, base: m(e.base) }; + case "shield": + return { ...e, base: m(e.base), gain: m(e.gain) }; + case "counter": + return { ...e, base: m(e.base) }; + case "clarify": + return { ...e, base: m(e.base), cut: e.cut / 2 }; + case "expose": + return { ...e, base: m(e.base), weak: m(e.weak) }; + case "office": + return { ...e, perWeek: m(e.perWeek) }; + case "money": + return { ...e, base: m(e.base), perMomentum: m(e.perMomentum) }; + case "base": + return { ...e, base: m(e.base) }; + case "draw": + return { ...e, cards: e.cards + 1 }; + case "rush": + return { ...e, energy: e.energy + 1 }; + case "buff": + return { ...e, base: m(e.base), mult: e.mult + 0.2 }; + case "probe": + case "power": + case "none": + return e; + } +} + +/** 找牌:一般的牌,或政策工坊寫的政策卡(id 以 policy: 開頭) */ +export const findCard = (id: string): CardDef | undefined => CARD_BY_ID.get(id) ?? (id.startsWith("policy:") ? policyCardDef(id) : undefined); + +/** 這張牌實際的定義(升級過的套「+」版) */ +export function cardDef(id: string, up = false): CardDef | undefined { + const base = findCard(id); + if (!base || !up) return base; + const p = base.plus ?? {}; + return { + ...base, + name: `${base.name}+`, + cost: p.cost ?? base.cost, + effect: p.effect ?? scaleEffect(base.effect), + keywords: p.keywords ?? base.keywords, + text: p.text ?? base.text, + }; +} + +/** 能不能升級:狀態牌不行,已經升級過的不行 */ +export const upgradable = (id: string, up?: boolean): boolean => !up && (findCard(id)?.rarity ?? "status") !== "status"; + +export const hasKeyword = (card: CardDef, k: Keyword): boolean => (card.keywords ?? []).includes(k); + +/** 能力牌的效果 */ +export const POWERS: Record = { + media: { tag: "media", mult: 1.25, label: "媒體訓練" }, + ground: { tag: "ground", mult: 1.15, label: "蹲點研究" }, +}; + +export interface EventDef { + id: string; + title: string; + text: string; + weight: number; + /** 有這個標籤的牌(雙方都算)效果倍率 */ + mods?: { tag: string; mult: number }[]; + /** 本週收入倍率 */ + income?: number; + /** 對手所有行動的倍率 */ + rival?: number; + /** 不好的事(逆風 9 級以上比較常出現) */ + bad?: boolean; +} + +export const EVENTS: readonly EventDef[] = [ + { id: "calm", title: "風平浪靜", text: "這週沒有大新聞,照自己的節奏打。", weight: 3 }, + { id: "typhoon", title: "颱風來襲", text: "地面行程效果 −40%(雙方都一樣),空戰照常。", weight: 1.5, mods: [{ tag: "ground", mult: 0.6 }], bad: true }, + { id: "festival", title: "大型廟會", text: "宮廟牌效果加倍。", weight: 1.5, mods: [{ tag: "temple", mult: 2 }] }, + { id: "talkshow", title: "政論節目熱議選情", text: "媒體牌效果 +40%(雙方都一樣)。", weight: 1.5, mods: [{ tag: "media", mult: 1.4 }] }, + { id: "meme", title: "網路迷因爆紅", text: "網路牌效果 +60%。", weight: 1.2, mods: [{ tag: "online", mult: 1.6 }] }, + { id: "recession", title: "景氣不好", text: "本週收入減半,募款牌只剩七成。", weight: 1, income: 0.5, mods: [{ tag: "money", mult: 0.7 }], bad: true }, + { id: "gaffe", title: "對手陣營忙著滅火", text: "對手這週的行動效果 −30%。", weight: 1, rival: 0.7 }, + { id: "scandal", title: "社會案件延燒", text: "攻擊與政見批評的效果 +50%(雙方都一樣)。", weight: 1, mods: [{ tag: "attack", mult: 1.5 }], bad: true }, + { id: "heatwave", title: "熱浪來襲", text: "大家躲在冷氣房滑手機:地面牌 −20%、網路牌 +30%。", weight: 1, mods: [{ tag: "ground", mult: 0.8 }, { tag: "online", mult: 1.3 }] }, + { id: "holiday", title: "連假返鄉潮", text: "地廣人稀的區人變多:組織牌 +30%。", weight: 1, mods: [{ tag: "org", mult: 1.3 }] }, + { id: "donations", title: "小額捐款湧入", text: "本週收入加倍。", weight: 0.8, income: 2 }, + { id: "ghost_month", title: "中元普渡", text: "各地普渡拜拜:宮廟牌 +50%、地面牌 +10%。", weight: 0.9, mods: [{ tag: "temple", mult: 1.5 }, { tag: "ground", mult: 1.1 }] }, + { id: "sports", title: "國手奪金", text: "全國都在看比賽,新聞版面被佔滿:媒體牌 −30%(雙方都一樣)。", weight: 0.8, mods: [{ tag: "media", mult: 0.7 }], bad: true }, + { id: "prices", title: "物價上漲", text: "大家荷包變薄:本週收入 −30%。", weight: 0.8, income: 0.7, bad: true }, + { id: "outage", title: "社群平台當機", text: "網路牌 −50%(雙方都一樣)。", weight: 0.7, mods: [{ tag: "online", mult: 0.5 }], bad: true }, + { id: "fair", title: "地方節慶", text: "各區活動多、人潮多:地面牌 +20%。", weight: 1, mods: [{ tag: "ground", mult: 1.2 }] }, +]; + +export const EVENT_BY_ID = new Map(EVENTS.map((e) => [e.id, e])); + +/** 對手意圖的基準票數(同樣以 100 萬人投票為準) */ +export const INTENT_BASE = { + canvass: 1720, + rally: 3450, + tv: 4830, + online: 2990, + attack: 2880, + smear: 2070, + stake: 2880, +} as const; + +/** 對手是真實人物時用的中性說法(docs/22) */ +export const INTENT_LABELS: Record = { + canvass: "掃街", + rally: "造勢", + tv: "電視廣告", + online: "網路廣告", + attack: "批評你的政見", + smear: "到你的票倉拉票", + stake: "佈樁", +}; + +/** 對手意圖對應的標籤(每週事件的倍率用) */ +export const INTENT_TAGS: Record = { + canvass: ["ground"], + rally: ["ground", "rally"], + tv: ["media", "tv"], + online: ["media", "online"], + attack: ["attack"], + smear: ["ground"], + stake: ["org"], +}; diff --git a/backend/packages/rogue/src/feats.ts b/backend/packages/rogue/src/feats.ts new file mode 100644 index 0000000..5c2ea3e --- /dev/null +++ b/backend/packages/rogue/src/feats.ts @@ -0,0 +1,63 @@ +import { flagOwner } from "./mechanics.ts"; +import type { RunState } from "./state.ts"; + +/** 成就(docs/22):開票時算這局拿到哪些;解鎖紀錄存在玩家自己的瀏覽器 */ +export interface FeatDef { + id: string; + name: string; + text: string; +} + +export const FEATS: readonly FeatDef[] = [ + { id: "win", name: "凍蒜!", text: "當選一次" }, + { id: "landslide", name: "壓倒性勝利", text: "贏 8 個百分點以上" }, + { id: "squeaker", name: "驚險過關", text: "贏不到 1 個百分點" }, + { id: "comeback", name: "逆轉勝", text: "第 4 週民調落後 3 個百分點以上,最後當選" }, + { id: "underdog", name: "以小搏大", text: "開局底盤落後 5 個百分點以上,最後當選" }, + { id: "all_flags", name: "全區插旗", text: "開票時每一區都插著你的旗" }, + { id: "clean", name: "乾淨選戰", text: "沒打過任何攻擊牌就當選" }, + { id: "debate_sweep", name: "辯論三戰全勝", text: "電視辯論三回合都贏" }, + { id: "crisis_zero", name: "黑函零損失", text: "匿名黑函危機沒有掉任何一票" }, + { id: "combo4", name: "四連拳", text: "同一週在同一區打出 4 種不同的牌" }, + { id: "flipper", name: "翻轉王", text: "一局翻轉 5 個區" }, + { id: "big_hit", name: "一張定江山", text: "一張牌在一區拉到相當於全市 0.6% 的票" }, + { id: "thin_deck", name: "精實牌組", text: "牌組 8 張以下當選" }, + { id: "rich", name: "財源滾滾", text: "資金超過 3,000 萬" }, + { id: "full_staff", name: "滿編團隊", text: "帶滿 5 位幕僚" }, + { id: "shopper", name: "物資行常客", text: "一局買 4 樣東西" }, + { id: "asc5", name: "逆風高手", text: "逆風 5 級以上當選" }, + { id: "asc10", name: "逆風傳說", text: "逆風 10 級當選" }, + { id: "daily", name: "每日一戰", text: "完成一場每日一戰" }, + { id: "career_legislator", name: "國會新科", text: "政治生涯:選上立委" }, + { id: "career_mayor", name: "地方首長", text: "政治生涯:選上縣市長" }, + { id: "career_president", name: "登上大位", text: "政治生涯:選上總統" }, +]; + +export function featsOf(s: RunState, won: boolean, margin: number): string[] { + const deck = s.draw.length + s.discard.length + s.hand.length; + const ok: Record = { + win: won, + landslide: won && margin >= 0.08, + squeaker: won && margin < 0.01, + comeback: won && s.stats.pollGap >= 3, + underdog: won && s.startGap <= -5, + all_flags: s.towns.every((t) => flagOwner(t) === "you"), + clean: won && s.stats.attacks === 0, + debate_sweep: s.stats.debateWins >= 3, + crisis_zero: s.crisisDone && s.stats.crisisLoss === 0, + combo4: s.stats.maxCombo >= 4, + flipper: s.stats.flips >= 5, + big_hit: s.stats.bigHit >= 6000, + thin_deck: won && deck <= 8, + rich: s.money >= 3000, + full_staff: s.advisors.length >= 5, + shopper: s.stats.bought >= 4, + asc5: won && s.options.ascension >= 5, + asc10: won && s.options.ascension >= 10, + daily: s.options.daily !== null, + career_legislator: won && s.options.career?.stage === 1, + career_mayor: won && s.options.career?.stage === 2, + career_president: won && s.options.career?.stage === 3, + }; + return FEATS.filter((f) => ok[f.id]).map((f) => f.id); +} diff --git a/backend/packages/rogue/src/index.ts b/backend/packages/rogue/src/index.ts new file mode 100644 index 0000000..ed7b1ba --- /dev/null +++ b/backend/packages/rogue/src/index.ts @@ -0,0 +1,14 @@ +export * from "./state.ts"; +export * from "./data.ts"; +export * from "./advisors.ts"; +export * from "./content.ts"; +export * from "./mechanics.ts"; +export * from "./rules.ts"; +export * from "./rival.ts"; +export * from "./route.ts"; +export * from "./scenes.ts"; +export * from "./feats.ts"; +export * from "./view.ts"; +export * from "./bots.ts"; +export * from "./tutorial.ts"; +export * from "./ultimate.ts"; diff --git a/backend/packages/rogue/src/local.ts b/backend/packages/rogue/src/local.ts new file mode 100644 index 0000000..d81988d --- /dev/null +++ b/backend/packages/rogue/src/local.ts @@ -0,0 +1,343 @@ +import { AGE_BANDS, type CandidatePublic, type RogueTrait } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, N_LEANS, computeVoteModel, createMatch, viewFor, type World } from "@election2026/engine"; +import type { TopologyLike } from "./setup.ts"; +import type { RogueSetup, TownSetup } from "./state.ts"; + +/** + * 政治生涯的地方選舉(docs/23):里長、議員。 + * - 里長:你住的那個里(真實的里名、選舉人數、人口結構),里裡分成三塊(虛構的地名),對手是虛構的現任里長。 + * - 議員:那個里所在的議員選區(中選會 2022 年的選區、席次、最後一席的得票率)。 + * 選區有三個以上的區就一區一塊;不到三區就把村里分成幾群(用最大那個里的名字叫「XX里一帶」)。 + * 多席次:贏過最後一席(虛構的現任議員)就當選,不用贏過第一高票。 + * 雙方底盤用縣市長劇本的選民模型(自創角色取代同黨的人)算各里的相對強弱,再換算成這種選舉的票數。 + */ + +export const VILLAGE_WEEKS = 5; +export const COUNCIL_WEEKS = 6; +/** 里長選舉的投票率(一般約五到六成) */ +const VILLAGE_TURNOUT = 0.6; +/** + * 選舉人數 ÷ 戶籍 20 歲以上人口:2024 總統大選全國選舉人數 ÷ 2023 年 12 月戶籍 20 歲以上人口 = 0.9987 + * (中選會選舉資料庫、內政部戶政司 ODRP014;桃園逐里 0.987–1.013)。 + * 里長關用「現在的 20 歲以上人口 × 這個比例」算選舉人數:資料包裡的選舉人數是上一次選舉時的里界, + * 里重劃過就對不上(例如桃園 2020→2026 新設 13 個里、41 個里差超過一成五,18 第 49 項)。 + */ +export const ELECTORS_PER_ADULT = 0.9987; + +/** 議員選區(data/build/council/2022.json 的一筆) */ +export interface CouncilDistrict { + id: string; + countyCode: string; + countyName: string; + district: string; + indigenous: string | null; + seats: number; + electors: number; + validVotes: number; + towns: string[]; + villages: string[]; + threshold: { name: string; votes: number; share: number } | null; +} + +export class LocalRaceError extends Error {} + +const YOUNG = [AGE_BANDS.indexOf("20-29"), AGE_BANDS.indexOf("30-39")]; +const OLD = AGE_BANDS.indexOf("65+"); +const SURNAMES = ["林", "陳", "黃", "張", "李", "王", "吳", "劉", "蔡", "楊", "許", "鄭"]; + +function rng(seed: number): () => number { + let a = seed >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), a | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** 虛構的對手(不是真實人物) */ +function fictional(id: string, name: string, number: number, description: string): CandidatePublic { + return { id, name, party: null, slot: "other", number, isPlayer: false, description, issueIds: [], tags: [], avatar: null, runningMate: null, gender: null, slogan: null, sloganSource: null }; +} + +interface VillageModel { + /** 每個里:預計投票人數、自創角色的預期得票率、年齡、宮廟、密度 */ + cast: number[]; + youShare: number[]; + adults: number[]; + young: number[]; + old: number[]; + you: CandidatePublic; +} + +/** 跑一次縣市長劇本的選民模型,取每個里的投票人數和自創角色的得票率 */ +function villageModel(world: World, candidateId: string): VillageModel { + const { scenario, pack, params } = world; + const ci = scenario.candidates.findIndex((c) => c.id === candidateId); + if (ci < 0) throw new LocalRaceError(`劇本中沒有候選人 ${candidateId}`); + const state = createMatch(world, "rogue-local", 1, candidateId); + const model = computeVoteModel(state, scenario, pack, params, null); + const nCells = pack.cells.length; + const n = pack.villages.length; + const out = { cast: new Array(n).fill(0), youShare: new Array(n).fill(0), adults: new Array(n).fill(0), young: new Array(n).fill(0), old: new Array(n).fill(0) }; + const youVotes = new Array(n).fill(0); + for (let i = 0; i < nCells; i++) { + const v = Math.floor(i / CELLS_PER_VILLAGE); + const people = pack.cells[i]!; + const casting = people * model.turnout[i]!; + out.cast[v] += casting; + youVotes[v] += casting * model.probs[ci * nCells + i]!; + out.adults[v] += people; + const age = Math.floor((i % CELLS_PER_VILLAGE) / N_LEANS); + if (YOUNG.includes(age)) out.young[v] += people; + if (age === OLD) out.old[v] += people; + } + for (let v = 0; v < n; v++) out.youShare[v] = out.cast[v]! > 0 ? youVotes[v]! / out.cast[v]! : 0; + const you = viewFor(state, world, candidateId).candidates[ci]!; + return { ...out, you: { ...you, number: 1 } }; +} + +/** 一群村里的特色(和全縣市平均比) */ +function traitsOf(world: World, m: VillageModel, idx: readonly number[]): RogueTrait[] { + const { pack } = world; + const sum = (xs: readonly number[]) => idx.reduce((a, i) => a + xs[i]!, 0); + const adults = sum(m.adults) || 1; + const all = m.adults.reduce((a, b) => a + b, 0) || 1; + const meanYoung = m.young.reduce((a, b) => a + b, 0) / all; + const meanOld = m.old.reduce((a, b) => a + b, 0) / all; + const temples = idx.reduce((a, i) => a + pack.villages[i]!.templesPer1000 * m.adults[i]!, 0) / adults; + const density = idx.reduce((a, i) => a + pack.villages[i]!.density * m.adults[i]!, 0) / adults; + const traits: RogueTrait[] = []; + if (sum(m.young) / adults >= meanYoung * 1.05) traits.push("young"); + if (sum(m.old) / adults >= meanOld * 1.15) traits.push("old"); + if (temples >= pack.meanTemples * 1.4) traits.push("temples"); + if (density >= pack.meanDensity * 1.5) traits.push("dense"); + if (density <= pack.meanDensity * 0.3) traits.push("rural"); + const town = pack.towns[pack.villages[idx[0]!]!.townIndex]; + if ((town?.hakkaShare ?? 0) >= 0.4) traits.push("hakka"); + return traits; +} + +const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); + +/** 自創角色在這群村里比全縣市平均強多少(0.7–1.4 倍) */ +function tilt(m: VillageModel, idx: readonly number[]): number { + const cast = idx.reduce((a, i) => a + m.cast[i]!, 0) || 1; + const here = idx.reduce((a, i) => a + m.cast[i]! * m.youShare[i]!, 0) / cast; + const allCast = m.cast.reduce((a, b) => a + b, 0) || 1; + const mean = m.cast.reduce((a, c, i) => a + c * m.youShare[i]!, 0) / allCast; + return mean > 0 ? clamp((here / mean) ** 0.6, 0.7, 1.4) : 1; +} + +const townName = (world: World, vi: number) => world.pack.towns[world.pack.villages[vi]!.townIndex]?.name ?? ""; + +/** 里長:你的里分成三塊,名字照這塊的特色取 */ +const BLOCK_NAMES: Partial> = { temples: "廟口", old: "老街", young: "新社區", dense: "大樓區", rural: "田邊", hakka: "伙房" }; +const PLAIN_BLOCKS = ["市場邊", "學校旁", "公園邊", "溪邊"]; + +export function villageSetup(world: World, candidateId: string, villageCode: string | null, seed: number): RogueSetup { + const m = villageModel(world, candidateId); + const { pack } = world; + const rand = rng(seed); + // 沒指定就照人口隨機挑一個里(有人住、有選舉人) + let vi = villageCode ? pack.villages.findIndex((v) => v.code === villageCode) : -1; + if (villageCode && vi < 0) throw new LocalRaceError(`這個縣市沒有村里 ${villageCode}`); + if (vi < 0) { + const total = m.cast.reduce((a, b) => a + b, 0); + let x = rand() * total; + vi = m.cast.findIndex((c) => (x -= c) <= 0); + if (vi < 0) vi = m.cast.length - 1; + } + const village = pack.villages[vi]!; + const electors = Math.round(m.adults[vi]! * ELECTORS_PER_ADULT); + const cast = Math.max(600, Math.round(electors * VILLAGE_TURNOUT)); + const traits = traitsOf(world, m, [vi]); + const t = tilt(m, [vi]); + // 三塊:第一塊照里的特色,另外兩塊用一般地名;人數大約 4:3:3 + const names = [...new Set([...traits.map((x) => BLOCK_NAMES[x]).filter((x): x is string => !!x), ...PLAIN_BLOCKS])].slice(0, 3); + const shares = [0.4, 0.33, 0.27]; + const blockTraits: RogueTrait[][] = [traits.slice(0, 2), traits.includes("young") ? [] : ["young"], traits.includes("old") ? [] : ["old"]]; + const towns: TownSetup[] = names.map((name, i) => { + // 第一關:和現任里長大致拉平。里長選舉看人脈、和政黨關係不大:你在這個里的政黨底盤(tilt)最多讓你多或少 3 個百分點 + // (原本是 0.45 × tilt,對手陣營很強的里一開局就落後十幾個百分點、5 週追不回來,18 第 55 項) + const you = clamp(0.45 + clamp((t - 1) * 0.12, -0.03, 0.03) + (rand() - 0.5) * 0.03, 0.3, 0.58); + const rival = clamp(0.45 + (rand() - 0.5) * 0.06, 0.3, 0.6); + const others = Math.max(0.05, 1 - you - rival); + const sum = you + rival + others; + return { + code: `V${i + 1}`, + name, + voters: Math.round(cast * shares[i]!), + lean: { you: you / sum, rival: rival / sum, others: others / sum }, + traits: blockTraits[i]!, + neighbors: i === 0 ? ["V2"] : i === 1 ? ["V1", "V3"] : ["V2"], + }; + }); + const surname = SURNAMES[Math.floor(rand() * SURNAMES.length)]!; + return { + scenarioId: `village:${village.code}`, + scenarioName: `${townName(world, vi)}${village.name}里長選舉`, + packId: "", + countyCode: pack.countyCode, + countyName: world.scenario.region.countyName, + area: `${townName(world, vi)}${village.name}`, + office: "里長", + you: m.you, + rival: fictional("rival", `${surname}里長`, 2, `連任多屆的現任里長`), + others: [], + towns, + money: 300, + rivalStyle: "ground", + rivalReal: false, + othersTop: 1, + }; +} + +/** 議員:把村里分成幾群(同一區的村里放一起,照代碼順序切,人數差不多) */ +function groupVillages(world: World, m: VillageModel, idx: readonly number[], groups: number): number[][] { + const byTown = new Map(); + for (const i of idx) byTown.set(world.pack.villages[i]!.townIndex, [...(byTown.get(world.pack.villages[i]!.townIndex) ?? []), i]); + const ordered = [...byTown.values()].flatMap((list) => list.sort((a, b) => world.pack.villages[a]!.code.localeCompare(world.pack.villages[b]!.code))); + const total = ordered.reduce((a, i) => a + m.cast[i]!, 0); + const out: number[][] = []; + let acc = 0; + let cur: number[] = []; + for (const i of ordered) { + cur.push(i); + acc += m.cast[i]!; + if (acc >= (total * (out.length + 1)) / groups && out.length < groups - 1) { + out.push(cur); + cur = []; + } + } + if (cur.length) out.push(cur); + return out; +} + +/** 同一群村里的地圖代碼:區代碼(一區一塊)或 G1、G2…(村里分群) */ +export interface CouncilLayout { + setup: RogueSetup; + /** 村里 → 遊戲裡的區代碼(前端畫地圖用);一區一塊時是 null */ + groupOf: Record | null; +} + +export function councilSetup(world: World, candidateId: string, district: CouncilDistrict, seed: number, topology?: TopologyLike | null): CouncilLayout { + const m = villageModel(world, candidateId); + const { pack } = world; + const rand = rng(seed); + const want = new Set(district.villages); + const idx = pack.villages.map((v, i) => (want.has(v.code) ? i : -1)).filter((i) => i >= 0); + if (idx.length === 0) throw new LocalRaceError(`找不到${district.countyName}${district.district}的村里`); + const byTown = new Map(); + for (const i of idx) byTown.set(pack.villages[i]!.townIndex, [...(byTown.get(pack.villages[i]!.townIndex) ?? []), i]); + const perTown = byTown.size >= 3; + const groups = perTown ? [...byTown.values()] : groupVillages(world, m, idx, clamp(Math.round(idx.length / 10), 3, 6)); + const totalCast = groups.flat().reduce((a, i) => a + m.cast[i]!, 0) || 1; + // 最後一席的得票率;沒有資料就用 1 / (席次 + 1) 的一半 + const line = district.threshold?.share ?? 0.5 / (district.seats + 1); + const groupOf: Record = {}; + const towns: TownSetup[] = groups.map((g, k) => { + const code = perTown ? pack.towns[pack.villages[g[0]!]!.townIndex]!.code : `G${k + 1}`; + if (!perTown) for (const i of g) groupOf[pack.villages[i]!.code] = code; + const biggest = g.reduce((a, i) => (m.cast[i]! > m.cast[a]! ? i : a), g[0]!); + const name = perTown ? pack.towns[pack.villages[g[0]!]!.townIndex]!.name : `${pack.villages[biggest]!.name}一帶`; + const cast = g.reduce((a, i) => a + m.cast[i]!, 0); + const t = tilt(m, g); + // 你稍微落後最後一席;你的政黨在這群村里比較強,你就多一點 + const you = line * 0.93 * t * (1 + (rand() - 0.5) * 0.08); + const rival = line * 1.03 * (1 + (rand() - 0.5) * 0.08); + return { + code, + name, + voters: Math.round((district.validVotes * cast) / totalCast), + lean: { you, rival, others: Math.max(0, 1 - you - rival) }, + traits: traitsOf(world, m, g), + }; + }); + if (topology) { + const neighbors = groupNeighbors(topology, (code) => (perTown ? code.slice(0, 8) : (groupOf[code] ?? null))); + for (const t of towns) t.neighbors = neighbors.get(t.code) ?? []; + } + const surname = SURNAMES[Math.floor(rand() * SURNAMES.length)]!; + return { + groupOf: perTown ? null : groupOf, + setup: { + scenarioId: `council:${district.id}`, + scenarioName: `${district.countyName}議員${district.district}`, + packId: world.scenario.packId, + countyCode: pack.countyCode, + countyName: district.countyName, + area: `${district.countyName}${district.district}`, + office: "議員", + you: m.you, + rival: fictional("rival", `${surname}議員`, 2, `爭取連任的現任議員,上次差一點就落選`), + others: [], + towns, + money: 500, + rivalStyle: "balanced", + rivalReal: false, + // 多席次:只要贏過最後一席就當選 + othersTop: 0, + seats: district.seats, + threshold: line, + ...(perTown ? {} : { groups: groupOf }), + }, + }; +} + +/** 村里分群的相鄰關係:兩群的村里共用邊界(arc)就是鄰居 */ +function groupNeighbors(topology: TopologyLike, groupOf: (villageCode: string) => string | null): Map { + const byArc = new Map>(); + const ids = (arcs: unknown, out: number[] = []): number[] => { + if (typeof arcs === "number") out.push(arcs < 0 ? ~arcs : arcs); + else if (Array.isArray(arcs)) for (const a of arcs) ids(a, out); + return out; + }; + for (const g of topology.objects.villages?.geometries ?? []) { + const group = groupOf(String(g.properties?.code ?? "")); + if (!group) continue; + for (const arc of ids(g.arcs)) byArc.set(arc, (byArc.get(arc) ?? new Set()).add(group)); + } + const out = new Map>(); + for (const set of byArc.values()) { + if (set.size < 2) continue; + for (const a of set) for (const b of set) if (a !== b) out.set(a, (out.get(a) ?? new Set()).add(b)); + } + return new Map([...out].map(([k, v]) => [k, [...v].sort()])); +} + +/** 這個里所在的議員選區(區域選區,不含原住民選區) */ +/** 這個區只屬於一個(非原住民)議員選區時,回傳那個選區 */ +const soleDistrict = (districts: readonly CouncilDistrict[], town: string): CouncilDistrict | undefined => { + const hits = districts.filter((d) => !d.indigenous && d.towns.includes(town)); + return hits.length === 1 ? hits[0] : undefined; +}; + +/** + * 這個里在哪個議員選區:先找 2022 年的村里名單;2022 年以後才成立的里(例如桃園後來新設的里)不在名單裡, + * 就看它所在的區(里代碼前 8 碼)——整個區都屬於同一個選區時就是那個選區。 + */ +export const districtOfVillage = (districts: readonly CouncilDistrict[], village: string): CouncilDistrict | undefined => + districts.find((d) => !d.indigenous && d.villages.includes(village)) ?? soleDistrict(districts, village.slice(0, 8)); + +/** 把 2022 年以後才成立、所在的區整個屬於這個選區的里補進選區(村里名單是 2022 年的) */ +export function districtWithNewVillages(district: CouncilDistrict, districts: readonly CouncilDistrict[], villageCodes: readonly string[]): CouncilDistrict { + const known = new Set(districts.flatMap((d) => d.villages)); + const extra = villageCodes.filter((code) => !known.has(code) && soleDistrict(districts, code.slice(0, 8))?.id === district.id); + return extra.length ? { ...district, villages: [...district.villages, ...extra] } : district; +} + +/** 這個縣市的區和里(政治生涯里長關挑里用);選舉人數照里長關的算法(現在的 20 歲以上人口 × 0.9987) */ +export function villageList(world: World): { towns: { name: string; villages: { code: string; name: string; electors: number }[] }[] } { + const { pack } = world; + return { + towns: pack.towns.map((t, ti) => ({ + name: t.name, + villages: pack.villages + .map((v, vi) => ({ v, vi })) + .filter(({ v }) => v.townIndex === ti) + .map(({ v }) => ({ code: v.code, name: v.name, electors: Math.round(v.adults * ELECTORS_PER_ADULT) })) + .sort((a, b) => a.code.localeCompare(b.code)), + })), + }; +} diff --git a/backend/packages/rogue/src/mechanics.ts b/backend/packages/rogue/src/mechanics.ts new file mode 100644 index 0000000..972d332 --- /dev/null +++ b/backend/packages/rogue/src/mechanics.ts @@ -0,0 +1,120 @@ +import { EVENT_BY_ID, EVENTS, type EventDef } from "./data.ts"; +import { FLAG_LEAD, HAND_MAX, MOMENTUM_MAX, shuffle, townLead, type Owner, type RunState, type TownState } from "./state.ts"; + +/** 規則與對手 AI 共用的小工具:幕僚、每週事件、逆風難度、搬票、抽牌、插旗 */ +export const has = (s: RunState, advisor: string): boolean => s.advisors.includes(advisor); +export const momentumMax = (s: RunState): number => MOMENTUM_MAX + (has(s, "rally_king") ? 2 : 0); +export const eventOf = (s: RunState): EventDef => EVENT_BY_ID.get(s.event) ?? EVENTS[0]!; +/** 逆風難度達到第 n 級 */ +export const asc = (s: RunState, n: number): boolean => s.options.ascension >= n; + +/** 逆風難度每一級多的不利條件(docs/22) */ +export const ASCENSION: readonly string[] = [ + "標準難度", + "對手強度 +12%", + "起始資金 −40%", + "每週收入 −40%", + "下一站只有 2 個選項,選牌、選幕僚也只有 2 個", + "開局牌組多一張「人情包袱」", + "對手從第 4 週起每週多 1 個行動", + "對手開局聲勢 2", + "你的牌效果 −8%", + "黑函危機加倍,壞事件更常出現", + "開局落後 3 個百分點", +]; +export const MAX_ASCENSION = ASCENSION.length - 1; + +/** 每週事件對這些標籤的倍率(雙方都適用) */ +export function eventMult(s: RunState, tags: readonly string[]): number { + return (eventOf(s).mods ?? []).filter((m) => tags.includes(m.tag)).reduce((a, m) => a * m.mult, 1); +} + +export function addMomentum(s: RunState, n: number): void { + s.momentum = Math.max(0, Math.min(momentumMax(s), s.momentum + n)); +} +export function addRivalMomentum(s: RunState, n: number): void { + s.rivalMomentum = Math.max(0, Math.min(MOMENTUM_MAX, s.rivalMomentum + n)); +} + +/** 從還沒表態的人拉票;拉完了才從對手那邊搶(搶的效率只有一半)。回傳實際加的票 */ +export function moveVotes(t: TownState, n: number, side: "you" | "rival"): number { + if (n <= 0) return 0; + const fromUndecided = Math.min(n, t.undecided); + t.undecided -= fromUndecided; + const other = side === "you" ? "rival" : "you"; + const stolen = Math.min(t[other], (n - fromUndecided) * 0.5); + t[other] -= stolen; + t[side] += fromUndecided + stolen; + return fromUndecided + stolen; +} + +/** 支持者被拉走、變回還沒表態。回傳實際少的票 */ +export function loseVotes(t: TownState, n: number, side: "you" | "rival"): number { + const lost = Math.min(Math.max(0, n), t[side]); + t[side] -= lost; + t.undecided += lost; + return lost; +} + +/** 依權重把一個總數分到各區 */ +export function spread(towns: readonly TownState[], total: number, weight: (t: TownState) => number): number[] { + const w = towns.map(weight); + const sum = w.reduce((a, b) => a + b, 0) || 1; + return w.map((x) => (total * x) / sum); +} + +/** 全市加票(正)或掉票(負),依人口分配;回傳實際變化 */ +export function cityVotes(s: RunState, total: number, side: "you" | "rival" = "you", weight?: (t: TownState) => number): number { + if (total >= 0) { + const parts = spread(s.towns, total, weight ?? ((t) => t.voters)); + return s.towns.reduce((a, t, i) => a + moveVotes(t, parts[i]!, side), 0); + } + const parts = spread(s.towns, -total, (t) => t[side]); + return -s.towns.reduce((a, t, i) => a + loseVotes(t, parts[i]!, side), 0); +} + +/** 抽牌:抽完就把棄牌堆洗回來;手牌最多 HAND_MAX 張 */ +export function drawCards(s: RunState, n: number): void { + for (let i = 0; i < n && s.hand.length < HAND_MAX; i++) { + if (s.draw.length === 0) { + s.draw = shuffle(s, s.discard); + s.discard = []; + } + const next = s.draw.shift(); + if (!next) return; + s.hand.push(next); + } +} + +export const flagOwner = (t: TownState): Owner => { + const lead = townLead(t); + return lead >= FLAG_LEAD ? "you" : lead <= -FLAG_LEAD ? "rival" : null; +}; + +/** + * 重新插旗。把對手的旗翻過來(中間掉成沒人插旗也算):你的聲勢 +1;你的旗被翻走:對手聲勢 +1。 + * 回傳這次翻過來的區(給記錄用) + */ +export function updateFlags(s: RunState): { gained: TownState[]; lost: TownState[] } { + const gained: TownState[] = []; + const lost: TownState[] = []; + for (const t of s.towns) { + const next = flagOwner(t); + t.flag = next; + if (!next || next === t.was) continue; + if (t.was === "rival") gained.push(t); + if (t.was === "you") lost.push(t); + t.was = next; + } + if (gained.length) { + addMomentum(s, 1); + s.stats.flips += gained.length; + s.lastWeek.flips += gained.length; + for (const t of gained) s.log.push({ side: "you", text: `翻轉!你在${t.name}插旗,聲勢 +1`, town: t.code, votes: 0 }); + } + if (lost.length) { + addRivalMomentum(s, 1); + for (const t of lost) s.log.push({ side: "rival", text: `${s.setup.rival.name}在${t.name}翻盤插旗`, town: t.code, votes: 0 }); + } + return { gained, lost }; +} diff --git a/backend/packages/rogue/src/meta.ts b/backend/packages/rogue/src/meta.ts new file mode 100644 index 0000000..81981e9 --- /dev/null +++ b/backend/packages/rogue/src/meta.ts @@ -0,0 +1,121 @@ +import type { CareerAbilities, IslandBuilding, IslandPerk, PolicySpec, RogueTrait } from "@election2026/protocol"; +import type { CardDef } from "./data.ts"; + +/** + * 跨局成長(docs/23):政策島的建築、政治生涯的角色能力、政策工坊寫的政策。 + * 進度存在玩家的瀏覽器,開局時帶給伺服器;伺服器只檢查範圍、照這裡的規則套用。 + */ + +export const BUILDINGS: readonly (IslandBuilding & { perk: string })[] = [ + { id: "hub", name: "交通樞紐", art: "sound_truck", perk: "前 N 週體力 +1", levels: ["第 1 週體力 +1", "前 2 週體力 +1", "前 3 週體力 +1"], cost: [3, 6, 10] }, + { id: "care", name: "長照中心", art: "market_visit", perk: "長輩多的區 +8%/級", levels: ["長輩多的區 +8%", "長輩多的區 +16%", "長輩多的區 +24%"], cost: [3, 6, 10] }, + { id: "nursery", name: "托育園", art: "forum", perk: "年輕人多的區 +8%/級", levels: ["年輕人多的區 +8%", "年輕人多的區 +16%", "年輕人多的區 +24%"], cost: [3, 6, 10] }, + { id: "techpark", name: "科技園區", art: "online_ad", perk: "網路牌 +10%/級", levels: ["網路牌 +10%", "網路牌 +20%", "網路牌 +30%"], cost: [3, 6, 10] }, + { id: "nightmarket", name: "觀光夜市", art: "night_market", perk: "市場、夜市牌 +10%/級,開局資金 +50 萬/級", levels: ["市場夜市牌 +10%、資金 +50 萬", "+20%、+100 萬", "+30%、+150 萬"], cost: [3, 6, 10] }, + { id: "plaza", name: "宮廟廣場", art: "temple_visit", perk: "宮廟牌 +10%/級", levels: ["宮廟牌 +10%", "宮廟牌 +20%", "宮廟牌 +30%"], cost: [3, 6, 10] }, + { id: "media", name: "媒體中心", art: "tv_ad", perk: "媒體牌 +6%/級", levels: ["媒體牌 +6%", "媒體牌 +12%", "媒體牌 +18%"], cost: [3, 6, 10] }, + { id: "volunteer", name: "志工之家", art: "recruit_volunteers", perk: "第 1 週多抽 N 張", levels: ["第 1 週多抽 1 張", "多抽 2 張", "多抽 3 張"], cost: [3, 6, 10] }, + { id: "academy", name: "競選學院", art: "study", perk: "開局 N 張牌升級", levels: ["開局 1 張牌升級", "開局 2 張牌升級", "開局 3 張牌升級"], cost: [4, 8, 12] }, + { id: "vault", name: "競選金庫", art: "party_fund", perk: "開局資金 +150 萬/級", levels: ["開局資金 +150 萬", "+300 萬", "+450 萬"], cost: [3, 6, 10] }, + { id: "hq", name: "競選總部", art: "open_office", perk: "開局聲勢 +1/級", levels: ["開局聲勢 +1", "開局聲勢 +2", "開局聲勢 +3"], cost: [4, 8, 12] }, + { id: "library", name: "政策研究院", art: "white_paper", perk: "每局可以多帶 1 份政策", levels: ["可以帶 2 份政策", "可以帶 3 份政策", "所有政策牌 +15%"], cost: [3, 6, 10] }, +]; + +export const BUILDING_BY_ID = new Map(BUILDINGS.map((b) => [b.id, b])); + +/** 政策島的建築等級:只收認得的 id,等級夾在 1–3 */ +export function perkLevels(perks: readonly IslandPerk[]): Record { + const out: Record = {}; + for (const p of perks) if (BUILDING_BY_ID.has(p.id)) out[p.id] = Math.max(1, Math.min(3, p.level)); + return out; +} + +/** 每局可以帶幾份政策:基本 1 份,政策研究院 1、2 級各多 1 份 */ +export const policySlots = (perks: Record): number => 1 + Math.min(2, perks.library ?? 0); + +export const ABILITY_LABELS: Record = { + eloquence: "口才", + organization: "組織", + media: "媒體", + finance: "財務", + integrity: "清廉", +}; + +/** 角色能力的效果說明(畫面用) */ +export const ABILITY_EFFECTS: Record = { + eloquence: "記者會、座談類的牌每級 +4%;3 級起辯論多一張論點,5 級看得出最好的論點", + organization: "樁腳每級 +10%、地面牌每級 +3%", + media: "媒體牌每級 +5%、爆紅機率每級 +3%", + finance: "開局資金每級 +80 萬、每週收入每級 +15 萬", + integrity: "黑函損失每級 −12%、記者追問掉票每級 −15%", +}; + +// ── 政策工坊 ── + +const TARGET: Record = { + old: { trait: "old", label: "長輩" }, + young: { trait: "young", label: "年輕人" }, + workers: { trait: "dense", label: "上班族" }, + farmers: { trait: "rural", label: "農漁民" }, + hakka: { trait: "hakka", label: "客家鄉親" }, + believers: { trait: "temples", label: "信眾" }, + families: { trait: "young", label: "育兒家庭" }, +}; + +export const POLICY_LABELS = { + target: Object.fromEntries(Object.entries(TARGET).map(([k, v]) => [k, v.label])) as Record, + method: { subsidy: "補助", build: "蓋建設", law: "修法", tax_cut: "減稅" } as Record, + funding: { tax: "加稅", debt: "舉債", cut: "刪別的預算", invest: "招商" } as Record, +}; + +/** + * 政策落地(docs/23):每種政策對象在島上有一棟「家」,那棟蓋越高,這份政策的牌越強(每級 +10%)。 + * 畫面(政策工坊、小島)照這張表顯示政策落在哪一棟。 + */ +export const POLICY_HOME: Record = { + old: "care", + young: "techpark", + workers: "hub", + farmers: "nightmarket", + hakka: "plaza", + believers: "plaza", + families: "nursery", +}; +export const POLICY_HOME_STEP = 0.1; + +/** 政策卡 id 裡的對象(不是政策卡回 null) */ +export const policyTargetOf = (id: string): PolicySpec["target"] | null => { + const m = /^policy:\d:(\w+):/.exec(id); + return m && m[1]! in TARGET ? (m[1] as PolicySpec["target"]) : null; +}; + +/** 政策卡的 id:policy:序號:對象:做法:財源(牌名另外存在這一局,見 RunState.policyNames) */ +export const policyCardId = (i: number, p: PolicySpec): string => `policy:${i}:${p.target}:${p.method}:${p.funding}`; + +const FUNDING_MULT: Record = { tax: 1, debt: 0.9, cut: 1.15, invest: 0.9 }; + +/** 由政策卡的 id 算出這張牌;格式不對回 undefined */ +export function policyCardDef(id: string): CardDef | undefined { + const m = /^policy:(\d):(\w+):(\w+):(\w+)$/.exec(id); + if (!m) return undefined; + const [, , target, method, funding] = m as unknown as [string, string, PolicySpec["target"], PolicySpec["method"], PolicySpec["funding"]]; + const t = TARGET[target]; + const fm = FUNDING_MULT[funding]; + if (!t || fm === undefined || !(method in POLICY_LABELS.method)) return undefined; + const n = (x: number) => Math.round((x * fm) / 10) * 10; + const name = `${t.label}${POLICY_LABELS.method[method]}政策`; + const side: CardDef["side"] = funding === "tax" ? { curse: "reporter" } : funding === "cut" ? { backlash: 350 } : funding === "invest" ? { money: 100 } : undefined; + const moneyMult = funding === "tax" ? 0.5 : funding === "debt" ? 0 : 1; + const base = { id, name, rarity: "rare" as const, side }; + const cost = (c: number) => Math.round(c * moneyMult); + switch (method) { + case "subsidy": + return { ...base, art: "small_donations", cost: 1, money: cost(150), tags: ["ground", "policy"], target: "town", effect: { kind: "gain", base: n(2070) }, bonus: [{ trait: t.trait, mult: 1.8 }], text: `該區 +{n};${t.label}多的區 ×1.8` }; + case "build": + return { ...base, art: "open_office", cost: 2, money: cost(250), tags: ["org", "policy"], target: "town", effect: { kind: "office", perWeek: n(690) }, bonus: [{ trait: t.trait, mult: 1.5 }], text: `該區現在和之後每週 +{n};${t.label}多的區 ×1.5` }; + case "law": + return { ...base, art: "white_paper", cost: 1, money: 0, tags: ["press", "media", "policy"], target: "city", effect: { kind: "city", base: n(2070), weight: t.trait, momentum: 1 }, text: `全市 +{n},${t.label}多的區分到較多,聲勢 +1` }; + case "tax_cut": + return { ...base, art: "announce_policy", cost: 1, money: 0, tags: ["media", "policy"], target: "city", effect: { kind: "city", base: n(2990), weight: t.trait }, text: `全市 +{n},${t.label}多的區分到較多` }; + } +} diff --git a/backend/packages/rogue/src/rival.ts b/backend/packages/rogue/src/rival.ts new file mode 100644 index 0000000..f43a15b --- /dev/null +++ b/backend/packages/rogue/src/rival.ts @@ -0,0 +1,180 @@ +import type { RogueIntentKind } from "@election2026/protocol"; +import { INTENT_BASE, INTENT_LABELS, INTENT_TAGS } from "./data.ts"; +import { addRivalMomentum, asc, cityVotes, eventMult, eventOf, has, loseVotes, moveVotes, spread } from "./mechanics.ts"; +import { newCard, pickWeighted, round10, type Intent, type RivalStyle, type RunState, type TownState } from "./state.ts"; + +/** + * 對手 AI(docs/21、22):每週一開始就把要做的事亮在地圖上(像《殺戮尖塔》的敵人意圖),週末才執行。 + * 只看公開的資訊:各區支持度、你上週把牌打在哪裡。越接近投票日行動越多、越強。 + * 對手是真實人物時,行動名稱是中性的(批評你的政見、到你的票倉拉票),不寫抹黑、爆料。 + */ + +/** 對手整體強度(平衡報告調整用) */ +export const RIVAL_POWER = 0.92; +/** 每週變強多少 */ +export const RIVAL_GROWTH = 0.035; +/** 第 5 週預告、第 7 週執行的大型造勢 */ +export const BIG_RALLY_WEEK = 7; +export const BIG_RALLY_MULT = 2; + +/** 對手性格:開局亮出來,影響出招比例與被動能力 */ +export const RIVAL_TRAITS: Record = { + balanced: { name: "後發制人", text: "前期比較弱,每週變強的幅度比較大" }, + ground: { name: "組織戰", text: "佈樁的盾 ×1.4,常常跑基層" }, + air: { name: "空戰", text: "電視、網路廣告效果 ×1.2" }, +}; + +const STYLE_WEIGHTS: Record> = { + balanced: { canvass: 3, rally: 1.5, tv: 1.5, online: 1.2, attack: 1, smear: 0.8, stake: 1 }, + ground: { canvass: 4, rally: 2, tv: 0.8, online: 0.6, attack: 0.8, smear: 1, stake: 1.5 }, + air: { canvass: 2, rally: 1, tv: 2.5, online: 2, attack: 1.2, smear: 0.6, stake: 0.6 }, +}; + +/** 每週最多幾個同一類的行動 */ +const LIMITS: Partial> = { rally: 1, tv: 1, online: 1, attack: 1, smear: 1, stake: 1 }; + +export const intentsThisWeek = (s: RunState): number => (s.week <= 2 ? 2 : s.week < s.totalWeeks ? 3 : 4) + (asc(s, 6) && s.week >= 4 ? 1 : 0); + +export function rivalPower(s: RunState): number { + const style = s.setup.rivalStyle; + const growth = style === "balanced" ? 0.05 : RIVAL_GROWTH; + const start = style === "balanced" ? 0.92 : 1; + // 新手教學的老里長比較弱,照提示打就會贏 + const tutorial = s.options.tutorial ? 0.4 : 1; + return RIVAL_POWER * start * tutorial * s.scale * (1 + growth * (s.week - 1)) * (1 + 0.08 * s.rivalMomentum) * (eventOf(s).rival ?? 1) * (asc(s, 1) ? 1.12 : 1); +} + +/** 對手性格帶來的倍率 */ +const styleMult = (s: RunState, kind: RogueIntentKind): number => { + const style = s.setup.rivalStyle; + if (style === "ground" && kind === "stake") return 1.4; + if (style === "air" && (kind === "tv" || kind === "online")) return 1.2; + return 1; +}; + +const closeness = (t: TownState): number => 1 - Math.abs(t.you - t.rival) / (t.you + t.rival || 1); + +function chooseTown(s: RunState, kind: RogueIntentKind, used: ReadonlySet): TownState { + const open = s.towns.filter((t) => !used.has(t.code)); + const pool = open.length ? open : s.towns; + const focus = (t: TownState) => (s.lastFocus.includes(t.code) ? 1 : 0); + const weight = (t: TownState): number => { + if (kind === "smear") return t.you * (1 + focus(t)) * (t.flag === "you" ? 1.5 : 1); + if (kind === "stake") return t.voters * (0.5 + closeness(t)) * (1 + 2 * focus(t)); + return t.voters * (0.5 + closeness(t)) * (1 + 0.8 * focus(t)); + }; + return pickWeighted(s, pool, weight) ?? pool[0]!; +} + +function intentAmount(s: RunState, kind: RogueIntentKind, town: TownState | null): number { + // 打在某一區的行動和你的牌一樣,人多的區效果大 + const reach = town && kind !== "stake" ? town.reach : 1; + return round10(INTENT_BASE[kind] * rivalPower(s) * reach * eventMult(s, INTENT_TAGS[kind]) * styleMult(s, kind)); +} + +export function planIntents(s: RunState): Intent[] { + const weights = STYLE_WEIGHTS[s.setup.rivalStyle]; + const count = new Map(); + const used = new Set(); + const out: Intent[] = []; + // 預告過的大型造勢這週執行 + if (s.nextBig && s.week === BIG_RALLY_WEEK) { + const t = s.towns.find((x) => x.code === s.nextBig!.town); + out.push({ ...s.nextBig, id: `i${s.week}-big`, amount: round10(intentAmount(s, "rally", t ?? null) * BIG_RALLY_MULT) }); + count.set("rally", 1); + if (t) used.add(t.code); + s.nextBig = null; + } + const n = intentsThisWeek(s); + for (let k = out.length; k < n; k++) { + const kinds = (Object.keys(weights) as RogueIntentKind[]).filter((kind) => { + if ((count.get(kind) ?? 0) >= (LIMITS[kind] ?? 9)) return false; + // 第一週還沒什麼好批評的 + if ((kind === "attack" || kind === "smear") && s.week < 2) return false; + return true; + }); + const kind = pickWeighted(s, kinds, (x) => weights[x])!; + count.set(kind, (count.get(kind) ?? 0) + 1); + const city = kind === "tv" || kind === "online" || kind === "attack"; + const town = city ? null : chooseTown(s, kind, used); + if (town) used.add(town.code); + out.push({ id: `i${s.week}-${k}`, kind, town: town?.code ?? null, amount: intentAmount(s, kind, town), cut: 1 }); + } + return out; +} + +/** 第 5 週:預告第 7 週的大型造勢(選人多、選情接近的區) */ +export function announceBigRally(s: RunState): void { + if (s.week !== BIG_RALLY_WEEK - 2 || s.totalWeeks < BIG_RALLY_WEEK) return; + const town = pickWeighted(s, s.towns, (t) => t.voters * closeness(t) ** 2) ?? s.towns[0]!; + s.nextBig = { id: "big", kind: "rally", town: town.code, amount: round10(intentAmount(s, "rally", town) * BIG_RALLY_MULT * (1 + RIVAL_GROWTH * 2)), cut: 1, big: true }; +} + +/** 對手的佈樁一宣布就生效:擋你這週在那區的牌 */ +export function applyRivalShields(s: RunState): void { + for (const i of s.intents) { + if (i.kind !== "stake") continue; + const t = s.towns.find((x) => x.code === i.town); + if (t) t.rivalShield += i.amount; + } +} + +export const intentLabel = (s: RunState, i: Intent): string => { + const town = s.towns.find((t) => t.code === i.town)?.name; + return `${i.big ? "大型" : ""}${INTENT_LABELS[i.kind]}${town ? `・${town}` : "・全市"}`; +}; + +/** 幕僚讓對手這個行動打折的倍率:批評遇到公關高手減半、你插旗的區有鐵票部隊減半 */ +export function intentDamp(s: RunState, i: Intent): number { + if (i.kind === "attack") return has(s, "spin_doctor") ? 0.5 : 1; + const t = s.towns.find((x) => x.code === i.town); + return t && t.flag === "you" && has(s, "iron_base") ? 0.5 : 1; +} + +/** 週末:對手照意圖行動。你在那區的樁腳先擋;批評遇到「公關高手」減半,還會塞「記者追問」 */ +export function executeIntent(s: RunState, i: Intent): void { + const t = s.towns.find((x) => x.code === i.town) ?? null; + const amount = i.amount * i.cut * intentDamp(s, i); + const name = s.setup.rival.name; + const label = intentLabel(s, i); + if (i.kind === "stake") return; + // 打對台、澄清、事實查核讓對手少拉的票:先列出來,攻守的效果才看得到 + const prevented = i.amount * (1 - i.cut) * intentDamp(s, i); + if (prevented >= 1) { + const how = i.kind === "attack" ? (i.cut === 0 ? "批評被你完全擋下" : "批評被你擋掉一部分") : "被你打對台"; + s.log.push({ side: "you", text: `${name}${label}${how}`, town: i.town, votes: 0, blocked: Math.round(prevented) }); + } + if (i.kind === "tv" || i.kind === "online") { + const parts = spread(s.towns, amount, (x) => x.voters * (x.traits.includes(i.kind === "tv" ? "old" : "young") ? 1.5 : 1)); + const net = s.towns.reduce((a, x, k) => a + moveVotes(x, parts[k]!, "rival"), 0); + s.log.push({ side: "rival", text: `${name}${label}`, town: null, votes: -Math.round(net) }); + return; + } + if (i.kind === "attack") { + if (amount <= 0) { + s.log.push({ side: "you", text: `${name}${label}:已經被你擋下`, town: null, votes: 0 }); + return; + } + const lost = cityVotes(s, -amount); + s.log.push({ side: "rival", text: `${name}${label}`, town: null, votes: Math.round(lost) }); + s.discard.push(newCard(s, "reporter")); + s.log.push({ side: "system", text: "記者追問塞進你的牌組", town: null, votes: 0 }); + s.lastWeek.attacked = true; + return; + } + if (!t) return; + const blocked = Math.min(t.shield, amount); + t.shield -= blocked; + const rest = amount - blocked; + if (blocked > 0) s.log.push({ side: "you", text: `樁腳擋下${name}在${t.name}的${INTENT_LABELS[i.kind]}`, town: t.code, votes: 0, blocked: Math.round(blocked) }); + if (i.kind === "smear") { + // 到你的票倉拉票:你的支持者被拉走一部分(變回還沒表態),對手拿到一半 + const lost = loseVotes(t, rest, "you"); + moveVotes(t, lost * 0.5, "rival"); + s.log.push({ side: "rival", text: `${name}${label}`, town: t.code, votes: -Math.round(lost) }); + return; + } + const net = moveVotes(t, rest, "rival"); + s.log.push({ side: "rival", text: `${name}${label}`, town: t.code, votes: -Math.round(net) }); + if (i.kind === "rally") addRivalMomentum(s, i.big ? 3 : 2); +} diff --git a/backend/packages/rogue/src/route.ts b/backend/packages/rogue/src/route.ts new file mode 100644 index 0000000..461a20f --- /dev/null +++ b/backend/packages/rogue/src/route.ts @@ -0,0 +1,291 @@ +import { ENCOUNTERS } from "@election2026/content"; +import type { EncounterDef } from "@election2026/engine"; +import { ADVISORS } from "./advisors.ts"; +import { STOP_EVENTS, STOP_EVENT_BY_ID } from "./content.ts"; +import { REWARD_CARDS, cardDef, upgradable } from "./data.ts"; +import { addMomentum, asc, cityVotes, has, moveVotes } from "./mechanics.ts"; +import { applyOutcome, choiceBlocked, rollChoice } from "./scenes.ts"; +import type { MiniGameKind } from "@election2026/protocol"; +import { MAX_ADVISORS, gainCard, newCard, pickWeighted, rand, shuffle, type RunState, type ShopItem, type Stop, type StopKind } from "./state.ts"; + +/** + * 每週結束後的「下一站」(docs/22,像《殺戮尖塔》的地圖):三選一,再進那一站做選擇。 + * 也可以都不選,改拿 SKIP_MONEY 萬。 + */ + +export const SKIP_MONEY = 150; +/** 商店價格(萬元) */ +export const PRICES = { common: 120, rare: 220, advisor: 300, remove: 100 } as const; +/** 深入基層:三個遭遇的總分(−6 到 +6)決定那區加多少票 */ +export const ENCOUNTER_BASE = 1380; +export const ENCOUNTER_STEP = 0.3; +/** + * 選戰小遊戲(docs/23):玩完回報 0–100 分,70 分算「玩得不錯」。 + * 掃街握手:那區加票;造勢:聲勢 +0/1/2 加全市少量票;看板卡位:那區每週多一點票(據點)。 + */ +export const MINIGAME = { handshake: 2300, handshakeHot: 90, rallyVotes: 600, rallyStep: [40, 80], billboardBase: 250, billboardStep: 6, good: 70 } as const; +export const MINIGAME_INFO: Record = { + handshake: { title: "掃街握手", text: "人群裡有人舉手,時間內握越多手越好;那一區加票" }, + rally: { title: "造勢喊凍蒜", text: "跟著鼓點喊凍蒜,拍子越準聲勢越高" }, + billboard: { title: "看板卡位", text: "把看板推到人流最多的路口;那一區之後每週多一點票" }, +}; + +export const STOP_LABELS: Record = { + card: { title: "拜會地方", text: "三選一,加一張新牌" }, + advisor: { title: "招募幕僚", text: "三選一,加一位幕僚" }, + upgrade: { title: "黨部研習", text: "升級一張牌(+版)" }, + remove: { title: "整頓行程", text: "從牌組拿掉一張牌" }, + shop: { title: "競選物資行", text: "用資金買牌、幕僚、刪牌" }, + encounter: { title: "深入基層", text: "親自拜票,連遇三個人" }, + event: { title: "地方抉擇", text: "有代價、有風險的選擇" }, + minigame: { title: "選戰小遊戲", text: "掃街、造勢或看板卡位,玩得好就加成" }, +}; + +const deckOf = (s: RunState) => [...s.draw, ...s.discard, ...s.hand]; +const optionCount = (s: RunState) => (asc(s, 4) ? 2 : 3); +const advisorOpen = (s: RunState) => s.advisors.length < MAX_ADVISORS; + +/** 這週結束後可以去的下一站 */ +export function makeRoute(s: RunState): StopKind[] { + const out: StopKind[] = []; + const must: StopKind = s.week % 2 === 0 && advisorOpen(s) ? "advisor" : "card"; + out.push(must); + const weights: Record = { + card: must === "card" ? 0 : 2.5, + advisor: must === "advisor" || !advisorOpen(s) ? 0 : 0.6, + upgrade: 1.5, + remove: deckOf(s).length > 8 ? 1 : 0, + shop: s.money >= 200 ? 1.3 : 0, + encounter: 1.2, + event: STOP_EVENTS.some((e) => !s.seen.includes(e.id)) ? 1.3 : 0, + minigame: s.options.tutorial ? 0 : 1.1, + }; + while (out.length < optionCount(s)) { + const kinds = (Object.keys(weights) as StopKind[]).filter((k) => !out.includes(k)); + const k = pickWeighted(s, kinds, (x) => weights[x]); + if (!k) break; + out.push(k); + } + return shuffle(s, out); +} + +function cardOptions(s: RunState, n: number): string[] { + const options: string[] = []; + const pool = REWARD_CARDS.filter((c) => c.effect.kind !== "kneel" || s.week >= s.totalWeeks - 3); + while (options.length < n) { + const c = pickWeighted( + s, + pool.filter((x) => !options.includes(x.id)), + (x) => (x.rarity === "rare" ? 1 : 3), + ); + if (!c) break; + options.push(c.id); + } + return options; +} + +/** 選情最接近的大區(深入基層、小遊戲去那裡) */ +const contestedTown = (s: RunState) => pickWeighted(s, s.towns, (t) => t.voters * (1 - Math.abs(t.you - t.rival) / (t.you + t.rival || 1)) ** 3) ?? s.towns[0]!; + +const encounterPool = (): readonly EncounterDef[] => ENCOUNTERS.filter((e) => e.activities.some((a) => ["*", "market_visit", "night_market", "street_interview", "door_to_door", "pilgrimage"].includes(a))); + +function makeStop(s: RunState, kind: StopKind): Stop { + switch (kind) { + case "card": + return { kind, options: cardOptions(s, optionCount(s)) }; + case "advisor": + return { kind, options: shuffle(s, ADVISORS.filter((a) => !has(s, a.id))).slice(0, optionCount(s)).map((a) => a.id) }; + case "upgrade": + case "remove": + return { kind }; + case "shop": { + const items: ShopItem[] = cardOptions(s, 3).map((id) => ({ kind: "card", id, price: cardDef(id)!.rarity === "rare" ? PRICES.rare : PRICES.common, sold: false })); + const advisor = advisorOpen(s) ? shuffle(s, ADVISORS.filter((a) => !has(s, a.id)))[0] : undefined; + if (advisor) items.push({ kind: "advisor", id: advisor.id, price: PRICES.advisor, sold: false }); + items.push({ kind: "remove", id: "remove", price: PRICES.remove, sold: false }); + return { kind, items }; + } + case "encounter": { + const town = contestedTown(s); + return { kind, town: town.code, encounters: shuffle(s, encounterPool()).slice(0, 3).map((e) => e.id), step: 0, score: 0, notes: [] }; + } + case "minigame": { + const game = (["handshake", "rally", "billboard"] as const)[Math.floor(rand(s) * 3)]!; + // 難度:第 1 週 0.1,越後面越難,最高 0.9 + const level = Math.min(0.9, 0.1 + (0.8 * (s.week - 1)) / Math.max(1, s.totalWeeks - 2)); + return { kind, game, town: game === "rally" ? null : contestedTown(s).code, level: Math.round(level * 100) / 100, seed: Math.floor(rand(s) * 2 ** 31) }; + } + case "event": { + // 選了這扇門才算看過(pickRoute),沒選的之後還可能出現 + const pool = STOP_EVENTS.filter((e) => !s.seen.includes(e.id)); + const e = pool[Math.floor(rand(s) * pool.length)] ?? STOP_EVENTS[0]!; + return { kind, id: e.id }; + } + } +} + +/** 這週結束:排好三扇門,門裡的內容也先備好(畫面直接攤開,一次點選就拿到) */ +export function prepareRoute(s: RunState): void { + s.route = makeRoute(s); + s.routeStops = s.route.map((k) => makeStop(s, k)); +} + +/** 拜會地方、招募幕僚、地方抉擇:在門上直接選,不用再進門 */ +export const pickInDoor = (kind: StopKind): boolean => kind === "card" || kind === "advisor" || kind === "event"; + +/** + * 選下一站;skip 是不去,改拿資金。option:門上直接選的選項(拜會地方、招募幕僚、地方抉擇),一次完成。 + * done 之後由呼叫的人開始下一週 + */ +export function pickRoute(s: RunState, pick: number | "skip", option?: number): { error: string } | { done: boolean } { + if (!s.route) return { error: "現在沒有下一站可以選" }; + if (pick === "skip") { + s.money += SKIP_MONEY; + s.log.push({ side: "system", text: `回總部休息:資金 +${SKIP_MONEY} 萬`, town: null, votes: 0 }); + s.route = null; + s.routeStops = null; + return { done: true }; + } + const kind = s.route[pick]; + if (!kind) return { error: "沒有這一站" }; + const stop = s.routeStops?.[pick] ?? makeStop(s, kind); + s.route = null; + s.routeStops = null; + if (stop.kind === "event") s.seen.push(stop.id); + s.stop = stop; + s.phase = "stop"; + if (option !== undefined && pickInDoor(kind)) return pickStop(s, option, null); + return { done: false }; +} + +const removeCard = (s: RunState, uid: string): boolean => { + for (const pile of [s.draw, s.discard, s.hand]) { + const i = pile.findIndex((c) => c.uid === uid); + if (i >= 0) { + pile.splice(i, 1); + s.stats.removed += 1; + return true; + } + } + return false; +}; + +export const encounterById = (id: string): EncounterDef | undefined => ENCOUNTERS.find((e) => e.id === id); + +/** 在這一站做選擇。pick 是第幾個選項;target 是要升級、刪掉的牌(uid)。done 之後開始下一週 */ +export function pickStop(s: RunState, pick: number | "skip", target: string | null): { error: string } | { done: boolean } { + const stop = s.stop; + if (!stop) return { error: "現在不在任何一站" }; + if (pick === "skip" && stop.kind !== "encounter") { + s.stop = null; + return { done: true }; + } + switch (stop.kind) { + case "card": { + const id = stop.options[pick as number]; + if (!id) return { error: "沒有這個選項" }; + gainCard(s, newCard(s, id)); + s.log.push({ side: "you", text: `牌組加入「${cardDef(id)!.name}」,下週一定會抽到`, town: null, votes: 0 }); + break; + } + case "advisor": { + const id = stop.options[pick as number]; + if (!id || !advisorOpen(s)) return { error: "沒有這個選項" }; + s.advisors.push(id); + break; + } + case "upgrade": { + const c = deckOf(s).find((x) => x.uid === target); + if (!c || !upgradable(c.id, c.up)) return { error: "選一張可以升級的牌" }; + c.up = true; + s.stats.upgraded += 1; + s.log.push({ side: "you", text: `「${cardDef(c.id)!.name}」升級了`, town: null, votes: 0 }); + break; + } + case "remove": { + if (!target || !removeCard(s, target)) return { error: "選一張要拿掉的牌" }; + break; + } + case "shop": { + const item = stop.items[pick as number]; + if (!item || item.sold) return { error: "沒有這個商品" }; + if (s.money < item.price) return { error: "資金不夠" }; + if (item.kind === "remove" && (!target || !removeCard(s, target))) return { error: "選一張要拿掉的牌" }; + if (item.kind === "advisor" && !advisorOpen(s)) return { error: "幕僚已經滿了" }; + s.money -= item.price; + item.sold = true; + s.stats.bought += 1; + if (item.kind === "card") gainCard(s, newCard(s, item.id)); + if (item.kind === "advisor") s.advisors.push(item.id); + // 商店可以一直買,按「離開」才結束 + return { done: false }; + } + case "encounter": { + const town = s.towns.find((t) => t.code === stop.town)!; + if (stop.step >= stop.encounters.length) { + s.stop = null; + return { done: true }; + } + const e = encounterById(stop.encounters[stop.step]!); + const option = e?.options[pick === "skip" ? -1 : pick]; + if (!e || !option) return { error: "沒有這個選項" }; + const result = option.roll ? (rand(s) < option.roll.chance ? option.roll.success : option.roll.failure) : option; + stop.score += result.score; + stop.notes.push(fillVars(result.text, s, town.name)); + stop.step += 1; + if (stop.step >= stop.encounters.length) { + const mult = Math.max(0, 1 + ENCOUNTER_STEP * stop.score); + const net = moveVotes(town, ENCOUNTER_BASE * s.scale * town.reach * mult * (1 + 0.08 * s.momentum), "you"); + s.log.push({ side: "you", text: `深入基層・${town.name}(應對 ${stop.score >= 0 ? "+" : ""}${stop.score})`, town: town.code, votes: Math.round(net) }); + if (stop.score >= 4) { + addMomentum(s, 1); + s.log.push({ side: "you", text: "鄉親口耳相傳:聲勢 +1", town: town.code, votes: 0 }); + } + } + return { done: false }; + } + case "minigame": { + if (typeof pick !== "number" || pick < 0 || pick > 100) return { error: "小遊戲分數要在 0–100" }; + playMinigame(s, stop, Math.round(pick)); + break; + } + case "event": { + const def = STOP_EVENT_BY_ID.get(stop.id); + const choice = def?.choices[pick as number]; + if (!def || !choice) return { error: "沒有這個選項" }; + const blocked = choiceBlocked(s, choice); + if (blocked) return { error: blocked }; + applyOutcome(s, rollChoice(s, choice), "between"); + break; + } + } + s.stop = null; + return { done: true }; +} + +/** 小遊戲的分數換成效果 */ +function playMinigame(s: RunState, stop: Extract, score: number): void { + const info = MINIGAME_INFO[stop.game]; + const town = s.towns.find((t) => t.code === stop.town) ?? null; + s.stats.minigames = (s.stats.minigames ?? 0) + 1; + if (stop.game === "handshake" && town) { + const net = moveVotes(town, ((MINIGAME.handshake * s.scale * town.reach * score) / MINIGAME.good) * (1 + 0.08 * s.momentum), "you"); + s.log.push({ side: "you", text: `${info.title}・${town.name}(${score} 分)`, town: town.code, votes: Math.round(net) }); + if (score >= MINIGAME.handshakeHot) { + addMomentum(s, 1); + s.log.push({ side: "you", text: "握手握到手痠,照片上了地方新聞:聲勢 +1", town: town.code, votes: 0 }); + } + } else if (stop.game === "rally") { + const gain = MINIGAME.rallyStep.filter((x) => score >= x).length; + if (gain) addMomentum(s, gain); + const net = cityVotes(s, (MINIGAME.rallyVotes * s.scale * score) / 100); + s.log.push({ side: "you", text: `${info.title}(${score} 分)${gain ? `:聲勢 +${gain}` : ":台下反應普通"}`, town: null, votes: Math.round(net) }); + } else if (town) { + const perWeek = MINIGAME.billboardBase + MINIGAME.billboardStep * score; + town.office += perWeek; + s.log.push({ side: "you", text: `${info.title}・${town.name}(${score} 分):看板據點每週 +${Math.round(perWeek * s.scale * town.reach)} 票`, town: town.code, votes: 0 }); + } +} + +export const fillVars = (text: string, s: RunState, town: string): string => + text.replace(/\{town\}/g, town).replace(/\{temple\}/g, "地方大廟").replace(/\{name\}/g, s.setup.you.name).replace(/\{opponent\}/g, s.setup.rival.name); diff --git a/backend/packages/rogue/src/rules.ts b/backend/packages/rogue/src/rules.ts new file mode 100644 index 0000000..4cd5f5b --- /dev/null +++ b/backend/packages/rogue/src/rules.ts @@ -0,0 +1,404 @@ +import type { MiniGameKind, RogueResult } from "@election2026/protocol"; +import { ADVISOR_BY_ID } from "./advisors.ts"; +import type { IslandPerk, PolicySpec } from "@election2026/protocol"; +import { MINOR_REPORTER_MULT, ORIGINS, PARTY_LEAN_SHIFT, type Background } from "@election2026/protocol"; +import { CARD_BY_ID, cardDef, EVENTS, findCard, hasKeyword, REPORTER_PENALTY, STARTER_DECK, upgradable } from "./data.ts"; +import { perkLevels, policyCardId, policySlots } from "./meta.ts"; +import { asc, cityVotes, drawCards, eventOf, flagOwner, has, moveVotes, updateFlags } from "./mechanics.ts"; +import { featsOf } from "./feats.ts"; +import { announceBigRally, applyRivalShields, executeIntent, planIntents } from "./rival.ts"; +import { pickRoute, pickStop, prepareRoute } from "./route.ts"; +import { applyUltimate, chargeUltimate, secondChance } from "./ultimate.ts"; +import { committedShares, resolveScene, sceneFor } from "./scenes.ts"; +import { + BASE_ENERGY, + FLAG_INCOME, + HAND_SIZE, + SAVE_VERSION, + TOTAL_WEEKS, + UNDECIDED_START, + WEEKLY_INCOME, + cloneState, + addTally, + emptyStats, + gainCard, + newCard, + pickWeighted, + rand, + shuffle, + totals, + townReach, + type CardInst, + type RogueSetup, + type RunOptions, + type RunState, + type TownState, +} from "./state.ts"; + +export { blockedReason, cardCost, comboBonus, COMBO_MAX, COMBO_STEP, counterable, attackable, MOMENTUM_STEP, playCard, type PlayResult } from "./cards.ts"; +export { committedShares } from "./scenes.ts"; +export { SKIP_MONEY } from "./route.ts"; + +/** 開票時,每一點聲勢讓還沒表態的人有 1.5% 投給該陣營 */ +export const MOMENTUM_TURNOUT = 0.015; +/** 逆風 10 級:開局落後幾個百分點 */ +const ASC10_GAP = 0.03; + +function pickEvent(s: RunState): string { + if (s.week === 1 || s.options.tutorial) return "calm"; + const badBoost = asc(s, 9) ? 2 : 1; + return pickWeighted( + s, + EVENTS.filter((e) => e.id !== s.event), + (e) => e.weight * (e.bad ? badBoost : 1), + )!.id; +} + +/** 你的開局底盤加減 d(比例),從對手和其他人照比例移過來(或還回去) */ +function shiftLean(lean: { you: number; rival: number; others: number }, d: number): { you: number; rival: number; others: number } { + const you = Math.max(0.01, Math.min(0.98, lean.you + d)); + const rest = lean.rival + lean.others || 1; + const left = 1 - you; + return { you, rival: (lean.rival / rest) * left, others: (lean.others / rest) * left }; +} + +/** 新的一週:事件、對手意圖(樁腳馬上生效)、體力、抽牌、開場劇情 */ +function startWeek(s: RunState): void { + s.week += 1; + s.event = pickEvent(s); + secondChance(s); + const prev = s.lastWeek; + s.lastWeek = { attacked: false, rallied: false, flips: 0 }; + const eve = s.week === s.totalWeeks && !s.options.tutorial ? 1 : 0; + const hub = s.week <= (s.options.perks?.hub ?? 0) ? 1 : 0; + s.energyMax = BASE_ENERGY + (has(s, "chief") ? 1 : 0) + (has(s, "scheduler") ? 1 : 0) + eve + hub; + s.energy = Math.max(0, s.energyMax + s.energyNext); + s.energyNext = 0; + s.buffs = []; + s.playedThisWeek = 0; + s.onlinePlayed = 0; + s.weekCards = []; + const start = committedShares(s); + s.tally = { gained: 0, lost: 0, blocked: 0, startYou: start.you, startRival: start.rival }; + const volunteers = s.week === 1 ? (s.options.perks?.volunteer ?? 0) : 0; + drawCards(s, HAND_SIZE + (has(s, "youth_corps") ? 1 : 0) - (has(s, "scheduler") ? 1 : 0) + volunteers); + if (has(s, "party_org")) s.hand.push(newCard(s, "walkx")); + if (s.partyStorm === s.week) { + s.hand.push(newCard(s, "storm")); + s.log.push({ side: "system", text: "黨中央風波:記者追問你對黨內爭議的看法(手上多一張「黨中央風波」,這週回應)", town: null, votes: 0 }); + } + if (has(s, "mascot") && s.momentum < 1) s.momentum = 1; + announceBigRally(s); + s.intents = planIntents(s); + applyRivalShields(s); + s.scene = sceneFor(s, prev); + // 記者堵麥不擋出牌:變成這週要處理的事件,結束這週前回答就好;辯論、黑函是大場面,先處理 + s.phase = s.scene && s.scene.kind !== "press" ? "scene" : "plan"; +} + +export interface CreateOptions extends Partial> { + /** 新手教學:指定開局牌組(照順序抽) */ + deck?: string[]; + /** 政策島的建築 */ + perks?: readonly IslandPerk[]; + /** 政策工坊寫的政策(照政策研究院的等級決定能帶幾份) */ + policies?: readonly PolicySpec[]; + /** 政治生涯從上一場帶過來的幕僚、牌、資金 */ + carry?: { advisors: string[]; cards: { id: string; up: boolean }[]; money: number; momentum?: number }; +} + +/** 政治生涯一共幾關(里長 → 議員 → 立委 → 縣市長 → 總統) */ +export const CAREER_STAGES = 5; + +export function createRun(setup: RogueSetup, runId: string, seed: number, opts: CreateOptions = {}): RunState { + const options: RunOptions = { + ascension: Math.max(0, Math.min(10, Math.round(opts.ascension ?? 0))), + weeks: opts.weeks ?? TOTAL_WEEKS, + tutorial: opts.tutorial ?? false, + daily: opts.daily ?? null, + even: opts.even ?? false, + career: opts.career ?? null, + abilities: opts.abilities ?? null, + abilitiesBasis: opts.abilitiesBasis ?? null, + perks: perkLevels(opts.perks ?? []), + origin: opts.origin ?? null, + ...(opts.noUltimate ? { noUltimate: true } : {}), + }; + const voters = setup.towns.reduce((a, t) => a + t.voters, 0); + const meanVoters = voters / (setup.towns.length || 1); + const gap = options.ascension >= 10 ? ASC10_GAP / 2 : 0; + const { towns, ...rest } = setup; + const s: RunState = { + version: SAVE_VERSION, + runId, + seed, + rng: seed >>> 0 || 1, + setup: rest, + options, + scale: voters / 1_000_000, + week: 0, + totalWeeks: options.weeks, + phase: "plan", + energy: BASE_ENERGY, + energyMax: BASE_ENERGY, + energyNext: 0, + money: Math.round(setup.money * (options.ascension >= 2 ? 0.6 : 1)), + momentum: 0, + rivalMomentum: options.ascension >= 7 ? 2 : 0, + leverage: 0, + towns: towns.map((t) => { + const committed = t.voters * (1 - UNDECIDED_START); + // 黨的資源:大黨的包袱(中間選民起步少一點)、小黨的清新形象(多一點);從對手和其他人照比例移過來 + const partyShift = options.origin ? PARTY_LEAN_SHIFT[options.origin.kind] : 0; + const lean = partyShift ? shiftLean(t.lean, partyShift) : t.lean; + const shift = Math.min(gap, lean.you); + return { + code: t.code, + name: t.name, + voters: t.voters, + you: committed * (lean.you - shift), + rival: committed * (lean.rival + shift), + others: committed * lean.others, + undecided: t.voters * UNDECIDED_START, + traits: [...t.traits], + neighbors: [...(t.neighbors ?? [])], + shield: 0, + rivalShield: 0, + office: 0, + played: [], + reach: townReach(t.voters, meanVoters), + flag: null, + was: null, + }; + }), + draw: [], + hand: [], + discard: [], + exhausted: [], + nextUid: 0, + advisors: [], + powers: [], + buffs: [], + intents: [], + nextBig: null, + event: "calm", + playedThisWeek: 0, + onlinePlayed: 0, + scene: null, + route: null, + stop: null, + log: [], + history: [], + lastFocus: [], + lastWeek: { attacked: false, rallied: false, flips: 0 }, + seen: [], + crisisDone: false, + startGap: 0, + stats: emptyStats(), + result: null, + }; + for (const t of s.towns) t.flag = t.was = flagOwner(t); + const deck = opts.deck ?? [...STARTER_DECK, ...(options.ascension >= 5 ? ["favor"] : [])]; + const cards = deck.map((id): CardInst => newCard(s, id)); + s.draw = opts.deck ? cards : shuffle(s, cards); + // 政治生涯:帶過來的牌放在最上面(第一週就抽到)、幕僚、資金(伺服器已經檢查過 id) + for (const c of opts.carry?.cards ?? []) if (CARD_BY_ID.has(c.id)) gainCard(s, newCard(s, c.id, c.up)); + for (const a of opts.carry?.advisors ?? []) if (ADVISOR_BY_ID.has(a) && !s.advisors.includes(a)) s.advisors.push(a); + s.money += opts.carry?.money ?? 0; + // 出身專屬牌放在最上面(第一週就抽到);大黨的包袱:第 3 或第 4 週有一次黨中央風波 + const originCard = options.origin ? ORIGINS[options.origin.background as Background]?.card : undefined; + if (originCard && CARD_BY_ID.has(originCard)) gainCard(s, newCard(s, originCard)); + // 大黨的黨部:開局多一張「黨部動員掃街」(不花體力) + if (options.origin?.kind === "major") gainCard(s, newCard(s, "walkx")); + s.partyStorm = options.origin?.kind === "major" && options.weeks >= 5 ? 3 + Math.floor(rand(s) * 2) : null; + // 政策島:資金、聲勢、升級開局牌;政治生涯的財務能力 + const perks = options.perks; + s.money += 150 * (perks.vault ?? 0) + 50 * (perks.nightmarket ?? 0) + 80 * (options.abilities?.finance ?? 0); + s.momentum = Math.min(5, (perks.hq ?? 0) + (opts.carry?.momentum ?? 0)); + for (let k = 0; k < (perks.academy ?? 0); k++) { + const pool = s.draw.filter((c) => upgradable(c.id, c.up) && c.id !== "dinner"); + const c = pool[Math.floor(rand(s) * pool.length)]; + if (c) c.up = true; + } + // 政策工坊:帶進來的政策放在最上面,第一週就抽到 + (opts.policies ?? []).slice(0, policySlots(perks)).forEach((p, i) => { + const id = policyCardId(i, p); + if (!findCard(id)) return; + s.policyNames = { ...s.policyNames, [id]: p.name }; + gainCard(s, newCard(s, id)); + }); + const start = committedShares(s); + s.startGap = (start.you - start.rival) * 100; + s.history.push({ week: 0, ...start }); + startWeek(s); + return s; +} + +const grade = (margin: number): RogueResult["grade"] => (margin >= 0.08 ? "S" : margin >= 0.03 ? "A" : margin > 0 ? "B" : margin >= -0.03 ? "C" : "D"); + +/** 開票日:還沒表態的人,依雙方聲勢有一小部分會出來投票(聲勢高的一方帶出比較多),其他人留在家 */ +function turnoutOf(s: RunState, t: TownState): { you: number; rival: number } { + const youTurnout = MOMENTUM_TURNOUT * (has(s, "pollster") ? 1.5 : 1); + return { you: t.undecided * youTurnout * s.momentum, rival: t.undecided * MOMENTUM_TURNOUT * s.rivalMomentum }; +} + +/** 如果今天開票(含聲勢帶出的未表態):雙方得票率;畫面上的「今天開票預估」 */ +export function electionForecast(s: RunState): { you: number; rival: number } { + let you = 0; + let rival = 0; + let cast = 0; + for (const t of s.towns) { + const extra = turnoutOf(s, t); + you += t.you + extra.you; + rival += t.rival + extra.rival; + cast += t.you + t.rival + t.others + extra.you + extra.rival; + } + return { you: you / (cast || 1), rival: rival / (cast || 1) }; +} + +function election(s: RunState): RogueResult { + for (const t of s.towns) { + const extra = turnoutOf(s, t); + t.you += extra.you; + t.rival += extra.rival; + t.undecided -= extra.you + extra.rival; + } + const t = totals(s.towns); + const cast = t.you + t.rival + t.others || 1; + const youShare = t.you / cast; + const rivalShare = t.rival / cast; + const won = t.you > t.rival && t.you > t.others * (s.setup.othersTop ?? 1); + // 多席次的得票率都很小:用你和最後一席(對手)之間的差距評分,換算成兩人對決 + const margin = s.setup.seats && s.setup.seats > 1 ? (t.you - t.rival) / (t.you + t.rival || 1) : youShare - rivalShare; + return { + won, + you: Math.round(t.you), + rival: Math.round(t.rival), + others: Math.round(t.others), + youShare, + rivalShare, + grade: grade(margin), + byTown: s.towns.map((x) => ({ code: x.code, you: Math.round(x.you), rival: Math.round(x.rival), others: Math.round(x.others) })), + feats: featsOf(s, won, margin), + }; +} + +/** 週末手上的牌:保留的留著、虛無的消失、其他進棄牌堆;文膽多留一張最貴的 */ +function cleanupHand(s: RunState): void { + const keep: CardInst[] = []; + const rest: CardInst[] = []; + for (const c of s.hand) { + const def = cardDef(c.id, c.up)!; + if (hasKeyword(def, "retain")) keep.push(c); + else if (hasKeyword(def, "ethereal")) s.exhausted.push(c); + else rest.push(c); + } + if (has(s, "speechwriter")) { + const best = [...rest].filter((c) => cardDef(c.id)!.rarity !== "status").sort((a, b) => cardDef(b.id, b.up)!.cost - cardDef(a.id, a.up)!.cost)[0]; + if (best) { + keep.push(best); + rest.splice(rest.indexOf(best), 1); + } + } + s.discard.push(...rest); + s.hand = keep; +} + +/** 結束這週:服務處加票、對手照意圖行動、記者追問、聲勢消退、收入,然後選下一站(最後一週直接開票) */ +export function endWeek(state: RunState): RunState | { error: string } { + if (state.phase !== "plan") return { error: "現在不能結束這週" }; + if (state.scene?.kind === "press") return { error: "先回答記者的問題" }; + const s = cloneState(state); + s.log = []; + for (const t of s.towns.filter((x) => x.office > 0)) { + const net = moveVotes(t, t.office * s.scale * t.reach, "you"); + s.log.push({ side: "you", text: `${t.name}服務處`, town: t.code, votes: Math.round(net) }); + } + if (has(s, "councilors")) { + for (const t of s.towns.filter((x) => x.flag === "you")) { + const net = moveVotes(t, 460 * s.scale * t.reach, "you"); + s.log.push({ side: "you", text: `議員聯盟・${t.name}`, town: t.code, votes: Math.round(net) }); + } + } + for (const intent of s.intents) executeIntent(s, intent); + const reporters = s.hand.filter((c) => c.id === "reporter" || c.id === "storm").length; + if (reporters > 0 && !has(s, "crisis_team")) { + const integrity = 1 - 0.15 * (s.options.abilities?.integrity ?? 0); + const fresh = s.options.origin?.kind === "minor" ? MINOR_REPORTER_MULT : 1; + const lost = cityVotes(s, -REPORTER_PENALTY * s.scale * reporters * integrity * fresh); + s.log.push({ side: "rival", text: `沒回應記者追問 ×${reporters}`, town: null, votes: Math.round(lost) }); + } + s.momentum = Math.max(0, s.momentum - 1); + s.rivalMomentum = Math.max(0, s.rivalMomentum - 1); + updateFlags(s); + const flags = s.towns.filter((t) => t.flag === "you").length; + const income = Math.round( + WEEKLY_INCOME * (eventOf(s).income ?? 1) * (asc(s, 3) ? 0.6 : 1) + + (has(s, "tycoon") ? 150 : 0) + + flags * FLAG_INCOME + + (has(s, "cfo") ? 60 * s.energy : 0) + + 15 * (s.options.abilities?.finance ?? 0), + ); + s.money += income; + s.log.push({ side: "system", text: `本週收入 ${income} 萬${flags ? `(含 ${flags} 面旗的小額捐款)` : ""}`, town: null, votes: 0 }); + s.lastFocus = s.towns + .filter((t) => t.played.length > 0) + .sort((a, b) => b.played.length - a.played.length) + .slice(0, 2) + .map((t) => t.code); + cleanupHand(s); + for (const t of s.towns) { + t.shield = 0; + t.rivalShield = 0; + t.played = []; + } + addTally(s, s.log); + s.history.push({ week: s.week, ...committedShares(s) }); + chargeUltimate(s, s.lastWeek.flips); + if (s.week >= s.totalWeeks) { + s.result = election(s); + s.intents = []; + s.phase = "finished"; + return s; + } + prepareRoute(s); + s.phase = "route"; + return s; +} + +/** 放大絕招(ultimate.ts):kind 是哪一招,score 是小遊戲分數,towns 是掃街馬拉松挑的區 */ +export function ultimate(state: RunState, kind: MiniGameKind, score: number, towns?: readonly string[]): RunState | { error: string } { + const s = cloneState(state); + s.log = []; + const error = applyUltimate(s, kind, score, towns); + if (error) return error; + updateFlags(s); + addTally(s, s.log); + return s; +} + +/** + * 做選擇:開場劇情(堵麥、辯論、黑函)、下一站、站內的選項。 + * pick 是第幾個選項("skip" 是不選/離開);target 是要升級或拿掉的牌(uid) + */ +export function choose(state: RunState, pick: number | "skip", target: string | null = null, option?: number): RunState | { error: string } { + const s = cloneState(state); + s.log = []; + if (s.phase === "scene" || (s.phase === "plan" && s.scene?.kind === "press")) { + const error = resolveScene(s, pick === "skip" ? 0 : pick); + return error ? { error } : s; + } + if (s.phase === "route") { + const r = pickRoute(s, pick, option); + if ("error" in r) return r; + if (r.done) startWeek(s); + return s; + } + if (s.phase === "stop") { + const r = pickStop(s, pick, target); + if ("error" in r) return r; + if (r.done) startWeek(s); + return s; + } + return { error: "現在沒有要選的事" }; +} diff --git a/backend/packages/rogue/src/scenes.ts b/backend/packages/rogue/src/scenes.ts new file mode 100644 index 0000000..a1ee353 --- /dev/null +++ b/backend/packages/rogue/src/scenes.ts @@ -0,0 +1,331 @@ +import { ADVISORS } from "./advisors.ts"; +import { + CRISIS_CHOICES, + DEBATE_ARGS, + DEBATE_CHALLENGES, + DEBATE_DEBT_CHALLENGE, + DEBATE_MID, + DEBATE_MOVES, + DEBATE_POLICY_ARG, + DEBATE_TOPICS, + PRESS, + PRESS_BY_ID, + type Choice, + type Outcome, + type PressTrigger, +} from "./content.ts"; +import { findCard, upgradable } from "./data.ts"; +import { addMomentum, addRivalMomentum, asc, cityVotes, has, loseVotes, spread } from "./mechanics.ts"; +import { MAX_ADVISORS, addTally, gainCard, newCard, pickWeighted, rand, shuffle, totals, type DebateArg, type DebateMove, type RunState, type Scene } from "./state.ts"; + +/** + * 每週開場的劇情(docs/22):記者堵麥、電視辯論(第 3 週)、民調公布(第 4 週)、匿名黑函危機(第 6 週)。 + * 劇情在對手亮出意圖、你抽完牌之後出現,選完才開始出牌。 + */ + +export const DEBATE_WEEK = 3; +export const POLL_WEEK = 4; +export const CRISIS_WEEK = 6; +/** 辯論贏一回合:全市加票(基準),連續答對 ×1.5、×2;輸一回合:你掉票 */ +export const DEBATE_WIN = 1730; +export const DEBATE_LOSS = 860; +export const DEBATE_COMBO = [1, 1.5, 2] as const; +/** 用自己寫的政策回應數字質疑:再 ×1.3 */ +export const DEBATE_POLICY_BONUS = 1.3; +/** 匿名黑函:全市掉票(基準) */ +export const CRISIS_BASE = 3450; + +export const committedShares = (s: RunState) => { + const t = totals(s.towns); + const cast = t.you + t.rival + t.others || 1; + return { you: t.you / cast, rival: t.rival / cast }; +}; + +/** 劇情的結果:加減票、聲勢、資金、牌… when 是「這週」(出牌前)或「下週」(週與週之間) */ +export function applyOutcome(s: RunState, o: Outcome, when: "now" | "between"): void { + s.log.push({ side: "system", text: o.text, town: null, votes: 0 }); + if (o.votes) { + const net = cityVotes(s, o.votes * s.scale); + s.log.push({ side: "you", text: o.votes > 0 ? "全市加票" : "全市掉票", town: null, votes: Math.round(net) }); + } + if (o.rivalVotes) { + const parts = spread(s.towns, o.rivalVotes * s.scale, (t) => t.rival); + const hurt = s.towns.reduce((a, t, i) => a + loseVotes(t, parts[i]!, "rival"), 0); + s.log.push({ side: "you", text: `${s.setup.rival.name}的支持者動搖`, town: null, votes: Math.round(hurt) }); + } + if (o.momentum) addMomentum(s, o.momentum); + if (o.rivalMomentum) addRivalMomentum(s, o.rivalMomentum); + if (o.money) s.money = Math.max(0, s.money + o.money); + if (o.leverage) s.leverage = Math.max(0, s.leverage + o.leverage); + if (o.energy) { + if (when === "now") s.energy = Math.max(0, s.energy + o.energy); + else s.energyNext += o.energy; + } + if (o.card) { + const card = newCard(s, o.card, o.upCard); + if (when === "now") s.hand.push(card); + else gainCard(s, card); + } + for (const id of o.status ?? []) s.discard.push(newCard(s, id)); + if (o.upgrade) { + const pool = [...s.draw, ...s.discard, ...s.hand].filter((c) => upgradable(c.id, c.up)); + if (pool.length) { + const c = pool[Math.floor(rand(s) * pool.length)]!; + c.up = true; + s.stats.upgraded += 1; + s.log.push({ side: "you", text: "牌組裡一張牌升級了", town: null, votes: 0 }); + } + } + if (o.advisor && s.advisors.length < MAX_ADVISORS) { + const pool = ADVISORS.filter((a) => !has(s, a.id)); + const a = pool[Math.floor(rand(s) * pool.length)]; + if (a) { + s.advisors.push(a.id); + s.log.push({ side: "you", text: `${a.name}加入團隊`, town: null, votes: 0 }); + } + } +} + +/** 選項能不能選:資源不夠的不行 */ +export const choiceBlocked = (s: RunState, c: Pick): string | null => { + if (c.needs?.money && s.money < c.needs.money) return "資金不夠"; + if (c.needs?.leverage && s.leverage < c.needs.leverage) return "沒有把柄"; + return null; +}; + +/** 擲骰:照機率決定結果 */ +export const rollChoice = (s: RunState, c: Choice): Outcome => (c.roll && rand(s) >= c.roll.chance ? c.roll.fail : c.outcome); + +function pressScene(s: RunState, prev: RunState["lastWeek"]): Scene | null { + const shares = committedShares(s); + const active = new Set(["any"]); + if (prev.attacked) active.add("attacked"); + if (prev.rallied) active.add("rallied"); + if (prev.flips > 0) active.add("flipped"); + if (s.event === "typhoon") active.add("typhoon"); + if (s.money < 200) active.add("poor"); + if (s.money >= 1500) active.add("rich"); + active.add(shares.you >= shares.rival ? "leading" : "trailing"); + const pool = PRESS.filter((p) => active.has(p.trigger) && !s.seen.includes(p.id)); + const pick = pickWeighted(s, pool, (p) => (p.trigger === "any" ? 1 : 3)); + if (!pick) return null; + s.seen.push(pick.id); + return { kind: "press", id: pick.id }; +} + +const MOVES: DebateMove[] = ["policy", "emotion", "question"]; +/** 對手的風格:地面型多談感受、空戰型多翻紀錄 */ +const STYLE_MOVES: Record> = { + balanced: { policy: 1, emotion: 1, question: 1 }, + ground: { policy: 1, emotion: 1.5, question: 0.7 }, + air: { policy: 1.1, emotion: 0.7, question: 1.4 }, +}; +/** 論點從你的牌組來:政策、記者會類的牌多就多數據,地面牌多就多故事,媒體、攻擊牌多就多反問 */ +const ARG_TAGS: Record = { + policy: ["policy", "press", "intel"], + emotion: ["ground", "temple", "market", "rally"], + question: ["attack", "media", "defend"], +}; +export const DEBATE_HAND = 5; + +/** 這一局帶的政策:名字和財源 */ +function policiesIn(s: RunState): { name: string; debt: boolean }[] { + return Object.entries(s.policyNames ?? {}).map(([id, name]) => ({ name, debt: id.endsWith(":debt") })); +} + +/** 辯論看不看得出最好的回應:辯論教練,或口才 5 級 */ +export const debateSure = (s: RunState): boolean => has(s, "debate_coach") || (s.options.abilities?.eloquence ?? 0) >= 5; + +function debateScene(s: RunState): Scene { + const topics = shuffle(s, DEBATE_TOPICS).slice(0, 3); + const style = STYLE_MOVES[s.setup.rivalStyle]; + const needs = topics.map(() => pickWeighted(s, MOVES, (m) => style[m])!); + const challenges = topics.map((topic, i) => { + const pool = DEBATE_CHALLENGES[needs[i]!]; + return pool[Math.floor(rand(s) * pool.length)]!.replace("{topic}", topic); + }); + const policies = policiesIn(s); + // 舉債的政策:第二回合一定被問「錢從哪裡來」 + const debt = policies.find((p) => p.debt); + if (debt) { + needs[1] = "policy"; + challenges[1] = DEBATE_DEBT_CHALLENGE.replace("{policy}", debt.name); + } + // 抽論點:三種各一張,其餘照牌組的組成加權;口才 3 級以上多一張;財源扎實的政策各一張 + const deck = [...s.draw, ...s.discard, ...s.hand].map((c) => findCard(c.id)).filter((c) => !!c); + const weight = (m: DebateMove) => 1 + deck.filter((c) => c.tags.some((t) => ARG_TAGS[m].includes(t))).length; + const size = DEBATE_HAND + ((s.options.abilities?.eloquence ?? 0) >= 3 ? 1 : 0); + const used = { policy: 0, emotion: 0, question: 0 }; + const hand: DebateArg[] = policies.filter((p) => !p.debt).map((p) => ({ kind: "policy", text: DEBATE_POLICY_ARG.replace("{policy}", p.name), policy: p.name })); + const add = (kind: DebateMove) => { + const pool = DEBATE_ARGS[kind]; + hand.push({ kind, text: pool[used[kind]++ % pool.length]! }); + }; + // 三種論點至少各一張(不然只能硬選),其餘照牌組加權 + for (const kind of MOVES) if (!hand.some((a) => a.kind === kind)) add(kind); + while (hand.length < size) add(pickWeighted(s, MOVES, weight)!); + return { kind: "debate", round: 0, topics, challenges, needs, hand: shuffle(s, hand), history: [], wins: 0, losses: 0, combo: 0 }; +} + +/** 論點對質疑:最好的贏、普通的平手、不好的輸 */ +export const debateResult = (arg: DebateMove, need: DebateMove): "win" | "lose" | "tie" => (arg === need ? "win" : DEBATE_MID[need] === arg ? "tie" : "lose"); + +/** 手上最好的那張(看得出來的時候畫面會標出來;電腦玩家也用這個) */ +export function bestArg(hand: readonly DebateArg[], need: DebateMove): number { + const score = (a: DebateArg) => ({ win: 2, tie: 1, lose: 0 })[debateResult(a.kind, need)] + (a.policy ? 0.5 : 0); + let best = 0; + hand.forEach((a, i) => { + if (score(a) > score(hand[best]!)) best = i; + }); + return best; +} + +/** 舊存檔讀進來:猜拳辯論換成論點連擊;民調改成自動公布(不再停在民調畫面) */ +export function migrateRun(s: RunState): RunState { + if (s.scene?.kind === "debate" && !Array.isArray((s.scene as { hand?: unknown }).hand)) s.scene = debateScene(s); + if (s.scene?.kind === "poll") { + s.poll = { week: s.week, you: s.scene.you, rival: s.scene.rival, lead: s.scene.lead }; + s.scene = null; + s.phase = "plan"; + } + return s; +} + +/** 民調公布(第 4 週):自動,不用點;結果記在 s.poll,畫面的跑馬燈和狀態列顯示 */ +function publishPoll(s: RunState): void { + const shares = committedShares(s); + // 民調有誤差:±1 個百分點 + const noise = (rand(s) - 0.5) * 0.02; + const you = shares.you + noise / 2; + const rival = shares.rival - noise / 2; + const lead = you >= rival; + s.stats.pollGap = (rival - you) * 100; + if (lead) { + addMomentum(s, 1); + s.log.push({ side: "you", text: "民調領先,西瓜效應:聲勢 +1", town: null, votes: 0 }); + } else { + s.hand.push(newCard(s, "sympathy")); + s.log.push({ side: "you", text: "民調落後,支持者危機意識上升:手上多一張「悲情催票」", town: null, votes: 0 }); + } + s.poll = { week: s.week, you, rival, lead }; +} + +function crisisScene(s: RunState): Scene { + const amount = CRISIS_BASE * s.scale * (asc(s, 9) ? 2 : 1) * (has(s, "lawyer") ? 0.5 : 1) * (1 - 0.12 * (s.options.abilities?.integrity ?? 0)); + s.crisisDone = true; + return { kind: "crisis", amount }; +} + +/** 這週開場的劇情;新手教學沒有 */ +export function sceneFor(s: RunState, prev: RunState["lastWeek"]): Scene | null { + if (s.options.tutorial || s.week < 2) return null; + if (s.week === DEBATE_WEEK) return debateScene(s); + if (s.week === POLL_WEEK) { + publishPoll(s); + return null; + } + if (s.week === CRISIS_WEEK) return crisisScene(s); + return pressScene(s, prev); +} + +/** 選劇情的選項;回傳錯誤訊息或 null(成功,狀態直接改在 s 上) */ +export function resolveScene(s: RunState, pick: number): string | null { + const error = resolveSceneInner(s, pick); + if (!error) addTally(s, s.log); + return error; +} + +function resolveSceneInner(s: RunState, pick: number): string | null { + const scene = s.scene; + if (!scene) return "現在沒有要選的事"; + const close = () => { + s.scene = null; + s.phase = "plan"; + }; + switch (scene.kind) { + case "press": { + const def = PRESS_BY_ID.get(scene.id); + const choice = def?.choices[pick]; + if (!choice) return "沒有這個選項"; + const blocked = choiceBlocked(s, choice); + if (blocked) return blocked; + applyOutcome(s, rollChoice(s, choice), "now"); + close(); + return null; + } + case "poll": + close(); + return null; + case "debate": { + if (scene.round >= scene.topics.length) { + close(); + return null; + } + const arg = scene.hand[pick]; + if (!arg) return "沒有這個論點"; + const need = scene.needs[scene.round]!; + const result = debateResult(arg.kind, need); + const head = `辯論第 ${scene.round + 1} 回合(${scene.topics[scene.round]}):你${DEBATE_MOVES[arg.kind].label}`; + let votes = 0; + if (result === "win") { + scene.wins += 1; + scene.combo += 1; + addMomentum(s, 1); + const mult = DEBATE_COMBO[Math.min(scene.combo, DEBATE_COMBO.length) - 1]! * (arg.policy ? DEBATE_POLICY_BONUS : 1); + votes = Math.round(cityVotes(s, DEBATE_WIN * mult * s.scale)); + s.log.push({ side: "you", text: `${head},說服了觀眾!${scene.combo > 1 ? `${scene.combo} 連擊 ×${DEBATE_COMBO[Math.min(scene.combo, DEBATE_COMBO.length) - 1]},` : ""}聲勢 +1`, town: null, votes }); + } else if (result === "lose") { + scene.losses += 1; + scene.combo = 0; + addRivalMomentum(s, 1); + votes = Math.round(cityVotes(s, -DEBATE_LOSS * s.scale)); + s.log.push({ side: "rival", text: `${head},答非所問,對手佔上風`, town: null, votes }); + } else { + scene.combo = 0; + s.log.push({ side: "system", text: `${head},回答得普通,平分秋色`, town: null, votes: 0 }); + } + scene.hand.splice(pick, 1); + scene.history.push({ arg, result, combo: scene.combo, votes }); + scene.round += 1; + if (scene.round >= scene.topics.length) { + s.stats.debateWins = scene.wins; + if (scene.wins === scene.topics.length) { + s.hand.push(newCard(s, "soundbite")); + s.log.push({ side: "you", text: "三連擊全勝!手上多一張「辯論金句」", town: null, votes: 0 }); + } + } + return null; + } + case "crisis": { + const choice = CRISIS_CHOICES[pick]; + if (!choice) return "沒有這個選項"; + if ("money" in choice && s.money < choice.money) return "資金不夠"; + let factor = 1; + const status: string[] = []; + s.log.push({ side: "system", text: "網路流傳一份匿名黑函,內容沒有根據", town: null, votes: 0 }); + if (choice.id === "sue") { + s.money -= choice.money; + factor = 0.3; + } else if (choice.id === "ignore") { + if (rand(s) < 0.5) factor = 0.4; + else { + factor = 1.2; + status.push("reporter", "reporter"); + } + } else if (choice.id === "sympathy") { + factor = 0.7; + addMomentum(s, 2); + status.push("reporter"); + } else { + factor = 0; + s.energy = Math.max(0, s.energy - 1); + } + const lost = factor > 0 ? cityVotes(s, -scene.amount * factor) : 0; + s.stats.crisisLoss = Math.max(0, -lost / s.scale); + s.log.push({ side: lost < 0 ? "rival" : "you", text: `${choice.label}:${factor === 0 ? "黑函沒有造成損失" : `損失剩 ${Math.round(factor * 100)}%`}`, town: null, votes: Math.round(lost) }); + for (const id of status) s.discard.push(newCard(s, id)); + close(); + return null; + } + } +} diff --git a/backend/packages/rogue/src/setup.ts b/backend/packages/rogue/src/setup.ts new file mode 100644 index 0000000..c278b1c --- /dev/null +++ b/backend/packages/rogue/src/setup.ts @@ -0,0 +1,176 @@ +import { AGE_BANDS, type RogueTrait } from "@election2026/protocol"; +import { CELLS_PER_VILLAGE, N_LEANS, aggregate, computeVoteModel, createMatch, viewFor, type World } from "@election2026/engine"; +import type { RogueSetup, TownSetup } from "./state.ts"; + +/** 地圖拓撲(topology.json)裡用得到的部分 */ +export interface TopologyLike { + objects: Record }[] }>; +} + +/** + * 從真實資料建開局(docs/21): + * - 各區預計投票人數、雙方底盤:用原本的選民模型(人口、年齡、政黨傾向、歷史投票率)算開局的預期得票。 + * - 各區特色:年齡結構、每千人宮廟數、人口密度、客家人口比例,和全縣市平均比較。 + * 規則本身不碰選民模型;開局之後的變化都是牌面上看得到的數字。 + */ + +const YOUNG = [AGE_BANDS.indexOf("20-29"), AGE_BANDS.indexOf("30-39")]; +const OLD = AGE_BANDS.indexOf("65+"); + +interface TownStats { + adults: number; + young: number; + old: number; + temples: number; + density: number; +} + +function townStats(world: World): TownStats[] { + const { pack } = world; + const stats = pack.towns.map(() => ({ adults: 0, young: 0, old: 0, temples: 0, density: 0 })); + pack.villages.forEach((v, vi) => { + const s = stats[v.townIndex]!; + const base = vi * CELLS_PER_VILLAGE; + let adults = 0; + for (let k = 0; k < CELLS_PER_VILLAGE; k++) { + const n = pack.cells[base + k]!; + const age = Math.floor(k / N_LEANS); + adults += n; + if (YOUNG.includes(age)) s.young += n; + if (age === OLD) s.old += n; + } + s.adults += adults; + s.temples += v.templesPer1000 * adults; + s.density += v.density * adults; + }); + return stats; +} + +/** 和全縣市平均比,明顯偏高(或偏低)才算這區的特色 */ +export function townTraits(world: World): RogueTrait[][] { + const stats = townStats(world); + const all = stats.reduce((a, s) => ({ adults: a.adults + s.adults, young: a.young + s.young, old: a.old + s.old, temples: a.temples + s.temples, density: a.density + s.density }), { + adults: 0, + young: 0, + old: 0, + temples: 0, + density: 0, + }); + const mean = { young: all.young / all.adults, old: all.old / all.adults, temples: all.temples / all.adults, density: all.density / all.adults }; + return stats.map((s, ti) => { + const traits: RogueTrait[] = []; + if (s.adults === 0) return traits; + if (s.young / s.adults >= mean.young * 1.05) traits.push("young"); + if (s.old / s.adults >= mean.old * 1.15) traits.push("old"); + if (s.temples / s.adults >= mean.temples * 1.4) traits.push("temples"); + const density = s.density / s.adults / mean.density; + if (density >= 1.5) traits.push("dense"); + if (density <= 0.3) traits.push("rural"); + if ((world.pack.towns[ti]!.hakkaShare ?? 0) >= 0.4) traits.push("hakka"); + return traits; + }); +} + +/** 把 arcs(多層巢狀陣列)攤平成 arc 編號;負數 ~i 和 i 是同一條邊 */ +function arcIds(arcs: unknown, out: number[] = []): number[] { + if (typeof arcs === "number") out.push(arcs < 0 ? ~arcs : arcs); + else if (Array.isArray(arcs)) for (const a of arcs) arcIds(a, out); + return out; +} + +/** + * 相鄰的區:共用同一條邊界(arc)的就是鄰居。縣市層級(總統選舉)用鄉鎮的邊界組成縣市。 + * codes 是遊戲裡的區代碼;不在裡面的區(選區外)不算。 + */ +export function townNeighbors(topology: TopologyLike, codes: readonly string[], level: "town" | "county" = "town"): Map { + const wanted = new Set(codes); + const byArc = new Map>(); + for (const g of topology.objects.towns?.geometries ?? []) { + const town = String(g.properties?.townCode ?? ""); + const code = level === "county" ? `${town.slice(0, 5)}000` : town; + if (!wanted.has(code)) continue; + for (const arc of arcIds(g.arcs)) { + const set = byArc.get(arc) ?? new Set(); + set.add(code); + byArc.set(arc, set); + } + } + const out = new Map>(codes.map((c) => [c, new Set()])); + for (const set of byArc.values()) { + if (set.size < 2) continue; + for (const a of set) for (const b of set) if (a !== b) out.get(a)!.add(b); + } + return new Map([...out].map(([k, v]) => [k, [...v].sort()])); +} + +export interface SetupOptions { + /** 勢均力敵:雙方全市底盤拉平(劇本 id 結尾是 -even 的一定拉平) */ + even?: boolean; + /** 照真實底盤時最多落後幾個百分點(比例,例如 0.15):政治生涯保留真實差距,但不會開局就沒機會(18 第 57 項) */ + maxGap?: number; + topology?: TopologyLike | null; +} + +/** 由劇本與玩家選的候選人建開局;對手是開局預期得票最高的其他候選人,其他人合併成「其他」 */ +export function buildSetup(world: World, candidateId: string, opts: SetupOptions = {}): RogueSetup { + const { scenario, pack, params } = world; + const ci = scenario.candidates.findIndex((c) => c.id === candidateId); + if (ci < 0) throw new Error(`劇本中沒有候選人 ${candidateId}`); + const state = createMatch(world, "rogue-setup", 1, candidateId); + const agg = aggregate(computeVoteModel(state, scenario, pack, params, null), pack, scenario.candidates.length); + const ri = agg.votes.map((v, i) => ({ v, i })).filter((x) => x.i !== ci).sort((a, b) => b.v - a.v)[0]!.i; + const traits = townTraits(world); + // 「勢均力敵」劇本:雙方全市底盤拉平,各區的強弱分布不變 + const even = opts.even || scenario.id.endsWith("-even"); + const youAll = agg.byTown.reduce((a, row) => a + row[ci]!, 0); + const rivalAll = agg.byTown.reduce((a, row) => a + row[ri]!, 0); + const castAll = agg.byTown.reduce((a, row) => a + row.reduce((x, y) => x + y, 0), 0) || 1; + const cap = opts.maxGap ?? null; + const tooFar = !even && cap !== null && (rivalAll - youAll) / castAll > cap; + // 落後超過上限:雙方合計不變,拉到剛好落後 cap(各區的強弱分布不變) + const capped = tooFar ? { you: (youAll + rivalAll - cap * castAll) / 2, rival: (youAll + rivalAll + cap * castAll) / 2 } : null; + const fix = even + ? { you: (youAll + rivalAll) / 2 / youAll, rival: (youAll + rivalAll) / 2 / rivalAll } + : capped + ? { you: capped.you / youAll, rival: capped.rival / rivalAll } + : { you: 1, rival: 1 }; + const towns: TownSetup[] = pack.towns.map((t, ti) => { + const row = agg.byTown[ti]!; + const cast = row.reduce((a, b) => a + b, 0) || 1; + const others = Math.max(0, cast - row[ci]! - row[ri]!) / cast; + const you = (row[ci]! * fix.you) / cast; + const rival = (row[ri]! * fix.rival) / cast; + // 拉平後各區比例可能不再加總 1,依比例縮回去 + const sum = you + rival + others; + return { code: t.code, name: t.name, voters: Math.round(cast), lean: { you: you / sum, rival: rival / sum, others: others / sum }, traits: traits[ti]! }; + }); + if (opts.topology) { + const neighbors = townNeighbors(opts.topology, towns.map((t) => t.code), scenario.region.regionLevel ?? "town"); + for (const t of towns) t.neighbors = neighbors.get(t.code) ?? []; + } + // 其他候選人裡最強的一位:開票時要贏過的是他,不是其他人的票加起來 + const otherVotes = agg.votes.map((v, i) => (i === ci || i === ri ? 0 : v)); + const othersSum = otherVotes.reduce((a, b) => a + b, 0); + const othersTop = othersSum > 0 ? Math.max(...otherVotes) / othersSum : 1; + const people = viewFor(state, world, candidateId).candidates; + const style = scenario.candidates[ri]!.aiStyle; + return { + scenarioId: scenario.id, + scenarioName: scenario.name, + packId: scenario.packId, + countyCode: scenario.region.countyCode, + countyName: scenario.region.countyName, + area: scenario.region.area ?? scenario.region.countyName, + office: scenario.region.office, + you: people[ci]!, + rival: people[ri]!, + others: people.filter((_, i) => i !== ci && i !== ri), + towns, + // 劇本的起始資金(元)換成萬元;遊戲裡的花費也是萬元 + money: Math.max(300, Math.round(scenario.candidates[ci]!.startingMoney / 10_000)), + rivalStyle: style === "ground" || style === "air" ? style : "balanced", + // 自創角色以外都是真實人物 + rivalReal: scenario.candidates[ri]!.id !== "custom", + othersTop, + }; +} diff --git a/backend/packages/rogue/src/state.ts b/backend/packages/rogue/src/state.ts new file mode 100644 index 0000000..6ce5486 --- /dev/null +++ b/backend/packages/rogue/src/state.ts @@ -0,0 +1,360 @@ +import type { CandidatePublic, CareerAbilities, MiniGameKind, PartyKind, RogueIntentKind, RogueLog, RogueResult, RogueTrait } from "@election2026/protocol"; + +/** 一區的起始資料:真實人口、投票率、各陣營的底盤(由選民模型算出,見 setup.ts) */ +export interface TownSetup { + code: string; + name: string; + voters: number; + /** 起始支持比例(你、對手、其他人,加總 1) */ + lean: { you: number; rival: number; others: number }; + traits: RogueTrait[]; + /** 相鄰的區(地圖拓撲算出;沒有拓撲時是空的) */ + neighbors?: string[]; +} + +export type RivalStyle = "balanced" | "ground" | "air"; + +export interface RogueSetup { + scenarioId: string; + scenarioName: string; + packId: string; + countyCode: string; + countyName: string; + /** 選區名稱(例如「高雄市第 4 選舉區」);舊存檔沒有,用縣市名稱 */ + area?: string; + office: string; + you: CandidatePublic; + rival: CandidatePublic; + others: CandidatePublic[]; + towns: TownSetup[]; + /** 起始資金(萬元) */ + money: number; + /** 對手 AI 的風格(劇本設定) */ + rivalStyle: RivalStyle; + /** 對手是真實人物(行動名稱要中性,docs/22) */ + rivalReal: boolean; + /** 「其他候選人」裡最強的那一位佔其他人票數的比例(開票判斷當選用;沒寫是 1) */ + othersTop?: number; + /** 多席次(議員):選幾席;贏過最後一席(對手)就當選 */ + seats?: number; + /** 多席次:最後一席的得票率(真實資料,畫面說明用) */ + threshold?: number; + /** 議員選區把村里分群時:村里 → 遊戲裡的區代碼(前端畫地圖用) */ + groups?: Record; +} + +export interface RunOptions { + /** 逆風難度 0–10 */ + ascension: number; + /** 一局幾週(新手教學 3 週) */ + weeks: number; + /** 新手教學:固定牌組、沒有辯論和黑函 */ + tutorial: boolean; + /** 每日一戰(只是標記,給成就和畫面用) */ + daily: string | null; + /** 勢均力敵(開局已經在 setup 拉平;這裡記下來給「再選一次」用) */ + even: boolean; + /** 玩真實候選人時,開局能力的依據(公開選舉紀錄) */ + abilitiesBasis?: string | null; + /** 政治生涯的第幾關 */ + career: { stage: number; total: number } | null; + /** 政治生涯的角色能力(沒有是 null) */ + abilities: CareerAbilities | null; + /** 政策島的建築等級(id → 1–3) */ + perks: Record; + /** 自創角色的出身與政黨(18 第 53 項:專屬起始牌、黨的資源);真實候選人、舊存檔是 null */ + origin?: RunOrigin | null; + /** 關掉大絕招(只給模擬對照用) */ + noUltimate?: boolean; +} + +export interface RunOrigin { + background: string; + party: string | null; + kind: PartyKind; +} + +export type Owner = "you" | "rival" | null; + +export interface TownState { + code: string; + name: string; + voters: number; + you: number; + rival: number; + others: number; + undecided: number; + traits: RogueTrait[]; + neighbors: string[]; + shield: number; + rivalShield: number; + office: number; + played: string[]; + /** 區的大小係數:人越多,同一個行程接觸到的人越多(見 townReach) */ + reach: number; + /** 插旗:已表態的票裡領先 FLAG_LEAD 以上 */ + flag: Owner; + /** 上一個插旗的人(從對手手上拿過來才算翻轉,中間掉成沒人插旗也算) */ + was: Owner; +} + +export interface CardInst { + uid: string; + id: string; + /** 升級過(「+」版) */ + up?: boolean; +} + +export interface Intent { + id: string; + kind: RogueIntentKind; + town: string | null; + amount: number; + cut: number; + /** 預告過的大型行動 */ + big?: boolean; +} + +/** 電視辯論的三種論點:拿數據、講故事、反問對手 */ +export type DebateMove = "policy" | "emotion" | "question"; + +/** 你手上的一張論點;policy 是你自己寫的政策名字 */ +export interface DebateArg { + kind: DebateMove; + text: string; + policy?: string; +} + +export interface DebateRound { + arg: DebateArg; + result: "win" | "lose" | "tie"; + combo: number; + votes: number; +} + +export type Scene = + | { kind: "press"; id: string } + | { + kind: "debate"; + round: number; + topics: string[]; + /** 每回合的質疑和最好的回應 */ + challenges: string[]; + needs: DebateMove[]; + hand: DebateArg[]; + history: DebateRound[]; + wins: number; + losses: number; + /** 連續答對幾回合 */ + combo: number; + } + | { kind: "crisis"; amount: number } + | { kind: "poll"; you: number; rival: number; lead: boolean }; + +export type StopKind = "card" | "advisor" | "upgrade" | "remove" | "shop" | "encounter" | "event" | "minigame"; + +export interface ShopItem { + kind: "card" | "advisor" | "remove"; + id: string; + price: number; + sold: boolean; +} + +export type Stop = + | { kind: "card"; options: string[] } + | { kind: "advisor"; options: string[] } + | { kind: "upgrade" } + | { kind: "remove" } + | { kind: "shop"; items: ShopItem[] } + | { kind: "encounter"; town: string; encounters: string[]; step: number; score: number; notes: string[] } + | { kind: "event"; id: string } + | { kind: "minigame"; game: MiniGameKind; town: string | null; level: number; seed: number }; + +export interface RunStats { + played: number; + attacks: number; + flips: number; + maxCombo: number; + bigHit: number; + debateWins: number; + /** 玩了幾次選戰小遊戲(舊存檔沒有) */ + minigames?: number; + /** 放了幾次大絕招(舊存檔沒有) */ + ultimates?: number; + crisisLoss: number; + /** 第 4 週民調落後幾個百分點(逆轉勝用) */ + pollGap: number; + bought: number; + removed: number; + upgraded: number; +} + +export interface RunState { + version: 2; + runId: string; + seed: number; + /** 亂數狀態(每次抽亂數都往前推,存檔重開也接得上) */ + rng: number; + setup: Omit; + options: RunOptions; + /** 數字的比例尺:全市投票人數 / 100 萬(小縣市的牌面數字跟著變小) */ + scale: number; + week: number; + totalWeeks: number; + phase: "scene" | "plan" | "route" | "stop" | "finished"; + energy: number; + energyMax: number; + /** 下週體力的調整(地方抉擇、黑函危機) */ + energyNext: number; + money: number; + momentum: number; + rivalMomentum: number; + leverage: number; + towns: TownState[]; + draw: CardInst[]; + hand: CardInst[]; + discard: CardInst[]; + /** 這局用掉的「消耗」牌 */ + exhausted: CardInst[]; + nextUid: number; + advisors: string[]; + /** 打過的能力牌(整局有效) */ + powers: string[]; + /** 這週的加成(政策白皮書) */ + buffs: { tag: string; mult: number }[]; + intents: Intent[]; + /** 對手預告的大型行動(下週執行) */ + nextBig: Intent | null; + event: string; + /** 這週已經打過的牌、網路牌張數 */ + playedThisWeek: number; + onlinePlayed: number; + /** 正在結算的這張牌花了幾點體力(夜貓子用;結算完歸零) */ + paying?: number; + /** 這週打過的牌(每週一次的牌用) */ + weekCards?: string[]; + /** 政策卡的名字(玩家自己取的;id → 名字) */ + policyNames?: Record; + /** 這週的戰果(結算畫面、狀態列用) */ + tally?: { gained: number; lost: number; blocked: number; startYou: number; startRival: number }; + scene: Scene | null; + route: StopKind[] | null; + /** 下一站每扇門裡面的內容(開門前就備好,畫面直接攤開;舊存檔沒有) */ + routeStops?: Stop[] | null; + /** 最近一次民調(第 4 週自動公布;舊存檔沒有) */ + poll?: { week: number; you: number; rival: number; lead: boolean } | null; + stop: Stop | null; + log: RogueLog[]; + history: { week: number; you: number; rival: number }[]; + /** 上週你出牌最多的區(對手會跟過去) */ + lastFocus: string[]; + /** 這週發生的事(下週堵麥出題用) */ + lastWeek: { attacked: boolean; rallied: boolean; flips: number }; + /** 出現過的堵麥題目、地方抉擇(不重複) */ + seen: string[]; + /** 黑函危機發生過 */ + crisisDone: boolean; + /** 大黨的包袱:「黨中央風波」在第幾週(沒有是 null;舊存檔沒有這個欄位) */ + partyStorm?: number | null; + /** 大絕招(ultimate.ts):集氣 0–100、放過幾次、這局最多幾次(舊存檔沒有,用到時補上) */ + ult?: { charge: number; used: number; max: number }; + /** 開局時全市已表態的票裡你領先幾個百分點(以小搏大的成就用) */ + startGap: number; + stats: RunStats; + result: RogueResult | null; +} + +export const SAVE_VERSION = 2; +export const TOTAL_WEEKS = 8; +export const HAND_SIZE = 5; +/** 手牌上限:抽牌抽到這麼多張就停 */ +export const HAND_MAX = 10; +export const BASE_ENERGY = 3; +export const MAX_ADVISORS = 5; +export const MOMENTUM_MAX = 5; +/** 開局時還沒表態的比例 */ +export const UNDECIDED_START = 0.3; +/** 每週固定收入(萬元:小額捐款、政黨補助) */ +export const WEEKLY_INCOME = 100; +/** 插旗:已表態的票裡領先幾個百分點 */ +export const FLAG_LEAD = 0.08; +/** 每面旗每週的小額捐款(萬元) */ +export const FLAG_INCOME = 20; + +/** 可重現的亂數(mulberry32):回傳 [0, 1) 與新的狀態 */ +export function nextRandom(rng: number): [number, number] { + const next = (rng + 0x6d2b79f5) | 0; + let t = next; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return [((t ^ (t >>> 14)) >>> 0) / 4294967296, next]; +} + +/** 在這份狀態副本上抽一個亂數(只在規則函式內部、對副本使用) */ +export function rand(s: RunState): number { + const [x, next] = nextRandom(s.rng); + s.rng = next; + return x; +} + +export function shuffle(s: RunState, items: readonly T[]): T[] { + const out = [...items]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(rand(s) * (i + 1)); + [out[i], out[j]] = [out[j]!, out[i]!]; + } + return out; +} + +export function pickWeighted(s: RunState, items: readonly T[], weight: (x: T) => number): T | undefined { + const total = items.reduce((a, x) => a + Math.max(0, weight(x)), 0); + if (total <= 0) return undefined; + let r = rand(s) * total; + for (const x of items) { + r -= Math.max(0, weight(x)); + if (r <= 0) return x; + } + return items[items.length - 1]; +} + +/** 規則函式不改輸入:先複製一份再改 */ +export const cloneState = (s: RunState): RunState => structuredClone(s); + +export const totals = (towns: readonly TownState[]) => + towns.reduce((a, t) => ({ you: a.you + t.you, rival: a.rival + t.rival, others: a.others + t.others, undecided: a.undecided + t.undecided, voters: a.voters + t.voters }), { + you: 0, + rival: 0, + others: 0, + undecided: 0, + voters: 0, + }); + +/** 區的大小係數:(這區投票人數 / 各區平均)^0.3,夾在 0.6–1.4;小區約 ×0.7、大區約 ×1.3 */ +export const townReach = (voters: number, meanVoters: number): number => Math.min(1.4, Math.max(0.6, (voters / (meanVoters || 1)) ** 0.3)); + +/** 把票數四捨五入到十位,牌面和畫面上的數字比較好讀 */ +/** 票數取整:大的取到十位;里長選舉這種幾千人的小選舉,數字小,取到個位(不然都變成 0) */ +export const round10 = (n: number): number => (Math.abs(n) < 200 ? Math.round(n) : Math.round(n / 10) * 10); + +/** 已表態的票裡,你領先對手幾個百分點(負的是落後) */ +export const townLead = (t: Pick): number => (t.you - t.rival) / (t.you + t.rival + t.others || 1); + +export const newCard = (s: RunState, id: string, up = false): CardInst => ({ uid: `c${s.nextUid++}`, id, ...(up ? { up: true } : {}) }); + +/** 把這些紀錄算進這週的戰果:正的是你拉到、負的是被拉走、blocked 是擋下 */ +export function addTally(s: RunState, entries: readonly { votes: number; blocked?: number }[]): void { + const t = s.tally ?? { gained: 0, lost: 0, blocked: 0, startYou: 0, startRival: 0 }; + for (const e of entries) { + if (e.votes > 0) t.gained += e.votes; + else t.lost -= e.votes; + t.blocked += e.blocked ?? 0; + } + s.tally = t; +} + +/** 拿到新牌(下一站、物資行、地方抉擇):放在抽牌堆最上面,下週一定抽到(狀態牌、詛咒牌照樣進棄牌堆) */ +export function gainCard(s: RunState, card: CardInst): void { + s.draw.unshift(card); +} + +export const emptyStats = (): RunStats => ({ played: 0, attacks: 0, flips: 0, maxCombo: 0, bigHit: 0, debateWins: 0, crisisLoss: 0, pollGap: 0, bought: 0, removed: 0, upgraded: 0 }); diff --git a/backend/packages/rogue/src/tutorial.ts b/backend/packages/rogue/src/tutorial.ts new file mode 100644 index 0000000..d80a902 --- /dev/null +++ b/backend/packages/rogue/src/tutorial.ts @@ -0,0 +1,51 @@ +import type { CandidatePublic } from "@election2026/protocol"; +import type { RogueSetup } from "./state.ts"; + +/** + * 新手教學(docs/22):虛構的「三個里的里長選舉」,3 週、固定牌組,5 分鐘學會出牌、看意圖、組合拳、打對台。 + * 地名、人名都是虛構的;人數照一般的里(幾千人投票)。 + */ + +export const TUTORIAL_WEEKS = 3; + +/** 開局手牌照這個順序抽:第一週 掃街、宮廟、菜市場、佈樁、造勢 */ +export const TUTORIAL_DECK = ["canvass", "temple", "market", "stake", "rally", "canvass", "counter", "dinner", "night", "canvass", "market", "clarify", "walk", "temple", "canvass"]; + +const person = (id: string, name: string, slot: CandidatePublic["slot"], number: number, description: string, gender: "m" | "f"): CandidatePublic => ({ + id, + name, + party: null, + slot, + number, + isPlayer: id === "you", + description, + issueIds: [], + tags: [], + avatar: null, + runningMate: null, + gender, + slogan: null, + sloganSource: null, +}); + +export function tutorialSetup(): RogueSetup { + return { + scenarioId: "tutorial", + scenarioName: "新手教學:幸福里里長選舉", + packId: "", + countyCode: "", + countyName: "幸福里", + office: "里長", + you: person("you", "新人候選人", "other", 1, "第一次參選的你", "f"), + rival: person("rival", "老里長", "other", 2, "連任三屆的老里長", "m"), + others: [], + towns: [ + { code: "T1", name: "廟口", voters: 4200, lean: { you: 0.43, rival: 0.45, others: 0.12 }, traits: ["temples", "old"], neighbors: ["T2"] }, + { code: "T2", name: "新村", voters: 6100, lean: { you: 0.46, rival: 0.42, others: 0.12 }, traits: ["young", "dense"], neighbors: ["T1", "T3"] }, + { code: "T3", name: "田尾", voters: 2900, lean: { you: 0.41, rival: 0.47, others: 0.12 }, traits: ["rural", "old"], neighbors: ["T2"] }, + ], + money: 300, + rivalStyle: "ground", + rivalReal: false, + }; +} diff --git a/backend/packages/rogue/src/ultimate.ts b/backend/packages/rogue/src/ultimate.ts new file mode 100644 index 0000000..65d580e --- /dev/null +++ b/backend/packages/rogue/src/ultimate.ts @@ -0,0 +1,121 @@ +import type { MiniGameKind } from "@election2026/protocol"; +import { addMomentum, cityVotes, moveVotes } from "./mechanics.ts"; +import { committedShares } from "./scenes.ts"; +import type { RunState, TownState } from "./state.ts"; + +/** + * 大絕招(18 第 57 項):落後很多也有機會翻盤,但要靠玩小遊戲玩得好。 + * - 集氣:每週結算時,落後 1 個百分點集 8%(落後 10 點一週就集八成);領先時每週只集 2%;這週翻轉一區再 +10%。 + * - 次數:基本 1 次;倒數第 3 週(8 週選戰的第 6 週)開始時,如果已經放過、還落後超過 8 個百分點,可以再放 1 次(直接集滿)。 + * - 放招:挑一招、玩那個小遊戲(0–100 分)。威力=分數 × 落後倍率(落後 0 點 ×1、10 點 ×2、15 點以上 ×2.5)。 + */ + +export const ULT = { + /** 每落後 1 個百分點,每週集幾 % */ + perPoint: 8, + /** 領先或平手時每週集幾 % */ + ahead: 2, + /** 這週翻轉一區(插旗換成你)多集幾 % */ + flip: 10, + /** 第二次大絕招:落後超過幾個百分點(比例) */ + secondGap: 0.08, + /** 落後倍率:1 + 落後幾個百分點 ÷ 10,最多 2.5 */ + maxMult: 2.5, + /** 選前之夜大造勢:全市每百萬選民加幾票(分數 100、倍率 1 時) */ + city: 15_000, + /** 掃街馬拉松、看板大作戰:每一區(一般大小)加幾票 */ + town: 5_500, + /** 看板大作戰:搶回的區之後每週多幾票(據點) */ + office: 300, +} as const; + +export const ULTIMATES: Record = { + rally: { name: "選前之夜大造勢", game: "造勢喊凍蒜", text: "全市大幅加票,聲勢 +2" }, + handshake: { name: "掃街馬拉松", game: "掃街握手", text: "你挑的 3 個區大幅加票" }, + billboard: { name: "看板大作戰", game: "看板卡位", text: "對手插旗、差距最小的 3 個區搶票,之後每週還有據點票" }, +}; + +const ensure = (s: RunState) => (s.ult ??= { charge: 0, used: 0, max: 1 }); + +/** 你落後對手幾個百分點(已表態的票;領先是負的) */ +export function deficit(s: RunState): number { + const c = committedShares(s); + return (c.rival - c.you) * 100; +} + +export const ultMultiplier = (s: RunState): number => Math.min(ULT.maxMult, 1 + Math.max(0, deficit(s)) / 10); + +/** 現在可以放大絕招嗎 */ +export const ultReady = (s: RunState): boolean => { + const u = s.ult ?? { charge: 0, used: 0, max: 1 }; + return !s.options.tutorial && !s.options.noUltimate && u.used < u.max && u.charge >= 100; +}; + +/** 週末結算後集氣(endWeek 呼叫);flips 是這週翻轉的區數 */ +export function chargeUltimate(s: RunState, flips: number): void { + if (s.options.tutorial || s.options.noUltimate) return; + const u = ensure(s); + if (u.used >= u.max) return; + const d = deficit(s); + const gain = (d > 0 ? d * ULT.perPoint : ULT.ahead) + flips * ULT.flip; + u.charge = Math.min(100, u.charge + gain); +} + +/** 新的一週開始(startWeek 呼叫):倒數第 3 週,放過一次、還落後很多,就再給一次 */ +export function secondChance(s: RunState): boolean { + if (s.options.tutorial || s.options.noUltimate) return false; + const u = ensure(s); + if (s.week !== s.totalWeeks - 2 || u.used < 1 || u.max > 1) return false; + if (deficit(s) <= ULT.secondGap * 100) return false; + u.max = 2; + u.charge = 100; + s.log.push({ side: "system", text: "還落後很多,支持者不放棄:大絕招又集滿了,可以再放一次", town: null, votes: 0 }); + return true; +} + +/** 掃街馬拉松沒有挑區時:你和對手差距最小的 3 個區(對手領先優先) */ +export function suggestTowns(s: RunState, n = 3): string[] { + const gap = (t: TownState) => (t.rival - t.you) / (t.voters || 1); + return [...s.towns] + .sort((a, b) => Math.abs(gap(a) - 0.01) - Math.abs(gap(b) - 0.01)) + .slice(0, n) + .map((t) => t.code); +} + +/** 放大絕招:kind 是哪一招,score 是小遊戲分數(0–100),towns 是掃街馬拉松挑的區 */ +export function applyUltimate(s: RunState, kind: MiniGameKind, score: number, towns?: readonly string[]): { error: string } | null { + if (!ultReady(s)) return { error: "大絕招還沒集滿" }; + if (s.phase !== "plan") return { error: "現在不能放大絕招" }; + const u = ensure(s); + const pts = Math.max(0, Math.min(100, Math.round(score))) / 100; + const mult = ultMultiplier(s); + const info = ULTIMATES[kind]; + const label = `大絕招・${info.name}(${Math.round(pts * 100)} 分,落後倍率 ×${mult.toFixed(1)})`; + if (kind === "rally") { + const net = cityVotes(s, ULT.city * s.scale * pts * mult); + const m = pts >= 0.7 ? 2 : pts >= 0.4 ? 1 : 0; + if (m) addMomentum(s, m); + s.log.push({ side: "you", text: `${label}${m ? `:聲勢 +${m}` : ""}`, town: null, votes: Math.round(net) }); + } else { + const picked = kind === "handshake" ? (towns ?? []).filter((c) => s.towns.some((t) => t.code === c)) : []; + const codes = kind === "handshake" ? (picked.length ? picked : suggestTowns(s)).slice(0, 3) : rivalFlags(s); + for (const code of codes) { + const t = s.towns.find((x) => x.code === code)!; + const net = moveVotes(t, ULT.town * s.scale * t.reach * pts * mult, "you"); + if (kind === "billboard") t.office += ULT.office * pts; + s.log.push({ side: "you", text: `${label}・${t.name}`, town: t.code, votes: Math.round(net) }); + } + } + u.used += 1; + u.charge = 0; + s.stats.ultimates = (s.stats.ultimates ?? 0) + 1; + return null; +} + +/** 看板大作戰的目標:對手插旗、差距最小的 3 個區(不夠就補差距最小的區) */ +function rivalFlags(s: RunState): string[] { + const gap = (t: TownState) => (t.rival - t.you) / (t.voters || 1); + const flags = s.towns.filter((t) => t.flag === "rival").sort((a, b) => gap(a) - gap(b)); + const rest = suggestTowns(s, 6).filter((c) => !flags.some((t) => t.code === c)); + return [...flags.map((t) => t.code), ...rest].slice(0, 3); +} diff --git a/backend/packages/rogue/src/view.ts b/backend/packages/rogue/src/view.ts new file mode 100644 index 0000000..718a4f8 --- /dev/null +++ b/backend/packages/rogue/src/view.ts @@ -0,0 +1,393 @@ +import type { RogueCard, RogueCatalog, RogueChoice, RogueDeckCard, RogueOffer, RoguePreview, RogueScene, RogueStop, RogueView } from "@election2026/protocol"; +import { ADVISOR_BY_ID, ADVISORS } from "./advisors.ts"; +import { blockedReason, cardCost, counterable, attackable, defOf, playCard } from "./cards.ts"; +import { CRISIS_CHOICES, DEBATE_MOVES, PRESS_BY_ID, STOP_EVENT_BY_ID, type Choice } from "./content.ts"; +import { ORIGINS } from "@election2026/protocol"; +import { ULTIMATES, deficit, suggestTowns, ultMultiplier, ultReady } from "./ultimate.ts"; +import { CARD_BY_ID, EVENTS, KEYWORD_LABELS, ORIGIN_CARDS, POWERS, REPORTER_PENALTY, REWARD_CARDS, cardDef, findCard, upgradable, type CardDef } from "./data.ts"; +import { FEATS } from "./feats.ts"; +import { ABILITY_EFFECTS, ABILITY_LABELS, BUILDINGS, POLICY_HOME } from "./meta.ts"; +import { ASCENSION, eventOf, has, momentumMax } from "./mechanics.ts"; +import { BIG_RALLY_WEEK, RIVAL_TRAITS, intentDamp, intentLabel } from "./rival.ts"; +import { encounterById, fillVars, MINIGAME_INFO, pickInDoor, PRICES, SKIP_MONEY, STOP_LABELS } from "./route.ts"; +import { bestArg, choiceBlocked, debateSure } from "./scenes.ts"; +import { electionForecast } from "./rules.ts"; +import { MAX_ADVISORS, round10, totals, type CardInst, type RunState, type ShopItem, type Stop } from "./state.ts"; + +const fmt = (n: number): string => round10(n).toLocaleString("en-US"); + +/** 牌面:大字(主要數字)和一句話,數字已乘上這個縣市的比例尺 */ +function face(s: RunState | null, card: CardDef): { value: string | null; text: string } { + const scale = s?.scale ?? 1; + const e = card.effect; + const n = (base: number) => base * scale; + const fill = (text: string, v: Record) => text.replace(/\{(\w+)\}/g, (_, k: string) => v[k] ?? ""); + switch (e.kind) { + case "gain": + case "rally": + case "spread": + case "city": + case "gamble": + case "kneel": + case "flags": + return { value: `+${fmt(n(e.base))}`, text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "shield": { + const shield = n(e.base) * (s && has(s, "old_stake") ? 2 : 1); + return e.gain > e.base + ? { value: `+${fmt(n(e.gain))}`, text: fill(card.text, { n: fmt(n(e.gain)), s: fmt(shield) }) } + : { value: `盾 ${fmt(shield)}`, text: fill(card.text, { n: fmt(shield) }) }; + } + case "counter": + return { value: `剩${Math.round(e.cut * 10)}成`, text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "clarify": + return { value: e.cut === 0 ? "全擋" : "擋批評", text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "nullify": + return { value: "失效", text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "probe": + return { value: "把柄", text: card.text }; + case "expose": + case "contrast": + return { value: `−${fmt(n(e.base))}`, text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "office": + return { value: `+${fmt(n(e.perWeek))}/週`, text: fill(card.text, { n: fmt(n(e.perWeek)) }) }; + case "money": + return { value: `+${e.base}萬`, text: fill(card.text, { m: String(e.base) }) }; + case "base": + return { value: `+${fmt(n(e.base))}×${e.towns}`, text: fill(card.text, { n: fmt(n(e.base)) }) }; + case "draw": + return { value: `抽${e.cards}`, text: card.text.replace("2", String(e.cards)) }; + case "rush": + return { value: `體力+${e.energy}`, text: card.text.replace("+2", `+${e.energy}`) }; + case "buff": + return { value: `×${e.mult}`, text: fill(card.text, { n: fmt(n(e.base)) }).replace("×1.5", `×${e.mult}`) }; + case "power": + return { value: "能力", text: card.text }; + case "answer": + return { value: "回應", text: fill(card.text, { n: fmt(n(e.base)), n2: fmt(n(REPORTER_PENALTY)) }) }; + case "none": + return { value: null, text: card.text }; + } +} + +const keywordLabels = (card: CardDef) => (card.keywords ?? []).map((k) => KEYWORD_LABELS[k]); + +/** 政策卡用玩家取的名字 */ +const named = (s: RunState, card: CardDef, up: boolean): CardDef => { + const name = s.policyNames?.[card.id]; + return name ? { ...card, name: `${name}${up ? "+" : ""}` } : card; +}; + +export function cardView(s: RunState, c: CardInst): RogueCard { + const card = named(s, defOf(c), !!c.up); + const cost = cardCost(s, card); + return { + uid: c.uid, + id: c.id, + name: card.name, + art: card.art, + cost: cost.energy, + money: cost.money, + rarity: card.rarity, + tags: [...card.tags], + target: card.target, + ...face(s, card), + keywords: keywordLabels(card), + up: !!c.up, + blocked: s.phase === "plan" ? blockedReason(s, card) : null, + }; +} + +function deckCard(s: RunState, c: CardInst, pile: RogueDeckCard["pile"]): RogueDeckCard { + const card = named(s, defOf(c), !!c.up); + const plus = upgradable(c.id, c.up) ? cardDef(c.id, true)! : null; + return { + uid: c.uid, + id: c.id, + name: card.name, + art: card.art, + cost: card.cost, + money: card.money, + rarity: card.rarity, + tags: [...card.tags], + target: card.target, + ...face(s, card), + keywords: keywordLabels(card), + up: !!c.up, + pile, + plus: plus ? { name: plus.name, cost: plus.cost, ...face(s, plus) } : null, + }; +} + +export function cardOffer(s: RunState | null, id: string, extra: Partial = {}): RogueOffer { + const card = findCard(id)!; + return { kind: "card", id, name: card.name, art: card.art, rarity: card.rarity, tags: [...card.tags], keywords: keywordLabels(card), cost: card.cost, money: card.money, ...face(s, card), price: null, sold: false, ...extra }; +} + +function advisorOffer(id: string, extra: Partial = {}): RogueOffer { + const a = ADVISOR_BY_ID.get(id)!; + return { kind: "advisor", id, name: a.name, text: a.text, art: a.art, rarity: "advisor", tags: [], keywords: [], cost: null, money: null, value: null, price: null, sold: false, ...extra }; +} + +function shopOffer(s: RunState, item: ShopItem): RogueOffer { + const extra = { price: item.price, sold: item.sold }; + if (item.kind === "card") return cardOffer(s, item.id, extra); + if (item.kind === "advisor") return advisorOffer(item.id, extra); + return { kind: "remove", id: "remove", name: "刪牌服務", text: "從牌組拿掉一張牌", art: "rest", rarity: "service", tags: ["status"], keywords: [], cost: null, money: null, value: null, ...extra }; +} + +const choiceView = (s: RunState, c: Choice): RogueChoice => ({ label: c.label, hint: c.hint, blocked: choiceBlocked(s, c), risky: !!c.roll }); + +function sceneView(s: RunState): RogueScene | null { + const scene = s.scene; + if (!scene) return null; + switch (scene.kind) { + case "press": { + const def = PRESS_BY_ID.get(scene.id)!; + return { kind: "press", question: def.question, choices: def.choices.map((c) => choiceView(s, c)) }; + } + case "debate": { + const done = scene.round >= scene.topics.length; + const sure = debateSure(s); + return { + kind: "debate", + round: scene.round, + rounds: scene.topics.length, + topic: done ? null : scene.topics[scene.round]!, + challenge: done ? null : scene.challenges[scene.round]!, + sure, + best: done || !sure ? null : bestArg(scene.hand, scene.needs[scene.round]!), + hand: scene.hand.map((a) => ({ kind: a.kind, label: DEBATE_MOVES[a.kind].label, text: a.text, policy: !!a.policy })), + moves: (["policy", "emotion", "question"] as const).map((id) => ({ id, label: DEBATE_MOVES[id].label, counters: DEBATE_MOVES[id].counters })), + history: scene.history.map((h, i) => ({ topic: scene.topics[i]!, challenge: scene.challenges[i]!, you: h.arg.kind, text: h.arg.text, result: h.result, combo: h.combo, votes: h.votes })), + combo: scene.combo, + wins: scene.wins, + losses: scene.losses, + }; + } + case "crisis": + return { + kind: "crisis", + amount: Math.round(scene.amount), + choices: CRISIS_CHOICES.map((c) => ({ label: c.label, hint: c.hint, blocked: "money" in c && s.money < c.money ? "資金不夠" : null, risky: c.id === "ignore" })), + }; + case "poll": + return { kind: "poll", you: scene.you, rival: scene.rival, lead: scene.lead }; + } +} + +function stopView(s: RunState): RogueStop | null { + return s.stop ? stopViewOf(s, s.stop) : null; +} + +function stopViewOf(s: RunState, stop: Stop): RogueStop { + switch (stop.kind) { + case "card": + return { kind: "card", options: stop.options.map((id) => cardOffer(s, id)) }; + case "advisor": + return { kind: "advisor", options: stop.options.map((id) => advisorOffer(id)) }; + case "upgrade": + case "remove": + return { kind: stop.kind }; + case "shop": + return { kind: "shop", items: stop.items.map((i) => shopOffer(s, i)) }; + case "encounter": { + const town = s.towns.find((t) => t.code === stop.town)!; + const e = stop.step < stop.encounters.length ? encounterById(stop.encounters[stop.step]!) : undefined; + return { + kind: "encounter", + town: town.code, + townName: town.name, + step: stop.step, + total: stop.encounters.length, + score: stop.score, + current: e ? { who: fillVars(e.who, s, town.name), line: fillVars(e.line, s, town.name), options: e.options.map((o) => ({ label: fillVars(o.label, s, town.name), risky: !!o.roll })) } : null, + notes: [...stop.notes], + }; + } + case "minigame": { + const town = s.towns.find((t) => t.code === stop.town) ?? null; + return { kind: "minigame", game: stop.game, ...MINIGAME_INFO[stop.game], town: town?.code ?? null, townName: town?.name ?? null, level: stop.level, seed: stop.seed }; + } + case "event": { + const def = STOP_EVENT_BY_ID.get(stop.id)!; + return { kind: "event", title: def.title, text: def.text, art: def.art, choices: def.choices.map((c) => choiceView(s, c)) }; + } + } +} + +/** + * 預估:把每張手牌打在每個目標上「試算」一次(機率事件取期望值),算出對選情的影響: + * 你多的票+對手少的票+擋掉的對手行動。畫面上的數字和真正打出去的結果用同一套規則。 + */ +export function previewsFor(s: RunState): Record { + const before = totals(s.towns); + const out: Record = {}; + for (const inst of s.hand) { + const card = defOf(inst); + if (blockedReason(s, card)) { + out[inst.uid] = []; + continue; + } + const targets = card.target === "town" ? s.towns.map((t) => t.code) : card.target === "intent" ? counterable(s).map((i) => i.id) : card.target === "attack" ? attackable(s).map((i) => i.id) : [null]; + out[inst.uid] = targets.flatMap((target): RoguePreview[] => { + const r = playCard(s, inst.uid, target, true); + if ("error" in r) return []; + const after = totals(r.state.towns); + // 打對台、澄清:對手的行動被削弱,少掉的部分也算進來(對手的樁腳只在你之後打那區時才有差,不算) + const prevented = r.state.intents + .filter((i) => i.kind !== "stake") + .reduce((a, i) => a + i.amount * intentDamp(s, i) * ((s.intents.find((x) => x.id === i.id)?.cut ?? i.cut) - i.cut), 0); + // 佈樁:這週可以擋掉對手在這區的行動(原本的樁腳已經擋住的部分不算) + let blocked = 0; + if (card.effect.kind === "shield" && target) { + const before = s.towns.find((t) => t.code === target)?.shield ?? 0; + const added = (r.state.towns.find((t) => t.code === target)?.shield ?? 0) - before; + const threat = r.state.intents.filter((i) => i.town === target && ["canvass", "rally", "smear"].includes(i.kind)).reduce((a, i) => a + i.amount * i.cut * intentDamp(s, i), 0); + blocked = Math.min(added, Math.max(0, threat - before)); + } + const notes = [...r.notes]; + if (blocked > 0) notes.push(`可擋對手 ${fmt(blocked)}`); + return [{ target: target ?? "city", votes: Math.round(after.you - before.you - (after.rival - before.rival) + prevented + blocked), note: notes.join("・") }]; + }); + } + return out; +} + +/** 雙方的代表色:照政黨色;教學關卡和同色的對手換成不屬於任何政黨的顏色 */ +function colorsOf(s: RunState): RogueView["colors"] { + if (s.options.tutorial) return { you: "#d6457a", rival: "#6b4fbb" }; + const you = `var(--slot-${s.setup.you.slot})`; + const rival = s.setup.rival.slot === s.setup.you.slot ? "#7a5cc4" : `var(--slot-${s.setup.rival.slot})`; + return { you, rival }; +} + +export function toView(s: RunState): RogueView { + const ev = eventOf(s); + const big = s.nextBig; + return { + runId: s.runId, + seed: s.seed, + scenarioId: s.setup.scenarioId, + scenarioName: s.setup.scenarioName, + packId: s.setup.packId, + countyCode: s.setup.countyCode, + countyName: s.setup.countyName, + area: s.setup.area ?? s.setup.countyName, + seats: s.setup.seats ?? 1, + threshold: s.setup.threshold ?? null, + office: s.setup.office, + options: { ascension: s.options.ascension, tutorial: s.options.tutorial, daily: s.options.daily, even: s.options.even || s.setup.scenarioId.endsWith("-even"), career: s.options.career ?? null, abilities: s.options.abilities ?? null, abilitiesBasis: s.options.abilitiesBasis ?? null, origin: s.options.origin ?? null }, + week: s.week, + totalWeeks: s.totalWeeks, + phase: s.phase, + energy: s.energy, + energyMax: s.energyMax, + money: Math.round(s.money), + momentum: s.momentum, + rivalMomentum: s.rivalMomentum, + momentumMax: momentumMax(s), + leverage: s.leverage, + you: s.setup.you, + rival: s.setup.rival, + others: s.setup.others, + colors: colorsOf(s), + rivalTrait: RIVAL_TRAITS[s.setup.rivalStyle], + towns: s.towns.map((t) => ({ + code: t.code, + name: t.name, + voters: Math.round(t.voters), + you: Math.round(t.you), + rival: Math.round(t.rival), + others: Math.round(t.others), + undecided: Math.round(t.undecided), + traits: [...t.traits], + neighbors: [...t.neighbors], + shield: Math.round(t.shield), + rivalShield: Math.round(t.rivalShield), + office: t.office > 0, + played: t.played.map((id) => ({ id, name: s.policyNames?.[id] ?? findCard(id)?.name ?? id, art: findCard(id)?.art ?? id })), + flag: t.flag, + })), + intents: s.intents.map((i) => ({ id: i.id, kind: i.kind, label: intentLabel(s, i), town: i.town, amount: Math.round(i.amount), cut: i.cut, big: !!i.big })), + nextBig: big && big.town ? { week: BIG_RALLY_WEEK, town: big.town, label: intentLabel(s, big), amount: Math.round(big.amount) } : null, + event: { id: ev.id, title: ev.title, text: ev.text }, + hand: s.hand.map((c) => cardView(s, c)), + drawCount: s.draw.length, + discardCount: s.discard.length, + exhaustedCount: s.exhausted.length, + deck: [...s.draw.map((c) => deckCard(s, c, "draw")), ...s.hand.map((c) => deckCard(s, c, "hand")), ...s.discard.map((c) => deckCard(s, c, "discard"))].sort( + (a, b) => a.name.localeCompare(b.name, "zh-Hant") || Number(a.up) - Number(b.up), + ), + advisors: s.advisors.map((id) => ADVISOR_BY_ID.get(id)!).map((a) => ({ id: a.id, name: a.name, text: a.text, art: a.art, school: a.school })), + advisorSlots: MAX_ADVISORS, + powers: s.powers.map((p) => POWERS[p]?.label ?? p), + buffs: s.buffs.map((b) => `這週媒體牌 ×${b.mult}`), + previews: s.phase === "plan" ? previewsFor(s) : {}, + scene: sceneView(s), + // 門上直接攤開內容(拜會地方的三張牌、幕僚、地方抉擇的選項),一次點選就拿到 + route: s.route ? s.route.map((kind, i) => ({ kind, ...STOP_LABELS[kind], preview: pickInDoor(kind) && s.routeStops?.[i] ? stopViewOf(s, s.routeStops[i]!) : null })) : null, + poll: s.poll ?? null, + ultimate: s.options.tutorial + ? null + : { + charge: Math.round(s.ult?.charge ?? 0), + ready: ultReady(s), + used: s.ult?.used ?? 0, + max: s.ult?.max ?? 1, + mult: Math.round(ultMultiplier(s) * 10) / 10, + deficit: Math.round(deficit(s) * 10) / 10, + options: (Object.keys(ULTIMATES) as (keyof typeof ULTIMATES)[]).map((kind) => ({ kind, ...ULTIMATES[kind] })), + suggest: suggestTowns(s), + }, + stop: stopView(s), + skipMoney: SKIP_MONEY, + log: [...s.log], + forecast: electionForecast(s), + tally: (() => { + const t = s.tally ?? { gained: 0, lost: 0, blocked: 0, startYou: 0, startRival: 0 }; + return { gained: Math.round(t.gained), lost: Math.round(t.lost), blocked: Math.round(t.blocked), startYou: t.startYou, startRival: t.startRival }; + })(), + notes: [], + history: s.history.map((h) => ({ ...h })), + result: s.result, + }; +} + +/** 圖鑑:全部的牌、幕僚、成就、逆風難度 */ +/** 圖鑑:還沒拿到的牌、幕僚、事件怎麼拿到(畫面上灰色的格子寫這個) */ +const SPECIAL_HOW: Record = { + sympathy: "民調公布時落後,手上會多一張", + soundbite: "電視辯論三連擊全勝", + walkx: "幕僚「黨部組織部」每週送一張", + reporter: "沒擋下對手的「批評你的政見」、加稅財源的政策、某些記者堵麥的回答", + storm: "自創角色是民進黨或國民黨:第 3 或第 4 週的黨中央風波", + favor: "地方抉擇或記者堵麥選了欠人情的回答", + tired: "地方抉擇、熬夜行程的代價", +}; + +/** 出身專屬牌 → 哪個出身 */ +const ORIGIN_OF_CARD = new Map(Object.entries(ORIGINS).map(([bg, o]) => [o.card, bg])); + +function cardHow(c: CardDef): string { + if (SPECIAL_HOW[c.id]) return SPECIAL_HOW[c.id]!; + if (ORIGIN_OF_CARD.has(c.id)) return `自創角色的出身選「${ORIGIN_OF_CARD.get(c.id)}」,開局就有一張`; + if (c.rarity === "basic") return "開局牌組就有"; + if (c.rarity === "status") return "劇情或對手的行動塞進牌組"; + const where = c.rarity === "rare" ? "拜會地方、競選物資行、地方抉擇(稀有,比較少出現)" : "拜會地方(三選一)、競選物資行、地方抉擇"; + return c.effect.kind === "kneel" ? `${where};最後 3 週才會出現` : where; +} + +export function catalog(): RogueCatalog { + return { + abilities: (Object.keys(ABILITY_LABELS) as (keyof typeof ABILITY_LABELS)[]).map((id) => ({ id, label: ABILITY_LABELS[id], effect: ABILITY_EFFECTS[id] })), + policyHome: { ...POLICY_HOME }, + buildings: BUILDINGS.map(({ perk: _perk, ...b }) => ({ ...b, levels: [...b.levels], cost: [...b.cost] })), + cards: [...REWARD_CARDS, ...ORIGIN_CARDS, ...[...CARD_BY_ID.values()].filter((c) => c.rarity === "basic" || c.rarity === "status")].map((c) => ({ ...cardOffer(null, c.id), how: cardHow(c) })), + advisors: ADVISORS.map((a) => ({ id: a.id, name: a.name, text: a.text, art: a.art, school: a.school, how: "招募幕僚(偶數週一定有這扇門)、競選物資行、地方抉擇;政治生涯當選後可以帶 2 位到下一場" })), + feats: FEATS.map((f) => ({ ...f })), + ascension: [...ASCENSION], + events: EVENTS.map((e) => ({ id: e.id, title: e.title, text: e.text, how: "每週開始時隨機發生,多打幾週就會遇到" })), + }; +} + +export { PRICES }; diff --git a/backend/packages/rogue/test/fixtures.ts b/backend/packages/rogue/test/fixtures.ts new file mode 100644 index 0000000..a5f2ccb --- /dev/null +++ b/backend/packages/rogue/test/fixtures.ts @@ -0,0 +1,69 @@ +import type { CandidatePublic } from "@election2026/protocol"; +import { choose, endWeek } from "../src/rules.ts"; +import type { RogueSetup, RunState } from "../src/state.ts"; + +/** 測試共用:一個四區的假城市、往前推進的小工具 */ + +export const person = (id: string, number: number, isPlayer = false): CandidatePublic => ({ + id, + name: id, + party: null, + slot: "other", + number, + isPlayer, + description: "", + issueIds: [], + tags: [], + avatar: null, + runningMate: null, + gender: null, + slogan: null, + sloganSource: null, +}); + +export const lean = { you: 0.45, rival: 0.45, others: 0.1 }; +export const SETUP: RogueSetup = { + scenarioId: "test", + scenarioName: "測試市長", + packId: "test", + countyCode: "00000", + countyName: "測試市", + office: "市長", + you: person("me", 1, true), + rival: person("rival", 2), + others: [person("minor", 3)], + towns: [ + { code: "A", name: "甲區", voters: 300_000, lean, traits: ["dense", "young"], neighbors: ["B"] }, + { code: "B", name: "乙區", voters: 200_000, lean, traits: ["old", "temples"], neighbors: ["A", "C"] }, + { code: "C", name: "丙區", voters: 50_000, lean, traits: ["rural"], neighbors: ["B"] }, + { code: "D", name: "丁區", voters: 150_000, lean, traits: ["hakka"], neighbors: [] }, + ], + money: 1000, + rivalStyle: "balanced", + rivalReal: true, +}; + +export const must = (r: RunState | { error: string }): RunState => { + if ("error" in r) throw new Error(r.error); + return r; +}; + +/** 一週一週往前(不出牌、下一站都不去),到第 week 週開場 */ +export function advance(s: RunState, week: number): RunState { + while (s.week < week) s = must(choose(must(endWeek(toPlan(s))), "skip")); + return s; +} + +/** 一路選第一個選項,直到可以出牌 */ +export function toPlan(s: RunState): RunState { + // 記者堵麥在出牌階段也要先回答(s.scene 還在) + for (let k = 0; k < 20 && (s.phase !== "plan" || s.scene) && s.phase !== "finished"; k++) { + if (s.phase === "stop" && (s.stop?.kind === "upgrade" || s.stop?.kind === "remove")) s = must(choose(s, "skip")); + else if (s.phase === "stop" && s.stop?.kind === "shop") s = must(choose(s, "skip")); + else { + const r = choose(s, 0); + s = "error" in r ? must(choose(s, 1)) : r; + } + } + return s; +} diff --git a/backend/packages/rogue/test/meta.test.ts b/backend/packages/rogue/test/meta.test.ts new file mode 100644 index 0000000..c8298cd --- /dev/null +++ b/backend/packages/rogue/test/meta.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from "vitest"; +import { cardDef, findCard } from "../src/data.ts"; +import { policyCardDef, policyCardId, policySlots } from "../src/meta.ts"; +import { MINIGAME } from "../src/route.ts"; +import { choose, createRun, endWeek, playCard, ultimate } from "../src/rules.ts"; +import { ultReady } from "../src/ultimate.ts"; +import { CRISIS_BASE } from "../src/scenes.ts"; +import { totals, type RunState } from "../src/state.ts"; +import { toView } from "../src/view.ts"; +import { SETUP, advance, must, toPlan } from "./fixtures.ts"; + +/** 跨局成長(docs/23):政策島的建築、政治生涯的能力、政策工坊的政策、選戰小遊戲 */ + +const deck = (s: RunState) => [...s.draw, ...s.discard, ...s.hand]; + +describe("政策島的建築", () => { + it("競選金庫、觀光夜市加開局資金;競選總部加聲勢;競選學院升級開局牌", () => { + const base = createRun(SETUP, "r", 5); + const s = createRun(SETUP, "r", 5, { + perks: [ + { id: "vault", level: 2 }, + { id: "nightmarket", level: 1 }, + { id: "hq", level: 1 }, + { id: "academy", level: 2 }, + ], + }); + expect(s.money - base.money).toBe(150 * 2 + 50); + expect(s.momentum).toBe(1); + expect(deck(s).filter((c) => c.up).length).toBe(2); + }); + + it("不認得的建築不算、等級夾在 1–3", () => { + const s = createRun(SETUP, "r", 5, { perks: [{ id: "casino", level: 3 }, { id: "vault", level: 9 }] }); + expect(s.options.perks).toEqual({ vault: 3 }); + }); + + it("交通樞紐前幾週體力 +1;志工之家第 1 週多抽牌", () => { + const s = createRun(SETUP, "r", 5, { perks: [{ id: "hub", level: 2 }, { id: "volunteer", level: 1 }] }); + expect(s.energyMax).toBe(4); + expect(s.hand).toHaveLength(6); + const w3 = advance(s, 3); + expect(w3.energyMax).toBe(3); + }); + + it("長照中心讓長輩多的區更有效", () => { + const plain = createRun(SETUP, "r", 5); + const care = createRun(SETUP, "r", 5, { perks: [{ id: "care", level: 2 }] }); + const play = (s: RunState) => { + const t = structuredClone(s); + t.hand = [{ uid: "x", id: "canvass" }]; + t.energy = 3; + const r = playCard(t, "x", "B"); + if ("error" in r) throw new Error(r.error); + return r.state.towns.find((x) => x.code === "B")!.you - s.towns.find((x) => x.code === "B")!.you; + }; + expect(play(care) / play(plain)).toBeCloseTo(1.16, 1); + }); + + it("政策研究院:每局可以帶的政策份數", () => { + expect(policySlots({})).toBe(1); + expect(policySlots({ library: 1 })).toBe(2); + expect(policySlots({ library: 3 })).toBe(3); + }); +}); + +describe("政治生涯的能力", () => { + it("財務:開局資金、每週收入都變多", () => { + const base = createRun(SETUP, "r", 5); + const rich = createRun(SETUP, "r", 5, { abilities: { eloquence: 0, organization: 0, media: 0, finance: 2, integrity: 0 } }); + expect(rich.money - base.money).toBe(160); + const income = (s: RunState) => must(endWeek(toPlan(s))).money - s.money; + expect(income(rich) - income(base)).toBe(30); + }); + + it("清廉:匿名黑函的損失變小", () => { + const clean = advance(createRun(SETUP, "r", 33, { abilities: { eloquence: 0, organization: 0, media: 0, finance: 0, integrity: 5 } }), 6); + expect(clean.scene!.kind).toBe("crisis"); + expect((clean.scene as { amount: number }).amount).toBeCloseTo(CRISIS_BASE * clean.scale * 0.4); + }); + + it("口才 3 級辯論多一張論點、5 級看得出最好的論點", () => { + const talk = (eloquence: number) => advance(createRun(SETUP, "r", 21, { abilities: { eloquence, organization: 0, media: 0, finance: 0, integrity: 0 } }), 3); + const d0 = talk(0).scene as Extract; + const d3 = talk(3).scene as Extract; + expect(d3.hand.length).toBe(d0.hand.length + 1); + expect((toView(talk(4)).scene as { best: number | null }).best).toBeNull(); + expect((toView(talk(5)).scene as { best: number | null }).best).not.toBeNull(); + }); +}); + +describe("政策工坊", () => { + const policy = { name: "銀髮安心卡", target: "old", method: "subsidy", funding: "tax" } as const; + + it("政策變成一張牌:第 1 週就在手上、用玩家取的名字", () => { + const s = createRun(SETUP, "r", 5, { policies: [policy] }); + const id = policyCardId(0, policy); + expect(s.hand.some((c) => c.id === id)).toBe(true); + const view = toView(s); + expect(view.hand.find((c) => c.id === id)!.name).toBe("銀髮安心卡"); + expect(findCard(id)!.cost).toBe(1); + }); + + it("沒有政策研究院只能帶 1 份", () => { + const s = createRun(SETUP, "r", 5, { policies: [policy, { ...policy, name: "第二份" }] }); + expect(Object.keys(s.policyNames ?? {})).toHaveLength(1); + }); + + it("財源:加稅花費少一半但多一張記者追問;招商加資金;刪預算全市掉一點票", () => { + const play = (funding: "tax" | "invest" | "cut") => { + const p = { ...policy, funding }; + const s = createRun(SETUP, "r", 5, { policies: [p] }); + const uid = s.hand.find((c) => c.id === policyCardId(0, p))!.uid; + const r = playCard(s, uid, "B"); + if ("error" in r) throw new Error(r.error); + return { before: s, after: r.state }; + }; + const tax = play("tax"); + expect(tax.after.discard.filter((c) => c.id === "reporter").length).toBe(1); + expect(policyCardDef(policyCardId(0, { ...policy, funding: "tax" }))!.money).toBe(Math.round(policyCardDef(policyCardId(0, { ...policy, funding: "cut" }))!.money * 0.5)); + const invest = play("invest"); + expect(invest.after.money - invest.before.money).toBe(100 - policyCardDef(policyCardId(0, { ...policy, funding: "invest" }))!.money); + const cut = play("cut"); + expect(cut.after.log.some((l) => l.text.includes("被刪預算"))).toBe(true); + }); + + it("政策落地:這份政策的「家」(上班族→交通樞紐)每級 +10%", () => { + const p = { name: "通勤補助", target: "workers", method: "subsidy", funding: "tax" } as const; + const gain = (perks: { id: string; level: number }[]) => { + const s = createRun(SETUP, "r", 5, { policies: [p], perks }); + const uid = s.hand.find((c) => c.id === policyCardId(0, p))!.uid; + const r = playCard(s, uid, "C"); + if ("error" in r) throw new Error(r.error); + return { votes: r.state.towns.find((t) => t.code === "C")!.you - s.towns.find((t) => t.code === "C")!.you, notes: r.notes }; + }; + const plain = gain([]); + const landed = gain([{ id: "hub", level: 2 }]); + expect(landed.votes / plain.votes).toBeCloseTo(1.2, 1); + expect(landed.notes.some((n) => n.includes("交通樞紐落地"))).toBe(true); + }); + + it("格式不對的政策牌 id 找不到", () => { + expect(policyCardDef("policy:0:aliens:subsidy:tax")).toBeUndefined(); + expect(policyCardDef("policy:x")).toBeUndefined(); + expect(cardDef("policy:0:old:subsidy:tax")).toBeDefined(); + }); +}); + +describe("選戰小遊戲", () => { + /** 直接把下一站換成小遊戲 */ + function atGame(game: "handshake" | "rally" | "billboard"): RunState { + const s = must(endWeek(toPlan(createRun(SETUP, "r", 8)))); + s.route = null; + s.phase = "stop"; + s.stop = { kind: "minigame", game, town: game === "rally" ? null : "A", level: 0.3, seed: 1 }; + return s; + } + + it("掃街握手:分數越高那一區加越多票,90 分以上聲勢 +1", () => { + const a = atGame("handshake"); + const low = must(choose(a, 30)); + const high = must(choose(atGame("handshake"), 95)); + const gain = (x: RunState) => x.towns.find((t) => t.code === "A")!.you - a.towns.find((t) => t.code === "A")!.you; + expect(gain(high)).toBeGreaterThan(gain(low) * 2); + expect(high.momentum).toBeGreaterThan(low.momentum); + }); + + it("造勢喊凍蒜:40、80 分各一個門檻", () => { + const m = (score: number) => { + const s = atGame("rally"); + return must(choose(s, score)).momentum - s.momentum; + }; + expect([m(20), m(50), m(85)]).toEqual([0, 1, 2]); + }); + + it("看板卡位:那一區之後每週多票", () => { + const s = must(choose(atGame("billboard"), 70)); + expect(s.towns.find((t) => t.code === "A")!.office).toBe(MINIGAME.billboardBase + MINIGAME.billboardStep * 70); + }); + + it("不玩不給分;分數超過 100 不行", () => { + const s = atGame("handshake"); + const skipped = must(choose(s, "skip")); + expect(totals(skipped.towns).you).toBeCloseTo(totals(s.towns).you); + expect("error" in choose(atGame("rally"), 101)).toBe(true); + }); + + it("小遊戲的畫面資料:遊戲、區、難度、種子", () => { + const v = toView(atGame("billboard")).stop as { kind: string; game: string; townName: string; seed: number }; + expect(v).toMatchObject({ kind: "minigame", game: "billboard", townName: "甲區", seed: 1 }); + }); +}); + +describe("出身與黨的資源(18 第 53 項)", () => { + const origin = (party: string | null, background = "律師") => ({ background, party, kind: (party === "民主進步黨" || party === "中國國民黨" ? "major" : party === "台灣民眾黨" ? "tpp" : "minor") as "major" | "tpp" | "minor" }); + + it("出身專屬牌第一週就在手上,不會出現在獎勵裡", () => { + const s = createRun(SETUP, "r", 5, { origin: origin(null, "律師") }); + expect(s.hand.some((c) => c.id === "origin_legal")).toBe(true); + expect(cardDef("origin_legal")?.tags).toContain("origin"); + }); + + it("大黨:第 3 或第 4 週黨中央風波(手上多一張),開局多一張黨部動員掃街", () => { + const s = createRun(SETUP, "r", 5, { origin: origin("中國國民黨") }); + expect([3, 4]).toContain(s.partyStorm); + expect([...s.hand, ...s.draw].some((c) => c.id === "walkx")).toBe(true); + const w = advance(s, s.partyStorm!); + expect(w.hand.some((c) => c.id === "storm")).toBe(true); + expect(w.log.some((l) => l.text.startsWith("黨中央風波"))).toBe(true); + }); + + it("小黨、無黨籍:起步多 0.2 個百分點,沒有黨中央風波", () => { + const base = createRun(SETUP, "r", 5); + const s = createRun(SETUP, "r", 5, { origin: origin("時代力量") }); + expect(s.partyStorm).toBeNull(); + const committed = (x: RunState) => x.towns.reduce((a, t) => a + t.you + t.rival + t.others, 0); + const gain = (totals(s.towns).you - totals(base.towns).you) / committed(base); + expect(gain).toBeCloseTo(0.002, 3); + }); +}); + +describe("大絕招(18 第 57 項)", () => { + /** 開局硬調成落後 gap 個百分點 */ + const behind = (gap: number) => ({ + ...SETUP, + towns: SETUP.towns.map((t) => ({ ...t, lean: { you: t.lean.you - gap / 200, rival: t.lean.rival + gap / 200, others: t.lean.others } })), + }); + + it("落後越多集越快;集滿可以放,玩得好票加得多,放完就沒了", () => { + let s = createRun(behind(14), "r", 5); + expect(ultReady(s)).toBe(false); + s = advance(s, 2); + expect(s.ult!.charge).toBeGreaterThanOrEqual(100); + expect(ultReady(s)).toBe(true); + s = toPlan(s); + const good = must(ultimate(s, "rally", 95)); + const bad = must(ultimate(s, "rally", 20)); + const gain = (x: RunState) => totals(x.towns).you - totals(s.towns).you; + expect(gain(good)).toBeGreaterThan(gain(bad) * 3); + expect(ultReady(good)).toBe(false); + expect("error" in ultimate(good, "rally", 90)).toBe(true); + }); + + it("領先時集得很慢", () => { + const s = advance(createRun(behind(-10), "r", 5), 3); + expect(s.ult!.charge).toBeLessThan(20); + }); + + it("掃街馬拉松只加挑的區;新手教學沒有大絕招", () => { + let s = toPlan(advance(createRun(behind(14), "r", 5), 2)); + const code = s.towns[0]!.code; + const r = must(ultimate(s, "handshake", 80, [code])); + expect(r.towns[0]!.you).toBeGreaterThan(s.towns[0]!.you); + expect(r.towns[1]!.you).toBe(s.towns[1]!.you); + s = createRun(SETUP, "t", 5, { tutorial: true }); + expect(toView(s).ultimate).toBeNull(); + }); +}); diff --git a/backend/packages/rogue/test/rules.test.ts b/backend/packages/rogue/test/rules.test.ts new file mode 100644 index 0000000..132c4fc --- /dev/null +++ b/backend/packages/rogue/test/rules.test.ts @@ -0,0 +1,502 @@ +import { describe, expect, it } from "vitest"; +import { runBot, type BotName } from "../src/bots.ts"; +import { PRESS, STOP_EVENTS } from "../src/content.ts"; +import { CARD_BY_ID, cardDef, PLUS_MULT, REPORTER_PENALTY } from "../src/data.ts"; +import { choose, COMBO_STEP, createRun, endWeek, playCard } from "../src/rules.ts"; +import { townNeighbors } from "../src/setup.ts"; +import { FLAG_LEAD, totals, UNDECIDED_START, type Intent, type RunState } from "../src/state.ts"; +import { TUTORIAL_DECK, TUTORIAL_WEEKS, tutorialSetup } from "../src/tutorial.ts"; +import { previewsFor, toView } from "../src/view.ts"; +import { SETUP, advance, must, toPlan } from "./fixtures.ts"; + +const SCALE = 0.7; +/** 牌的基準票數(直接讀資料,調平衡時測試不用跟著改) */ +const cardBase = (id: string, up = false): number => { + const e = cardDef(id, up)!.effect as { base?: number }; + return e.base ?? 0; +}; +const effect = (id: string) => CARD_BY_ID.get(id)!.effect as unknown as Record; + +/** 指定手牌、換掉對手意圖(連同對手已經生效的樁腳),方便算數字 */ +function withHand(s: RunState, ids: string[], intents: Intent[] = []): RunState { + const copy = structuredClone(s); + return { ...copy, phase: "plan", scene: null, towns: copy.towns.map((t) => ({ ...t, shield: 0, rivalShield: 0 })), hand: ids.map((id, i) => ({ uid: `t${i}`, id })), intents, energy: 9, money: 5000, momentum: 0 }; +} + +const ok = (r: ReturnType): RunState => { + if ("error" in r) throw new Error(r.error); + return r.state; +}; + +describe("開局", () => { + it("同一個種子同一局;第一週 3 點體力、5 張手牌、對手 2 個意圖(第一週不批評)", () => { + const a = createRun(SETUP, "r", 42); + expect(createRun(SETUP, "r", 42)).toEqual(a); + expect(createRun(SETUP, "r", 43).hand.map((c) => c.id)).not.toEqual(a.hand.map((c) => c.id)); + expect(a.version).toBe(2); + expect(a.week).toBe(1); + expect(a.phase).toBe("plan"); + expect(a.energy).toBe(3); + expect(a.hand).toHaveLength(5); + expect(a.intents).toHaveLength(2); + expect(a.intents.some((i) => i.kind === "attack" || i.kind === "smear")).toBe(false); + const t = totals(a.towns); + expect(t.undecided / t.voters).toBeCloseTo(UNDECIDED_START); + expect(a.scale).toBeCloseTo(SCALE); + expect(a.towns[0]!.reach).toBeGreaterThan(1.1); + expect(a.towns[2]!.reach).toBeLessThan(0.75); + // 存檔:可以轉成 JSON 再讀回來 + expect(JSON.parse(JSON.stringify(a))).toEqual(a); + }); + + it("逆風難度:資金 −40%、牌組多人情包袱、對手開局聲勢、開局落後", () => { + const easy = createRun(SETUP, "r", 5); + const hard = createRun(SETUP, "r", 5, { ascension: 10 }); + expect(hard.money).toBe(Math.round(easy.money * 0.6)); + expect([...hard.draw, ...hard.hand].some((c) => c.id === "favor")).toBe(true); + expect(hard.rivalMomentum).toBe(2); + const gap = (s: RunState) => (totals(s.towns).you - totals(s.towns).rival) / (totals(s.towns).voters * (1 - UNDECIDED_START)); + expect(gap(easy) - gap(hard)).toBeCloseTo(0.03, 3); + expect(hard.startGap).toBeLessThan(easy.startGap); + }); +}); + +describe("出牌", () => { + const base = createRun(SETUP, "r", 1); + + it("掃街打在人口密集的區 ×1.3;花體力、牌進棄牌堆、不改原本的狀態", () => { + const s = withHand(base, ["canvass"]); + const before = structuredClone(s); + const after = ok(playCard(s, "t0", "A")); + expect(s).toEqual(before); + expect(after.towns[0]!.you - s.towns[0]!.you).toBeCloseTo(cardBase("canvass") * SCALE * s.towns[0]!.reach * 1.3); + expect(after.energy).toBe(8); + expect(after.hand).toHaveLength(0); + expect(after.discard.at(-1)!.id).toBe("canvass"); + expect(after.towns[0]!.played).toEqual(["canvass"]); + }); + + it("組合拳:同一區第二種牌 +15%,同一種牌不算", () => { + const s = withHand(base, ["canvass", "night", "canvass"]); + const one = ok(playCard(s, "t0", "A")); + const two = ok(playCard(one, "t1", "A")); + const reach = s.towns[0]!.reach; + expect(two.towns[0]!.you - one.towns[0]!.you).toBeCloseTo(cardBase("night") * SCALE * reach * 1.5 * (1 + COMBO_STEP)); + const again = ok(playCard(two, "t2", "A")); + expect(again.towns[0]!.you - two.towns[0]!.you).toBeCloseTo(cardBase("canvass") * SCALE * reach * 1.3); + }); + + it("升級:+版數字 ×1.35、名字加+;服務處+少 1 點體力", () => { + expect(cardBase("canvass", true)).toBe(Math.round((cardBase("canvass") * PLUS_MULT) / 10) * 10); + expect(cardDef("canvass", true)!.name).toBe("掃街拜票+"); + expect(cardDef("office", true)!.cost).toBe(1); + const s = withHand(base, ["canvass"]); + s.hand[0]!.up = true; + const after = ok(playCard(s, "t0", "C")); + expect(after.towns[2]!.you - s.towns[2]!.you).toBeCloseTo(cardBase("canvass", true) * SCALE * s.towns[2]!.reach); + }); + + it("造勢擴散到隔壁區兩成半,聲勢 +2", () => { + const s = withHand(base, ["rally"]); + const after = ok(playCard(s, "t0", "B")); + const b = s.towns[1]!; + // 區的大小係數離 1 不到 0.05 就不算 + const reach = Math.abs(b.reach - 1) >= 0.05 ? b.reach : 1; + expect(after.towns[1]!.you - b.you).toBeCloseTo(cardBase("rally") * SCALE * reach); + expect(after.towns[0]!.you - s.towns[0]!.you).toBeCloseTo(cardBase("rally") * 0.25 * SCALE * s.towns[0]!.reach); + expect(after.towns[3]!.you).toBeCloseTo(s.towns[3]!.you); + expect(after.momentum).toBe(2); + }); + + it("消耗的牌打完就沒了;能力牌整局有效", () => { + const s = withHand(base, ["mediatraining", "tv"]); + const one = ok(playCard(s, "t0", null)); + expect(one.exhausted.map((c) => c.id)).toEqual(["mediatraining"]); + expect(one.discard.some((c) => c.id === "mediatraining")).toBe(false); + expect(one.powers).toEqual(["media"]); + const plain = ok(playCard(s, "t1", null)); + const trained = ok(playCard(one, "t1", null)); + const gain = (x: RunState) => totals(x.towns).you; + expect((gain(trained) - gain(one)) / (gain(plain) - gain(s))).toBeCloseTo(1.25, 1); + }); + + it("對手的樁腳先擋掉你在那區的票", () => { + const s = withHand(base, ["canvass"]); + s.towns[2]!.rivalShield = 500; + const after = ok(playCard(s, "t0", "C")); + expect(after.towns[2]!.you - s.towns[2]!.you).toBeCloseTo(cardBase("canvass") * SCALE * s.towns[2]!.reach - 500); + expect(after.towns[2]!.rivalShield).toBe(0); + }); + + it("打對台:對手那區的行動剩四成,你在那區加票;週末對手只拿到四成", () => { + const intent: Intent = { id: "i1", kind: "canvass", town: "B", amount: 3000, cut: 1 }; + const s = withHand(base, ["counter"], [intent]); + const after = ok(playCard(s, "t0", "i1")); + expect(after.intents[0]!.cut).toBe(effect("counter").cut); + expect(after.towns[1]!.you).toBeGreaterThan(s.towns[1]!.you); + const ended = must(endWeek(after)); + expect(ended.towns[1]!.rival - after.towns[1]!.rival).toBeCloseTo(3000 * effect("counter").cut!); + // 擋下的票列在結算裡,也算進這週的戰果 + expect(ended.log.find((l) => l.blocked)?.blocked).toBe(Math.round(3000 * (1 - effect("counter").cut!))); + expect(ended.tally!.blocked).toBeGreaterThan(0); + expect(ended.tally!.gained).toBeGreaterThan(0); + }); + + it("佈樁:週末擋掉對手在這區的行動", () => { + const intent: Intent = { id: "i1", kind: "canvass", town: "D", amount: 1000, cut: 1 }; + const s = withHand(base, ["stake"], [intent]); + const after = ok(playCard(s, "t0", "D")); + expect(after.towns[3]!.shield).toBeCloseTo(cardBase("stake") * SCALE); + const ended = must(endWeek(after)); + expect(ended.towns[3]!.rival).toBeCloseTo(after.towns[3]!.rival); + }); + + it("對手批評你:澄清剩兩成;沒擋下來會塞一張記者追問", () => { + const intent: Intent = { id: "i1", kind: "attack", town: null, amount: 2000, cut: 1 }; + const s = withHand(base, ["clarify"], [intent]); + const after = ok(playCard(s, "t0", null)); + expect(after.intents[0]!.cut).toBeCloseTo(0.2); + const ended = must(endWeek(after)); + expect(totals(after.towns).you - totals(ended.towns).you).toBeCloseTo(400, 0); + expect(ended.discard.some((c) => c.id === "reporter")).toBe(true); + // 事實查核:讓這個批評完全失效 + const checked = ok(playCard(withHand(base, ["factcheck"], [intent]), "t0", "i1")); + expect(checked.intents[0]!.cut).toBe(0); + expect(must(endWeek(checked)).discard.some((c) => c.id === "reporter")).toBe(false); + }); + + it("記者追問留在手上過週末會掉票;回應就移除", () => { + const s = withHand(base, ["reporter"]); + const ended = must(endWeek(s)); + expect(totals(s.towns).you - totals(ended.towns).you).toBeCloseTo(REPORTER_PENALTY * SCALE, 0); + const answered = ok(playCard(s, "t0", null)); + expect(answered.exhausted.map((c) => c.id)).toEqual(["reporter"]); + }); + + it("爆料:有把柄全額、用掉一個;沒把柄效果小還會反傷", () => { + const s = withHand(base, ["expose"]); + const weak = ok(playCard(s, "t0", null)); + expect(totals(s.towns).rival - totals(weak.towns).rival).toBeCloseTo(effect("expose").weak! * SCALE); + expect(totals(s.towns).you - totals(weak.towns).you).toBeCloseTo(effect("expose").backlash! * SCALE); + const strong = ok(playCard({ ...s, leverage: 1 }, "t0", null)); + expect(totals(s.towns).rival - totals(strong.towns).rival).toBeCloseTo(cardBase("expose") * SCALE); + expect(strong.leverage).toBe(0); + expect(strong.stats.attacks).toBe(1); + }); + + it("插旗與翻轉:把對手插旗的區拉過來,聲勢 +1", () => { + const s = withHand(base, ["door", "door", "door"]); + const c = s.towns[2]!; + const committed = c.you + c.rival + c.others; + c.you = committed * 0.42; + c.rival = committed * 0.5; + c.flag = "rival"; + c.was = "rival"; + let x = s; + for (const uid of ["t0", "t1", "t2"]) x = ok(playCard(x, uid, "C")); + expect(x.towns[2]!.flag).toBe("you"); + expect(x.stats.flips).toBe(1); + expect(x.momentum).toBe(1); + expect(x.log.some((l) => l.text.includes("翻轉"))).toBe(true); + expect(FLAG_LEAD).toBeGreaterThan(0); + }); + + it("打出去的牌結算完才進棄牌堆:抽牌不會把自己抽回來;加體力的牌每週一次", () => { + const s = withHand(base, ["volunteers", "allnighter"]); + s.draw = []; + s.discard = []; + const drew = ok(playCard(s, "t0", null)); + expect(drew.hand.map((c) => c.id)).toEqual(["allnighter"]); + expect(drew.discard.map((c) => c.id)).toEqual(["volunteers"]); + const rushed = ok(playCard(drew, "t1", null)); + expect(rushed.energy).toBe(drew.energy + 2); + rushed.hand.push({ uid: "again", id: "allnighter" }); + expect(playCard(rushed, "again", null)).toEqual({ error: "這週已經打過了" }); + }); + + it("一次打好幾區的牌也算打過:同一週再打一次不算組合拳", () => { + const s = withHand(base, ["calls", "calls"]); + const one = ok(playCard(s, "t0", null)); + const two = ok(playCard(one, "t1", null)); + expect(one.towns.filter((t) => t.played.includes("calls"))).toHaveLength(3); + const gained = (a: RunState, b: RunState) => totals(b.towns).you - totals(a.towns).you; + expect(gained(one, two)).toBeCloseTo(gained(s, one), 0); + }); + + it("佈樁的預估只算還沒被擋住的威脅", () => { + const intent: Intent = { id: "i1", kind: "canvass", town: "D", amount: 1000, cut: 1 }; + const s = withHand(base, ["stake", "stake"], [intent]); + const first = previewsFor(s).t0!.find((p) => p.target === "D")!; + expect(first.note).toContain("可擋對手 1,000"); + const after = ok(playCard(s, "t0", "D")); + const second = previewsFor(after).t1!.find((p) => p.target === "D")!; + expect(second.note).not.toContain("可擋對手"); + }); + + it("不能打的牌說明原因:體力、資金、最後一週才能打、不能打的狀態牌", () => { + const s = { ...withHand(base, ["rally", "kneel", "favor"]), energy: 1 }; + expect(playCard(s, "t0", "A")).toEqual({ error: "體力不夠" }); + expect(playCard({ ...s, energy: 3 }, "t1", null)).toEqual({ error: "最後一週才能打" }); + expect(playCard({ ...s, energy: 3, money: 100 }, "t0", "A")).toEqual({ error: "資金不夠" }); + expect(playCard(s, "t2", null)).toEqual({ error: "這張牌不能打" }); + }); +}); + +describe("預估", () => { + it("預估數字和真的打出去一樣(不含機率的牌)", () => { + const s = withHand(createRun(SETUP, "r", 7), ["canvass", "temple", "tv", "rally"]); + const previews = previewsFor(s); + for (const [uid, target] of [["t0", "A"], ["t1", "B"], ["t2", null], ["t3", "B"]] as const) { + const p = previews[uid]!.find((x) => x.target === (target ?? "city"))!; + const after = ok(playCard(s, uid, target)); + const swing = totals(after.towns).you - totals(s.towns).you - (totals(after.towns).rival - totals(s.towns).rival); + expect(p.votes).toBe(Math.round(swing)); + } + expect(previews.t1!.find((x) => x.target === "B")!.note).toContain("宮廟多 ×2"); + }); +}); + +describe("週與週之間", () => { + it("結束這週 → 下一站三選一(門上直接攤開內容,一次點選就拿到);第 2 週有記者堵麥但不擋出牌", () => { + const s = createRun(SETUP, "r", 3); + const ended = must(endWeek(s)); + expect(ended.phase).toBe("route"); + expect(ended.route).toHaveLength(3); + expect(ended.route).toContain("card"); + expect(totals(ended.towns).rival).toBeGreaterThan(totals(s.towns).rival); + const door = ended.route!.indexOf("card"); + // 門上直接攤開三張牌 + const view0 = toView(ended); + const preview = view0.route![door]!.preview as { kind: string; options: { id: string }[] }; + expect(preview.kind).toBe("card"); + const picked = preview.options[1]!.id; + // 選門+選牌一次完成 + const next = must(choose(ended, door, null, 1)); + expect(next.week).toBe(2); + expect(next.hand).toHaveLength(5); + // 新牌放在抽牌堆最上面:下一週就在手上 + expect(next.hand.some((c) => c.id === picked)).toBe(true); + // 記者堵麥:出牌階段就可以出牌,但結束這週前要回答 + expect(next.phase).toBe("plan"); + expect(next.scene!.kind).toBe("press"); + expect(toView(next).scene!.kind).toBe("press"); + expect("error" in endWeek(next)).toBe(true); + const answered = must(choose(next, 0)); + expect(answered.phase).toBe("plan"); + expect(answered.scene).toBeNull(); + // 還是可以先進門再選(舊的兩步) + const at = must(choose(ended, door)); + expect(at.phase).toBe("stop"); + expect((at.stop as { options: string[] }).options[1]).toBe(picked); + // 不去下一站:改拿資金 + const skipped = must(choose(must(endWeek(answered)), "skip")); + expect(skipped.week).toBe(3); + expect(skipped.money).toBeGreaterThan(0); + }); + + it("第 4 週民調自動公布,不用點", () => { + const s = advance(createRun(SETUP, "r", 12), 4); + expect(s.week).toBe(4); + expect(s.phase).toBe("plan"); + expect(s.scene).toBeNull(); + expect(s.poll!.week).toBe(4); + expect(toView(s).poll!.week).toBe(4); + }); + + it("第 2 週一定可以找幕僚;商店買東西扣錢,刪牌服務拿掉一張牌", () => { + let s = toPlan(must(choose(must(endWeek(createRun(SETUP, "r", 9))), "skip"))); + s = must(endWeek(s)); + expect(s.week).toBe(2); + expect(s.route).toContain("advisor"); + const shop = structuredClone(s); + shop.phase = "stop"; + shop.route = null; + shop.stop = { kind: "shop", items: [{ kind: "card", id: "tv", price: 120, sold: false }, { kind: "remove", id: "remove", price: 100, sold: false }] }; + shop.money = 1000; + const bought = must(choose(shop, 0)); + expect(bought.money).toBe(880); + expect(bought.phase).toBe("stop"); + // 買的牌放在抽牌堆最上面,下週一定抽到 + expect(bought.draw[0]!.id).toBe("tv"); + const victim = [...bought.draw, ...bought.discard][0]!; + const removed = must(choose(bought, 1, victim.uid)); + expect([...removed.draw, ...removed.discard, ...removed.hand].some((c) => c.uid === victim.uid)).toBe(false); + expect(removed.money).toBe(780); + expect(choose(removed, 0)).toEqual({ error: "沒有這個商品" }); + expect(must(choose(removed, "skip")).week).toBe(3); + }); + + it("升級一張牌、深入基層三個遭遇之後那區加票", () => { + const s = must(endWeek(createRun(SETUP, "r", 4))); + const up = structuredClone(s); + up.phase = "stop"; + up.stop = { kind: "upgrade" }; + const target = up.draw[0]!; + const done = must(choose(up, 0, target.uid)); + expect([...done.draw, ...done.discard, ...done.hand].find((c) => c.uid === target.uid)!.up).toBe(true); + + const enc = structuredClone(s); + enc.phase = "stop"; + enc.stop = { kind: "encounter", town: "A", encounters: ["heckler", "selfie_kids", "lost_grandma"], step: 0, score: 0, notes: [] }; + let x = must(choose(enc, 0)); + x = must(choose(x, 0)); + x = must(choose(x, 0)); + expect(x.stop!.kind).toBe("encounter"); + expect((x.stop as { score: number }).score).toBe(5); + expect(x.towns[0]!.you).toBeGreaterThan(enc.towns[0]!.you); + expect(must(choose(x, "skip")).week).toBe(2); + }); +}); + +describe("劇情", () => { + it("第 3 週論點連擊辯論:有辯論教練看得出最好的論點,三連擊加成越來越大、拿到辯論金句", () => { + let s = createRun(SETUP, "r", 21); + s.advisors = ["debate_coach"]; + s = advance(s, 3); + expect(s.week).toBe(3); + const scene = s.scene as Extract; + expect(scene.kind).toBe("debate"); + expect(scene.hand.length).toBeGreaterThanOrEqual(5); + // 三種論點至少各一張 + expect(new Set(scene.hand.map((a) => a.kind)).size).toBe(3); + // 確定手上有答得出來的論點(抽論點有運氣) + scene.hand = [...scene.needs.map((kind) => ({ kind, text: "測試" })), { kind: "policy", text: "多一張" }]; + for (let round = 0; round < 3; round++) { + const view = toView(s).scene as Extract["scene"]>, { kind: "debate" }>; + expect(view.sure).toBe(true); + expect(view.challenge).toBeTruthy(); + s = must(choose(s, view.best!)); + } + const done = s.scene as Extract; + expect(done.wins).toBe(3); + expect(done.history.map((h) => h.combo)).toEqual([1, 2, 3]); + // 第三回合 ×2:大約是第一回合的兩倍 + expect(done.history[2]!.votes / done.history[0]!.votes).toBeGreaterThan(1.6); + expect(s.hand.some((c) => c.id === "soundbite")).toBe(true); + s = must(choose(s, 0)); + expect(s.phase).toBe("plan"); + }); + + it("辯論:答非所問會輸、普通的平手,連擊中斷;沒有教練看不到最好的論點", () => { + let s = advance(createRun(SETUP, "r", 21), 3); + const scene = s.scene as Extract; + // 三回合都是數字質疑:拿數據最好、反問普通、講故事最差 + scene.needs = ["policy", "policy", "policy"]; + scene.hand = [ + { kind: "policy", text: "對" }, + { kind: "emotion", text: "錯" }, + { kind: "question", text: "普通" }, + ]; + expect((toView(s).scene as { best: number | null }).best).toBeNull(); + const before = s.momentum; + for (let i = 0; i < 3; i++) s = must(choose(s, 0)); + const d = s.scene as Extract; + expect(d.history.map((h) => h.result)).toEqual(["win", "lose", "tie"]); + expect(d.history[1]!.votes).toBeLessThan(0); + expect(d.combo).toBe(0); + expect(d.wins).toBe(1); + expect(s.momentum).toBeGreaterThanOrEqual(before); + }); + + it("舉債的政策第二回合會被追問;財源扎實的政策變成一張論點", () => { + const policies = [ + { name: "長照好安心", target: "old", method: "subsidy", funding: "invest" }, + { name: "全民蓋公園", target: "families", method: "build", funding: "debt" }, + ] as const; + let s = createRun(SETUP, "r", 21, { policies, perks: [{ id: "library", level: 1 }] }); + s = advance(s, 3); + const scene = s.scene as Extract; + expect(scene.challenges[1]).toContain("全民蓋公園"); + expect(scene.needs[1]).toBe("policy"); + expect(scene.hand.some((a) => a.policy === "長照好安心")).toBe(true); + expect(scene.hand.some((a) => a.policy === "全民蓋公園")).toBe(false); + }); + + it("第 6 週匿名黑函:公開資料自清沒有損失、這週體力 −1", () => { + let s = createRun(SETUP, "r", 33); + s = advance(s, 6); + expect(s.week).toBe(6); + expect(s.scene!.kind).toBe("crisis"); + const before = totals(s.towns).you; + const after = must(choose(s, 3)); + expect(totals(after.towns).you).toBeCloseTo(before); + expect(after.energy).toBe(s.energy - 1); + expect(after.stats.crisisLoss).toBe(0); + const ignored = must(choose(s, 2)); + expect(totals(ignored.towns).you).toBeLessThan(before); + expect(ignored.momentum).toBeGreaterThan(s.momentum); + }); +}); + +describe("一局", () => { + it("每種模擬玩家都能打完整場;打得好比什麼都不做好", () => { + const bots: BotName[] = ["idle", "random", "naive", "casual", "greedy", "ground", "air", "attack"]; + const results = Object.fromEntries(bots.map((b) => [b, runBot(SETUP, 11, b)])); + for (const b of bots) expect(results[b]!.phase).toBe("finished"); + expect(results.greedy!.result!.youShare).toBeGreaterThan(results.idle!.result!.youShare); + expect(results.greedy!.advisors.length).toBeGreaterThan(0); + const view = toView(results.greedy!); + expect(view.result!.byTown).toHaveLength(4); + expect(view.history).toHaveLength(9); + expect(Array.isArray(view.result!.feats)).toBe(true); + // 逆風 10 級也打得完 + expect(runBot(SETUP, 12, "greedy", { ascension: 10 }).phase).toBe("finished"); + }); + + it("新手教學:3 週、照順序發牌、沒有辯論和黑函", () => { + const s = createRun(tutorialSetup(), "t", 1, { tutorial: true, weeks: TUTORIAL_WEEKS, deck: TUTORIAL_DECK }); + expect(s.hand.map((c) => c.id)).toEqual(TUTORIAL_DECK.slice(0, 5)); + expect(toView(s).colors.you).not.toBe(toView(s).colors.rival); + const done = runBot(tutorialSetup(), 2, "greedy", { tutorial: true, weeks: TUTORIAL_WEEKS, deck: TUTORIAL_DECK }); + expect(done.phase).toBe("finished"); + expect(done.history).toHaveLength(TUTORIAL_WEEKS + 1); + }); + + it("堵麥與地方抉擇:牌和狀態牌都存在、每題至少一個不需要資源的選項、不重複", () => { + const ids = new Set(); + for (const def of [...PRESS, ...STOP_EVENTS]) { + expect(ids.has(def.id)).toBe(false); + ids.add(def.id); + expect(def.choices.some((c) => !c.needs)).toBe(true); + for (const c of def.choices) { + for (const o of [c.outcome, ...(c.roll ? [c.roll.fail] : [])]) { + if (o.card) expect(CARD_BY_ID.has(o.card)).toBe(true); + for (const st of o.status ?? []) expect(CARD_BY_ID.get(st)?.rarity).toBe("status"); + } + } + } + expect(PRESS.length).toBeGreaterThanOrEqual(20); + expect(STOP_EVENTS.length).toBeGreaterThanOrEqual(20); + }); + + it("每張牌的資料完整;+版都算得出來", () => { + for (const [id, card] of CARD_BY_ID) { + expect(card.id).toBe(id); + expect(card.text.length).toBeGreaterThan(0); + expect(cardDef(id, true)!.name).toContain("+"); + } + }); +}); + +describe("相鄰的區", () => { + it("共用邊界的區是鄰居;縣市層級用鄉鎮組成縣市", () => { + const topology = { + objects: { + towns: { + geometries: [ + { type: "Polygon", arcs: [[0, 1]], properties: { townCode: "10001010" } }, + { type: "Polygon", arcs: [[~1, 2]], properties: { townCode: "10001020" } }, + { type: "Polygon", arcs: [[~2, 3]], properties: { townCode: "10002010" } }, + { type: "Polygon", arcs: [[4]], properties: { townCode: "10003010" } }, + ], + }, + }, + }; + const towns = townNeighbors(topology, ["10001010", "10001020", "10002010", "10003010"]); + expect(towns.get("10001010")).toEqual(["10001020"]); + expect(towns.get("10001020")).toEqual(["10001010", "10002010"]); + expect(towns.get("10003010")).toEqual([]); + const counties = townNeighbors(topology, ["10001000", "10002000", "10003000"], "county"); + expect(counties.get("10001000")).toEqual(["10002000"]); + }); +}); diff --git a/backend/packages/rogue/tsconfig.json b/backend/packages/rogue/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/packages/rogue/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/packages/scenarios/package.json b/backend/packages/scenarios/package.json new file mode 100644 index 0000000..d617841 --- /dev/null +++ b/backend/packages/scenarios/package.json @@ -0,0 +1,15 @@ +{ + "name": "@election2026/scenarios", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "劇本目錄:手工劇本(content)加上管線產生的全台縣市長劇本,伺服器與模擬工具共用", + "exports": { ".": "./src/index.ts" }, + "scripts": { "test": "vitest run", "typecheck": "tsc -p tsconfig.json" }, + "dependencies": { + "@election2026/content": "workspace:*", + "@election2026/engine": "workspace:*", + "@election2026/pack-loader": "workspace:*", + "@election2026/protocol": "workspace:*" + } +} diff --git a/backend/packages/scenarios/src/index.ts b/backend/packages/scenarios/src/index.ts new file mode 100644 index 0000000..af75224 --- /dev/null +++ b/backend/packages/scenarios/src/index.ts @@ -0,0 +1,27 @@ +import { SCENARIOS as HANDMADE, scenariosFromSpec } from "@election2026/content"; +import type { Scenario } from "@election2026/engine"; +import { DEFAULT_SCENARIOS_ROOT, SCENARIO_SETS, loadAllSpecs, loadCalibration } from "@election2026/pack-loader"; + +export interface ScenarioRegistry { + all: readonly Scenario[]; + find(id: string): Scenario | undefined; +} + +/** + * 所有可以玩的劇本:2022 桃園市長用手工劇本(有逐一查證的簡介與校準),其他由管線資料產生: + * 2014、2018、2022 縣市長;2020、2024 區域立委;1996 年起歷屆總統。管線資料不存在時只有手工劇本。 + */ +export async function loadScenarioRegistry(root = DEFAULT_SCENARIOS_ROOT): Promise { + const specs = await loadAllSpecs(root); + const calibrations = new Map>>( + await Promise.all(SCENARIO_SETS.map(async (set) => [set, await loadCalibration(set, root)] as const)), + ); + // 手工劇本取代同一場(同縣市、同投票日)的管線劇本,其他年份照常產生 + const handmade = new Set(HANDMADE.map((s) => `${s.region.countyCode}|${s.electionDate}`)); + const generated = specs + .filter(({ spec }) => !(spec.kind === "mayor" && handmade.has(`${spec.countyCode}|${spec.electionDate}`))) + .flatMap(({ key, set, spec }) => scenariosFromSpec(spec, calibrations.get(set)?.counties[key])); + const all = [...HANDMADE, ...generated]; + const byId = new Map(all.map((s) => [s.id, s])); + return { all, find: (id) => byId.get(id) }; +} diff --git a/backend/packages/scenarios/test/registry.test.ts b/backend/packages/scenarios/test/registry.test.ts new file mode 100644 index 0000000..853efe5 --- /dev/null +++ b/backend/packages/scenarios/test/registry.test.ts @@ -0,0 +1,96 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { DEFAULT_PACKS_ROOT, DEFAULT_SCENARIOS_ROOT } from "@election2026/pack-loader"; +import { describe, expect, it } from "vitest"; +import { loadScenarioRegistry } from "../src/index.ts"; + +const built = existsSync(join(DEFAULT_SCENARIOS_ROOT, "2022-local", "63000.json")); + +describe.skipIf(!built)("全台劇本目錄", () => { + it("每個有資料的縣市都有歷史劇本,資料包也都存在", async () => { + const reg = await loadScenarioRegistry(); + const counties = new Set(reg.all.map((s) => s.region.countyCode)); + expect(counties.size).toBeGreaterThanOrEqual(21); + for (const s of reg.all) expect(existsSync(join(DEFAULT_PACKS_ROOT, s.packId, "manifest.json")), s.id).toBe(true); + }); + + it("候選人 id、號次不重複;真實結果的候選人都在名單上;沒有人被設成奧步型", async () => { + const reg = await loadScenarioRegistry(); + for (const s of reg.all) { + const ids = new Set(s.candidates.map((c) => c.id)); + expect(ids.size, s.id).toBe(s.candidates.length); + for (const row of Object.values(s.actual?.byVillage ?? {})) for (const id of Object.keys(row)) expect(ids.has(id), `${s.id} ${id}`).toBe(true); + for (const c of s.candidates) expect(c.aiStyle, `${s.id} ${c.name}`).not.toBe("dirty"); + } + }); + + it("臺北市有 12 位候選人,黃珊珊用民眾黨支持的槽位", async () => { + const reg = await loadScenarioRegistry(); + const taipei = reg.find("local2022-63000")!; + expect(taipei.candidates).toHaveLength(12); + expect(taipei.candidates.find((c) => c.name === "黃珊珊")?.slot).toBe("c"); + expect(taipei.spendingCap).toBe(84_589_000); + }); + + it("2024 總統與 73 個區域立委選區", async () => { + const reg = await loadScenarioRegistry(); + const in2024 = reg.all.filter((s) => s.electionDate.startsWith("2024")); + const pres = in2024.filter((s) => s.region.kind === "president" && !s.hypothetical); + expect(pres).toHaveLength(1); + expect(pres[0]!.candidates.map((c) => c.name)).toEqual(["柯文哲", "賴清德", "侯友宜"]); + expect(pres[0]!.region.regionLevel).toBe("county"); + const leg = in2024.filter((s) => s.region.kind === "legislator" && !s.hypothetical); + expect(leg).toHaveLength(73); + expect(leg.every((s) => (s.villages?.length ?? 0) > 0)).toBe(true); + }); + + it.skipIf(!existsSync(join(DEFAULT_SCENARIOS_ROOT, "2018-local", "63000.json")))("2018 縣市長(含嘉義市)、2020 總統與立委", async () => { + const reg = await loadScenarioRegistry(); + const history = (year: string, kind: string) => reg.all.filter((s) => s.electionDate.startsWith(year) && s.region.kind === kind && !s.hypothetical); + expect(history("2018", "mayor")).toHaveLength(22); + expect(reg.find("local2018-63000")?.candidates.map((c) => c.name)).toContain("柯文哲"); + expect(reg.find("local2018-63000")?.spendingCap).toBe(87_475_000); + const pres = history("2020", "president"); + expect(pres.map((s) => s.id)).toEqual(["pres2020"]); + expect(pres[0]!.spendingCap).toBe(430_297_000); + expect(pres[0]!.publicHistoryElection).toBe("2016-president"); + expect(history("2020", "legislator")).toHaveLength(73); + // 不同年份的候選人 id 不會撞在一起 + const ids = reg.all.flatMap((s) => (s.hypothetical ? [] : s.candidates.map((c) => c.id))); + expect(new Set(ids).size).toBe(ids.length); + }); + + it.skipIf(!existsSync(join(DEFAULT_SCENARIOS_ROOT, "2014-local", "63000.json")))("經典之戰:2014 縣市長", async () => { + const reg = await loadScenarioRegistry(); + const mayors = reg.all.filter((s) => s.electionDate === "2014-11-29" && s.region.kind === "mayor" && !s.hypothetical); + expect(mayors).toHaveLength(22); + const taipei = reg.find("local2014-63000")!; + expect(taipei.candidates.map((c) => c.name)).toEqual(expect.arrayContaining(["連勝文", "柯文哲"])); + expect(taipei.spendingCap).toBe(87_690_000); + expect(taipei.publicHistoryElection).toBe("2012-president"); + expect(reg.find("local2014-68000")?.region.office).toBe("市長"); + // 沒有政治獻金資料:備註要說清楚 + expect(taipei.notes.some((n) => n.includes("沒有 2014 年這場選舉的候選人申報資料"))).toBe(true); + }); + + it.skipIf(!existsSync(join(DEFAULT_SCENARIOS_ROOT, "1996-president", "00000.json")))("經典之戰:1996 年起歷屆總統", async () => { + const reg = await loadScenarioRegistry(); + const pres = reg.all.filter((s) => s.region.kind === "president" && !s.hypothetical); + expect(pres.map((s) => s.electionDate.slice(0, 4)).sort()).toEqual(["1996", "2000", "2004", "2008", "2012", "2016", "2020", "2024"]); + const first = reg.find("pres1996")!; + expect(first.candidates.map((c) => [c.name, c.runningMate])).toEqual([ + ["陳履安", "王清峰"], + ["李登輝", "連戰"], + ["彭明敏", "謝長廷"], + ["林洋港", "郝柏村"], + ]); + // 第一次直選之前沒有總統選舉,地圖的「上次選舉」用 1995 年立委 + expect(first.publicHistoryElection).toBe("1995-legislator"); + expect(reg.find("pres2012")?.publicHistoryElection).toBe("2008-president"); + for (const s of pres) { + expect(s.region.regionLevel).toBe("county"); + // 舊縣市都併進現在的 22 個縣市 + expect(new Set(Object.keys(s.actual?.byVillage ?? {}).map((c) => c.slice(0, 5))).size).toBe(22); + } + }); +}); diff --git a/backend/packages/scenarios/tsconfig.json b/backend/packages/scenarios/tsconfig.json new file mode 100644 index 0000000..45805b0 --- /dev/null +++ b/backend/packages/scenarios/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"], "noUncheckedIndexedAccess": false }, + "include": ["src", "test"] +} diff --git a/backend/packages/scenarios/vitest.config.ts b/backend/packages/scenarios/vitest.config.ts new file mode 100644 index 0000000..5539adc --- /dev/null +++ b/backend/packages/scenarios/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ test: { include: ["test/**/*.test.ts"] } }); diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yaml new file mode 100644 index 0000000..1b8cb5c --- /dev/null +++ b/backend/pnpm-lock.yaml @@ -0,0 +1,3218 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + mapshaper: + specifier: ^0.7.98 + version: 0.7.98(@types/geojson@7946.0.8)(@types/node@26.6.5) + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)) + + apps/server: + dependencies: + '@election2026/content': + specifier: workspace:* + version: link:../../packages/content + '@election2026/engine': + specifier: workspace:* + version: link:../../packages/engine + '@election2026/pack-loader': + specifier: workspace:* + version: link:../../packages/pack-loader + '@election2026/protocol': + specifier: workspace:* + version: link:../../packages/protocol + '@election2026/rogue': + specifier: workspace:* + version: link:../../packages/rogue + '@election2026/scenarios': + specifier: workspace:* + version: link:../../packages/scenarios + '@fastify/rate-limit': + specifier: ^11.2.1 + version: 11.2.1 + fastify: + specifier: ^5.12.7 + version: 5.12.7 + zod: + specifier: ^4.6.7 + version: 4.6.7 + + apps/sim: + dependencies: + '@election2026/content': + specifier: workspace:* + version: link:../../packages/content + '@election2026/engine': + specifier: workspace:* + version: link:../../packages/engine + '@election2026/pack-loader': + specifier: workspace:* + version: link:../../packages/pack-loader + '@election2026/protocol': + specifier: workspace:* + version: link:../../packages/protocol + '@election2026/rogue': + specifier: workspace:* + version: link:../../packages/rogue + '@election2026/scenarios': + specifier: workspace:* + version: link:../../packages/scenarios + + packages/content: + dependencies: + '@election2026/engine': + specifier: workspace:* + version: link:../engine + '@election2026/protocol': + specifier: workspace:* + version: link:../protocol + devDependencies: + '@election2026/pack-loader': + specifier: workspace:* + version: link:../pack-loader + + packages/engine: + dependencies: + '@election2026/protocol': + specifier: workspace:* + version: link:../protocol + + packages/pack-loader: + dependencies: + '@election2026/engine': + specifier: workspace:* + version: link:../engine + '@election2026/protocol': + specifier: workspace:* + version: link:../protocol + zod: + specifier: ^4.6.7 + version: 4.6.7 + + packages/protocol: + dependencies: + zod: + specifier: ^4.6.7 + version: 4.6.7 + devDependencies: + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)) + + packages/rogue: + dependencies: + '@election2026/content': + specifier: workspace:* + version: link:../content + '@election2026/engine': + specifier: workspace:* + version: link:../engine + '@election2026/protocol': + specifier: workspace:* + version: link:../protocol + + packages/scenarios: + dependencies: + '@election2026/content': + specifier: workspace:* + version: link:../content + '@election2026/engine': + specifier: workspace:* + version: link:../engine + '@election2026/pack-loader': + specifier: workspace:* + version: link:../pack-loader + '@election2026/protocol': + specifier: workspace:* + version: link:../protocol + +packages: + + '@bokuweb/zstd-wasm@0.0.27': + resolution: {integrity: sha512-GDm2uOTK3ESjnYmSeLQifJnBsRCWajKLvN32D2ZcQaaCIJI/Hse9s74f7APXjHit95S10UImsRGkTsbwHmrtmg==} + + '@fastify/ajv-compiler@4.0.7': + resolution: {integrity: sha512-VP0yIfwlc1ohj733keYDqyHm1VWeP9VQxYomunhr90jkC4aNNibbkrRiaNgPgqj1ORxUenILR4qzA/ppYBNAtQ==} + + '@fastify/deepmerge@3.2.4': + resolution: {integrity: sha512-kc8GQq5gX9RRhw0rov3DMrN8wS8yRlxJRdDzsYwwdBV/wazuVgc/1K7CKL90tlvu3RlHan6Y0R0aE3nJtBz2eQ==} + + '@fastify/error@4.2.1': + resolution: {integrity: sha512-MYBumuIwP+5MIpXSyKm6/o1Eigcoij186lWUssX3LH5U8KWqU0ktZhzC4CErIX9EJeQeRGI+zJZQWakBlFbUcg==} + + '@fastify/fast-json-stringify-compiler@5.1.1': + resolution: {integrity: sha512-pyxRKk7UpUnnrztP9pF4+ZYxusEQ4LifTyzRdiXmyql1QezNHxO02D25MVU2o4kMeAMYWAjG6RKRlojgkbiDAw==} + + '@fastify/forwarded@3.1.2': + resolution: {integrity: sha512-89WiRG+hW3VQSfCwg4Hb8b43PeyEX15K5+lEfsZ4EUth/FyOjS/lv8HsVuswUNXWiSnxMGNouE/fq/0w3VumHQ==} + + '@fastify/merge-json-schemas@0.2.2': + resolution: {integrity: sha512-d/gx9sRbUCVgGRGzma46wLcwiY8noTqO2Nmjg/vbTARxHRE5bdh5PIL8s97Lt1X7ScRWRW52eVYxwIoPwIdVUA==} + + '@fastify/proxy-addr@5.1.2': + resolution: {integrity: sha512-uqB4QsgVoro0XDC+DIftIMGXHdBPn+lK6Ek3xXAIxPMCJfqxnbtyEoMCm2KPUVOuIosd7Cyw9HawEqMFM/UA+g==} + + '@fastify/rate-limit@11.2.1': + resolution: {integrity: sha512-uTQjii3tJUnb6ZyEMcunuvKE3FDKNZEaPpxdyWADDgthHnUV1swdvwuiZfi3DDDgxm1iBrhOkQ/w0yDBQ8qJtA==} + + '@inquirer/ansi@2.0.9': + resolution: {integrity: sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/checkbox@5.2.7': + resolution: {integrity: sha512-/+QmGE/9bvE/EobaZDnzYe+T+QWoJrnmxwBQNtoi2OVSUR9d1znYsNyEoUrOZvFSxDYttrhzRIpXpaLkN+iIsg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/confirm@6.3.4': + resolution: {integrity: sha512-ZwnaZZDa1zxsyVrN32s447ydMnKcw7e8WWNT+R+Qsu0zAn8Rs6yi9d1B80Kob1Ul2cfUi7t8JD2t4/K7uEZpqA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/core@12.0.5': + resolution: {integrity: sha512-c0ZSnO9oVk/IlEGoZK3u8b3IZQeu9I6jUkXJSQnQEVRXsjKvtAq3AGqFL2LgfJhlzMZne08pZHWRWasIcI3Rew==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/editor@5.3.5': + resolution: {integrity: sha512-6lU3/pPx5z3lHWejFW061MV4qZooBQYv/+EeGhNOPiP/i+hrYsHfxxBnnDGsAfg8YdLUd69YckoeOjtr3QuAUg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/expand@5.1.7': + resolution: {integrity: sha512-eiJ31YFCaB6fLoJCqLIn8S6eqUyME6vwr8KcP5h8cxmA+bV9RRVPO+kywoxb7G63HduDXV6sN/SM7o2R+ahEcQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/external-editor@3.0.6': + resolution: {integrity: sha512-rWmw6WG8JZ7LMn/srXEylYGhL6EXXJeROE7/4x4GREh6NgzqJBDbIgpNGsYoLPfobeb4VZtEYzPGnT5EFNYhiQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/figures@2.0.9': + resolution: {integrity: sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/input@5.1.8': + resolution: {integrity: sha512-psOSTgkL8y/OtgJJYbqJ0oISr2QBE0U1Ro/qQdA/EKjeJiwiUTQgQmq8o4ESNzVOWthIeh3YLD7BCUR9dKnR5g==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/number@4.2.5': + resolution: {integrity: sha512-lEy7LWsdF5qHx5QjHZqabUqM9P7i5uTMCt8GRzqxmwXXKbapKJDA+ucVflVVPAyj4snD5DTAD4L+sct85XOlOQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/password@5.2.4': + resolution: {integrity: sha512-T7ir3fflSSVCYEVqNyMBq+pIMsilQRtbZcD5gxn6Ewsin5TJWBxrGBdXveWtmeXVAeoInfhS+BhBUZaL4sFSDg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/prompts@8.7.4': + resolution: {integrity: sha512-SAJt+QhY5rOJAIgZBw9TrHWfgrp6wsb9cqRCyqax+Hl6EiFfRXmD9EsIWkST8yq/dQ8H46Is2Sr/JG7Ls/LQ+Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/rawlist@5.3.7': + resolution: {integrity: sha512-XveEe8v3BHj9ec00n+9i8FHjWhXjS6+jCTizYvXCqKUKtgkrq9xid8S5j3mYGW96qfxG3mwNoud3m3v8GDk9Pw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/search@4.3.5': + resolution: {integrity: sha512-kIUecMugEN2YTvTmff+uYz0nAE0f9RFNDVZknfrh264vAQM9P8tnsXiUp7z8XbGuNIBEtFMJhvc9QquawpC46A==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/select@5.2.7': + resolution: {integrity: sha512-pRDWO4dTqSAvFQdO8yclKMtXNDm9K9HmvWB5UZmT3clw2OlOBNXveHzhyFmO/0d0yJMqlPcNITus1Jtpm6t8VQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/type@4.2.0': + resolution: {integrity: sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@lukeed/ms@2.0.2': + resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==} + engines: {node: '>=8'} + + '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': + resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==} + cpu: [arm64] + os: [darwin] + + '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': + resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==} + cpu: [x64] + os: [darwin] + + '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': + resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==} + cpu: [arm64] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': + resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==} + cpu: [arm] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': + resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==} + cpu: [x64] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': + resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==} + cpu: [x64] + os: [win32] + + '@ngageoint/geopackage@4.2.10': + resolution: {integrity: sha512-+QV4/N0JDW0iXJAtdvYnvzYt5GXZWh/RqELjIg61FSXIxKE/fy+j+EIxlThF29KueP3mL9hEN3ijqDwAEIl6DQ==} + hasBin: true + + '@oxc-project/types@0.155.0': + resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} + + '@petamoriken/float16@3.9.3': + resolution: {integrity: sha512-8awtpHXCx/bNpFt4mt2xdkgtgVvKqty8VbjHI/WWWQuEw+KLzFot3f4+LkQY9YmOtq7A5GdOnqoIC8Pdygjk2g==} + + '@pinojs/redact@0.4.0': + resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + + '@placemarkio/tokml@0.3.9': + resolution: {integrity: sha512-LjD/rzPWF/0gY2tCoS4IPLQZ3/DqxzCmI3/V+dmXdWuZmyi3UIhHgxVfJ//bopxSjWHuGwY/qu4iyuNM+xluug==} + + '@repeaterjs/repeater@3.1.0': + resolution: {integrity: sha512-TaoVksZRSx2KWYYpyLQtMQXXeS98VsgZImzW65xmiVgbYhXLk+aEsmzPLirqVuE4/XuUapH2iMtxUzaBNDzdSQ==} + + '@resvg/resvg-wasm@2.6.2': + resolution: {integrity: sha512-FqALmHI8D4o6lk/LRWDnhw95z5eO+eAa6ORjVg09YRR7BkcM6oPHU9uyC0gtQG5vpFLvgpeU4+zEAz2H8APHNw==} + engines: {node: '>= 10'} + + '@rolldown/binding-android-arm-eabi@1.2.15': + resolution: {integrity: sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.15': + resolution: {integrity: sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.15': + resolution: {integrity: sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.15': + resolution: {integrity: sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.15': + resolution: {integrity: sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + resolution: {integrity: sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.15': + resolution: {integrity: sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.15': + resolution: {integrity: sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + resolution: {integrity: sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + resolution: {integrity: sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.15': + resolution: {integrity: sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.15': + resolution: {integrity: sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.15': + resolution: {integrity: sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + resolution: {integrity: sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.15': + resolution: {integrity: sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@rollup/rollup-linux-x64-gnu@4.65.0': + resolution: {integrity: sha512-GExdD15WPvu/x/drELjVam7vX8EsPgvTMOa/iJL/p/4m/oOqzbb7JXZg8fXR4hlXtg/sF2zyTZ3bR0AEtEMlhQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@swc/helpers@0.5.23': + resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} + + '@tmcw/togeojson@5.8.1': + resolution: {integrity: sha512-2YNrbis3l5kS0XrYwiHEZcGwiRp0MJ5CvwGwtMWp2z2tsVlskeec2qgvKHnF0RCwI5GnjrrBOoKsWfndEnd3LA==} + peerDependencies: + '@types/geojson': '*' + + '@turf/bbox@6.3.0': + resolution: {integrity: sha512-N4ue5Xopu1qieSHP2MA/CJGWHPKaTrVXQJjzHRNcY1vtsO126xbSaJhWUrFc5x5vVkXp0dcucGryO0r5m4o/KA==} + + '@turf/bbox@6.5.0': + resolution: {integrity: sha512-RBbLaao5hXTYyyg577iuMtDB8ehxMlUqHEJiMs8jT1GHkFhr6sYre3lmLsPeYEi/ZKj5TP5tt7fkzNdJ4GIVyw==} + + '@turf/bearing@6.5.0': + resolution: {integrity: sha512-dxINYhIEMzgDOztyMZc20I7ssYVNEpSv04VbMo5YPQsqa80KO3TFvbuCahMsCAW5z8Tncc8dwBlEFrmRjJG33A==} + + '@turf/boolean-clockwise@6.5.0': + resolution: {integrity: sha512-45+C7LC5RMbRWrxh3Z0Eihsc8db1VGBO5d9BLTOAwU4jR6SgsunTfRWR16X7JUwIDYlCVEmnjcXJNi/kIU3VIw==} + + '@turf/boolean-point-in-polygon@6.5.0': + resolution: {integrity: sha512-DtSuVFB26SI+hj0SjrvXowGTUCHlgevPAIsukssW6BG5MlNSBQAo70wpICBNJL6RjukXg8d2eXaAWuD/CqL00A==} + + '@turf/boolean-point-on-line@6.5.0': + resolution: {integrity: sha512-A1BbuQ0LceLHvq7F/P7w3QvfpmZqbmViIUPHdNLvZimFNLo4e6IQunmzbe+8aSStH9QRZm3VOflyvNeXvvpZEQ==} + + '@turf/boolean-within@6.5.0': + resolution: {integrity: sha512-YQB3oU18Inx35C/LU930D36RAVe7LDXk1kWsQ8mLmuqYn9YdPsDQTMTkLJMhoQ8EbN7QTdy333xRQ4MYgToteQ==} + + '@turf/clone@6.5.0': + resolution: {integrity: sha512-mzVtTFj/QycXOn6ig+annKrM6ZlimreKYz6f/GSERytOpgzodbQyOgkfwru100O1KQhhjSudKK4DsQ0oyi9cTw==} + + '@turf/distance@6.5.0': + resolution: {integrity: sha512-xzykSLfoURec5qvQJcfifw/1mJa+5UwByZZ5TZ8iaqjGYN0vomhV9aiSLeYdUGtYRESZ+DYC/OzY+4RclZYgMg==} + + '@turf/helpers@6.5.0': + resolution: {integrity: sha512-VbI1dV5bLFzohYYdgqwikdMVpe7pJ9X3E+dlr425wa2/sMJqYDhTO++ec38/pcPvPE6oD9WEEeU3Xu3gza+VPw==} + + '@turf/intersect@6.5.0': + resolution: {integrity: sha512-2legGJeKrfFkzntcd4GouPugoqPUjexPZnOvfez+3SfIMrHvulw8qV8u7pfVyn2Yqs53yoVCEjS5sEpvQ5YRQg==} + + '@turf/invariant@6.5.0': + resolution: {integrity: sha512-Wv8PRNCtPD31UVbdJE/KVAWKe7l6US+lJItRR/HOEW3eh+U/JwRCSUl/KZ7bmjM/C+zLNoreM2TU6OoLACs4eg==} + + '@turf/line-intersect@6.5.0': + resolution: {integrity: sha512-CS6R1tZvVQD390G9Ea4pmpM6mJGPWoL82jD46y0q1KSor9s6HupMIo1kY4Ny+AEYQl9jd21V3Scz20eldpbTVA==} + + '@turf/line-segment@6.5.0': + resolution: {integrity: sha512-jI625Ho4jSuJESNq66Mmi290ZJ5pPZiQZruPVpmHkUw257Pew0alMmb6YrqYNnLUuiVVONxAAKXUVeeUGtycfw==} + + '@turf/meta@6.5.0': + resolution: {integrity: sha512-RrArvtsV0vdsCBegoBtOalgdSOfkBrTJ07VkpiCnq/491W67hnMWmDu7e6Ztw0C3WldRYTXkg3SumfdzZxLBHA==} + + '@turf/point-to-line-distance@6.5.0': + resolution: {integrity: sha512-opHVQ4vjUhNBly1bob6RWy+F+hsZDH9SA0UW36pIRzfpu27qipU18xup0XXEePfY6+wvhF6yL/WgCO2IbrLqEA==} + + '@turf/polygon-to-line@6.5.0': + resolution: {integrity: sha512-5p4n/ij97EIttAq+ewSnKt0ruvuM+LIDzuczSzuHTpq4oS7Oq8yqg5TQ4nzMVuK41r/tALCk7nAoBuw3Su4Gcw==} + + '@turf/projection@6.5.0': + resolution: {integrity: sha512-/Pgh9mDvQWWu8HRxqpM+tKz8OzgauV+DiOcr3FCjD6ubDnrrmMJlsf6fFJmggw93mtVPrZRL6yyi9aYCQBOIvg==} + + '@turf/rhumb-bearing@6.5.0': + resolution: {integrity: sha512-jMyqiMRK4hzREjQmnLXmkJ+VTNTx1ii8vuqRwJPcTlKbNWfjDz/5JqJlb5NaFDcdMpftWovkW5GevfnuzHnOYA==} + + '@turf/rhumb-distance@6.5.0': + resolution: {integrity: sha512-oKp8KFE8E4huC2Z1a1KNcFwjVOqa99isxNOwfo4g3SUABQ6NezjKDDrnvC4yI5YZ3/huDjULLBvhed45xdCrzg==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/geojson@7946.0.8': + resolution: {integrity: sha512-1rkryxURpr6aWP7R786/UQOkJ3PcpQiWkAXBmdWc7ryFWqN6a4xfK7BtjXvFBKO9LjQ+MWQSWxYeZX1OApnArA==} + + '@types/node@26.6.5': + resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} + + '@types/proj4@2.5.2': + resolution: {integrity: sha512-/Nmfn9p08yaYw6xo5f2b0L+2oHk2kZeOkp5v+4VCeNfq+ETlLQbmHmC97/pjDIEZy8jxwz7pdPpwNzDHM5cuJw==} + + '@types/rbush@4.0.0': + resolution: {integrity: sha512-+N+2H39P8X+Hy1I5mC6awlTX54k3FhiUmvt7HWzGJZvF+syUAAxP/stwppS8JE84YHqFgRMv6fCy31202CMFxQ==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + '@xmldom/xmldom@0.8.15': + resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==} + engines: {node: '>=10.0.0'} + + '@zarrita/storage@0.2.0': + resolution: {integrity: sha512-855ZXqtnds7spnT8vNvD+MXa3QExP1m2GqShe8yt7uZXHnQLgJHgkpVwFjE1B0KDDRO0ki09hmk6OboTaIfPsQ==} + + JSONStream@1.3.5: + resolution: {integrity: sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==} + hasBin: true + + abstract-logging@2.0.1: + resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==} + + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + atomic-sleep@1.0.0: + resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} + engines: {node: '>=8.0.0'} + + avvio@9.3.1: + resolution: {integrity: sha512-QyTKW61/qlba+cUQBm/sT9X8lri4UdomqSDwCnrnj1IvLVDRRiXRkz4CgBRWB+/cmfC7SK5WQc8T1vSdGvaUcQ==} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + better-sqlite3@12.11.1: + resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==} + engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} + + better-sqlite3@13.0.3: + resolution: {integrity: sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==} + engines: {node: '>=22'} + + bindings@1.5.0: + resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + brotli@1.3.3: + resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + bundle-name@4.1.1: + resolution: {integrity: sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==} + engines: {node: '>=18'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + chalk@4.1.1: + resolution: {integrity: sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==} + engines: {node: '>=10'} + + chardet@2.2.0: + resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==} + + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + + clone@2.1.2: + resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} + engines: {node: '>=0.8'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + commander@14.0.3: + resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} + engines: {node: '>=20'} + + concat-stream@2.0.0: + resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==} + engines: {'0': node >= 6.0} + + cookie@2.0.1: + resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==} + engines: {node: '>=22'} + + cookies@0.8.0: + resolution: {integrity: sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==} + engines: {node: '>= 0.8'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-scale-chromatic@3.0.0: + resolution: {integrity: sha512-Lx9thtxAKrO2Pq6OO2Ua474opeziKr279P/TKZsMAhYyNDD3EnCffdbgeSYN5O7m2ByQsxtuP2CSDczNUIZ22g==} + engines: {node: '>=12'} + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + + default-browser-id@5.0.1: + resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} + engines: {node: '>=18'} + + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} + engines: {node: '>=18'} + + define-lazy-prop@3.0.0: + resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==} + engines: {node: '>=12'} + + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + + depd@2.0.0: + resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} + engines: {node: '>= 0.8'} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dfa@1.2.0: + resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==} + + duplexer@0.1.2: + resolution: {integrity: sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==} + + earcut@3.2.4: + resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + event-stream@4.0.1: + resolution: {integrity: sha512-qACXdu/9VHPBzcyhdOWR5/IahhGMf0roTeZJfzz077GwylcDd90yOHLouhmv7GJ5XzPi6ekaQWd8AvPP2nOvpA==} + + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-decode-uri-component@1.0.1: + resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stringify@7.2.0: + resolution: {integrity: sha512-q18imgm9fEdQVfvJbRJALE9VP/A5HGme0+NUnWcmFYM9rbQbLkZZk20FyIp1LQ8gDOauQKwqMc52YozqFaQyOw==} + + fast-querystring@1.1.2: + resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} + + fast-string-truncated-width@3.0.3: + resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} + + fast-string-width@3.0.2: + resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} + + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} + + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} + + fast-wrap-ansi@0.2.2: + resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} + + fastify-plugin@6.0.1: + resolution: {integrity: sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==} + + fastify@5.12.7: + resolution: {integrity: sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw==} + + fastq@1.20.3: + resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + + file-uri-to-path@1.0.0: + resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} + + find-my-way@9.10.0: + resolution: {integrity: sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q==} + engines: {node: '>=20'} + + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + + flatbush@4.6.2: + resolution: {integrity: sha512-nNT7MFJ58Q4IAm3aYsEg+zgZGpdRcmR1i4U+aa8c+r91jmYZg7FTQwNnIMC0FyBqVZTbClKdAnrJkKkfp1BOvw==} + + flatgeobuf@4.6.1: + resolution: {integrity: sha512-oj1QaFZ91dxI+HdX/t4iu7sdMOz1y2wKDLdNvz+5n70WQ1qpMC19P4mjvS/j4tcllYlYioKCGPIKF3uR9RGuOg==} + + flatqueue@3.1.0: + resolution: {integrity: sha512-Ia4qIYrrsEqIRx3c3XhkT+QDLQuUV5ovsr6ah1rIgKT5wclhoGK3lAMS1bWRAWxlx7wtlTBpV7QXB5d9fOSRxA==} + + fontkit@2.0.4: + resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==} + + from@0.1.7: + resolution: {integrity: sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==} + + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + fzstd@0.1.1: + resolution: {integrity: sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA==} + + geographiclib-geodesic@2.2.0: + resolution: {integrity: sha512-cIedo9VTYb0DFufodgibDmVfsWe9EASqb/kUByl09xc6PZYvLvlc89BHCThtGTPf2OII/zWJGxsR3Uz6O7QOVw==} + + geographiclib@1.48.0: + resolution: {integrity: sha512-WIpDKKj2Gu+E4jkF3f3fg7OPF6T1/35tQXKc4jLLQrwjNiTZ5KrrYF5Gp0dQ/YbJIoCjb9vs2/abWTRsCEoi2w==} + deprecated: 'This package has been split into geographic-geodesic + geographiclib-dms; use one or both of these instead of geographiclib. WARNING: there''s a potential buffer overrun on this package. SWITCH TO THE NEW PACKAGES NOW.' + + geojson-rbush@3.2.0: + resolution: {integrity: sha512-oVltQTXolxvsz1sZnutlSuLDEcQAKYC/uXt9zDzJJ6bu0W+baTI8LZBaTup5afzibEH4N3jlq2p+a152wlBJ7w==} + + geojson-stream@0.1.0: + resolution: {integrity: sha512-svSg5fFXPaTiqzEBGXScA+nISaeC9rLvku2PH+wM5LToATUw2bLIrvls43ymnT9Xnp51nBPVyK9m4Af40KpJ7w==} + + geotiff-geokeys-to-proj4@2024.4.13: + resolution: {integrity: sha512-Jgtm/lcPkgB44wCqQHaVQx5/fyhmiVDRUKQcI/vMolsED8/GRWBnn5qkQo/CgutQg9xkGzig21DY9Px9mFRdvg==} + + geotiff@3.0.5: + resolution: {integrity: sha512-OWcL9S9+yDZ6iAlXMt32T1iwUApJM8UiD47xbm6ZP1h33d10fqkPs14EG/ttT5EnefpZSx3G15iDFC5FxUNUwA==} + engines: {node: '>=10.19'} + + geotiff@3.1.0-beta.0: + resolution: {integrity: sha512-wbVwOaQYuN+ywly5NoMXn37nHslwkQg5EFHqMeUTtjDACrSag0EEVlFsc+2DK3Pzmmp6XzJW2RTZOamPsBM6ng==} + engines: {node: '>=10.19'} + + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + hyparquet-compressors@1.1.2: + resolution: {integrity: sha512-0Hx6w0ZpVpNCefKy5xBYLTp6rKeZn/tsUzuliNzfKqSCdLcTQSfwATEoeedS703Y17k1qNS61HwRME5aOeNkPg==} + + hyparquet-writer@0.14.0: + resolution: {integrity: sha512-XRDZcw5pcoZoazLsKGnISGKzm8ql0dWwO9MamyU2sGOotypM8JW95J3oaLCroiCcO0sexfoI8naAK6KASFtNjg==} + + hyparquet@1.25.6: + resolution: {integrity: sha512-Q9W5IjkVch3ZMnYd4qFv2q8suu5Jc36yt7J+zUNM9grwnP1S189icp0jdEQKM5HJvQkTVy8NMiQ8n/dM5QAt1A==} + + hyparquet@1.31.5: + resolution: {integrity: sha512-KPVfaxW8xOiO2/4fjeiBfFNEXhGVw9tfcb9ha2iNZdJ3J/yBjEwIeAnTyyuhllFFTb9YO9wg0DfRAOnm6KCvBg==} + + hysnappy@1.1.1: + resolution: {integrity: sha512-/V9XcN2NtRyWjR4LYMfvnvasVVF8jbT/ej0eofBQjZel91E3D813FQ3mQC6gDSMMTCq/FJh28XHeyqr3I/oBRw==} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + + idb-keyval@6.3.0: + resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + image-size@2.0.4: + resolution: {integrity: sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==} + engines: {node: '>=18'} + hasBin: true + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + inquirer@14.2.4: + resolution: {integrity: sha512-xPVejWqfkjG9OxSirMqu3pdzGIGsma68j2S+nEOuuwMbU3pRTHnYs9d8my+1M6OMlqr8XZPwCPonZ2DKMwQDLg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + ip-address@10.7.5: + resolution: {integrity: sha512-t2v0rkILYv9WXmSL7TpAaU3HXgaFYOPUcH3QHgwQ++gpJuH3bqyMy4Fvt/DJCTKwzH3Cf+bAp5W/mFL39KPLzA==} + engines: {node: '>= 12'} + + ipaddr.js@2.5.0: + resolution: {integrity: sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==} + engines: {node: '>= 10'} + + is-docker@3.0.0: + resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + hasBin: true + + is-in-ssh@1.0.0: + resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==} + engines: {node: '>=20'} + + is-inside-container@1.0.0: + resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==} + engines: {node: '>=14.16'} + hasBin: true + + is-wsl@3.1.1: + resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==} + engines: {node: '>=16'} + + jpeg-js@0.4.4: + resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} + + json-schema-ref-resolver@3.0.1: + resolution: {integrity: sha512-w+HwgljXpVwZ3IidoUR1qPZxSOQ+NRQWuVe6a5pe8XbHsNZE4UAwVPUvzZagn7yBKbJtt6UJnRFYbNTRPZI45Q==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + jsonparse@1.3.1: + resolution: {integrity: sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==} + engines: {'0': node >= 0.2.0} + + kdbush@3.0.0: + resolution: {integrity: sha512-hRkd6/XW4HTsA9vjVpY9tuXJYLSlelnkTmVFu4M9/7MIYQtFcHpbugAU7UbOfjOiVSVYl2fqgBuJ32JUmRo5Ew==} + + keygrip@1.1.0: + resolution: {integrity: sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==} + engines: {node: '>= 0.6'} + + lerc@3.0.0: + resolution: {integrity: sha512-Rm4J/WaHhRa93nCN2mwWDZFoRVF18G1f47C+kvQWyHGEZxFpTUi73p7lMVSAndyxGt6lJ2/CFbOcf9ra5p8aww==} + + light-my-request@6.8.0: + resolution: {integrity: sha512-5Q8PjoSEdtGIB8fikZsTem5vgRo4F2mR6vUKTDW/H1g6MtAt8e3duQbg/QxL5yzg6BZhor2KOUm3hhWMWLTZwg==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + magic-bytes.js@1.13.1: + resolution: {integrity: sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==} + + magic-string@1.4.3: + resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==} + + map-stream@0.0.7: + resolution: {integrity: sha512-C0X0KQmGm3N2ftbTGBhSyuydQ+vV1LC3f3zPvT3RXHXNZrvfPZcoXp/N5DOa8vedX/rTMm2CjTtivFg2STJMRQ==} + + mapshaper@0.7.98: + resolution: {integrity: sha512-uTYMKQtprwogg3xh14xohZEntsvoRNZyI4Dx3axZctrzbAsXtDT3d2S9fFaAQzYkW8zWFGHlx2JYat0Pp9etSw==} + engines: {node: '>=20.11.0'} + hasBin: true + + mgrs@1.0.0: + resolution: {integrity: sha512-awNbTOqCxK1DBGjalK3xqWIstBZgN6fxsMSiXLs9/spqWkF2pAhb2rrYCFSsr1/tT7PhcDGjZndG8SWYn0byYA==} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + + mproj@0.1.6: + resolution: {integrity: sha512-tw30j10qLYWJoc1Q448T5cfcQ26wO4yc3KdYyHcX9ts9u83lC0qoXg+/FNQbiV3wb40R0rzU15bPyO6N+lpkxg==} + engines: {node: '>=0.12.0'} + hasBin: true + + msgpackr-extract@3.0.4: + resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==} + hasBin: true + + msgpackr@1.12.1: + resolution: {integrity: sha512-4EUH9tQHnMmEgzW/MdAP0KIfa1T9AF+htl0ffe2n5vb2EKn9y2co8ccpgWko6S52Jy1PQZKwRnx5/KkYjtd9MQ==} + + mute-stream@3.0.0: + resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==} + engines: {node: ^20.17.0 || >=22.9.0} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + + node-abi@3.101.0: + resolution: {integrity: sha512-bkb/RkuWCE64eWu1PCh3Fu2pGc9mKRs+kOE+FU2bGHRYlQa86/D321DSATV54AsCQMKz3/xSt9sRgraZTpqdhQ==} + engines: {node: '>=10'} + + node-addon-api@8.9.2: + resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==} + engines: {node: ^18 || ^20 || >= 21} + + node-gyp-build-optional-packages@5.2.2: + resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==} + hasBin: true + + numcodecs@0.3.2: + resolution: {integrity: sha512-6YSPnmZgg0P87jnNhi3s+FVLOcIn3y+1CTIgUulA3IdASzK9fJM87sUFkpyA+be9GibGRaST2wCgkD+6U+fWKw==} + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + ol@10.11.0: + resolution: {integrity: sha512-OJ+lrx7kx/1O7Xx18Ff9QkVnwZIEL0OuhJQSy2sYgzzDvyZ2qHvuZEGAajbSstUyBwaS1OtQ4RWnY84tRMDdqg==} + + on-exit-leak-free@2.1.2: + resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} + engines: {node: '>=14.0.0'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + open@11.0.4: + resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==} + engines: {node: '>=20'} + + pako@0.2.9: + resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==} + + pako@2.2.0: + resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==} + + parse-headers@2.0.6: + resolution: {integrity: sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==} + + pause-stream@0.0.11: + resolution: {integrity: sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==} + + pbf@5.1.2: + resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==} + hasBin: true + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + pino-abstract-transport@3.0.0: + resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + + pino-std-serializers@7.1.0: + resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} + + pino@10.4.0: + resolution: {integrity: sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==} + hasBin: true + + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + + polygon-clipping@0.15.7: + resolution: {integrity: sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==} + + postcss@8.5.31: + resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + engines: {node: ^10 || ^12 || >=14} + + powershell-utils@0.2.1: + resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==} + engines: {node: '>=20'} + + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + + process-warning@5.1.1: + resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==} + + proj4@2.8.0: + resolution: {integrity: sha512-baC+YcD4xsSqJ+CpCZljj2gcQDhlKb+J+Zjv/2KSBwWNjk4M0pafgQsE+mWurd84tflMIsP+7j7mtIpFDHzQfQ==} + + protocol-buffers-schema@3.6.1: + resolution: {integrity: sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + quick-format-unescaped@4.0.4: + resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} + + quick-lru@6.1.2: + resolution: {integrity: sha512-AAFUA5O1d83pIHEhJwWCq/RQcRukCkn/NSm2QsTEMle5f2hP0ChI2+3Xb051PZCkLryI/Ir1MVKviT2FIloaTQ==} + engines: {node: '>=12'} + + quickselect@2.0.0: + resolution: {integrity: sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw==} + + quickselect@3.0.0: + resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==} + + rbush@3.0.1: + resolution: {integrity: sha512-XRaVO0YecOpEuIvbhbpTrZgoiI6xBlz6hnlr6EHhd+0x9ase6EmeN+hdwwUaJvLcsFFQ8iWVF1GAK1yB0BWi0w==} + + rbush@4.0.1: + resolution: {integrity: sha512-IP0UpfeWQujYC8Jg162rMNc01Rf0gWMMAb2Uxus/Q0qOFw4lCcq6ZnQEZwUoJqWyUGJ9th7JjwI4yIWo+uvoAQ==} + + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + real-require@1.0.0: + resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} + + reference-spec-reader@0.2.0: + resolution: {integrity: sha512-q0mfCi5yZSSHXpCyxjgQeaORq3tvDsxDyzaadA/5+AbAUwRyRuuTh0aRQuE/vAOt/qzzxidJ5iDeu1cLHaNBlQ==} + + reproject@1.2.5: + resolution: {integrity: sha512-cTH78fi1uuv5gzW/GVepO4LbCvOUhO0X2BEyyvrKkYb4KPRmDPs7cZnIxemHPUIch/CoSI8MPLmXRHZFSHjbKw==} + hasBin: true + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + resolve-protobuf-schema@2.1.0: + resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==} + + restructure@3.0.2: + resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==} + + ret@0.5.1: + resolution: {integrity: sha512-Z/nyvABwcRnRD2mMP7Kz6G1dFZZqX1mNErOnxF42OCQKE07b9k9hK9SQxHL3LFEZUdzQaLM4dId1E/E6Vm4WhA==} + engines: {node: '>=10'} + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rfdc@1.4.1: + resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==} + + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + + rolldown@1.2.15: + resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rtree-sql.js@1.7.0: + resolution: {integrity: sha512-hue7klBnBrM6pvUPSnXNNgA0yN9FIjmhb8QveVY9q5h/3b//Cd8jaafUE0Ty89fuiamaLEHRw8eQq8mTn6Df5Q==} + + run-applescript@7.1.0: + resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==} + engines: {node: '>=18'} + + run-async@4.0.6: + resolution: {integrity: sha512-IoDlSLTs3Yq593mb3ZoKWKXMNu3UpObxhgA/Xuid5p4bbfi2jdY1Hj0m1K+0/tEuQTxIGMhQDqGjKb7RuxGpAQ==} + engines: {node: '>=0.12.0'} + + rw@1.3.3: + resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safe-regex2@5.1.2: + resolution: {integrity: sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==} + hasBin: true + + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + secure-json-parse@4.1.1: + resolution: {integrity: sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + set-cookie-parser@3.2.1: + resolution: {integrity: sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + simplify-js@1.2.4: + resolution: {integrity: sha512-vITfSlwt7h/oyrU42R83mtzFpwYk3+mkH9bOHqq/Qw6n8rtR7aE3NZQ5fbcyCUVVmuMJR6ynsAhOfK2qoah8Jg==} + + slice-source@0.4.1: + resolution: {integrity: sha512-YiuPbxpCj4hD9Qs06hGAz/OZhQ0eDuALN0lRWJez0eD/RevzKqGdUx1IOMUnXgpr+sXZLq3g8ERwbAH0bCb8vg==} + + sonic-boom@4.2.1: + resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + splaytree@3.2.3: + resolution: {integrity: sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==} + engines: {node: '>=18.20 || >=20'} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + split@1.0.1: + resolution: {integrity: sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + stream-combiner@0.2.2: + resolution: {integrity: sha512-6yHMqgLYDzQDcAkL+tjJDC5nSNuNIx0vZtRZeiPh7Saef7VHX9H5Ijn9l2VIol2zaNYlYEX6KyuT/237A58qEQ==} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + tar-fs@2.1.5: + resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + + thread-stream@4.2.0: + resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==} + engines: {node: '>=20'} + + through@2.3.8: + resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==} + + tiny-inflate@1.0.3: + resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + + tinybench@6.2.2: + resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyqueue@2.0.3: + resolution: {integrity: sha512-ppJZNDuKGgxzkHihX8v9v9G5f+18gzaTfrukGrq6ueg0lmH4nqVnA2IPG0AEH3jKEk2GRJCUhDoqpoiw3PHLBA==} + + toad-cache@3.7.4: + resolution: {integrity: sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==} + engines: {node: '>=20'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + tsscmp@1.0.6: + resolution: {integrity: sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==} + engines: {node: '>=0.6.x'} + + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + + typedarray@0.0.6: + resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + unicode-properties@1.4.1: + resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==} + + unicode-trie@2.0.0: + resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==} + + unzipit@2.0.0: + resolution: {integrity: sha512-DVeVIWUZCAQPNzm5sB0hpsG1GygTTdBnzNtYYEpInkttx5evkyqRgZi6rTczoySqp8hO5jHVKzrH0f23X8FZLg==} + engines: {node: '>=18'} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + web-worker@1.5.0: + resolution: {integrity: sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==} + + webworkify@1.5.0: + resolution: {integrity: sha512-AMcUeyXAhbACL8S2hqqdqOLqvJ8ylmIbNwUIqQujRSouf4+eUFaXbG6F1Rbu+srlJMmxQWsiU7mOJi0nMBfM1g==} + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + + wkt-parser@1.6.0: + resolution: {integrity: sha512-O2WMUagkdOKkgcfqZBUauysHVeifCwcs+zUd2QG7UIzVljLwK9g5xHUfL/TkQFwmQ3eF7oHFKGnMcb/kZdvbaw==} + + wkx@0.4.8: + resolution: {integrity: sha512-ikPXMM9IR/gy/LwiOSqWlSL3X/J5uk9EO2hHNRXS41eTLXaUFEVw9fn/593jW/tE5tedNg8YjT5HkCa4FqQZyQ==} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + wsl-utils@1.0.1: + resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} + engines: {node: '>=20'} + + xml-utils@1.10.2: + resolution: {integrity: sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==} + + zarrita@0.7.5: + resolution: {integrity: sha512-ZriOSEne+Wf2iuM0yjDZvUKpHNlug3dO7qJ6mAxXoOgsYV18DPOkAkwB9e0rf21bHcKcOffFuwoZwn5g6pvUeA==} + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + + zstddec@0.2.0: + resolution: {integrity: sha512-oyPnDa1X5c13+Y7mA/FDMNJrn4S8UNBe0KCqtDmor40Re7ALrPN6npFwyYVRRh+PqozZQdeg23QtbcamZnG5rA==} + +snapshots: + + '@bokuweb/zstd-wasm@0.0.27': {} + + '@fastify/ajv-compiler@4.0.7': + dependencies: + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + fast-uri: 4.2.3 + + '@fastify/deepmerge@3.2.4': {} + + '@fastify/error@4.2.1': {} + + '@fastify/fast-json-stringify-compiler@5.1.1': + dependencies: + fast-json-stringify: 7.2.0 + + '@fastify/forwarded@3.1.2': {} + + '@fastify/merge-json-schemas@0.2.2': + dependencies: + dequal: 2.0.3 + + '@fastify/proxy-addr@5.1.2': + dependencies: + '@fastify/forwarded': 3.1.2 + ipaddr.js: 2.5.0 + + '@fastify/rate-limit@11.2.1': + dependencies: + '@lukeed/ms': 2.0.2 + fastify-plugin: 6.0.1 + ip-address: 10.7.5 + toad-cache: 3.7.4 + + '@inquirer/ansi@2.0.9': + optional: true + + '@inquirer/checkbox@5.2.7(@types/node@26.6.5)': + dependencies: + '@inquirer/ansi': 2.0.9 + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/confirm@6.3.4(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/core@12.0.5(@types/node@26.6.5)': + dependencies: + '@inquirer/ansi': 2.0.9 + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.2.0(@types/node@26.6.5) + cli-width: 4.1.0 + fast-wrap-ansi: 0.2.2 + mute-stream: 3.0.0 + signal-exit: 4.1.0 + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/editor@5.3.5(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/external-editor': 3.0.6(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/expand@5.1.7(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/external-editor@3.0.6(@types/node@26.6.5)': + dependencies: + chardet: 2.2.0 + iconv-lite: 0.7.3 + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/figures@2.0.9': + optional: true + + '@inquirer/input@5.1.8(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/number@4.2.5(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/password@5.2.4(@types/node@26.6.5)': + dependencies: + '@inquirer/ansi': 2.0.9 + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/prompts@8.7.4(@types/node@26.6.5)': + dependencies: + '@inquirer/checkbox': 5.2.7(@types/node@26.6.5) + '@inquirer/confirm': 6.3.4(@types/node@26.6.5) + '@inquirer/editor': 5.3.5(@types/node@26.6.5) + '@inquirer/expand': 5.1.7(@types/node@26.6.5) + '@inquirer/input': 5.1.8(@types/node@26.6.5) + '@inquirer/number': 4.2.5(@types/node@26.6.5) + '@inquirer/password': 5.2.4(@types/node@26.6.5) + '@inquirer/rawlist': 5.3.7(@types/node@26.6.5) + '@inquirer/search': 4.3.5(@types/node@26.6.5) + '@inquirer/select': 5.2.7(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/rawlist@5.3.7(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/search@4.3.5(@types/node@26.6.5)': + dependencies: + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/select@5.2.7(@types/node@26.6.5)': + dependencies: + '@inquirer/ansi': 2.0.9 + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/figures': 2.0.9 + '@inquirer/type': 4.2.0(@types/node@26.6.5) + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@inquirer/type@4.2.0(@types/node@26.6.5)': + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@lukeed/ms@2.0.2': {} + + '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': + optional: true + + '@ngageoint/geopackage@4.2.10(@types/node@26.6.5)': + dependencies: + '@turf/bbox': 6.3.0 + '@turf/boolean-clockwise': 6.5.0 + '@turf/boolean-point-in-polygon': 6.5.0 + '@turf/boolean-within': 6.5.0 + '@turf/distance': 6.5.0 + '@turf/helpers': 6.5.0 + '@turf/intersect': 6.5.0 + '@turf/line-intersect': 6.5.0 + '@turf/point-to-line-distance': 6.5.0 + '@turf/polygon-to-line': 6.5.0 + '@types/geojson': 7946.0.8 + '@types/proj4': 2.5.2 + image-size: 2.0.4 + lodash: 4.18.1 + magic-bytes.js: 1.13.1 + proj4: 2.8.0 + reproject: 1.2.5 + rtree-sql.js: 1.7.0 + simplify-js: 1.2.4 + webworkify: 1.5.0 + wkx: 0.4.8 + optionalDependencies: + better-sqlite3: 13.0.3 + chalk: 4.1.1 + inquirer: 14.2.4(@types/node@26.6.5) + transitivePeerDependencies: + - '@types/node' + + '@oxc-project/types@0.155.0': {} + + '@petamoriken/float16@3.9.3': {} + + '@pinojs/redact@0.4.0': {} + + '@placemarkio/tokml@0.3.9': {} + + '@repeaterjs/repeater@3.1.0': {} + + '@resvg/resvg-wasm@2.6.2': {} + + '@rolldown/binding-android-arm-eabi@1.2.15': + optional: true + + '@rolldown/binding-android-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-x64@1.2.15': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.15': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.15': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.15': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.15': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.15': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@rollup/rollup-linux-x64-gnu@4.65.0': + optional: true + + '@swc/helpers@0.5.23': + dependencies: + tslib: 2.8.1 + + '@tmcw/togeojson@5.8.1(@types/geojson@7946.0.8)': + dependencies: + '@types/geojson': 7946.0.8 + + '@turf/bbox@6.3.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/meta': 6.5.0 + + '@turf/bbox@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/meta': 6.5.0 + + '@turf/bearing@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/boolean-clockwise@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/boolean-point-in-polygon@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/boolean-point-on-line@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/boolean-within@6.5.0': + dependencies: + '@turf/bbox': 6.5.0 + '@turf/boolean-point-in-polygon': 6.5.0 + '@turf/boolean-point-on-line': 6.5.0 + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/clone@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + + '@turf/distance@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/helpers@6.5.0': {} + + '@turf/intersect@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + polygon-clipping: 0.15.7 + + '@turf/invariant@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + + '@turf/line-intersect@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + '@turf/line-segment': 6.5.0 + '@turf/meta': 6.5.0 + geojson-rbush: 3.2.0 + + '@turf/line-segment@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + '@turf/meta': 6.5.0 + + '@turf/meta@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + + '@turf/point-to-line-distance@6.5.0': + dependencies: + '@turf/bearing': 6.5.0 + '@turf/distance': 6.5.0 + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + '@turf/meta': 6.5.0 + '@turf/projection': 6.5.0 + '@turf/rhumb-bearing': 6.5.0 + '@turf/rhumb-distance': 6.5.0 + + '@turf/polygon-to-line@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/projection@6.5.0': + dependencies: + '@turf/clone': 6.5.0 + '@turf/helpers': 6.5.0 + '@turf/meta': 6.5.0 + + '@turf/rhumb-bearing@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@turf/rhumb-distance@6.5.0': + dependencies: + '@turf/helpers': 6.5.0 + '@turf/invariant': 6.5.0 + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/geojson@7946.0.8': {} + + '@types/node@26.6.5': + dependencies: + undici-types: 8.9.0 + + '@types/proj4@2.5.2': {} + + '@types/rbush@4.0.0': + optional: true + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/mocker@5.0.5(vite@8.3.5(@types/node@26.6.5))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.3 + optionalDependencies: + vite: 8.3.5(@types/node@26.6.5) + + '@vitest/spy@5.0.5': {} + + '@xmldom/xmldom@0.8.15': {} + + '@zarrita/storage@0.2.0': + dependencies: + reference-spec-reader: 0.2.0 + unzipit: 2.0.0 + optional: true + + JSONStream@1.3.5: + dependencies: + jsonparse: 1.3.1 + through: 2.3.8 + + abstract-logging@2.0.1: {} + + adm-zip@0.6.1: {} + + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.9 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + optional: true + + assertion-error@2.0.1: {} + + atomic-sleep@1.0.0: {} + + avvio@9.3.1: + dependencies: + '@fastify/error': 4.2.1 + fastq: 1.20.3 + + base64-js@1.5.1: {} + + better-sqlite3@12.11.1: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + optional: true + + better-sqlite3@13.0.3: + dependencies: + node-addon-api: 8.9.2 + optional: true + + bindings@1.5.0: + dependencies: + file-uri-to-path: 1.0.0 + optional: true + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + optional: true + + brotli@1.3.3: + dependencies: + base64-js: 1.5.1 + + buffer-from@1.1.2: {} + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + optional: true + + bundle-name@4.1.1: + dependencies: + run-applescript: 7.1.0 + + chai@6.3.0: {} + + chalk@4.1.1: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + optional: true + + chardet@2.2.0: + optional: true + + chownr@1.1.4: + optional: true + + cli-width@4.1.0: + optional: true + + clone@2.1.2: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + optional: true + + color-name@1.1.4: + optional: true + + commander@14.0.3: {} + + concat-stream@2.0.0: + dependencies: + buffer-from: 1.1.2 + inherits: 2.0.4 + readable-stream: 3.6.2 + typedarray: 0.0.6 + + cookie@2.0.1: {} + + cookies@0.8.0: + dependencies: + depd: 2.0.0 + keygrip: 1.1.0 + + d3-color@3.1.0: {} + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-scale-chromatic@3.0.0: + dependencies: + d3-color: 3.1.0 + d3-interpolate: 3.0.1 + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + optional: true + + deep-extend@0.6.0: + optional: true + + default-browser-id@5.0.1: {} + + default-browser@5.5.1: + dependencies: + bundle-name: 4.1.1 + default-browser-id: 5.0.1 + + define-lazy-prop@3.0.0: {} + + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + + depd@2.0.0: {} + + dequal@2.0.3: {} + + detect-libc@2.1.2: {} + + dfa@1.2.0: {} + + duplexer@0.1.2: {} + + earcut@3.2.4: + optional: true + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + optional: true + + es-module-lexer@2.3.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + event-stream@4.0.1: + dependencies: + duplexer: 0.1.2 + from: 0.1.7 + map-stream: 0.0.7 + pause-stream: 0.0.11 + split: 1.0.1 + stream-combiner: 0.2.2 + through: 2.3.8 + + expand-template@2.0.3: + optional: true + + expect-type@1.4.0: {} + + fast-decode-uri-component@1.0.1: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stringify@7.2.0: + dependencies: + '@fastify/merge-json-schemas': 0.2.2 + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + fast-uri: 4.2.3 + json-schema-ref-resolver: 3.0.1 + rfdc: 1.4.1 + + fast-querystring@1.1.2: + dependencies: + fast-decode-uri-component: 1.0.1 + + fast-string-truncated-width@3.0.3: + optional: true + + fast-string-width@3.0.2: + dependencies: + fast-string-truncated-width: 3.0.3 + optional: true + + fast-uri@3.1.9: {} + + fast-uri@4.2.3: {} + + fast-wrap-ansi@0.2.2: + dependencies: + fast-string-width: 3.0.2 + optional: true + + fastify-plugin@6.0.1: {} + + fastify@5.12.7: + dependencies: + '@fastify/ajv-compiler': 4.0.7 + '@fastify/error': 4.2.1 + '@fastify/fast-json-stringify-compiler': 5.1.1 + '@fastify/proxy-addr': 5.1.2 + abstract-logging: 2.0.1 + avvio: 9.3.1 + fast-json-stringify: 7.2.0 + find-my-way: 9.10.0 + light-my-request: 6.8.0 + pino: 10.4.0 + process-warning: 5.1.1 + rfdc: 1.4.1 + secure-json-parse: 4.1.1 + semver: 7.8.5 + toad-cache: 3.7.4 + + fastq@1.20.3: + dependencies: + reusify: 1.1.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fflate@0.8.3: {} + + file-uri-to-path@1.0.0: + optional: true + + find-my-way@9.10.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-querystring: 1.1.2 + safe-regex2: 5.1.2 + + flatbuffers@25.9.23: {} + + flatbush@4.6.2: + dependencies: + flatqueue: 3.1.0 + + flatgeobuf@4.6.1: + dependencies: + '@bokuweb/zstd-wasm': 0.0.27 + '@repeaterjs/repeater': 3.1.0 + flatbuffers: 25.9.23 + slice-source: 0.4.1 + optionalDependencies: + ol: 10.11.0 + + flatqueue@3.1.0: {} + + fontkit@2.0.4: + dependencies: + '@swc/helpers': 0.5.23 + brotli: 1.3.3 + clone: 2.1.2 + dfa: 1.2.0 + fast-deep-equal: 3.1.3 + restructure: 3.0.2 + tiny-inflate: 1.0.3 + unicode-properties: 1.4.1 + unicode-trie: 2.0.0 + + from@0.1.7: {} + + fs-constants@1.0.0: + optional: true + + fsevents@2.3.3: + optional: true + + fzstd@0.1.1: {} + + geographiclib-geodesic@2.2.0: {} + + geographiclib@1.48.0: {} + + geojson-rbush@3.2.0: + dependencies: + '@turf/bbox': 6.3.0 + '@turf/helpers': 6.5.0 + '@turf/meta': 6.5.0 + '@types/geojson': 7946.0.8 + rbush: 3.0.1 + + geojson-stream@0.1.0: + dependencies: + JSONStream: 1.3.5 + through: 2.3.8 + + geotiff-geokeys-to-proj4@2024.4.13: {} + + geotiff@3.0.5: + dependencies: + '@petamoriken/float16': 3.9.3 + lerc: 3.0.0 + pako: 2.2.0 + parse-headers: 2.0.6 + quick-lru: 6.1.2 + web-worker: 1.5.0 + xml-utils: 1.10.2 + zstddec: 0.2.0 + + geotiff@3.1.0-beta.0: + dependencies: + '@petamoriken/float16': 3.9.3 + lerc: 3.0.0 + pako: 2.2.0 + parse-headers: 2.0.6 + quick-lru: 6.1.2 + web-worker: 1.5.0 + xml-utils: 1.10.2 + zstddec: 0.2.0 + optional: true + + github-from-package@0.0.0: + optional: true + + has-flag@4.0.0: + optional: true + + hyparquet-compressors@1.1.2: + dependencies: + fzstd: 0.1.1 + hysnappy: 1.1.1 + + hyparquet-writer@0.14.0: + dependencies: + hyparquet: 1.25.6 + + hyparquet@1.25.6: {} + + hyparquet@1.31.5: {} + + hysnappy@1.1.1: {} + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + optional: true + + idb-keyval@6.3.0: {} + + ieee754@1.2.1: + optional: true + + image-size@2.0.4: {} + + inherits@2.0.4: {} + + ini@1.3.8: + optional: true + + inquirer@14.2.4(@types/node@26.6.5): + dependencies: + '@inquirer/ansi': 2.0.9 + '@inquirer/core': 12.0.5(@types/node@26.6.5) + '@inquirer/prompts': 8.7.4(@types/node@26.6.5) + '@inquirer/type': 4.2.0(@types/node@26.6.5) + mute-stream: 3.0.0 + run-async: 4.0.6 + optionalDependencies: + '@types/node': 26.6.5 + optional: true + + ip-address@10.7.5: {} + + ipaddr.js@2.5.0: {} + + is-docker@3.0.0: {} + + is-in-ssh@1.0.0: {} + + is-inside-container@1.0.0: + dependencies: + is-docker: 3.0.0 + + is-wsl@3.1.1: + dependencies: + is-inside-container: 1.0.0 + + jpeg-js@0.4.4: {} + + json-schema-ref-resolver@3.0.1: + dependencies: + dequal: 2.0.3 + + json-schema-traverse@1.0.0: {} + + jsonparse@1.3.1: {} + + kdbush@3.0.0: {} + + keygrip@1.1.0: + dependencies: + tsscmp: 1.0.6 + + lerc@3.0.0: {} + + light-my-request@6.8.0: + dependencies: + '@fastify/deepmerge': 3.2.4 + cookie: 2.0.1 + process-warning: 5.1.1 + set-cookie-parser: 3.2.1 + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lodash@4.18.1: {} + + magic-bytes.js@1.13.1: {} + + magic-string@1.4.3: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + map-stream@0.0.7: {} + + mapshaper@0.7.98(@types/geojson@7946.0.8)(@types/node@26.6.5): + dependencies: + '@bokuweb/zstd-wasm': 0.0.27 + '@ngageoint/geopackage': 4.2.10(@types/node@26.6.5) + '@placemarkio/tokml': 0.3.9 + '@resvg/resvg-wasm': 2.6.2 + '@tmcw/togeojson': 5.8.1(@types/geojson@7946.0.8) + '@xmldom/xmldom': 0.8.15 + adm-zip: 0.6.1 + commander: 14.0.3 + cookies: 0.8.0 + d3-color: 3.1.0 + d3-interpolate: 3.0.1 + d3-scale-chromatic: 3.0.0 + delaunator: 5.1.0 + fflate: 0.8.3 + flatbush: 4.6.2 + flatgeobuf: 4.6.1 + fontkit: 2.0.4 + geographiclib-geodesic: 2.2.0 + geotiff: 3.0.5 + geotiff-geokeys-to-proj4: 2024.4.13 + hyparquet: 1.31.5 + hyparquet-compressors: 1.1.2 + hyparquet-writer: 0.14.0 + iconv-lite: 0.6.3 + idb-keyval: 6.3.0 + jpeg-js: 0.4.4 + kdbush: 3.0.0 + mproj: 0.1.6 + msgpackr: 1.12.1 + open: 11.0.4 + pngjs: 7.0.0 + rw: 1.3.3 + tinyqueue: 2.0.3 + optionalDependencies: + '@rollup/rollup-linux-x64-gnu': 4.65.0 + better-sqlite3: 12.11.1 + transitivePeerDependencies: + - '@types/geojson' + - '@types/node' + + mgrs@1.0.0: {} + + mimic-response@3.1.0: + optional: true + + minimist@1.2.8: {} + + mkdirp-classic@0.5.3: + optional: true + + mproj@0.1.6: + dependencies: + geographiclib: 1.48.0 + rw: 1.3.3 + + msgpackr-extract@3.0.4: + dependencies: + node-gyp-build-optional-packages: 5.2.2 + optionalDependencies: + '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4 + optional: true + + msgpackr@1.12.1: + optionalDependencies: + msgpackr-extract: 3.0.4 + + mute-stream@3.0.0: + optional: true + + nanoid@3.3.20: {} + + napi-build-utils@2.0.0: + optional: true + + node-abi@3.101.0: + dependencies: + semver: 7.8.5 + optional: true + + node-addon-api@8.9.2: + optional: true + + node-gyp-build-optional-packages@5.2.2: + dependencies: + detect-libc: 2.1.2 + optional: true + + numcodecs@0.3.2: + dependencies: + fflate: 0.8.3 + optional: true + + obug@3.0.0: {} + + ol@10.11.0: + dependencies: + '@types/rbush': 4.0.0 + earcut: 3.2.4 + geotiff: 3.1.0-beta.0 + pbf: 5.1.2 + rbush: 4.0.1 + zarrita: 0.7.5 + optional: true + + on-exit-leak-free@2.1.2: {} + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + optional: true + + open@11.0.4: + dependencies: + default-browser: 5.5.1 + define-lazy-prop: 3.0.0 + is-in-ssh: 1.0.0 + is-inside-container: 1.0.0 + powershell-utils: 0.2.1 + wsl-utils: 1.0.1 + + pako@0.2.9: {} + + pako@2.2.0: {} + + parse-headers@2.0.6: {} + + pause-stream@0.0.11: + dependencies: + through: 2.3.8 + + pbf@5.1.2: + dependencies: + resolve-protobuf-schema: 2.1.0 + optional: true + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + pino-abstract-transport@3.0.0: + dependencies: + split2: 4.2.0 + + pino-std-serializers@7.1.0: {} + + pino@10.4.0: + dependencies: + '@pinojs/redact': 0.4.0 + atomic-sleep: 1.0.0 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pino-std-serializers: 7.1.0 + process-warning: 5.1.1 + quick-format-unescaped: 4.0.4 + real-require: 1.0.0 + safe-stable-stringify: 2.5.0 + sonic-boom: 4.2.1 + thread-stream: 4.2.0 + + pngjs@7.0.0: {} + + polygon-clipping@0.15.7: + dependencies: + robust-predicates: 3.0.3 + splaytree: 3.2.3 + + postcss@8.5.31: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + powershell-utils@0.2.1: {} + + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.101.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.5 + tunnel-agent: 0.6.0 + optional: true + + process-warning@5.1.1: {} + + proj4@2.8.0: + dependencies: + mgrs: 1.0.0 + wkt-parser: 1.6.0 + + protocol-buffers-schema@3.6.1: + optional: true + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + optional: true + + quick-format-unescaped@4.0.4: {} + + quick-lru@6.1.2: {} + + quickselect@2.0.0: {} + + quickselect@3.0.0: + optional: true + + rbush@3.0.1: + dependencies: + quickselect: 2.0.0 + + rbush@4.0.1: + dependencies: + quickselect: 3.0.0 + optional: true + + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + optional: true + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + + real-require@1.0.0: {} + + reference-spec-reader@0.2.0: + optional: true + + reproject@1.2.5: + dependencies: + concat-stream: 2.0.0 + event-stream: 4.0.1 + geojson-stream: 0.1.0 + minimist: 1.2.8 + proj4: 2.8.0 + + require-from-string@2.0.2: {} + + resolve-protobuf-schema@2.1.0: + dependencies: + protocol-buffers-schema: 3.6.1 + optional: true + + restructure@3.0.2: {} + + ret@0.5.1: {} + + reusify@1.1.0: {} + + rfdc@1.4.1: {} + + robust-predicates@3.0.3: {} + + rolldown@1.2.15: + dependencies: + '@oxc-project/types': 0.155.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.15 + '@rolldown/binding-android-arm64': 1.2.15 + '@rolldown/binding-darwin-arm64': 1.2.15 + '@rolldown/binding-darwin-x64': 1.2.15 + '@rolldown/binding-freebsd-x64': 1.2.15 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.15 + '@rolldown/binding-linux-arm64-gnu': 1.2.15 + '@rolldown/binding-linux-arm64-musl': 1.2.15 + '@rolldown/binding-linux-ppc64-gnu': 1.2.15 + '@rolldown/binding-linux-s390x-gnu': 1.2.15 + '@rolldown/binding-linux-x64-gnu': 1.2.15 + '@rolldown/binding-linux-x64-musl': 1.2.15 + '@rolldown/binding-openharmony-arm64': 1.2.15 + '@rolldown/binding-win32-arm64-msvc': 1.2.15 + '@rolldown/binding-win32-x64-msvc': 1.2.15 + + rtree-sql.js@1.7.0: {} + + run-applescript@7.1.0: {} + + run-async@4.0.6: + optional: true + + rw@1.3.3: {} + + safe-buffer@5.2.1: {} + + safe-regex2@5.1.2: + dependencies: + ret: 0.5.1 + + safe-stable-stringify@2.5.0: {} + + safer-buffer@2.1.2: {} + + secure-json-parse@4.1.1: {} + + semver@7.8.5: {} + + set-cookie-parser@3.2.1: {} + + signal-exit@4.1.0: + optional: true + + simple-concat@1.0.1: + optional: true + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + optional: true + + simplify-js@1.2.4: {} + + slice-source@0.4.1: {} + + sonic-boom@4.2.1: + dependencies: + atomic-sleep: 1.0.0 + + source-map-js@1.2.2: {} + + splaytree@3.2.3: {} + + split2@4.2.0: {} + + split@1.0.1: + dependencies: + through: 2.3.8 + + std-env@4.3.0: {} + + stream-combiner@0.2.2: + dependencies: + duplexer: 0.1.2 + through: 2.3.8 + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-json-comments@2.0.1: + optional: true + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + optional: true + + tar-fs@2.1.5: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + optional: true + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + optional: true + + thread-stream@4.2.0: + dependencies: + real-require: 1.0.0 + + through@2.3.8: {} + + tiny-inflate@1.0.3: {} + + tinybench@6.2.2: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyqueue@2.0.3: {} + + toad-cache@3.7.4: {} + + tslib@2.8.1: {} + + tsscmp@1.0.6: {} + + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + optional: true + + typedarray@0.0.6: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@8.9.0: {} + + unicode-properties@1.4.1: + dependencies: + base64-js: 1.5.1 + unicode-trie: 2.0.0 + + unicode-trie@2.0.0: + dependencies: + pako: 0.2.9 + tiny-inflate: 1.0.3 + + unzipit@2.0.0: + optional: true + + util-deprecate@1.0.2: {} + + vite@8.3.5(@types/node@26.6.5): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.31 + rolldown: 1.2.15 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.5 + fsevents: 2.3.3 + + vitest@5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.5(@types/node@26.6.5)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.3 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@26.6.5) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.5 + transitivePeerDependencies: + - msw + + web-worker@1.5.0: {} + + webworkify@1.5.0: {} + + why-is-node-running@3.2.1: {} + + wkt-parser@1.6.0: {} + + wkx@0.4.8: + dependencies: + '@types/node': 26.6.5 + + wrappy@1.0.2: + optional: true + + wsl-utils@1.0.1: + dependencies: + is-wsl: 3.1.1 + powershell-utils: 0.2.1 + + xml-utils@1.10.2: {} + + zarrita@0.7.5: + dependencies: + '@zarrita/storage': 0.2.0 + numcodecs: 0.3.2 + optional: true + + zod@4.6.7: {} + + zstddec@0.2.0: {} diff --git a/backend/pnpm-workspace.yaml b/backend/pnpm-workspace.yaml new file mode 100644 index 0000000..0e5a073 --- /dev/null +++ b/backend/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - "packages/*" + - "apps/*" diff --git a/backend/tsconfig.base.json b/backend/tsconfig.base.json new file mode 100644 index 0000000..a086a40 --- /dev/null +++ b/backend/tsconfig.base.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": false, + "allowImportingTsExtensions": true, + "noEmit": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "skipLibCheck": true, + "resolveJsonModule": true + } +} diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 0000000..b7eabe0 --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,15 @@ +node_modules/ +dist/ +.DS_Store +._* +*.log +*.tsbuildinfo +coverage/ + +# 由 pnpm sync-fixtures 從後端複製 +public/fixtures/ + +# 祕密 +.env +.env.* +!.env.example diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000..aa055c0 --- /dev/null +++ b/web/README.md @@ -0,0 +1,28 @@ +# 選舉小鎮 — 前端 + +前端只依賴 `@election2026/protocol`(後端程式庫中的協定套件),不含任何遊戲規則,所有結算都在後端。整體架構見 `../backend/docs/README.md`。 + +畫面(hash 路由,`src/App.tsx`):首頁與選戰卡牌(`#/`、`#/rogue/<局>`)、政治生涯、圖鑑與成就、捏人物、服裝店、政策島、小遊戲、任期試玩、歷屆參選人, +以及開發用的資料檢視器(`#/viewer`)、美術總覽(`#/art`、`#/faces`)、頭像部件檢查(`#/avatar-check`)。 + +開發時要先啟動後端 API(`pnpm --filter @election2026/server start`,見後端 README);`/api` 由 Vite 轉給 `127.0.0.1:8787`。 + +## 開發 + +```bash +pnpm install +pnpm sync-fixtures # 從 ../backend/data/build/packs 複製資料包到 public/fixtures(需先在後端產生) +pnpm dev +``` + +讀取資料時會用協定的 Zod 定義驗證;格式和協定不符會直接顯示錯誤。 + +## 檢查 + +```bash +pnpm test +pnpm typecheck +pnpm build +``` + +設計 token(顏色、字型)集中在 `src/theme/tokens.css`。 diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..4267700 --- /dev/null +++ b/web/index.html @@ -0,0 +1,15 @@ + + + + + + 選舉小鎮 + + + + + +
+ + + diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..03dd50e --- /dev/null +++ b/web/package.json @@ -0,0 +1,37 @@ +{ + "name": "election-2026-web", + "private": true, + "type": "module", + "packageManager": "pnpm@10.33.0", + "description": "凍蒜 2026 前端。只依賴 @election2026/protocol,不含任何遊戲規則(docs/16)。", + "scripts": { + "dev": "vite", + "build": "tsc -p tsconfig.json && vite build", + "test": "vitest run", + "typecheck": "tsc -p tsconfig.json", + "sync-fixtures": "node scripts/sync-fixtures.mjs" + }, + "dependencies": { + "@election2026/protocol": "link:../backend/packages/protocol", + "d3-geo": "^3.1.1", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "three": "0.160.0", + "topojson-client": "^3.1.0" + }, + "devDependencies": { + "@types/d3-geo": "^3.1.1", + "@types/geojson": "^7946.0.16", + "@types/node": "^26.6.5", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/three": "0.160.0", + "@types/topojson-client": "^3.1.5", + "@types/topojson-specification": "^1.0.5", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } +} diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml new file mode 100644 index 0000000..c74a695 --- /dev/null +++ b/web/pnpm-lock.yaml @@ -0,0 +1,1082 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@election2026/protocol': + specifier: link:../backend/packages/protocol + version: link:../backend/packages/protocol + d3-geo: + specifier: ^3.1.1 + version: 3.1.1 + lucide-react: + specifier: ^1.61.0 + version: 1.61.0(@types/react@19.3.0)(react@19.3.1) + react: + specifier: ^19.3.1 + version: 19.3.1 + react-dom: + specifier: ^19.3.1 + version: 19.3.1(react@19.3.1) + three: + specifier: 0.160.0 + version: 0.160.0 + topojson-client: + specifier: ^3.1.0 + version: 3.1.0 + devDependencies: + '@types/d3-geo': + specifier: ^3.1.1 + version: 3.1.1 + '@types/geojson': + specifier: ^7946.0.16 + version: 7946.0.16 + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + '@types/three': + specifier: 0.160.0 + version: 0.160.0 + '@types/topojson-client': + specifier: ^3.1.5 + version: 3.1.5 + '@types/topojson-specification': + specifier: ^1.0.5 + version: 1.0.5 + '@vitejs/plugin-react': + specifier: ^6.1.2 + version: 6.1.2(vite@8.3.5(@types/node@26.6.5)) + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@26.6.5) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)) + +packages: + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.155.0': + resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} + + '@rolldown/binding-android-arm-eabi@1.2.15': + resolution: {integrity: sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.15': + resolution: {integrity: sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.15': + resolution: {integrity: sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.15': + resolution: {integrity: sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.15': + resolution: {integrity: sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + resolution: {integrity: sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.15': + resolution: {integrity: sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.15': + resolution: {integrity: sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + resolution: {integrity: sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + resolution: {integrity: sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.15': + resolution: {integrity: sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.15': + resolution: {integrity: sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.15': + resolution: {integrity: sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + resolution: {integrity: sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.15': + resolution: {integrity: sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/d3-geo@3.1.1': + resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + + '@types/node@26.6.5': + resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} + + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + + '@types/stats.js@0.17.4': + resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==} + + '@types/three@0.160.0': + resolution: {integrity: sha512-jWlbUBovicUKaOYxzgkLlhkiEQJkhCVvg4W2IYD2trqD2om3VK4DGLpHH5zQHNr7RweZK/5re/4IVhbhvxbV9w==} + + '@types/topojson-client@3.1.5': + resolution: {integrity: sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw==} + + '@types/topojson-specification@1.0.5': + resolution: {integrity: sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ==} + + '@types/webxr@0.5.24': + resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitejs/plugin-react@6.1.2': + resolution: {integrity: sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + oxc-transform-react: ^0.152.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + oxc-transform-react: + optional: true + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + commander@2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-geo@3.1.1: + resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==} + engines: {node: '>=12'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fflate@0.6.11: + resolution: {integrity: sha512-3JyEFWGjFn7zHmoa9+zG1BmW7X2okcmAB+0Cnu9UFbVs/jCBnl2A8o065ZlXiw145K3eBM3uLuzrYXC0RK7eDg==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lucide-react@1.61.0: + resolution: {integrity: sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==} + peerDependencies: + '@types/react': '*' + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + + magic-string@1.4.3: + resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==} + + meshoptimizer@0.18.1: + resolution: {integrity: sha512-ZhoIoL7TNV4s5B6+rx5mC//fw8/POGyNxS/DZyCJeiZ12ScLfVwRE/GfsxwiTkMYYD5DmK2/JXnEVXqL4rF+Sw==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.31: + resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + engines: {node: ^10 || ^12 || >=14} + + react-dom@19.3.1: + resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==} + peerDependencies: + react: ^19.3.1 + + react@19.3.1: + resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} + engines: {node: '>=0.10.0'} + + rolldown@1.2.15: + resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + three@0.160.0: + resolution: {integrity: sha512-DLU8lc0zNIPkM7rH5/e1Ks1Z8tWCGRq6g8mPowdDJpw1CFBJMU7UoJjC6PefXW7z//SSl0b2+GCw14LB+uDhng==} + + tinybench@6.2.2: + resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + topojson-client@3.1.0: + resolution: {integrity: sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==} + hasBin: true + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + +snapshots: + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.155.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.15': + optional: true + + '@rolldown/binding-android-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-x64@1.2.15': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.15': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.15': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.15': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.15': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.15': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/d3-geo@3.1.1': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/geojson@7946.0.16': {} + + '@types/node@26.6.5': + dependencies: + undici-types: 8.9.0 + + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + + '@types/stats.js@0.17.4': {} + + '@types/three@0.160.0': + dependencies: + '@types/stats.js': 0.17.4 + '@types/webxr': 0.5.24 + fflate: 0.6.11 + meshoptimizer: 0.18.1 + + '@types/topojson-client@3.1.5': + dependencies: + '@types/geojson': 7946.0.16 + '@types/topojson-specification': 1.0.5 + + '@types/topojson-specification@1.0.5': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/webxr@0.5.24': {} + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitejs/plugin-react@6.1.2(vite@8.3.5(@types/node@26.6.5))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 8.3.5(@types/node@26.6.5) + + '@vitest/mocker@5.0.5(vite@8.3.5(@types/node@26.6.5))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.3 + optionalDependencies: + vite: 8.3.5(@types/node@26.6.5) + + '@vitest/spy@5.0.5': {} + + assertion-error@2.0.1: {} + + chai@6.3.0: {} + + commander@2.20.3: {} + + csstype@3.2.3: {} + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-geo@3.1.1: + dependencies: + d3-array: 3.2.4 + + detect-libc@2.1.2: {} + + es-module-lexer@2.3.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fflate@0.6.11: {} + + fsevents@2.3.3: + optional: true + + internmap@2.0.3: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lucide-react@1.61.0(@types/react@19.3.0)(react@19.3.1): + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + magic-string@1.4.3: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + meshoptimizer@0.18.1: {} + + nanoid@3.3.20: {} + + obug@3.0.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.31: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + react-dom@19.3.1(react@19.3.1): + dependencies: + react: 19.3.1 + scheduler: 0.28.0 + + react@19.3.1: {} + + rolldown@1.2.15: + dependencies: + '@oxc-project/types': 0.155.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.15 + '@rolldown/binding-android-arm64': 1.2.15 + '@rolldown/binding-darwin-arm64': 1.2.15 + '@rolldown/binding-darwin-x64': 1.2.15 + '@rolldown/binding-freebsd-x64': 1.2.15 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.15 + '@rolldown/binding-linux-arm64-gnu': 1.2.15 + '@rolldown/binding-linux-arm64-musl': 1.2.15 + '@rolldown/binding-linux-ppc64-gnu': 1.2.15 + '@rolldown/binding-linux-s390x-gnu': 1.2.15 + '@rolldown/binding-linux-x64-gnu': 1.2.15 + '@rolldown/binding-linux-x64-musl': 1.2.15 + '@rolldown/binding-openharmony-arm64': 1.2.15 + '@rolldown/binding-win32-arm64-msvc': 1.2.15 + '@rolldown/binding-win32-x64-msvc': 1.2.15 + + scheduler@0.28.0: {} + + source-map-js@1.2.2: {} + + std-env@4.3.0: {} + + three@0.160.0: {} + + tinybench@6.2.2: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + topojson-client@3.1.0: + dependencies: + commander: 2.20.3 + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@8.9.0: {} + + vite@8.3.5(@types/node@26.6.5): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.31 + rolldown: 1.2.15 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.5 + fsevents: 2.3.3 + + vitest@5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.5(@types/node@26.6.5)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.3 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@26.6.5) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.5 + transitivePeerDependencies: + - msw + + why-is-node-running@3.2.1: {} diff --git a/web/public/assets/3d/characters/Textures/colormap.png b/web/public/assets/3d/characters/Textures/colormap.png new file mode 100644 index 0000000..166a545 Binary files /dev/null and b/web/public/assets/3d/characters/Textures/colormap.png differ diff --git a/web/public/assets/3d/characters/character-female-a.glb b/web/public/assets/3d/characters/character-female-a.glb new file mode 100644 index 0000000..eaeabab Binary files /dev/null and b/web/public/assets/3d/characters/character-female-a.glb differ diff --git a/web/public/assets/3d/characters/character-female-b.glb b/web/public/assets/3d/characters/character-female-b.glb new file mode 100644 index 0000000..9df43f7 Binary files /dev/null and b/web/public/assets/3d/characters/character-female-b.glb differ diff --git a/web/public/assets/3d/characters/character-female-c.glb b/web/public/assets/3d/characters/character-female-c.glb new file mode 100644 index 0000000..b1f470d Binary files /dev/null and b/web/public/assets/3d/characters/character-female-c.glb differ diff --git a/web/public/assets/3d/characters/character-female-d.glb b/web/public/assets/3d/characters/character-female-d.glb new file mode 100644 index 0000000..31bdbf9 Binary files /dev/null and b/web/public/assets/3d/characters/character-female-d.glb differ diff --git a/web/public/assets/3d/characters/character-female-e.glb b/web/public/assets/3d/characters/character-female-e.glb new file mode 100644 index 0000000..8deb349 Binary files /dev/null and b/web/public/assets/3d/characters/character-female-e.glb differ diff --git a/web/public/assets/3d/characters/character-female-f.glb b/web/public/assets/3d/characters/character-female-f.glb new file mode 100644 index 0000000..e658544 Binary files /dev/null and b/web/public/assets/3d/characters/character-female-f.glb differ diff --git a/web/public/assets/3d/characters/character-male-a.glb b/web/public/assets/3d/characters/character-male-a.glb new file mode 100644 index 0000000..18ff63f Binary files /dev/null and b/web/public/assets/3d/characters/character-male-a.glb differ diff --git a/web/public/assets/3d/characters/character-male-b.glb b/web/public/assets/3d/characters/character-male-b.glb new file mode 100644 index 0000000..149f8fe Binary files /dev/null and b/web/public/assets/3d/characters/character-male-b.glb differ diff --git a/web/public/assets/3d/characters/character-male-c.glb b/web/public/assets/3d/characters/character-male-c.glb new file mode 100644 index 0000000..04ee661 Binary files /dev/null and b/web/public/assets/3d/characters/character-male-c.glb differ diff --git a/web/public/assets/3d/characters/character-male-d.glb b/web/public/assets/3d/characters/character-male-d.glb new file mode 100644 index 0000000..4d7b980 Binary files /dev/null and b/web/public/assets/3d/characters/character-male-d.glb differ diff --git a/web/public/assets/3d/characters/character-male-e.glb b/web/public/assets/3d/characters/character-male-e.glb new file mode 100644 index 0000000..cfe7fef Binary files /dev/null and b/web/public/assets/3d/characters/character-male-e.glb differ diff --git a/web/public/assets/3d/characters/character-male-f.glb b/web/public/assets/3d/characters/character-male-f.glb new file mode 100644 index 0000000..4c6840b Binary files /dev/null and b/web/public/assets/3d/characters/character-male-f.glb differ diff --git a/web/public/assets/3d/festive/Textures/colormap.png b/web/public/assets/3d/festive/Textures/colormap.png new file mode 100644 index 0000000..af4140f Binary files /dev/null and b/web/public/assets/3d/festive/Textures/colormap.png differ diff --git a/web/public/assets/3d/festive/lights-colored.glb b/web/public/assets/3d/festive/lights-colored.glb new file mode 100644 index 0000000..4e97b06 Binary files /dev/null and b/web/public/assets/3d/festive/lights-colored.glb differ diff --git a/web/public/assets/3d/festive/present-b-round.glb b/web/public/assets/3d/festive/present-b-round.glb new file mode 100644 index 0000000..35e633b Binary files /dev/null and b/web/public/assets/3d/festive/present-b-round.glb differ diff --git a/web/public/assets/3d/food/Textures/colormap.png b/web/public/assets/3d/food/Textures/colormap.png new file mode 100644 index 0000000..1dfac9e Binary files /dev/null and b/web/public/assets/3d/food/Textures/colormap.png differ diff --git a/web/public/assets/3d/food/pineapple.glb b/web/public/assets/3d/food/pineapple.glb new file mode 100644 index 0000000..7941c55 Binary files /dev/null and b/web/public/assets/3d/food/pineapple.glb differ diff --git a/web/public/assets/3d/food/steamer.glb b/web/public/assets/3d/food/steamer.glb new file mode 100644 index 0000000..f1baafe Binary files /dev/null and b/web/public/assets/3d/food/steamer.glb differ diff --git a/web/public/assets/3d/nature/flower-red-a.glb b/web/public/assets/3d/nature/flower-red-a.glb new file mode 100644 index 0000000..00e9c06 Binary files /dev/null and b/web/public/assets/3d/nature/flower-red-a.glb differ diff --git a/web/public/assets/3d/nature/flower-yellow-a.glb b/web/public/assets/3d/nature/flower-yellow-a.glb new file mode 100644 index 0000000..26adf12 Binary files /dev/null and b/web/public/assets/3d/nature/flower-yellow-a.glb differ diff --git a/web/public/assets/3d/nature/plant-bush-large.glb b/web/public/assets/3d/nature/plant-bush-large.glb new file mode 100644 index 0000000..732f656 Binary files /dev/null and b/web/public/assets/3d/nature/plant-bush-large.glb differ diff --git a/web/public/assets/3d/nature/rock-small-a.glb b/web/public/assets/3d/nature/rock-small-a.glb new file mode 100644 index 0000000..b234712 Binary files /dev/null and b/web/public/assets/3d/nature/rock-small-a.glb differ diff --git a/web/public/assets/3d/nature/tree-default.glb b/web/public/assets/3d/nature/tree-default.glb new file mode 100644 index 0000000..1324744 Binary files /dev/null and b/web/public/assets/3d/nature/tree-default.glb differ diff --git a/web/public/assets/3d/nature/tree-oak.glb b/web/public/assets/3d/nature/tree-oak.glb new file mode 100644 index 0000000..b136723 Binary files /dev/null and b/web/public/assets/3d/nature/tree-oak.glb differ diff --git a/web/public/assets/3d/nature/tree-palm-short.glb b/web/public/assets/3d/nature/tree-palm-short.glb new file mode 100644 index 0000000..3c729f9 Binary files /dev/null and b/web/public/assets/3d/nature/tree-palm-short.glb differ diff --git a/web/public/assets/3d/nature/tree-palm-tall.glb b/web/public/assets/3d/nature/tree-palm-tall.glb new file mode 100644 index 0000000..0602c20 Binary files /dev/null and b/web/public/assets/3d/nature/tree-palm-tall.glb differ diff --git a/web/public/assets/3d/props/Textures/colormap.png b/web/public/assets/3d/props/Textures/colormap.png new file mode 100644 index 0000000..c149939 Binary files /dev/null and b/web/public/assets/3d/props/Textures/colormap.png differ diff --git a/web/public/assets/3d/props/arrow.glb b/web/public/assets/3d/props/arrow.glb new file mode 100644 index 0000000..d340c47 Binary files /dev/null and b/web/public/assets/3d/props/arrow.glb differ diff --git a/web/public/assets/3d/props/chest.glb b/web/public/assets/3d/props/chest.glb new file mode 100644 index 0000000..e9bff3c Binary files /dev/null and b/web/public/assets/3d/props/chest.glb differ diff --git a/web/public/assets/3d/props/coin-gold.glb b/web/public/assets/3d/props/coin-gold.glb new file mode 100644 index 0000000..d84e0e9 Binary files /dev/null and b/web/public/assets/3d/props/coin-gold.glb differ diff --git a/web/public/assets/3d/props/crate.glb b/web/public/assets/3d/props/crate.glb new file mode 100644 index 0000000..534ee89 Binary files /dev/null and b/web/public/assets/3d/props/crate.glb differ diff --git a/web/public/assets/3d/props/flag.glb b/web/public/assets/3d/props/flag.glb new file mode 100644 index 0000000..a9d8e98 Binary files /dev/null and b/web/public/assets/3d/props/flag.glb differ diff --git a/web/public/assets/3d/props/flowers.glb b/web/public/assets/3d/props/flowers.glb new file mode 100644 index 0000000..60da3e9 Binary files /dev/null and b/web/public/assets/3d/props/flowers.glb differ diff --git a/web/public/assets/3d/props/heart.glb b/web/public/assets/3d/props/heart.glb new file mode 100644 index 0000000..4a7a9ea Binary files /dev/null and b/web/public/assets/3d/props/heart.glb differ diff --git a/web/public/assets/3d/props/sign.glb b/web/public/assets/3d/props/sign.glb new file mode 100644 index 0000000..55552cb Binary files /dev/null and b/web/public/assets/3d/props/sign.glb differ diff --git a/web/public/assets/3d/props/star.glb b/web/public/assets/3d/props/star.glb new file mode 100644 index 0000000..a2a3318 Binary files /dev/null and b/web/public/assets/3d/props/star.glb differ diff --git a/web/public/assets/3d/props/tree.glb b/web/public/assets/3d/props/tree.glb new file mode 100644 index 0000000..7cfa14e Binary files /dev/null and b/web/public/assets/3d/props/tree.glb differ diff --git a/web/public/assets/3d/town-houses/Textures/colormap.png b/web/public/assets/3d/town-houses/Textures/colormap.png new file mode 100644 index 0000000..9838fb4 Binary files /dev/null and b/web/public/assets/3d/town-houses/Textures/colormap.png differ diff --git a/web/public/assets/3d/town-houses/Textures/variation-b.png b/web/public/assets/3d/town-houses/Textures/variation-b.png new file mode 100644 index 0000000..dc48876 Binary files /dev/null and b/web/public/assets/3d/town-houses/Textures/variation-b.png differ diff --git a/web/public/assets/3d/town-houses/building-type-a.glb b/web/public/assets/3d/town-houses/building-type-a.glb new file mode 100644 index 0000000..870bf63 Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-a.glb differ diff --git a/web/public/assets/3d/town-houses/building-type-b.glb b/web/public/assets/3d/town-houses/building-type-b.glb new file mode 100644 index 0000000..d25162a Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-b.glb differ diff --git a/web/public/assets/3d/town-houses/building-type-c.glb b/web/public/assets/3d/town-houses/building-type-c.glb new file mode 100644 index 0000000..91bbbac Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-c.glb differ diff --git a/web/public/assets/3d/town-houses/building-type-f.glb b/web/public/assets/3d/town-houses/building-type-f.glb new file mode 100644 index 0000000..db68497 Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-f.glb differ diff --git a/web/public/assets/3d/town-houses/building-type-h.glb b/web/public/assets/3d/town-houses/building-type-h.glb new file mode 100644 index 0000000..c7b279a Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-h.glb differ diff --git a/web/public/assets/3d/town-houses/building-type-k.glb b/web/public/assets/3d/town-houses/building-type-k.glb new file mode 100644 index 0000000..063716e Binary files /dev/null and b/web/public/assets/3d/town-houses/building-type-k.glb differ diff --git a/web/public/assets/3d/town-houses/fence-1x2.glb b/web/public/assets/3d/town-houses/fence-1x2.glb new file mode 100644 index 0000000..0a75ddf Binary files /dev/null and b/web/public/assets/3d/town-houses/fence-1x2.glb differ diff --git a/web/public/assets/3d/town-houses/planter.glb b/web/public/assets/3d/town-houses/planter.glb new file mode 100644 index 0000000..d899523 Binary files /dev/null and b/web/public/assets/3d/town-houses/planter.glb differ diff --git a/web/public/assets/3d/town-houses/tree-small.glb b/web/public/assets/3d/town-houses/tree-small.glb new file mode 100644 index 0000000..e080415 Binary files /dev/null and b/web/public/assets/3d/town-houses/tree-small.glb differ diff --git a/web/public/assets/3d/town-shops/Textures/colormap.png b/web/public/assets/3d/town-shops/Textures/colormap.png new file mode 100644 index 0000000..d0e5dfb Binary files /dev/null and b/web/public/assets/3d/town-shops/Textures/colormap.png differ diff --git a/web/public/assets/3d/town-shops/building-a.glb b/web/public/assets/3d/town-shops/building-a.glb new file mode 100644 index 0000000..0b56b49 Binary files /dev/null and b/web/public/assets/3d/town-shops/building-a.glb differ diff --git a/web/public/assets/3d/town-shops/building-c.glb b/web/public/assets/3d/town-shops/building-c.glb new file mode 100644 index 0000000..dfcc5e7 Binary files /dev/null and b/web/public/assets/3d/town-shops/building-c.glb differ diff --git a/web/public/assets/3d/town-shops/building-e.glb b/web/public/assets/3d/town-shops/building-e.glb new file mode 100644 index 0000000..d8307c3 Binary files /dev/null and b/web/public/assets/3d/town-shops/building-e.glb differ diff --git a/web/public/assets/3d/town-shops/building-h.glb b/web/public/assets/3d/town-shops/building-h.glb new file mode 100644 index 0000000..d670a1f Binary files /dev/null and b/web/public/assets/3d/town-shops/building-h.glb differ diff --git a/web/public/assets/3d/town-shops/building-k.glb b/web/public/assets/3d/town-shops/building-k.glb new file mode 100644 index 0000000..bea29a0 Binary files /dev/null and b/web/public/assets/3d/town-shops/building-k.glb differ diff --git a/web/public/assets/3d/town-shops/building-skyscraper-a.glb b/web/public/assets/3d/town-shops/building-skyscraper-a.glb new file mode 100644 index 0000000..4494841 Binary files /dev/null and b/web/public/assets/3d/town-shops/building-skyscraper-a.glb differ diff --git a/web/public/assets/3d/town-shops/detail-parasol-a.glb b/web/public/assets/3d/town-shops/detail-parasol-a.glb new file mode 100644 index 0000000..13b9148 Binary files /dev/null and b/web/public/assets/3d/town-shops/detail-parasol-a.glb differ diff --git a/web/public/assets/3d/vehicles/Textures/colormap.png b/web/public/assets/3d/vehicles/Textures/colormap.png new file mode 100644 index 0000000..5c4b185 Binary files /dev/null and b/web/public/assets/3d/vehicles/Textures/colormap.png differ diff --git a/web/public/assets/3d/vehicles/box.glb b/web/public/assets/3d/vehicles/box.glb new file mode 100644 index 0000000..d6e4109 Binary files /dev/null and b/web/public/assets/3d/vehicles/box.glb differ diff --git a/web/public/assets/3d/vehicles/sedan.glb b/web/public/assets/3d/vehicles/sedan.glb new file mode 100644 index 0000000..6bc9f1e Binary files /dev/null and b/web/public/assets/3d/vehicles/sedan.glb differ diff --git a/web/public/assets/3d/vehicles/taxi.glb b/web/public/assets/3d/vehicles/taxi.glb new file mode 100644 index 0000000..509e3cc Binary files /dev/null and b/web/public/assets/3d/vehicles/taxi.glb differ diff --git a/web/public/assets/3d/vehicles/truck.glb b/web/public/assets/3d/vehicles/truck.glb new file mode 100644 index 0000000..c0be5b3 Binary files /dev/null and b/web/public/assets/3d/vehicles/truck.glb differ diff --git a/web/public/assets/3d/vehicles/van.glb b/web/public/assets/3d/vehicles/van.glb new file mode 100644 index 0000000..e6f6635 Binary files /dev/null and b/web/public/assets/3d/vehicles/van.glb differ diff --git a/web/public/assets/LICENSES.md b/web/public/assets/LICENSES.md new file mode 100644 index 0000000..c2c4066 --- /dev/null +++ b/web/public/assets/LICENSES.md @@ -0,0 +1,208 @@ +# Asset licenses + +Every file under `web/public/assets/` comes from a source whose license allows free commercial use in a +game without attribution: **CC0 1.0 / public domain** for all art, audio and 3D, and the **SIL Open Font +License 1.1** for the two fonts. Credits below are a courtesy (CC0 does not require them). +Totals: 143 files (141 CC0, 2 OFL), after unused files were removed on 2026-10-28. +Collected 2026-10-25/26; each license was checked on the source page before download. + +Original license texts are in `licenses/` (one per Kenney pack, plus CC0 legal code, Poly Haven, +ambientCG and Open Peeps statements, and both OFL files). + +## Notes and modifications + +- **Fonts (OFL 1.1).** Both `.woff2` files are lossless WOFF2 wraps of the official release files + (only the checksum, the WOFF2 `head.flags` bit and the DSIG signature table change, as WOFF2 compression + defines). They are not subset and keep their original names. If you subset `jf-openhuninn` later, the + result is a *Modified Version* under OFL and must not use the Reserved Font Names "open huninn" / + "huninn" in the font's internal name. Fonts may be bundled with the game but not sold on their own. + jf open huninn's license notes its Hanzi derive from Kosugi Maru (Apache-2.0); keep + `licenses/jf-openhuninn-OFL.txt` with the font. +- **Trimmed or converted audio.** Files marked "trimmed" or "converted" were cut/faded/re-encoded with + ffmpeg. `sfx/drumroll.mp3`, `sfx/firecrackers.mp3` and `sfx/channel-switch.mp3` were assembled + from the CC0 one-shots named in their rows (derivative works of CC0 material). +- **Textures** were re-encoded as 1024 px JPEG. +- **3D models** are unmodified Kenney GLBs. Each folder keeps that kit's `Textures/colormap.png`, which + the GLBs load by relative path, so move each folder as a whole. +- No asset depicts a real person, politician, party logo, national flag or brand logo. +- **Minigame art (no files).** The illustrations for the three campaign minigames and their lobby + (`web/src/game/minigames/art.tsx`, plus the CSS-drawn crowd, stage and street grid) are original + inline SVG/CSS made for this project — no photos, no generated people. Their sounds reuse the CC0 + files listed below (`timer-tick`, `gong-bright`, `bell-ding`, `jingle-steel-up`, `jingle-tuba-sad`, + `buzz-short`, `chime-positive-*`, `coins-small`, `crowd-rally`, `applause`) or are synthesized with Web Audio + (drums, countdown beeps, camera shutter). + +## Files + +| file | what it is | source page URL | author | license | +|---|---|---|---|---| +| `fonts/gensen-rounded2-tw-heavy.woff2` | 源泉圓體 2 TW Heavy - very bold rounded display face for headlines — lossless WOFF2 wrap of GenSenRounded2TW-H.otf (no subsetting) | https://github.com/ButTaiwan/gensen-font (GenSenRounded2 TW, otf/TW) | ButTaiwan (GenSen Rounded 2) | SIL Open Font License 1.1 (`licenses/gensen-rounded-OFL.txt`) | +| `fonts/jf-openhuninn-2.1.woff2` | jf open 粉圓 (Huninn) v2.1 - round, friendly Traditional Chinese + Latin, 1 weight — lossless WOFF2 wrap of the release TTF (no subsetting, names unchanged) | https://github.com/justfont/open-huninn-font (release v2.1) | justfont (jf open huninn) | SIL Open Font License 1.1 (`licenses/jf-openhuninn-OFL.txt`) | +| `music/election-night-tension.ogg` | tense orchestral piece - timpani, snares, brass, strings (110 s) | https://opengameart.org/content/courtroom-and-judgement | Spring Spring | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/news-bed.ogg` | 17 s arpeggio/pad cue - works as news-desk bed | https://opengameart.org/content/17-second-sequence | Spring Spring | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/news-intro.mp3` | 12 s epic orchestral intro sting - parody TV news opener — converted from WAV | https://opengameart.org/content/production-theme-intro-epic-orchestra | nene | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/party-disco-loop.ogg` | funky disco party loop - bass, sax, brass (133 s) | https://opengameart.org/content/funky-disco-beats-to-boogiewoogie-to | Fupi | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/planning-loop.ogg` | relaxed brass + flute puzzle-game loop, 95 bpm (61 s) | https://opengameart.org/content/cozy-puzzle-title | MintoDog | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/theme-march.ogg` | upbeat cartoon march - trombone, snare, flute; seamless loop (64 s) | https://opengameart.org/content/childrens-march-theme | CleytonKauffman | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `music/victory-triumphant.mp3` | short celebratory strings + horns theme (27 s) — re-encoded 160 kbps | https://opengameart.org/content/triumphant | Emma_MA | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/applause.mp3` | big-hall crowd applause (8 s) — trimmed 1-9 s with fades | https://opengameart.org/content/applause-in-a-large-hall-or-church | eXpl0it3r | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/bell-ding.ogg` | small bell ding | https://opengameart.org/content/100-cc0-sfx | rubberduck | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/buzz-negative.ogg` | low error buzz | https://kenney.nl/assets/interface-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-interface-sounds.txt`) | +| `sfx/buzz-short.ogg` | very short error blip | https://kenney.nl/assets/interface-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-interface-sounds.txt`) | +| `sfx/card-deal-1.ogg` | card sliding across the table | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/card-deal-2.ogg` | card slide, brighter variant | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/card-flip.ogg` | short bright card snap (use for flip/reveal) | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/card-place.ogg` | card set down on table | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/card-shuffle.ogg` | deck riffle shuffle (3 s) | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/channel-switch.mp3` | TV channel switch: digital glitch click + short static — derived: interface-sounds glitch_001 + 0.35 s of 'Static' | https://kenney.nl/assets/interface-sounds + https://opengameart.org/content/static | Kenney (kenney.nl) + xhunterko | CC0 1.0 (`licenses/kenney-interface-sounds.txt, licenses/cc0-1.0-legalcode.txt`) | +| `sfx/chime-positive-1.ogg` | bright positive confirm chime | https://kenney.nl/assets/interface-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-interface-sounds.txt`) | +| `sfx/chime-positive-2.ogg` | warmer positive confirm chime | https://kenney.nl/assets/interface-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-interface-sounds.txt`) | +| `sfx/coins-small.ogg` | few coins clink | https://kenney.nl/assets/rpg-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-rpg-audio.txt`) | +| `sfx/coins.ogg` | handful of coins jingling | https://kenney.nl/assets/rpg-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-rpg-audio.txt`) | +| `sfx/crowd-cheer-fireworks.mp3` | happy crowd cheering + applause with fireworks (10 s) — trimmed 10-20 s with fades | https://opengameart.org/content/fireworks-with-applause-happy-people | Almitory | CC0 1.0 (page offers CC0 among several licenses; CC0 chosen) (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/crowd-ooh.ogg` | group 'ooooh' (teasing / scandal reaction) | https://opengameart.org/content/oooooooooooooo | Nocturnal_Vanguard (AuraVoice) | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/crowd-rally.mp3` | rowdy crowd shouting ambience (rally/protest, 10 s) — trimmed 2-12 s with fades | https://opengameart.org/content/crowd-shoutingspeaking-ambience | StarNinjas | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/dice-roll-1.ogg` | dice thrown and tumbling on table | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/dice-roll-2.ogg` | dice throw, shorter variant | https://kenney.nl/assets/casino-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-casino-audio.txt`) | +| `sfx/drumroll.mp3` | snare roll building up to a final hit (3 s) - for result reveals — derived: assembled from the single CC0 snare sample (repeated, accelerating, crescendo) | https://opengameart.org/content/an-interesting-snare-drum-sound | Spring Spring | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/firecrackers.mp3` | string of firecrackers popping (鞭炮, 4 s) — derived: random rapid sequence of the pack's CC0 bang_01-10 one-shots | https://opengameart.org/content/25-cc0-bang-firework-sfx | rubberduck | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/gong-bright.ogg` | brighter gong hit | https://opengameart.org/content/100-cc0-sfx | rubberduck | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/gong.ogg` | deeper gong hit | https://opengameart.org/content/100-cc0-sfx | rubberduck | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/jingle-steel-up.ogg` | rising steel-drum jingle (festive win) | https://kenney.nl/assets/music-jingles | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-music-jingles.txt`) | +| `sfx/jingle-tuba-sad.ogg` | comic sad 'wah-wah' tuba (4 s) | https://opengameart.org/content/happy-and-sad-tuba-fanfare | Trex0n | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/news-three-tone.ogg` | three-tone electronic chime (news bulletin ding) | https://kenney.nl/assets/digital-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-digital-audio.txt`) | +| `sfx/paper-crumple.mp3` | paper crumpled into a ball | https://opengameart.org/content/various-paper-sound-effects | Luckius | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/paper-rip.mp3` | paper tear | https://opengameart.org/content/various-paper-sound-effects | Luckius | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/paper-rustle-1.mp3` | quick paper rustle (flyer handed out) | https://opengameart.org/content/various-paper-sound-effects | Luckius | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/paper-rustle-2.mp3` | longer paper handling rustle (2.6 s) | https://opengameart.org/content/various-paper-sound-effects | Luckius | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/piece-hop-1.ogg` | light wooden tap (pawn hopping a space) | https://kenney.nl/assets/impact-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-impact-sounds.txt`) | +| `sfx/piece-hop-2.ogg` | light wooden tap variant | https://kenney.nl/assets/impact-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-impact-sounds.txt`) | +| `sfx/stamp-thump.ogg` | heavy muffled thump (rubber stamp hit) | https://kenney.nl/assets/impact-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-impact-sounds.txt`) | +| `sfx/timer-tick.ogg` | tiny clock tick | https://kenney.nl/assets/interface-sounds | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-interface-sounds.txt`) | +| `sfx/tv-static-loop.mp3` | 4 s steady static bed (loop) — trimmed 5-9 s | https://opengameart.org/content/static | xhunterko | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/tv-static.mp3` | 1 s burst of TV/radio static — trimmed 2-3 s | https://opengameart.org/content/static | xhunterko | CC0 1.0 (`licenses/cc0-1.0-legalcode.txt`) | +| `sfx/ui-click.ogg` | crisp short button click | https://kenney.nl/assets/ui-audio | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-ui-audio.txt`) | +| `textures/cardboard-diff.jpg` | clean brown corrugated cardboard, seamless (albedo) — re-encoded JPEG 1024px | https://ambientcg.com/view?id=Cardboard004 | ambientCG (Lennart Demes) | CC0 1.0 (`licenses/ambientcg-cc0.txt`) | +| `textures/wood-oak-light-diff.jpg` | light honey oak veneer, seamless (albedo) - brighter table option — re-encoded JPEG 1024px | https://polyhaven.com/a/oak_veneer_01 | Jenelle van Heerden (Poly Haven) | CC0 1.0 (`licenses/polyhaven-cc0.txt`) | +| `textures/wood-table-diff.jpg` | varnished reddish-brown wooden table top, seamless (albedo) — re-encoded JPEG 1024px | https://polyhaven.com/a/wood_table_001 | Dimitrios Savva, Rico Cilliers (Poly Haven) | CC0 1.0 (`licenses/polyhaven-cc0.txt`) | +| `textures/wood-table-normal.jpg` | normal map (OpenGL) for wood-table — re-encoded JPEG 1024px | https://polyhaven.com/a/wood_table_001 | Dimitrios Savva, Rico Cilliers (Poly Haven) | CC0 1.0 (`licenses/polyhaven-cc0.txt`) | +| `3d/characters/Textures/colormap.png` | shared palette texture the characters GLBs load via relative path | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-a.glb` | low-poly model: character female a | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-b.glb` | low-poly model: character female b | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-c.glb` | low-poly model: character female c | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-d.glb` | low-poly model: character female d | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-e.glb` | low-poly model: character female e | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-female-f.glb` | low-poly model: character female f | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-a.glb` | low-poly model: character male a | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-b.glb` | low-poly model: character male b | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-c.glb` | low-poly model: character male c | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-d.glb` | low-poly model: character male d | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-e.glb` | low-poly model: character male e | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/characters/character-male-f.glb` | low-poly model: character male f | https://kenney.nl/assets/mini-characters | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-mini-characters.txt`) | +| `3d/festive/Textures/colormap.png` | shared palette texture the festive GLBs load via relative path | https://kenney.nl/assets/holiday-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-holiday-kit.txt`) | +| `3d/festive/lights-colored.glb` | low-poly model: lights colored | https://kenney.nl/assets/holiday-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-holiday-kit.txt`) | +| `3d/festive/present-b-round.glb` | low-poly model: present b round | https://kenney.nl/assets/holiday-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-holiday-kit.txt`) | +| `3d/food/Textures/colormap.png` | shared palette texture the food GLBs load via relative path | https://kenney.nl/assets/food-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-food-kit.txt`) | +| `3d/food/pineapple.glb` | low-poly model: pineapple | https://kenney.nl/assets/food-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-food-kit.txt`) | +| `3d/food/steamer.glb` | low-poly model: steamer | https://kenney.nl/assets/food-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-food-kit.txt`) | +| `3d/nature/flower-red-a.glb` | low-poly model: flower red a (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/flower-yellow-a.glb` | low-poly model: flower yellow a (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/plant-bush-large.glb` | low-poly model: plant bush large (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/rock-small-a.glb` | low-poly model: rock small a (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/tree-default.glb` | low-poly model: tree default (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/tree-oak.glb` | low-poly model: tree oak (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/tree-palm-short.glb` | low-poly model: tree palm short (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/nature/tree-palm-tall.glb` | low-poly model: tree palm tall (vertex/material colours, no texture) | https://kenney.nl/assets/nature-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-nature-kit.txt`) | +| `3d/props/Textures/colormap.png` | shared palette texture the props GLBs load via relative path | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/arrow.glb` | low-poly model: arrow | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/chest.glb` | low-poly model: chest | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/coin-gold.glb` | low-poly model: coin gold | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/crate.glb` | low-poly model: crate | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/flag.glb` | low-poly model: flag | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/flowers.glb` | low-poly model: flowers | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/heart.glb` | low-poly model: heart | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/sign.glb` | low-poly model: sign | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/star.glb` | low-poly model: star | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/props/tree.glb` | low-poly model: tree | https://kenney.nl/assets/platformer-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-platformer-kit.txt`) | +| `3d/town-houses/Textures/colormap.png` | shared palette texture the town-houses GLBs load via relative path | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/Textures/variation-b.png` | shared palette texture the town-houses GLBs load via relative path | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-a.glb` | low-poly model: building type a | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-b.glb` | low-poly model: building type b | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-c.glb` | low-poly model: building type c | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-f.glb` | low-poly model: building type f | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-h.glb` | low-poly model: building type h | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/building-type-k.glb` | low-poly model: building type k | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/fence-1x2.glb` | low-poly model: fence 1x2 | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/planter.glb` | low-poly model: planter | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-houses/tree-small.glb` | low-poly model: tree small | https://kenney.nl/assets/city-kit-suburban | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-suburban.txt`) | +| `3d/town-shops/Textures/colormap.png` | shared palette texture the town-shops GLBs load via relative path | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-a.glb` | low-poly model: building a | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-c.glb` | low-poly model: building c | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-e.glb` | low-poly model: building e | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-h.glb` | low-poly model: building h | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-k.glb` | low-poly model: building k | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/building-skyscraper-a.glb` | low-poly model: building skyscraper a | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/town-shops/detail-parasol-a.glb` | low-poly model: detail parasol a | https://kenney.nl/assets/city-kit-commercial | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-city-kit-commercial.txt`) | +| `3d/vehicles/Textures/colormap.png` | shared palette texture the vehicles GLBs load via relative path | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | +| `3d/vehicles/box.glb` | low-poly model: box | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | +| `3d/vehicles/sedan.glb` | low-poly model: sedan | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | +| `3d/vehicles/taxi.glb` | low-poly model: taxi | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | +| `3d/vehicles/truck.glb` | low-poly model: truck | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | +| `3d/vehicles/van.glb` | low-poly model: van | https://kenney.nl/assets/car-kit | Kenney (kenney.nl) | CC0 1.0 (`licenses/kenney-car-kit.txt`) | + +## Format copies (added 2026-10-26) + +Every `.ogg` file in `sfx/` and `music/` also has an `.mp3` copy with the same name, re-encoded with ffmpeg +(libmp3lame, 96 kbps for effects, 112 kbps for music) so Safari can play it. Each copy carries the same +license and source as the `.ogg` row above. + +## Font subset (added 2026-10-26) + +`fonts/gensen-rounded2-tw-heavy.woff2` was moved out of the published folder (source copy kept at +`art/fonts/`). The game ships `fonts/tongsuan-rounded-heavy.woff2` instead: a subset (5,899 glyphs: every +character used by the game's code, scenario and place names, temple names, plus Big5 level-1 common +characters and punctuation) made with fontTools `pyftsubset`. Because a subset is a Modified Version under +the SIL OFL 1.1, it is renamed **Tongsuan Rounded Heavy** (it does not use the Reserved Font Name "Source" +or the original "GenSenRounded2" name). It remains under the SIL OFL 1.1 (`licenses/gensen-rounded-OFL.txt`). +Original: GenSenRounded2 TW H by ButTaiwan, https://github.com/ButTaiwan/gensen-font. + +## Avatar parts (added 2026-10-27, docs/24) + +The 27 avatar part drawings (hats, mask, vests, sashes, chest items, held items, frames) are **original vector art made +for this project** — hand-written SVG shapes, not traced from photos, not AI-generated, and not taken from any avatar +library (no Open Peeps / DiceBear / Avataaars material). They live outside `web/public/assets/` because a build step +(`pnpm avatar:build`) checks each SVG (no script, no external links, no text, nothing outside the 200×220 canvas) +and converts it to shape data in `backend/packages/protocol/src/avatar/art.generated.ts`. Lettering on the parts +(candidate number, name, 「必勝」, 「當選」…) is set at run time in the game's own fonts (OFL, listed above). +The four avatar styles (comic, chibi, retro pixel, sticker) are drawn by code from the same parts — no extra assets. +No part depicts a real person, party logo, national flag or brand logo. + +| file | what it is | source | author | license | +|---|---|---|---|---| +| `backend/packages/protocol/art/avatar/hat/campaign-cap.svg` | 競選鴨舌帽(`hat-campaign-cap`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/hat/victory-band.svg` | 必勝頭帶(`hat-victory-band`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/hat/bamboo.svg` | 斗笠(`hat-bamboo`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/hat/helmet.svg` | 機車安全帽(`hat-helmet`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/hat/bucket.svg` | 漁夫帽(`hat-bucket`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/mask/plain.svg` | 素色口罩(`mask-plain`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/mask/number.svg` | 號次口罩(`mask-number`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/outer/campaign-vest.svg` | 競選背心(`outer-campaign-vest`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/outer/volunteer-vest.svg` | 志工背心(`outer-volunteer-vest`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/outer/hivis.svg` | 工地反光背心(`outer-hivis`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/outer/raincoat.svg` | 輕便雨衣(`outer-raincoat`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/sash/red.svg` | 候選人紅布條(`sash-red`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/sash/thanks.svg` | 感謝鄉親謝票帶(`sash-thanks`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/sash/gold.svg` | 金色當選帶(`sash-gold`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/chest/corsage.svg` | 當選紅胸花(`chest-corsage`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/chest/name-tag.svg` | 名牌(`chest-name-tag`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/megaphone.svg` | 大聲公(`held-megaphone`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/flag.svg` | 三角競選旗(`held-flag`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/tissue.svg` | 面紙包(`held-tissue`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/fan.svg` | 團扇(`held-fan`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/mic.svg` | 麥克風(`held-mic`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/held/thermos.svg` | 保溫杯(`held-thermos`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/frame/gazette.svg` | 選舉公報框(`frame-gazette`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/frame/billboard.svg` | 看板框(`frame-billboard`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/frame/newspaper.svg` | 報紙頭版框(`frame-newspaper`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/frame/gold.svg` | 金色當選框(`frame-gold`) | original, drawn by hand for this project | Election Town project | original — no third-party material | +| `backend/packages/protocol/art/avatar/frame/neon.svg` | 霓虹宣傳車框(`frame-neon`) | original, drawn by hand for this project | Election Town project | original — no third-party material | diff --git a/web/public/assets/fonts/jf-openhuninn-2.1.woff2 b/web/public/assets/fonts/jf-openhuninn-2.1.woff2 new file mode 100644 index 0000000..156ec2d Binary files /dev/null and b/web/public/assets/fonts/jf-openhuninn-2.1.woff2 differ diff --git a/web/public/assets/fonts/tongsuan-rounded-heavy.woff2 b/web/public/assets/fonts/tongsuan-rounded-heavy.woff2 new file mode 100644 index 0000000..54d7440 Binary files /dev/null and b/web/public/assets/fonts/tongsuan-rounded-heavy.woff2 differ diff --git a/web/public/assets/licenses/ambientcg-cc0.txt b/web/public/assets/licenses/ambientcg-cc0.txt new file mode 100644 index 0000000..79f4465 --- /dev/null +++ b/web/public/assets/licenses/ambientcg-cc0.txt @@ -0,0 +1,8 @@ +ambientCG - license statement (copied from https://docs.ambientcg.com/license/, checked 2026-10-25) + +"All ambientCG assets are provided under the Creative Commons CC0 1.0 Universal License." +You may copy, modify, distribute and perform the assets, "even for commercial purposes, +all without asking permission." Credit is not required. + +Assets used: Cardboard004, Paper001, Paper003, Paper006, Fabric034 (1K-JPG). +Full CC0 1.0 legal code: cc0-1.0-legalcode.txt diff --git a/web/public/assets/licenses/cc0-1.0-legalcode.txt b/web/public/assets/licenses/cc0-1.0-legalcode.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/web/public/assets/licenses/cc0-1.0-legalcode.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/web/public/assets/licenses/gensen-rounded-OFL.txt b/web/public/assets/licenses/gensen-rounded-OFL.txt new file mode 100644 index 0000000..1dfc687 --- /dev/null +++ b/web/public/assets/licenses/gensen-rounded-OFL.txt @@ -0,0 +1,96 @@ +Copyright 2014-2019 Adobe (http://www.adobe.com/), with Reserved Font +Name 'Source'. Source is a trademark of Adobe in the United States +and/or other countries. + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/web/public/assets/licenses/jf-openhuninn-OFL.txt b/web/public/assets/licenses/jf-openhuninn-OFL.txt new file mode 100644 index 0000000..7058b6a --- /dev/null +++ b/web/public/assets/licenses/jf-openhuninn-OFL.txt @@ -0,0 +1,101 @@ +[Kosugi Maru] +Copyright (c) 2010 MOTOYA CO.,LTD. + +[Varela Round] +Copyright (c) 2011-2016 The Varela Round Project Authors (https://github.com/alefalefalef/Varela-Round-Hebrew/), with Reserved Font Names 'Varela' and 'Varela Round'. + +[jf open huninn] +Copyright (c) 2020-2024 The jf open huninn font is redistributed by justfont Co., LTD., with Reserved Font Names 'open huninn' and 'huninn'. under SIL Open Font License. The Hanzi part of this project was derived from Kosugi Maru under Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0). + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/web/public/assets/licenses/kenney-car-kit.txt b/web/public/assets/licenses/kenney-car-kit.txt new file mode 100644 index 0000000..60bca66 --- /dev/null +++ b/web/public/assets/licenses/kenney-car-kit.txt @@ -0,0 +1,28 @@ + + + Car Kit (3.1) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 02-04-2026 14:03 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • BlueSky: kenney.bsky.social + • Instagram: instagram.com/kenney_nl \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-casino-audio.txt b/web/public/assets/licenses/kenney-casino-audio.txt new file mode 100644 index 0000000..23cf876 --- /dev/null +++ b/web/public/assets/licenses/kenney-casino-audio.txt @@ -0,0 +1,21 @@ + + + Casino Audio (1.1) + + by Kenney Vleugels (Kenney.nl) + + ------------------------------ + + License (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You may use these assets in personal and commercial projects. + Credit (Kenney or www.kenney.nl) would be nice but is not mandatory. + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + + Follow on Twitter for updates: + @KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-city-kit-commercial.txt b/web/public/assets/licenses/kenney-city-kit-commercial.txt new file mode 100644 index 0000000..e15135d --- /dev/null +++ b/web/public/assets/licenses/kenney-city-kit-commercial.txt @@ -0,0 +1,28 @@ + + + City Kit Commercial (2.1) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 21-07-2025 18:16 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • BlueSky: kenney.bsky.social + • Instagram: instagram.com/kenney_nl \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-city-kit-suburban.txt b/web/public/assets/licenses/kenney-city-kit-suburban.txt new file mode 100644 index 0000000..cdc763a --- /dev/null +++ b/web/public/assets/licenses/kenney-city-kit-suburban.txt @@ -0,0 +1,28 @@ + + + City Kit Suburban (2.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 23-04-2025 20:22 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • BlueSky: kenney.bsky.social + • Instagram: instagram.com/kenney_nl \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-digital-audio.txt b/web/public/assets/licenses/kenney-digital-audio.txt new file mode 100644 index 0000000..29ebaed --- /dev/null +++ b/web/public/assets/licenses/kenney-digital-audio.txt @@ -0,0 +1,21 @@ + + + Digital Audio + + by Kenney Vleugels (Kenney.nl) + + ------------------------------ + + License (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You may use these assets in personal and commercial projects. + Credit (Kenney or www.kenney.nl) would be nice but is not mandatory. + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + + Follow on Twitter for updates: + @KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-food-kit.txt b/web/public/assets/licenses/kenney-food-kit.txt new file mode 100644 index 0000000..7348965 --- /dev/null +++ b/web/public/assets/licenses/kenney-food-kit.txt @@ -0,0 +1,28 @@ + + + Food Kit (2.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 26-06-2024 01:23 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • Instagram: instagram.com/kenney_nl + • Mastodon: mastodon.gamedev.place/@kenney \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-holiday-kit.txt b/web/public/assets/licenses/kenney-holiday-kit.txt new file mode 100644 index 0000000..15be9af --- /dev/null +++ b/web/public/assets/licenses/kenney-holiday-kit.txt @@ -0,0 +1,28 @@ + + + Holiday Kit (2.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 11-12-2024 14:31 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • Instagram: instagram.com/kenney_nl + • Mastodon: mastodon.gamedev.place/@kenney \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-impact-sounds.txt b/web/public/assets/licenses/kenney-impact-sounds.txt new file mode 100644 index 0000000..4890fe5 --- /dev/null +++ b/web/public/assets/licenses/kenney-impact-sounds.txt @@ -0,0 +1,23 @@ + + + Impact Sounds (1.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 19-12-2019 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + This content is free to use in personal, educational and commercial projects. + Support us by crediting Kenney or www.kenney.nl (this is not mandatory) + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + Patreon: http://patreon.com/kenney/ + + Follow on Twitter for updates: + http://twitter.com/KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-interface-sounds.txt b/web/public/assets/licenses/kenney-interface-sounds.txt new file mode 100644 index 0000000..1fc5acf --- /dev/null +++ b/web/public/assets/licenses/kenney-interface-sounds.txt @@ -0,0 +1,22 @@ + + + Interface Sounds (1.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 11-02-2020 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + This content is free to use in personal, educational and commercial projects. + Support us by crediting Kenney or www.kenney.nl (this is not mandatory) + + ------------------------------ + + Donate: http://support.kenney.nl + Patreon: http://patreon.com/kenney/ + + Follow on Twitter for updates: + http://twitter.com/KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-mini-characters.txt b/web/public/assets/licenses/kenney-mini-characters.txt new file mode 100644 index 0000000..a9a6d94 --- /dev/null +++ b/web/public/assets/licenses/kenney-mini-characters.txt @@ -0,0 +1,28 @@ + + + Mini Characters (1.0) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 17-07-2024 11:31 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • Instagram: instagram.com/kenney_nl + • Mastodon: mastodon.gamedev.place/@kenney \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-music-jingles.txt b/web/public/assets/licenses/kenney-music-jingles.txt new file mode 100644 index 0000000..52934bc --- /dev/null +++ b/web/public/assets/licenses/kenney-music-jingles.txt @@ -0,0 +1,21 @@ + + + Music Jingles + + by Kenney Vleugels (Kenney.nl) + + ------------------------------ + + License (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You may use these assets in personal and commercial projects. + Credit (Kenney or www.kenney.nl) would be nice but is not mandatory. + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + + Follow on Twitter for updates: + @KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-nature-kit.txt b/web/public/assets/licenses/kenney-nature-kit.txt new file mode 100644 index 0000000..f4c0bb6 --- /dev/null +++ b/web/public/assets/licenses/kenney-nature-kit.txt @@ -0,0 +1,23 @@ + + + Nature Kit (2.1) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 29-04-2020 01:02 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + This content is free to use in personal, educational and commercial projects. + Support us by crediting Kenney or www.kenney.nl (this is not mandatory) + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + Patreon: http://patreon.com/kenney/ + + Follow on Twitter for updates: + http://twitter.com/KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-platformer-kit.txt b/web/public/assets/licenses/kenney-platformer-kit.txt new file mode 100644 index 0000000..a6c14c6 --- /dev/null +++ b/web/public/assets/licenses/kenney-platformer-kit.txt @@ -0,0 +1,28 @@ + + + Platformer Kit (4.1) + + Created/distributed by Kenney (www.kenney.nl) + Creation date: 02-04-2026 11:29 + + ------------------------------ + + License: (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You can use this content for personal, educational, and commercial purposes. + + Support by crediting 'Kenney' or 'www.kenney.nl' (this is not a requirement) + + ------------------------------ + + • Website : www.kenney.nl + • Donate : www.kenney.nl/donate + + • Patreon : patreon.com/kenney + + Follow on social media for updates: + + • Twitter: twitter.com/KenneyNL + • BlueSky: kenney.bsky.social + • Instagram: instagram.com/kenney_nl \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-rpg-audio.txt b/web/public/assets/licenses/kenney-rpg-audio.txt new file mode 100644 index 0000000..c19921a --- /dev/null +++ b/web/public/assets/licenses/kenney-rpg-audio.txt @@ -0,0 +1,21 @@ + + + RPG Audio + + by Kenney Vleugels (Kenney.nl) + + ------------------------------ + + License (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You may use these assets in personal and commercial projects. + Credit (Kenney or www.kenney.nl) would be nice but is not mandatory. + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + + Follow on Twitter for updates: + @KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/kenney-ui-audio.txt b/web/public/assets/licenses/kenney-ui-audio.txt new file mode 100644 index 0000000..4ff46a6 --- /dev/null +++ b/web/public/assets/licenses/kenney-ui-audio.txt @@ -0,0 +1,21 @@ + + + UI SFX Set + + by Kenney Vleugels (Kenney.nl) + + ------------------------------ + + License (Creative Commons Zero, CC0) + http://creativecommons.org/publicdomain/zero/1.0/ + + You may use these assets in personal and commercial projects. + Credit (Kenney or www.kenney.nl) would be nice but is not mandatory. + + ------------------------------ + + Donate: http://support.kenney.nl + Request: http://request.kenney.nl + + Follow on Twitter for updates: + @KenneyNL \ No newline at end of file diff --git a/web/public/assets/licenses/polyhaven-cc0.txt b/web/public/assets/licenses/polyhaven-cc0.txt new file mode 100644 index 0000000..046f482 --- /dev/null +++ b/web/public/assets/licenses/polyhaven-cc0.txt @@ -0,0 +1,7 @@ +Poly Haven - license statement (copied from https://polyhaven.com/license, checked 2026-10-25) + +"Our assets are all licensed as CC0" - "You can use our assets for any purpose", +including commercial work. Attribution is not required (credit appreciated). + +Assets used: wood_table_001 (Dimitrios Savva, Rico Cilliers), oak_veneer_01 (Jenelle van Heerden). +Full CC0 1.0 legal code: cc0-1.0-legalcode.txt diff --git a/web/public/assets/music/election-night-tension.mp3 b/web/public/assets/music/election-night-tension.mp3 new file mode 100644 index 0000000..9b66931 Binary files /dev/null and b/web/public/assets/music/election-night-tension.mp3 differ diff --git a/web/public/assets/music/election-night-tension.ogg b/web/public/assets/music/election-night-tension.ogg new file mode 100644 index 0000000..2ee5c74 Binary files /dev/null and b/web/public/assets/music/election-night-tension.ogg differ diff --git a/web/public/assets/music/news-bed.mp3 b/web/public/assets/music/news-bed.mp3 new file mode 100644 index 0000000..290440d Binary files /dev/null and b/web/public/assets/music/news-bed.mp3 differ diff --git a/web/public/assets/music/news-bed.ogg b/web/public/assets/music/news-bed.ogg new file mode 100644 index 0000000..8a0111b Binary files /dev/null and b/web/public/assets/music/news-bed.ogg differ diff --git a/web/public/assets/music/news-intro.mp3 b/web/public/assets/music/news-intro.mp3 new file mode 100644 index 0000000..af514c5 Binary files /dev/null and b/web/public/assets/music/news-intro.mp3 differ diff --git a/web/public/assets/music/party-disco-loop.mp3 b/web/public/assets/music/party-disco-loop.mp3 new file mode 100644 index 0000000..9836a8a Binary files /dev/null and b/web/public/assets/music/party-disco-loop.mp3 differ diff --git a/web/public/assets/music/party-disco-loop.ogg b/web/public/assets/music/party-disco-loop.ogg new file mode 100644 index 0000000..75073d4 Binary files /dev/null and b/web/public/assets/music/party-disco-loop.ogg differ diff --git a/web/public/assets/music/planning-loop.mp3 b/web/public/assets/music/planning-loop.mp3 new file mode 100644 index 0000000..644b852 Binary files /dev/null and b/web/public/assets/music/planning-loop.mp3 differ diff --git a/web/public/assets/music/planning-loop.ogg b/web/public/assets/music/planning-loop.ogg new file mode 100644 index 0000000..488b135 Binary files /dev/null and b/web/public/assets/music/planning-loop.ogg differ diff --git a/web/public/assets/music/theme-march.mp3 b/web/public/assets/music/theme-march.mp3 new file mode 100644 index 0000000..6309bd2 Binary files /dev/null and b/web/public/assets/music/theme-march.mp3 differ diff --git a/web/public/assets/music/theme-march.ogg b/web/public/assets/music/theme-march.ogg new file mode 100644 index 0000000..60e77c2 Binary files /dev/null and b/web/public/assets/music/theme-march.ogg differ diff --git a/web/public/assets/music/victory-triumphant.mp3 b/web/public/assets/music/victory-triumphant.mp3 new file mode 100644 index 0000000..dba06c3 Binary files /dev/null and b/web/public/assets/music/victory-triumphant.mp3 differ diff --git a/web/public/assets/sfx/applause.mp3 b/web/public/assets/sfx/applause.mp3 new file mode 100644 index 0000000..26ecec3 Binary files /dev/null and b/web/public/assets/sfx/applause.mp3 differ diff --git a/web/public/assets/sfx/bell-ding.mp3 b/web/public/assets/sfx/bell-ding.mp3 new file mode 100644 index 0000000..8d7d5c0 Binary files /dev/null and b/web/public/assets/sfx/bell-ding.mp3 differ diff --git a/web/public/assets/sfx/bell-ding.ogg b/web/public/assets/sfx/bell-ding.ogg new file mode 100644 index 0000000..1d963bb Binary files /dev/null and b/web/public/assets/sfx/bell-ding.ogg differ diff --git a/web/public/assets/sfx/buzz-negative.mp3 b/web/public/assets/sfx/buzz-negative.mp3 new file mode 100644 index 0000000..e6b2501 Binary files /dev/null and b/web/public/assets/sfx/buzz-negative.mp3 differ diff --git a/web/public/assets/sfx/buzz-negative.ogg b/web/public/assets/sfx/buzz-negative.ogg new file mode 100644 index 0000000..2d0ad6d Binary files /dev/null and b/web/public/assets/sfx/buzz-negative.ogg differ diff --git a/web/public/assets/sfx/buzz-short.mp3 b/web/public/assets/sfx/buzz-short.mp3 new file mode 100644 index 0000000..e3f941a Binary files /dev/null and b/web/public/assets/sfx/buzz-short.mp3 differ diff --git a/web/public/assets/sfx/buzz-short.ogg b/web/public/assets/sfx/buzz-short.ogg new file mode 100644 index 0000000..cbeb4fb Binary files /dev/null and b/web/public/assets/sfx/buzz-short.ogg differ diff --git a/web/public/assets/sfx/card-deal-1.mp3 b/web/public/assets/sfx/card-deal-1.mp3 new file mode 100644 index 0000000..93e418f Binary files /dev/null and b/web/public/assets/sfx/card-deal-1.mp3 differ diff --git a/web/public/assets/sfx/card-deal-1.ogg b/web/public/assets/sfx/card-deal-1.ogg new file mode 100644 index 0000000..414b570 Binary files /dev/null and b/web/public/assets/sfx/card-deal-1.ogg differ diff --git a/web/public/assets/sfx/card-deal-2.mp3 b/web/public/assets/sfx/card-deal-2.mp3 new file mode 100644 index 0000000..32a75b8 Binary files /dev/null and b/web/public/assets/sfx/card-deal-2.mp3 differ diff --git a/web/public/assets/sfx/card-deal-2.ogg b/web/public/assets/sfx/card-deal-2.ogg new file mode 100644 index 0000000..20623e4 Binary files /dev/null and b/web/public/assets/sfx/card-deal-2.ogg differ diff --git a/web/public/assets/sfx/card-flip.mp3 b/web/public/assets/sfx/card-flip.mp3 new file mode 100644 index 0000000..4f50ca8 Binary files /dev/null and b/web/public/assets/sfx/card-flip.mp3 differ diff --git a/web/public/assets/sfx/card-flip.ogg b/web/public/assets/sfx/card-flip.ogg new file mode 100644 index 0000000..8424bec Binary files /dev/null and b/web/public/assets/sfx/card-flip.ogg differ diff --git a/web/public/assets/sfx/card-place.mp3 b/web/public/assets/sfx/card-place.mp3 new file mode 100644 index 0000000..d15cc8d Binary files /dev/null and b/web/public/assets/sfx/card-place.mp3 differ diff --git a/web/public/assets/sfx/card-place.ogg b/web/public/assets/sfx/card-place.ogg new file mode 100644 index 0000000..42bbfa8 Binary files /dev/null and b/web/public/assets/sfx/card-place.ogg differ diff --git a/web/public/assets/sfx/card-shuffle.mp3 b/web/public/assets/sfx/card-shuffle.mp3 new file mode 100644 index 0000000..1da710d Binary files /dev/null and b/web/public/assets/sfx/card-shuffle.mp3 differ diff --git a/web/public/assets/sfx/card-shuffle.ogg b/web/public/assets/sfx/card-shuffle.ogg new file mode 100644 index 0000000..8c73494 Binary files /dev/null and b/web/public/assets/sfx/card-shuffle.ogg differ diff --git a/web/public/assets/sfx/channel-switch.mp3 b/web/public/assets/sfx/channel-switch.mp3 new file mode 100644 index 0000000..d4ded61 Binary files /dev/null and b/web/public/assets/sfx/channel-switch.mp3 differ diff --git a/web/public/assets/sfx/chime-positive-1.mp3 b/web/public/assets/sfx/chime-positive-1.mp3 new file mode 100644 index 0000000..a10bf81 Binary files /dev/null and b/web/public/assets/sfx/chime-positive-1.mp3 differ diff --git a/web/public/assets/sfx/chime-positive-1.ogg b/web/public/assets/sfx/chime-positive-1.ogg new file mode 100644 index 0000000..4e01396 Binary files /dev/null and b/web/public/assets/sfx/chime-positive-1.ogg differ diff --git a/web/public/assets/sfx/chime-positive-2.mp3 b/web/public/assets/sfx/chime-positive-2.mp3 new file mode 100644 index 0000000..f11b559 Binary files /dev/null and b/web/public/assets/sfx/chime-positive-2.mp3 differ diff --git a/web/public/assets/sfx/chime-positive-2.ogg b/web/public/assets/sfx/chime-positive-2.ogg new file mode 100644 index 0000000..1586187 Binary files /dev/null and b/web/public/assets/sfx/chime-positive-2.ogg differ diff --git a/web/public/assets/sfx/coins-small.mp3 b/web/public/assets/sfx/coins-small.mp3 new file mode 100644 index 0000000..6c68417 Binary files /dev/null and b/web/public/assets/sfx/coins-small.mp3 differ diff --git a/web/public/assets/sfx/coins-small.ogg b/web/public/assets/sfx/coins-small.ogg new file mode 100644 index 0000000..73d92c5 Binary files /dev/null and b/web/public/assets/sfx/coins-small.ogg differ diff --git a/web/public/assets/sfx/coins.mp3 b/web/public/assets/sfx/coins.mp3 new file mode 100644 index 0000000..7daf385 Binary files /dev/null and b/web/public/assets/sfx/coins.mp3 differ diff --git a/web/public/assets/sfx/coins.ogg b/web/public/assets/sfx/coins.ogg new file mode 100644 index 0000000..c84e27d Binary files /dev/null and b/web/public/assets/sfx/coins.ogg differ diff --git a/web/public/assets/sfx/crowd-cheer-fireworks.mp3 b/web/public/assets/sfx/crowd-cheer-fireworks.mp3 new file mode 100644 index 0000000..64c0905 Binary files /dev/null and b/web/public/assets/sfx/crowd-cheer-fireworks.mp3 differ diff --git a/web/public/assets/sfx/crowd-ooh.mp3 b/web/public/assets/sfx/crowd-ooh.mp3 new file mode 100644 index 0000000..913ab5a Binary files /dev/null and b/web/public/assets/sfx/crowd-ooh.mp3 differ diff --git a/web/public/assets/sfx/crowd-ooh.ogg b/web/public/assets/sfx/crowd-ooh.ogg new file mode 100644 index 0000000..1588a14 Binary files /dev/null and b/web/public/assets/sfx/crowd-ooh.ogg differ diff --git a/web/public/assets/sfx/crowd-rally.mp3 b/web/public/assets/sfx/crowd-rally.mp3 new file mode 100644 index 0000000..db52e2c Binary files /dev/null and b/web/public/assets/sfx/crowd-rally.mp3 differ diff --git a/web/public/assets/sfx/dice-roll-1.mp3 b/web/public/assets/sfx/dice-roll-1.mp3 new file mode 100644 index 0000000..62aefc8 Binary files /dev/null and b/web/public/assets/sfx/dice-roll-1.mp3 differ diff --git a/web/public/assets/sfx/dice-roll-1.ogg b/web/public/assets/sfx/dice-roll-1.ogg new file mode 100644 index 0000000..b5198d2 Binary files /dev/null and b/web/public/assets/sfx/dice-roll-1.ogg differ diff --git a/web/public/assets/sfx/dice-roll-2.mp3 b/web/public/assets/sfx/dice-roll-2.mp3 new file mode 100644 index 0000000..c9afd05 Binary files /dev/null and b/web/public/assets/sfx/dice-roll-2.mp3 differ diff --git a/web/public/assets/sfx/dice-roll-2.ogg b/web/public/assets/sfx/dice-roll-2.ogg new file mode 100644 index 0000000..024744d Binary files /dev/null and b/web/public/assets/sfx/dice-roll-2.ogg differ diff --git a/web/public/assets/sfx/drumroll.mp3 b/web/public/assets/sfx/drumroll.mp3 new file mode 100644 index 0000000..772370a Binary files /dev/null and b/web/public/assets/sfx/drumroll.mp3 differ diff --git a/web/public/assets/sfx/firecrackers.mp3 b/web/public/assets/sfx/firecrackers.mp3 new file mode 100644 index 0000000..a958f61 Binary files /dev/null and b/web/public/assets/sfx/firecrackers.mp3 differ diff --git a/web/public/assets/sfx/gong-bright.mp3 b/web/public/assets/sfx/gong-bright.mp3 new file mode 100644 index 0000000..319db4c Binary files /dev/null and b/web/public/assets/sfx/gong-bright.mp3 differ diff --git a/web/public/assets/sfx/gong-bright.ogg b/web/public/assets/sfx/gong-bright.ogg new file mode 100644 index 0000000..519ce36 Binary files /dev/null and b/web/public/assets/sfx/gong-bright.ogg differ diff --git a/web/public/assets/sfx/gong.mp3 b/web/public/assets/sfx/gong.mp3 new file mode 100644 index 0000000..1347c9b Binary files /dev/null and b/web/public/assets/sfx/gong.mp3 differ diff --git a/web/public/assets/sfx/gong.ogg b/web/public/assets/sfx/gong.ogg new file mode 100644 index 0000000..be7460b Binary files /dev/null and b/web/public/assets/sfx/gong.ogg differ diff --git a/web/public/assets/sfx/jingle-steel-up.mp3 b/web/public/assets/sfx/jingle-steel-up.mp3 new file mode 100644 index 0000000..446b113 Binary files /dev/null and b/web/public/assets/sfx/jingle-steel-up.mp3 differ diff --git a/web/public/assets/sfx/jingle-steel-up.ogg b/web/public/assets/sfx/jingle-steel-up.ogg new file mode 100644 index 0000000..557aa4a Binary files /dev/null and b/web/public/assets/sfx/jingle-steel-up.ogg differ diff --git a/web/public/assets/sfx/jingle-tuba-sad.mp3 b/web/public/assets/sfx/jingle-tuba-sad.mp3 new file mode 100644 index 0000000..f3671f6 Binary files /dev/null and b/web/public/assets/sfx/jingle-tuba-sad.mp3 differ diff --git a/web/public/assets/sfx/jingle-tuba-sad.ogg b/web/public/assets/sfx/jingle-tuba-sad.ogg new file mode 100644 index 0000000..3645fb8 Binary files /dev/null and b/web/public/assets/sfx/jingle-tuba-sad.ogg differ diff --git a/web/public/assets/sfx/news-three-tone.mp3 b/web/public/assets/sfx/news-three-tone.mp3 new file mode 100644 index 0000000..8d5d9b9 Binary files /dev/null and b/web/public/assets/sfx/news-three-tone.mp3 differ diff --git a/web/public/assets/sfx/news-three-tone.ogg b/web/public/assets/sfx/news-three-tone.ogg new file mode 100644 index 0000000..d4f0f3a Binary files /dev/null and b/web/public/assets/sfx/news-three-tone.ogg differ diff --git a/web/public/assets/sfx/paper-crumple.mp3 b/web/public/assets/sfx/paper-crumple.mp3 new file mode 100644 index 0000000..9dc8366 Binary files /dev/null and b/web/public/assets/sfx/paper-crumple.mp3 differ diff --git a/web/public/assets/sfx/paper-rip.mp3 b/web/public/assets/sfx/paper-rip.mp3 new file mode 100644 index 0000000..4cb7972 Binary files /dev/null and b/web/public/assets/sfx/paper-rip.mp3 differ diff --git a/web/public/assets/sfx/paper-rustle-1.mp3 b/web/public/assets/sfx/paper-rustle-1.mp3 new file mode 100644 index 0000000..3434b22 Binary files /dev/null and b/web/public/assets/sfx/paper-rustle-1.mp3 differ diff --git a/web/public/assets/sfx/paper-rustle-2.mp3 b/web/public/assets/sfx/paper-rustle-2.mp3 new file mode 100644 index 0000000..89a45f2 Binary files /dev/null and b/web/public/assets/sfx/paper-rustle-2.mp3 differ diff --git a/web/public/assets/sfx/piece-hop-1.mp3 b/web/public/assets/sfx/piece-hop-1.mp3 new file mode 100644 index 0000000..563c820 Binary files /dev/null and b/web/public/assets/sfx/piece-hop-1.mp3 differ diff --git a/web/public/assets/sfx/piece-hop-1.ogg b/web/public/assets/sfx/piece-hop-1.ogg new file mode 100644 index 0000000..4bf6be6 Binary files /dev/null and b/web/public/assets/sfx/piece-hop-1.ogg differ diff --git a/web/public/assets/sfx/piece-hop-2.mp3 b/web/public/assets/sfx/piece-hop-2.mp3 new file mode 100644 index 0000000..63de5b2 Binary files /dev/null and b/web/public/assets/sfx/piece-hop-2.mp3 differ diff --git a/web/public/assets/sfx/piece-hop-2.ogg b/web/public/assets/sfx/piece-hop-2.ogg new file mode 100644 index 0000000..c27596a Binary files /dev/null and b/web/public/assets/sfx/piece-hop-2.ogg differ diff --git a/web/public/assets/sfx/stamp-thump.mp3 b/web/public/assets/sfx/stamp-thump.mp3 new file mode 100644 index 0000000..0047378 Binary files /dev/null and b/web/public/assets/sfx/stamp-thump.mp3 differ diff --git a/web/public/assets/sfx/stamp-thump.ogg b/web/public/assets/sfx/stamp-thump.ogg new file mode 100644 index 0000000..55e70b5 Binary files /dev/null and b/web/public/assets/sfx/stamp-thump.ogg differ diff --git a/web/public/assets/sfx/timer-tick.mp3 b/web/public/assets/sfx/timer-tick.mp3 new file mode 100644 index 0000000..1ebad96 Binary files /dev/null and b/web/public/assets/sfx/timer-tick.mp3 differ diff --git a/web/public/assets/sfx/timer-tick.ogg b/web/public/assets/sfx/timer-tick.ogg new file mode 100644 index 0000000..e5827a0 Binary files /dev/null and b/web/public/assets/sfx/timer-tick.ogg differ diff --git a/web/public/assets/sfx/tv-static-loop.mp3 b/web/public/assets/sfx/tv-static-loop.mp3 new file mode 100644 index 0000000..2c561ed Binary files /dev/null and b/web/public/assets/sfx/tv-static-loop.mp3 differ diff --git a/web/public/assets/sfx/tv-static.mp3 b/web/public/assets/sfx/tv-static.mp3 new file mode 100644 index 0000000..4180f32 Binary files /dev/null and b/web/public/assets/sfx/tv-static.mp3 differ diff --git a/web/public/assets/sfx/ui-click.mp3 b/web/public/assets/sfx/ui-click.mp3 new file mode 100644 index 0000000..14e6ac5 Binary files /dev/null and b/web/public/assets/sfx/ui-click.mp3 differ diff --git a/web/public/assets/sfx/ui-click.ogg b/web/public/assets/sfx/ui-click.ogg new file mode 100644 index 0000000..502a729 Binary files /dev/null and b/web/public/assets/sfx/ui-click.ogg differ diff --git a/web/public/assets/textures/cardboard-diff.jpg b/web/public/assets/textures/cardboard-diff.jpg new file mode 100644 index 0000000..47e2b0a Binary files /dev/null and b/web/public/assets/textures/cardboard-diff.jpg differ diff --git a/web/public/assets/textures/wood-oak-light-diff.jpg b/web/public/assets/textures/wood-oak-light-diff.jpg new file mode 100644 index 0000000..81e2ca7 Binary files /dev/null and b/web/public/assets/textures/wood-oak-light-diff.jpg differ diff --git a/web/public/assets/textures/wood-table-diff.jpg b/web/public/assets/textures/wood-table-diff.jpg new file mode 100644 index 0000000..b554979 Binary files /dev/null and b/web/public/assets/textures/wood-table-diff.jpg differ diff --git a/web/public/assets/textures/wood-table-normal.jpg b/web/public/assets/textures/wood-table-normal.jpg new file mode 100644 index 0000000..a068cee Binary files /dev/null and b/web/public/assets/textures/wood-table-normal.jpg differ diff --git a/web/public/cards/announce_policy.webp b/web/public/cards/announce_policy.webp new file mode 100644 index 0000000..15a9fdb Binary files /dev/null and b/web/public/cards/announce_policy.webp differ diff --git a/web/public/cards/banquet.webp b/web/public/cards/banquet.webp new file mode 100644 index 0000000..73a428b Binary files /dev/null and b/web/public/cards/banquet.webp differ diff --git a/web/public/cards/big_donor.webp b/web/public/cards/big_donor.webp new file mode 100644 index 0000000..9eff35c Binary files /dev/null and b/web/public/cards/big_donor.webp differ diff --git a/web/public/cards/buyout.webp b/web/public/cards/buyout.webp new file mode 100644 index 0000000..3df6f82 Binary files /dev/null and b/web/public/cards/buyout.webp differ diff --git a/web/public/cards/chicken_oath.webp b/web/public/cards/chicken_oath.webp new file mode 100644 index 0000000..cd164a1 Binary files /dev/null and b/web/public/cards/chicken_oath.webp differ diff --git a/web/public/cards/church_visit.webp b/web/public/cards/church_visit.webp new file mode 100644 index 0000000..dd8226a Binary files /dev/null and b/web/public/cards/church_visit.webp differ diff --git a/web/public/cards/concert.webp b/web/public/cards/concert.webp new file mode 100644 index 0000000..fa4a064 Binary files /dev/null and b/web/public/cards/concert.webp differ diff --git a/web/public/cards/councilor_allies.webp b/web/public/cards/councilor_allies.webp new file mode 100644 index 0000000..e177dde Binary files /dev/null and b/web/public/cards/councilor_allies.webp differ diff --git a/web/public/cards/crisis_pr.webp b/web/public/cards/crisis_pr.webp new file mode 100644 index 0000000..434e6ad Binary files /dev/null and b/web/public/cards/crisis_pr.webp differ diff --git a/web/public/cards/debate_training.webp b/web/public/cards/debate_training.webp new file mode 100644 index 0000000..ea443f9 Binary files /dev/null and b/web/public/cards/debate_training.webp differ diff --git a/web/public/cards/door_to_door.webp b/web/public/cards/door_to_door.webp new file mode 100644 index 0000000..b6c4f8b Binary files /dev/null and b/web/public/cards/door_to_door.webp differ diff --git a/web/public/cards/endorsement.webp b/web/public/cards/endorsement.webp new file mode 100644 index 0000000..a6a0fb0 Binary files /dev/null and b/web/public/cards/endorsement.webp differ diff --git a/web/public/cards/eve_online_ad.webp b/web/public/cards/eve_online_ad.webp new file mode 100644 index 0000000..494716e Binary files /dev/null and b/web/public/cards/eve_online_ad.webp differ diff --git a/web/public/cards/eve_phone_bank.webp b/web/public/cards/eve_phone_bank.webp new file mode 100644 index 0000000..d89db5b Binary files /dev/null and b/web/public/cards/eve_phone_bank.webp differ diff --git a/web/public/cards/eve_rally.webp b/web/public/cards/eve_rally.webp new file mode 100644 index 0000000..6f81bf5 Binary files /dev/null and b/web/public/cards/eve_rally.webp differ diff --git a/web/public/cards/eve_vote_buying.webp b/web/public/cards/eve_vote_buying.webp new file mode 100644 index 0000000..482a2aa Binary files /dev/null and b/web/public/cards/eve_vote_buying.webp differ diff --git a/web/public/cards/expose_press.webp b/web/public/cards/expose_press.webp new file mode 100644 index 0000000..270dad8 Binary files /dev/null and b/web/public/cards/expose_press.webp differ diff --git a/web/public/cards/facebook_live.webp b/web/public/cards/facebook_live.webp new file mode 100644 index 0000000..4acd07f Binary files /dev/null and b/web/public/cards/facebook_live.webp differ diff --git a/web/public/cards/fact_check.webp b/web/public/cards/fact_check.webp new file mode 100644 index 0000000..f655ff8 Binary files /dev/null and b/web/public/cards/fact_check.webp differ diff --git a/web/public/cards/factory_visit.webp b/web/public/cards/factory_visit.webp new file mode 100644 index 0000000..8db3cad Binary files /dev/null and b/web/public/cards/factory_visit.webp differ diff --git a/web/public/cards/fake_poll.webp b/web/public/cards/fake_poll.webp new file mode 100644 index 0000000..d3424d2 Binary files /dev/null and b/web/public/cards/fake_poll.webp differ diff --git a/web/public/cards/fire_staff.webp b/web/public/cards/fire_staff.webp new file mode 100644 index 0000000..a45846d Binary files /dev/null and b/web/public/cards/fire_staff.webp differ diff --git a/web/public/cards/flags_billboards.webp b/web/public/cards/flags_billboards.webp new file mode 100644 index 0000000..bd9b259 Binary files /dev/null and b/web/public/cards/flags_billboards.webp differ diff --git a/web/public/cards/forum.webp b/web/public/cards/forum.webp new file mode 100644 index 0000000..b19e77c Binary files /dev/null and b/web/public/cards/forum.webp differ diff --git a/web/public/cards/frame_vote_buying.webp b/web/public/cards/frame_vote_buying.webp new file mode 100644 index 0000000..f7507ad Binary files /dev/null and b/web/public/cards/frame_vote_buying.webp differ diff --git a/web/public/cards/fundraiser_dinner.webp b/web/public/cards/fundraiser_dinner.webp new file mode 100644 index 0000000..398f46a Binary files /dev/null and b/web/public/cards/fundraiser_dinner.webp differ diff --git a/web/public/cards/gifts.webp b/web/public/cards/gifts.webp new file mode 100644 index 0000000..070bb64 Binary files /dev/null and b/web/public/cards/gifts.webp differ diff --git a/web/public/cards/grassroots_walk.webp b/web/public/cards/grassroots_walk.webp new file mode 100644 index 0000000..6f6a8f8 Binary files /dev/null and b/web/public/cards/grassroots_walk.webp differ diff --git a/web/public/cards/hire_staff.webp b/web/public/cards/hire_staff.webp new file mode 100644 index 0000000..f1e17ec Binary files /dev/null and b/web/public/cards/hire_staff.webp differ diff --git a/web/public/cards/homecoming.webp b/web/public/cards/homecoming.webp new file mode 100644 index 0000000..926b553 Binary files /dev/null and b/web/public/cards/homecoming.webp differ diff --git a/web/public/cards/impersonate.webp b/web/public/cards/impersonate.webp new file mode 100644 index 0000000..d7c194a Binary files /dev/null and b/web/public/cards/impersonate.webp differ diff --git a/web/public/cards/influencer_live.webp b/web/public/cards/influencer_live.webp new file mode 100644 index 0000000..4433ce9 Binary files /dev/null and b/web/public/cards/influencer_live.webp differ diff --git a/web/public/cards/internal_poll.webp b/web/public/cards/internal_poll.webp new file mode 100644 index 0000000..a27da3f Binary files /dev/null and b/web/public/cards/internal_poll.webp differ diff --git a/web/public/cards/interview.webp b/web/public/cards/interview.webp new file mode 100644 index 0000000..3509c9b Binary files /dev/null and b/web/public/cards/interview.webp differ diff --git a/web/public/cards/investigate.webp b/web/public/cards/investigate.webp new file mode 100644 index 0000000..7e053a8 Binary files /dev/null and b/web/public/cards/investigate.webp differ diff --git a/web/public/cards/invite_oath.webp b/web/public/cards/invite_oath.webp new file mode 100644 index 0000000..d923036 Binary files /dev/null and b/web/public/cards/invite_oath.webp differ diff --git a/web/public/cards/kneel.webp b/web/public/cards/kneel.webp new file mode 100644 index 0000000..b0779fa Binary files /dev/null and b/web/public/cards/kneel.webp differ diff --git a/web/public/cards/lawsuit.webp b/web/public/cards/lawsuit.webp new file mode 100644 index 0000000..c150d7d Binary files /dev/null and b/web/public/cards/lawsuit.webp differ diff --git a/web/public/cards/line_groups.webp b/web/public/cards/line_groups.webp new file mode 100644 index 0000000..1b94017 Binary files /dev/null and b/web/public/cards/line_groups.webp differ diff --git a/web/public/cards/live_pledge.webp b/web/public/cards/live_pledge.webp new file mode 100644 index 0000000..676260b Binary files /dev/null and b/web/public/cards/live_pledge.webp differ diff --git a/web/public/cards/market_visit.webp b/web/public/cards/market_visit.webp new file mode 100644 index 0000000..5cf21a6 Binary files /dev/null and b/web/public/cards/market_visit.webp differ diff --git a/web/public/cards/media_training.webp b/web/public/cards/media_training.webp new file mode 100644 index 0000000..4f3677c Binary files /dev/null and b/web/public/cards/media_training.webp differ diff --git a/web/public/cards/night_market.webp b/web/public/cards/night_market.webp new file mode 100644 index 0000000..0b43a81 Binary files /dev/null and b/web/public/cards/night_market.webp differ diff --git a/web/public/cards/online_ad.webp b/web/public/cards/online_ad.webp new file mode 100644 index 0000000..3e024a5 Binary files /dev/null and b/web/public/cards/online_ad.webp differ diff --git a/web/public/cards/open_office.webp b/web/public/cards/open_office.webp new file mode 100644 index 0000000..d471c56 Binary files /dev/null and b/web/public/cards/open_office.webp differ diff --git a/web/public/cards/party_elder.webp b/web/public/cards/party_elder.webp new file mode 100644 index 0000000..2f025d5 Binary files /dev/null and b/web/public/cards/party_elder.webp differ diff --git a/web/public/cards/party_fund.webp b/web/public/cards/party_fund.webp new file mode 100644 index 0000000..1315f95 Binary files /dev/null and b/web/public/cards/party_fund.webp differ diff --git a/web/public/cards/phone_banking.webp b/web/public/cards/phone_banking.webp new file mode 100644 index 0000000..f4cb971 Binary files /dev/null and b/web/public/cards/phone_banking.webp differ diff --git a/web/public/cards/pilgrimage.webp b/web/public/cards/pilgrimage.webp new file mode 100644 index 0000000..38c9d6d Binary files /dev/null and b/web/public/cards/pilgrimage.webp differ diff --git a/web/public/cards/press_conference.webp b/web/public/cards/press_conference.webp new file mode 100644 index 0000000..64585cf Binary files /dev/null and b/web/public/cards/press_conference.webp differ diff --git a/web/public/cards/print_flyers.webp b/web/public/cards/print_flyers.webp new file mode 100644 index 0000000..abbd892 Binary files /dev/null and b/web/public/cards/print_flyers.webp differ diff --git a/web/public/cards/promise_bribe.webp b/web/public/cards/promise_bribe.webp new file mode 100644 index 0000000..825c6c5 Binary files /dev/null and b/web/public/cards/promise_bribe.webp differ diff --git a/web/public/cards/protest_government.webp b/web/public/cards/protest_government.webp new file mode 100644 index 0000000..0935c9b Binary files /dev/null and b/web/public/cards/protest_government.webp differ diff --git a/web/public/cards/protest_hq.webp b/web/public/cards/protest_hq.webp new file mode 100644 index 0000000..1abec36 Binary files /dev/null and b/web/public/cards/protest_hq.webp differ diff --git a/web/public/cards/radio_ad.webp b/web/public/cards/radio_ad.webp new file mode 100644 index 0000000..ce4d1f8 Binary files /dev/null and b/web/public/cards/radio_ad.webp differ diff --git a/web/public/cards/rally.webp b/web/public/cards/rally.webp new file mode 100644 index 0000000..6a1dbe2 Binary files /dev/null and b/web/public/cards/rally.webp differ diff --git a/web/public/cards/rebuttal_press.webp b/web/public/cards/rebuttal_press.webp new file mode 100644 index 0000000..ece1ee8 Binary files /dev/null and b/web/public/cards/rebuttal_press.webp differ diff --git a/web/public/cards/recruit_machine.webp b/web/public/cards/recruit_machine.webp new file mode 100644 index 0000000..e275f49 Binary files /dev/null and b/web/public/cards/recruit_machine.webp differ diff --git a/web/public/cards/recruit_volunteers.webp b/web/public/cards/recruit_volunteers.webp new file mode 100644 index 0000000..8acf8a4 Binary files /dev/null and b/web/public/cards/recruit_volunteers.webp differ diff --git a/web/public/cards/report_prosecutor.webp b/web/public/cards/report_prosecutor.webp new file mode 100644 index 0000000..23261a3 Binary files /dev/null and b/web/public/cards/report_prosecutor.webp differ diff --git a/web/public/cards/rest.webp b/web/public/cards/rest.webp new file mode 100644 index 0000000..e36ace0 Binary files /dev/null and b/web/public/cards/rest.webp differ diff --git a/web/public/cards/scene-procession.webp b/web/public/cards/scene-procession.webp new file mode 100644 index 0000000..d5d77f8 Binary files /dev/null and b/web/public/cards/scene-procession.webp differ diff --git a/web/public/cards/scene-typhoon.webp b/web/public/cards/scene-typhoon.webp new file mode 100644 index 0000000..e0852f4 Binary files /dev/null and b/web/public/cards/scene-typhoon.webp differ diff --git a/web/public/cards/self_fund.webp b/web/public/cards/self_fund.webp new file mode 100644 index 0000000..d6d8b00 Binary files /dev/null and b/web/public/cards/self_fund.webp differ diff --git a/web/public/cards/short_video.webp b/web/public/cards/short_video.webp new file mode 100644 index 0000000..08c2213 Binary files /dev/null and b/web/public/cards/short_video.webp differ diff --git a/web/public/cards/slush_fund.webp b/web/public/cards/slush_fund.webp new file mode 100644 index 0000000..095dc79 Binary files /dev/null and b/web/public/cards/slush_fund.webp differ diff --git a/web/public/cards/small_donations.webp b/web/public/cards/small_donations.webp new file mode 100644 index 0000000..0bee7bc Binary files /dev/null and b/web/public/cards/small_donations.webp differ diff --git a/web/public/cards/smear.webp b/web/public/cards/smear.webp new file mode 100644 index 0000000..a5da1f5 Binary files /dev/null and b/web/public/cards/smear.webp differ diff --git a/web/public/cards/sound_truck.webp b/web/public/cards/sound_truck.webp new file mode 100644 index 0000000..7c7a045 Binary files /dev/null and b/web/public/cards/sound_truck.webp differ diff --git a/web/public/cards/staged_attack.webp b/web/public/cards/staged_attack.webp new file mode 100644 index 0000000..88fb59f Binary files /dev/null and b/web/public/cards/staged_attack.webp differ diff --git a/web/public/cards/street_canvass.webp b/web/public/cards/street_canvass.webp new file mode 100644 index 0000000..eb2d4c8 Binary files /dev/null and b/web/public/cards/street_canvass.webp differ diff --git a/web/public/cards/street_interview.webp b/web/public/cards/street_interview.webp new file mode 100644 index 0000000..8ec37e8 Binary files /dev/null and b/web/public/cards/street_interview.webp differ diff --git a/web/public/cards/study.webp b/web/public/cards/study.webp new file mode 100644 index 0000000..ab73950 Binary files /dev/null and b/web/public/cards/study.webp differ diff --git a/web/public/cards/talk_show.webp b/web/public/cards/talk_show.webp new file mode 100644 index 0000000..f24cd93 Binary files /dev/null and b/web/public/cards/talk_show.webp differ diff --git a/web/public/cards/temple_visit.webp b/web/public/cards/temple_visit.webp new file mode 100644 index 0000000..1b35828 Binary files /dev/null and b/web/public/cards/temple_visit.webp differ diff --git a/web/public/cards/troll_army.webp b/web/public/cards/troll_army.webp new file mode 100644 index 0000000..715c0d7 Binary files /dev/null and b/web/public/cards/troll_army.webp differ diff --git a/web/public/cards/tv_ad.webp b/web/public/cards/tv_ad.webp new file mode 100644 index 0000000..5041d13 Binary files /dev/null and b/web/public/cards/tv_ad.webp differ diff --git a/web/public/cards/visit_associations.webp b/web/public/cards/visit_associations.webp new file mode 100644 index 0000000..59f6880 Binary files /dev/null and b/web/public/cards/visit_associations.webp differ diff --git a/web/public/cards/volunteer_calls.webp b/web/public/cards/volunteer_calls.webp new file mode 100644 index 0000000..fff2a29 Binary files /dev/null and b/web/public/cards/volunteer_calls.webp differ diff --git a/web/public/cards/vote_buying.webp b/web/public/cards/vote_buying.webp new file mode 100644 index 0000000..d2ba525 Binary files /dev/null and b/web/public/cards/vote_buying.webp differ diff --git a/web/public/cards/weddings_funerals.webp b/web/public/cards/weddings_funerals.webp new file mode 100644 index 0000000..dcdfdae Binary files /dev/null and b/web/public/cards/weddings_funerals.webp differ diff --git a/web/public/cards/white_paper.webp b/web/public/cards/white_paper.webp new file mode 100644 index 0000000..5c292e9 Binary files /dev/null and b/web/public/cards/white_paper.webp differ diff --git a/web/public/cards/workout.webp b/web/public/cards/workout.webp new file mode 100644 index 0000000..79d715c Binary files /dev/null and b/web/public/cards/workout.webp differ diff --git a/web/public/maps/taiwan-counties.json b/web/public/maps/taiwan-counties.json new file mode 100644 index 0000000..b7aa785 --- /dev/null +++ b/web/public/maps/taiwan-counties.json @@ -0,0 +1,24 @@ +{"type":"FeatureCollection", "features": [ +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[119.9582,26.1546],[119.9462,26.1656],[119.939,26.1562],[119.9338,26.1588],[119.9248,26.1612],[119.9238,26.1642],[119.9278,26.1696],[119.9174,26.175],[119.9184,26.1654],[119.9152,26.1536],[119.9168,26.141],[119.9344,26.1456],[119.945,26.1462],[119.9582,26.1546]]],[[[119.999,26.2226],[120.0146,26.2234],[120.0094,26.228],[120.0036,26.2236],[120.0016,26.2338],[119.9902,26.2316],[119.9672,26.2206],[119.9692,26.2104],[119.9656,26.2048],[119.9664,26.194],[119.9734,26.1978],[119.9728,26.2092],[119.9804,26.2164],[119.9822,26.2172],[119.999,26.2226]]],[[[119.9386,25.9734],[119.9386,25.9808],[119.9288,25.9726],[119.9386,25.9734]]],[[[119.9762,25.9682],[119.965,25.9584],[119.9674,25.9512],[119.9822,25.961],[119.98,25.9664],[119.9762,25.9682]]],[[[120.4856,26.3674],[120.4884,26.3574],[120.505,26.3656],[120.4992,26.3724],[120.4816,26.3712],[120.4822,26.3808],[120.4738,26.3828],[120.4738,26.376],[120.4856,26.3674]]]]},"properties":{"name":"連江縣","county":"09007"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[118.3446,24.4112],[118.3606,24.4266],[118.4016,24.4352],[118.4276,24.4238],[118.4358,24.408],[118.4492,24.4158],[118.4634,24.4346],[118.469,24.4578],[118.4628,24.484],[118.4506,24.51],[118.4386,24.5136],[118.4294,24.5274],[118.3978,24.5282],[118.384,24.5068],[118.3858,24.4936],[118.3722,24.4794],[118.372,24.479],[118.3658,24.4738],[118.3536,24.4714],[118.3366,24.4758],[118.3182,24.4932],[118.2928,24.49],[118.2862,24.4748],[118.296,24.4548],[118.303,24.4416],[118.2982,24.4292],[118.2968,24.4274],[118.2782,24.413],[118.2954,24.3992],[118.32,24.3858],[118.331,24.3894],[118.3446,24.4112]]],[[[118.2458,24.4142],[118.2668,24.432],[118.2692,24.446],[118.2454,24.456],[118.2306,24.452],[118.224,24.437],[118.223,24.4352],[118.2146,24.4148],[118.226,24.405],[118.2458,24.4142]]],[[[119.4584,24.9894],[119.4558,24.995],[119.4448,24.9996],[119.4476,24.9876],[119.4584,24.9894]]],[[[119.474,24.986],[119.4666,24.9794],[119.4736,24.9776],[119.474,24.986]]]]},"properties":{"name":"金門縣","county":"09020"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[121.8452,24.6446],[121.8382,24.6724],[121.8368,24.711],[121.8386,24.7178],[121.8264,24.732],[121.8206,24.7498],[121.8186,24.764],[121.818,24.7778],[121.8186,24.7894],[121.8202,24.8072],[121.8272,24.842],[121.8356,24.86],[121.8426,24.8758],[121.8612,24.8954],[121.8776,24.9104],[121.888,24.9356],[121.9042,24.9414],[121.925,24.9674],[121.966,24.983],[121.9604,24.9882],[121.9436,24.9872],[121.9186,24.9788],[121.9156,24.9794],[121.9076,24.9758],[121.8884,24.9632],[121.8612,24.9636],[121.8456,24.9592],[121.8398,24.9422],[121.8538,24.928],[121.832,24.905],[121.822,24.9042],[121.7934,24.8998],[121.7858,24.8908],[121.777,24.8694],[121.7474,24.8538],[121.7464,24.8532],[121.7326,24.8558],[121.711,24.8412],[121.7076,24.8388],[121.6978,24.8342],[121.6894,24.8174],[121.6688,24.8168],[121.63,24.809],[121.6236,24.7944],[121.6014,24.7886],[121.5922,24.7878],[121.5976,24.7726],[121.59,24.7518],[121.5968,24.7292],[121.587,24.7202],[121.5432,24.7056],[121.5368,24.6884],[121.5244,24.6838],[121.4928,24.6732],[121.48,24.6738],[121.4594,24.6732],[121.4354,24.6222],[121.4162,24.6022],[121.403,24.5918],[121.4122,24.573],[121.3946,24.5556],[121.4016,24.5292],[121.3862,24.517],[121.3706,24.4978],[121.3424,24.4818],[121.3272,24.461],[121.3176,24.4416],[121.328,24.434],[121.325,24.407],[121.3384,24.39],[121.3648,24.389],[121.3736,24.3682],[121.4018,24.3796],[121.437,24.383],[121.452,24.3646],[121.4982,24.3392],[121.5222,24.343],[121.556,24.3312],[121.56,24.3226],[121.607,24.3126],[121.6064,24.33],[121.6202,24.3454],[121.6254,24.3688],[121.631,24.3706],[121.6874,24.3348],[121.7144,24.3268],[121.774,24.3152],[121.7708,24.3326],[121.7826,24.3624],[121.7912,24.4082],[121.8004,24.4314],[121.8436,24.4766],[121.8418,24.5202],[121.8686,24.5276],[121.8726,24.5388],[121.8692,24.572],[121.879,24.5912],[121.886,24.5998],[121.858,24.6186],[121.8512,24.6302],[121.8452,24.6446]]],[[[121.9598,24.845],[121.9476,24.8512],[121.9402,24.8386],[121.948,24.8354],[121.9598,24.845]]]]},"properties":{"name":"宜蘭縣","county":"10002"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.0114,24.8126],[121.0184,24.807],[121.0212,24.802],[121.0214,24.8018],[121.0246,24.7886],[121.023,24.7852],[121.0266,24.7808],[121.0264,24.7808],[121.0264,24.7576],[121.02,24.7574],[121.0196,24.7584],[121.0136,24.7708],[121.0104,24.7732],[121.01,24.7734],[120.9866,24.777],[120.9878,24.7682],[120.9818,24.7672],[120.9708,24.7656],[120.9608,24.751],[120.9572,24.7484],[120.945,24.7444],[120.9354,24.7126],[120.9486,24.7112],[120.953,24.704],[120.9738,24.7118],[120.9652,24.6878],[120.9754,24.6846],[120.977,24.6736],[120.9928,24.6594],[121.0102,24.6562],[121.0082,24.6444],[121.0254,24.6412],[121.0408,24.627],[121.0432,24.6272],[121.0532,24.6154],[121.0716,24.614],[121.083,24.5906],[121.0622,24.5562],[121.0802,24.5414],[121.067,24.523],[121.0718,24.4984],[121.0978,24.4964],[121.1238,24.51],[121.1692,24.5026],[121.2032,24.5126],[121.2422,24.4784],[121.2624,24.4554],[121.2602,24.429],[121.3058,24.4326],[121.3176,24.4416],[121.3272,24.461],[121.3424,24.4818],[121.3706,24.4978],[121.3862,24.517],[121.4016,24.5292],[121.3946,24.5556],[121.4122,24.573],[121.403,24.5918],[121.3914,24.5864],[121.3728,24.5938],[121.3588,24.6174],[121.3658,24.6318],[121.3524,24.6436],[121.3532,24.6664],[121.3266,24.6936],[121.3032,24.693],[121.3076,24.7198],[121.2982,24.7332],[121.3076,24.7552],[121.3012,24.7632],[121.2932,24.7654],[121.2774,24.771],[121.2512,24.7944],[121.2432,24.8088],[121.2342,24.8042],[121.226,24.8016],[121.2216,24.7996],[121.2028,24.81],[121.1962,24.818],[121.1792,24.8264],[121.1738,24.8276],[121.1756,24.8322],[121.15,24.8444],[121.1614,24.8594],[121.1572,24.8722],[121.1582,24.8754],[121.1438,24.881],[121.1254,24.8802],[121.122,24.8802],[121.109,24.8978],[121.0922,24.8934],[121.0606,24.9036],[121.0576,24.906],[121.0604,24.9186],[121.0592,24.9272],[121.0576,24.9306],[121.0584,24.9368],[121.0462,24.9424],[121.034,24.9448],[121.0242,24.941],[121.007,24.9462],[121.001,24.9402],[120.9902,24.9358],[120.982,24.94],[120.9688,24.9268],[120.961,24.9078],[120.9468,24.8802],[120.9444,24.8754],[120.927,24.8554],[120.9252,24.8548],[120.9316,24.8526],[120.9412,24.8492],[120.944,24.844],[120.9448,24.841],[120.953,24.836],[120.963,24.8326],[120.9712,24.8314],[120.9812,24.8312],[120.983,24.831],[120.991,24.824],[120.9966,24.823],[120.999,24.8224],[121.007,24.8168],[121.0114,24.8126]]]},"properties":{"name":"新竹縣","county":"10004"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.7244,24.354],[120.7546,24.3318],[120.7646,24.3258],[120.7778,24.3206],[120.8114,24.3118],[120.8174,24.3076],[120.8232,24.2992],[120.825,24.2972],[120.8324,24.2914],[120.8502,24.2886],[120.8748,24.2948],[120.9058,24.2926],[120.9098,24.294],[120.9222,24.3028],[120.917,24.3358],[120.9378,24.3418],[120.991,24.3298],[121.0058,24.3306],[121.02,24.3092],[121.0384,24.2964],[121.0556,24.3106],[121.0816,24.324],[121.0866,24.3176],[121.1254,24.342],[121.141,24.3596],[121.168,24.3608],[121.1746,24.3738],[121.2036,24.3976],[121.2134,24.382],[121.2314,24.3838],[121.2436,24.4058],[121.2438,24.42],[121.2602,24.429],[121.2624,24.4554],[121.2422,24.4784],[121.2032,24.5126],[121.1692,24.5026],[121.1238,24.51],[121.0978,24.4964],[121.0718,24.4984],[121.067,24.523],[121.0802,24.5414],[121.0622,24.5562],[121.083,24.5906],[121.0716,24.614],[121.0532,24.6154],[121.0432,24.6272],[121.0408,24.627],[121.0254,24.6412],[121.0082,24.6444],[121.0102,24.6562],[120.9928,24.6594],[120.977,24.6736],[120.9754,24.6846],[120.9652,24.6878],[120.9738,24.7118],[120.953,24.704],[120.9486,24.7112],[120.9354,24.7126],[120.9342,24.7132],[120.9222,24.7152],[120.9138,24.7172],[120.9124,24.7316],[120.9058,24.7406],[120.8938,24.7324],[120.8746,24.7384],[120.8614,24.7216],[120.8554,24.7016],[120.8532,24.7004],[120.8486,24.6966],[120.8452,24.6934],[120.8412,24.6888],[120.8244,24.6736],[120.8016,24.669],[120.7982,24.6686],[120.7712,24.6554],[120.7612,24.6438],[120.757,24.6378],[120.75,24.6264],[120.7402,24.6212],[120.735,24.6174],[120.7208,24.605],[120.7046,24.5728],[120.7044,24.5726],[120.7006,24.5608],[120.6974,24.557],[120.6898,24.5376],[120.6846,24.5214],[120.668,24.4986],[120.665,24.4846],[120.6606,24.4814],[120.6568,24.4754],[120.6454,24.4644],[120.643,24.4622],[120.6374,24.4538],[120.6336,24.4504],[120.6218,24.4402],[120.6328,24.432],[120.6396,24.4278],[120.643,24.4168],[120.658,24.4068],[120.66,24.405],[120.6642,24.4016],[120.6786,24.387],[120.6916,24.3696],[120.7072,24.3578],[120.7164,24.3562],[120.7182,24.3558],[120.7244,24.354]]]},"properties":{"name":"苗栗縣","county":"10005"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.5496,24.114],[120.545,24.1168],[120.5434,24.1194],[120.5368,24.1248],[120.5312,24.1284],[120.5236,24.1414],[120.5248,24.1432],[120.523,24.1546],[120.5226,24.1554],[120.5198,24.1614],[120.5174,24.1658],[120.5126,24.177],[120.508,24.1874],[120.507,24.1882],[120.4566,24.2072],[120.4464,24.1924],[120.4424,24.1884],[120.4402,24.1862],[120.4314,24.1856],[120.4248,24.1776],[120.4164,24.1702],[120.4152,24.164],[120.412,24.1498],[120.407,24.1396],[120.3984,24.1236],[120.3864,24.097],[120.3848,24.0906],[120.3716,24.082],[120.3452,24.0668],[120.3424,24.0538],[120.3418,24.0478],[120.3342,24.014],[120.3164,23.9992],[120.3088,23.9868],[120.3078,23.9732],[120.3048,23.9706],[120.2804,23.949],[120.2806,23.9392],[120.28,23.9368],[120.272,23.9314],[120.2606,23.9184],[120.2506,23.8908],[120.2334,23.8834],[120.2204,23.8662],[120.2438,23.8414],[120.2586,23.8332],[120.2712,23.8298],[120.2876,23.8256],[120.298,23.823],[120.3002,23.8224],[120.302,23.8218],[120.3088,23.8204],[120.3246,23.8212],[120.3426,23.8222],[120.3458,23.8222],[120.3506,23.8222],[120.3516,23.8224],[120.3602,23.8232],[120.3752,23.8286],[120.3818,23.8286],[120.3888,23.828],[120.398,23.8274],[120.3984,23.8272],[120.403,23.827],[120.4154,23.8268],[120.4162,23.8268],[120.4396,23.8268],[120.4474,23.8206],[120.452,23.8172],[120.455,23.8168],[120.4554,23.8166],[120.458,23.8162],[120.4614,23.8148],[120.4626,23.8142],[120.465,23.8132],[120.4668,23.8124],[120.469,23.8116],[120.4838,23.8064],[120.4998,23.8032],[120.5122,23.8],[120.5134,23.8],[120.5176,23.7998],[120.5262,23.7992],[120.528,23.799],[120.5364,23.8014],[120.5434,23.8012],[120.551,23.8012],[120.5836,23.7932],[120.5866,23.792],[120.5938,23.791],[120.6078,23.7912],[120.6096,23.7912],[120.6102,23.7912],[120.6154,23.7912],[120.6168,23.791],[120.6308,23.7896],[120.6404,23.786],[120.6482,23.7876],[120.6574,23.7908],[120.6836,23.8014],[120.6838,23.8014],[120.6752,23.8198],[120.6562,23.8132],[120.6552,23.8128],[120.6506,23.8128],[120.6438,23.8182],[120.6402,23.8208],[120.64,23.8252],[120.6238,23.8294],[120.6244,23.8406],[120.622,23.8388],[120.6156,23.8406],[120.6236,23.8476],[120.626,23.8532],[120.6272,23.8566],[120.6266,23.8574],[120.6206,23.865],[120.62,23.8684],[120.6258,23.875],[120.6248,23.877],[120.6264,23.88],[120.629,23.8856],[120.6294,23.889],[120.6344,23.8994],[120.6338,23.9],[120.6306,23.9086],[120.633,23.9138],[120.6336,23.9196],[120.6372,23.9228],[120.637,23.9232],[120.631,23.929],[120.6286,23.9314],[120.6326,23.9344],[120.6342,23.9362],[120.6328,23.946],[120.6296,23.956],[120.6382,23.954],[120.6442,23.9622],[120.6468,23.9634],[120.6496,23.9818],[120.6502,23.9844],[120.645,23.9898],[120.6424,23.9914],[120.6382,24.0056],[120.6382,24.0074],[120.6432,24.0084],[120.649,24.0084],[120.6558,24.0084],[120.6672,24.007],[120.6786,24.014],[120.6764,24.0156],[120.6556,24.0306],[120.652,24.0286],[120.6322,24.0304],[120.6266,24.0298],[120.6264,24.0298],[120.6258,24.0468],[120.6256,24.062],[120.6252,24.0694],[120.6158,24.083],[120.6124,24.1024],[120.6026,24.103],[120.6018,24.1038],[120.5964,24.105],[120.5832,24.1096],[120.5818,24.1096],[120.566,24.1098],[120.5628,24.1108],[120.5562,24.1126],[120.5496,24.114]]]},"properties":{"name":"彰化縣","county":"10007"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.6442,23.9622],[120.6382,23.954],[120.6296,23.956],[120.6328,23.946],[120.6342,23.9362],[120.6326,23.9344],[120.6286,23.9314],[120.631,23.929],[120.637,23.9232],[120.6372,23.9228],[120.6336,23.9196],[120.633,23.9138],[120.6306,23.9086],[120.6338,23.9],[120.6344,23.8994],[120.6294,23.889],[120.629,23.8856],[120.6264,23.88],[120.6248,23.877],[120.6258,23.875],[120.62,23.8684],[120.6206,23.865],[120.6266,23.8574],[120.6272,23.8566],[120.626,23.8532],[120.6236,23.8476],[120.6156,23.8406],[120.622,23.8388],[120.6244,23.8406],[120.6238,23.8294],[120.64,23.8252],[120.6402,23.8208],[120.6438,23.8182],[120.6506,23.8128],[120.6552,23.8128],[120.6562,23.8132],[120.6752,23.8198],[120.6838,23.8014],[120.6836,23.8014],[120.6574,23.7908],[120.6482,23.7876],[120.6404,23.786],[120.6478,23.7744],[120.6534,23.7606],[120.6546,23.7484],[120.6558,23.735],[120.6444,23.7366],[120.6402,23.7308],[120.6398,23.7144],[120.6466,23.6918],[120.6444,23.6684],[120.6396,23.6608],[120.6382,23.6584],[120.635,23.6458],[120.6318,23.639],[120.6326,23.6202],[120.6514,23.6162],[120.6828,23.6108],[120.705,23.6172],[120.713,23.6278],[120.7308,23.6108],[120.753,23.6148],[120.7796,23.6016],[120.8138,23.601],[120.8172,23.5964],[120.817,23.5962],[120.8216,23.58],[120.8204,23.5732],[120.8196,23.561],[120.8128,23.5514],[120.8086,23.5362],[120.8182,23.5234],[120.8232,23.511],[120.8228,23.4998],[120.839,23.4712],[120.8896,23.4756],[120.9144,23.4748],[120.9476,23.4672],[120.9576,23.4696],[120.9668,23.4718],[120.9998,23.4622],[121.0158,23.4516],[121.0152,23.4354],[121.0518,23.4508],[121.059,23.4618],[121.039,23.4744],[121.054,23.4902],[121.0686,23.5184],[121.0922,23.5148],[121.1204,23.521],[121.135,23.515],[121.147,23.5272],[121.1476,23.553],[121.1604,23.5678],[121.1532,23.5866],[121.178,23.5826],[121.1946,23.6006],[121.2134,23.6002],[121.2354,23.6614],[121.2326,23.6762],[121.2408,23.7046],[121.2394,23.7244],[121.2296,23.7302],[121.2326,23.7506],[121.2132,23.7576],[121.2054,23.7712],[121.2284,23.7852],[121.2254,23.7982],[121.235,23.8182],[121.2398,23.841],[121.2528,23.8674],[121.2684,23.8838],[121.2678,23.907],[121.2746,23.9266],[121.2778,23.966],[121.2632,23.9788],[121.26,23.9924],[121.2766,24.0246],[121.2858,24.0398],[121.2832,24.0542],[121.3046,24.0684],[121.3228,24.0844],[121.3158,24.1164],[121.2828,24.1418],[121.2862,24.1774],[121.2982,24.1796],[121.3258,24.1962],[121.3492,24.1996],[121.343,24.2236],[121.3112,24.235],[121.2858,24.2292],[121.2604,24.2454],[121.238,24.2198],[121.2198,24.2292],[121.2032,24.2218],[121.1808,24.2122],[121.1676,24.2254],[121.1478,24.2128],[121.1354,24.1962],[121.1034,24.1958],[121.1012,24.1946],[121.0914,24.1828],[121.0526,24.1548],[121.0476,24.16],[121.0154,24.156],[120.9986,24.127],[120.9874,24.1196],[120.957,24.1242],[120.951,24.1276],[120.9318,24.1122],[120.9142,24.1078],[120.8962,24.1164],[120.8916,24.0986],[120.8786,24.0852],[120.8814,24.1006],[120.8726,24.1168],[120.8378,24.1178],[120.8286,24.0946],[120.8292,24.0742],[120.8154,24.069],[120.7966,24.0404],[120.7916,24.0352],[120.7864,24.0294],[120.7818,24.0228],[120.7796,24.02],[120.7704,24.0104],[120.7482,23.9998],[120.7318,24.009],[120.7086,24.006],[120.7036,24.0056],[120.691,24.0084],[120.6786,24.014],[120.6672,24.007],[120.6558,24.0084],[120.649,24.0084],[120.6432,24.0084],[120.6382,24.0074],[120.6382,24.0056],[120.6424,23.9914],[120.645,23.9898],[120.6502,23.9844],[120.6496,23.9818],[120.6468,23.9634],[120.6442,23.9622]]]},"properties":{"name":"南投縣","county":"10008"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[120.6398,23.7144],[120.6402,23.7308],[120.6444,23.7366],[120.6558,23.735],[120.6546,23.7484],[120.6534,23.7606],[120.6478,23.7744],[120.6404,23.786],[120.6308,23.7896],[120.6168,23.791],[120.6154,23.7912],[120.6102,23.7912],[120.6096,23.7912],[120.6078,23.7912],[120.5938,23.791],[120.5866,23.792],[120.5836,23.7932],[120.551,23.8012],[120.5434,23.8012],[120.5364,23.8014],[120.528,23.799],[120.5262,23.7992],[120.5176,23.7998],[120.5134,23.8],[120.5122,23.8],[120.4998,23.8032],[120.4838,23.8064],[120.469,23.8116],[120.4668,23.8124],[120.465,23.8132],[120.4626,23.8142],[120.4614,23.8148],[120.458,23.8162],[120.4554,23.8166],[120.455,23.8168],[120.452,23.8172],[120.4474,23.8206],[120.4396,23.8268],[120.4162,23.8268],[120.4154,23.8268],[120.403,23.827],[120.3984,23.8272],[120.398,23.8274],[120.3888,23.828],[120.3818,23.8286],[120.3752,23.8286],[120.3602,23.8232],[120.3516,23.8224],[120.3506,23.8222],[120.3458,23.8222],[120.3426,23.8222],[120.3246,23.8212],[120.3088,23.8204],[120.302,23.8218],[120.3002,23.8224],[120.298,23.823],[120.2876,23.8256],[120.2712,23.8298],[120.2586,23.8332],[120.2438,23.8414],[120.2204,23.8662],[120.2076,23.8372],[120.157,23.7844],[120.1692,23.759],[120.1918,23.7636],[120.2038,23.7796],[120.1982,23.7568],[120.177,23.7474],[120.1752,23.7386],[120.17,23.7106],[120.1778,23.7016],[120.1534,23.6962],[120.1374,23.6764],[120.1294,23.656],[120.1286,23.6544],[120.124,23.6432],[120.1144,23.6328],[120.1372,23.6206],[120.1402,23.6132],[120.1446,23.5946],[120.1432,23.5714],[120.1396,23.5498],[120.149,23.5348],[120.1458,23.5208],[120.164,23.5158],[120.1764,23.5122],[120.1824,23.5098],[120.1902,23.5102],[120.2018,23.5112],[120.2044,23.5118],[120.214,23.5078],[120.2292,23.5052],[120.2386,23.5074],[120.2468,23.517],[120.2468,23.5178],[120.2448,23.528],[120.2428,23.5364],[120.2426,23.5428],[120.2574,23.5446],[120.2622,23.5352],[120.2726,23.5316],[120.275,23.5402],[120.277,23.544],[120.2908,23.5506],[120.29,23.5542],[120.3016,23.5638],[120.3032,23.5634],[120.3038,23.5634],[120.3058,23.563],[120.3106,23.5652],[120.3096,23.568],[120.3082,23.5696],[120.3076,23.5706],[120.307,23.5712],[120.3094,23.5748],[120.3288,23.5754],[120.3336,23.5892],[120.3352,23.593],[120.355,23.5936],[120.3602,23.5962],[120.3662,23.606],[120.3666,23.6078],[120.3678,23.6076],[120.3768,23.6098],[120.38,23.6102],[120.3886,23.6214],[120.3944,23.624],[120.4008,23.6322],[120.4064,23.6316],[120.4138,23.6224],[120.421,23.6238],[120.4242,23.6182],[120.431,23.6192],[120.449,23.6298],[120.4676,23.6302],[120.4686,23.6302],[120.4826,23.6322],[120.484,23.6316],[120.506,23.6338],[120.5068,23.6288],[120.5174,23.6118],[120.5334,23.5968],[120.5362,23.5954],[120.5606,23.5886],[120.5628,23.5894],[120.564,23.5896],[120.5896,23.5858],[120.6188,23.5842],[120.62,23.585],[120.6266,23.5904],[120.6476,23.5932],[120.6436,23.5766],[120.6462,23.5764],[120.6926,23.5764],[120.718,23.569],[120.7362,23.5704],[120.7246,23.6036],[120.7308,23.6108],[120.713,23.6278],[120.705,23.6172],[120.6828,23.6108],[120.6514,23.6162],[120.6326,23.6202],[120.6318,23.639],[120.635,23.6458],[120.6382,23.6584],[120.6396,23.6608],[120.6444,23.6684],[120.6466,23.6918],[120.6398,23.7144]]],[[[120.081,23.5242],[120.0004,23.473],[120.0044,23.4604],[120.0246,23.4602],[120.0298,23.4796],[120.0606,23.4796],[120.0686,23.5022],[120.0952,23.5154],[120.081,23.5242]]]]},"properties":{"name":"雲林縣","county":"10009"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.1626,23.31],[120.1734,23.3004],[120.184,23.2904],[120.1908,23.3008],[120.2118,23.2926],[120.2124,23.2918],[120.2282,23.3096],[120.2282,23.3098],[120.2362,23.3246],[120.2384,23.3272],[120.2468,23.3272],[120.252,23.3298],[120.263,23.3372],[120.2608,23.3444],[120.2662,23.3526],[120.2768,23.348],[120.2862,23.3502],[120.2846,23.3636],[120.3028,23.376],[120.3106,23.3778],[120.3112,23.3838],[120.3146,23.3884],[120.336,23.3886],[120.345,23.3998],[120.3558,23.4018],[120.3618,23.4028],[120.3786,23.4034],[120.3822,23.4038],[120.3868,23.4048],[120.3894,23.4056],[120.408,23.4134],[120.4186,23.406],[120.4196,23.4038],[120.4298,23.4064],[120.4304,23.4066],[120.4382,23.4134],[120.459,23.4048],[120.4794,23.3876],[120.4952,23.3932],[120.496,23.384],[120.501,23.3678],[120.51,23.3536],[120.5048,23.3462],[120.5338,23.3364],[120.5354,23.3236],[120.5226,23.3118],[120.522,23.2874],[120.521,23.2796],[120.5206,23.2716],[120.5322,23.2552],[120.5194,23.2396],[120.5548,23.2176],[120.5782,23.2148],[120.5926,23.2398],[120.6098,23.2228],[120.6282,23.2294],[120.6534,23.2246],[120.6492,23.247],[120.6394,23.2706],[120.652,23.2912],[120.6562,23.2934],[120.6946,23.2844],[120.7122,23.3088],[120.7302,23.3106],[120.7478,23.322],[120.7586,23.3372],[120.7832,23.3422],[120.8032,23.3696],[120.8046,23.3708],[120.8286,23.375],[120.8492,23.419],[120.8872,23.4352],[120.8968,23.4508],[120.9284,23.4568],[120.9576,23.4696],[120.9476,23.4672],[120.9144,23.4748],[120.8896,23.4756],[120.839,23.4712],[120.8228,23.4998],[120.8232,23.511],[120.8182,23.5234],[120.8086,23.5362],[120.8128,23.5514],[120.8196,23.561],[120.8204,23.5732],[120.8216,23.58],[120.817,23.5962],[120.8172,23.5964],[120.8138,23.601],[120.7796,23.6016],[120.753,23.6148],[120.7308,23.6108],[120.7246,23.6036],[120.7362,23.5704],[120.718,23.569],[120.6926,23.5764],[120.6462,23.5764],[120.6436,23.5766],[120.6476,23.5932],[120.6266,23.5904],[120.62,23.585],[120.6188,23.5842],[120.5896,23.5858],[120.564,23.5896],[120.5628,23.5894],[120.5606,23.5886],[120.5362,23.5954],[120.5334,23.5968],[120.5174,23.6118],[120.5068,23.6288],[120.506,23.6338],[120.484,23.6316],[120.4826,23.6322],[120.4686,23.6302],[120.4676,23.6302],[120.449,23.6298],[120.431,23.6192],[120.4242,23.6182],[120.421,23.6238],[120.4138,23.6224],[120.4064,23.6316],[120.4008,23.6322],[120.3944,23.624],[120.3886,23.6214],[120.38,23.6102],[120.3768,23.6098],[120.3678,23.6076],[120.3666,23.6078],[120.3662,23.606],[120.3602,23.5962],[120.355,23.5936],[120.3352,23.593],[120.3336,23.5892],[120.3288,23.5754],[120.3094,23.5748],[120.307,23.5712],[120.3076,23.5706],[120.3082,23.5696],[120.3096,23.568],[120.3106,23.5652],[120.3058,23.563],[120.3038,23.5634],[120.3032,23.5634],[120.3016,23.5638],[120.29,23.5542],[120.2908,23.5506],[120.277,23.544],[120.275,23.5402],[120.2726,23.5316],[120.2622,23.5352],[120.2574,23.5446],[120.2426,23.5428],[120.2428,23.5364],[120.2448,23.528],[120.2468,23.5178],[120.2468,23.517],[120.2386,23.5074],[120.2292,23.5052],[120.214,23.5078],[120.2044,23.5118],[120.2018,23.5112],[120.1902,23.5102],[120.1824,23.5098],[120.1764,23.5122],[120.164,23.5158],[120.1458,23.5208],[120.119,23.515],[120.1194,23.4954],[120.1336,23.4882],[120.1578,23.495],[120.1696,23.4912],[120.1558,23.484],[120.1456,23.4722],[120.1468,23.4654],[120.1448,23.4598],[120.1522,23.4548],[120.1554,23.4482],[120.1558,23.428],[120.16,23.4054],[120.158,23.384],[120.158,23.3798],[120.1554,23.377],[120.1552,23.3758],[120.1458,23.3732],[120.1256,23.3594],[120.118,23.3402],[120.1444,23.3228],[120.1528,23.3132],[120.1626,23.31]],[[120.4088,23.5066],[120.4084,23.4984],[120.4132,23.502],[120.4256,23.5074],[120.4338,23.5098],[120.4326,23.5134],[120.4408,23.5182],[120.4482,23.5182],[120.4534,23.5158],[120.4548,23.5158],[120.4616,23.5046],[120.4616,23.5044],[120.4626,23.5008],[120.4666,23.4988],[120.4832,23.5054],[120.4838,23.496],[120.4854,23.4942],[120.5014,23.4898],[120.5094,23.473],[120.5004,23.4604],[120.4952,23.4528],[120.488,23.4534],[120.4712,23.4618],[120.4686,23.4616],[120.4596,23.4544],[120.4496,23.4434],[120.4396,23.4396],[120.436,23.4442],[120.4326,23.4504],[120.4312,23.4516],[120.4292,23.461],[120.4244,23.4612],[120.422,23.461],[120.412,23.4646],[120.4014,23.4634],[120.3942,23.4626],[120.397,23.4802],[120.394,23.4876],[120.3944,23.4896],[120.39,23.4994],[120.4088,23.5066]]]},"properties":{"name":"嘉義縣","county":"10010"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[120.4352,22.6288],[120.4336,22.619],[120.4352,22.6122],[120.4408,22.605],[120.4424,22.6036],[120.4462,22.597],[120.4468,22.5934],[120.4468,22.5922],[120.4464,22.5834],[120.4452,22.577],[120.4444,22.5706],[120.4408,22.5576],[120.4398,22.5562],[120.4336,22.546],[120.4302,22.5416],[120.4274,22.5342],[120.4258,22.5306],[120.4236,22.5212],[120.4228,22.5178],[120.4256,22.4986],[120.4252,22.492],[120.4248,22.4888],[120.4244,22.4846],[120.4242,22.4824],[120.4244,22.4688],[120.4372,22.4654],[120.4456,22.4644],[120.4402,22.4648],[120.4462,22.4544],[120.4548,22.4488],[120.4822,22.43],[120.4968,22.4192],[120.5102,22.4118],[120.5176,22.409],[120.5402,22.3972],[120.546,22.3974],[120.5668,22.3848],[120.5848,22.3724],[120.594,22.364],[120.6054,22.3408],[120.6362,22.3128],[120.649,22.2752],[120.6492,22.2558],[120.673,22.2286],[120.6848,22.2102],[120.6888,22.1882],[120.698,22.1424],[120.709,22.1228],[120.7168,22.0932],[120.701,22.0796],[120.7054,22.0638],[120.7046,22.0556],[120.7018,22.0552],[120.6872,22.0328],[120.6924,22.0096],[120.7136,21.9806],[120.7126,21.9662],[120.7106,21.9342],[120.7286,21.9184],[120.74,21.9268],[120.7514,21.9508],[120.7702,21.9524],[120.783,21.9436],[120.8192,21.9348],[120.8512,21.8964],[120.8672,21.9028],[120.8626,21.9176],[120.8424,21.95],[120.8442,21.9794],[120.8532,21.989],[120.8758,21.9988],[120.8782,22.0108],[120.8972,22.0412],[120.893,22.0692],[120.902,22.1054],[120.8892,22.1158],[120.8866,22.1298],[120.897,22.144],[120.8908,22.1954],[120.899,22.2298],[120.8962,22.2464],[120.8664,22.2298],[120.8586,22.2408],[120.8372,22.2448],[120.8356,22.2454],[120.8166,22.2624],[120.7988,22.2606],[120.7886,22.294],[120.7968,22.3184],[120.7924,22.3304],[120.7856,22.3434],[120.768,22.3474],[120.7632,22.359],[120.7434,22.3672],[120.7538,22.405],[120.7804,22.4094],[120.7848,22.4288],[120.7822,22.4342],[120.7764,22.449],[120.7516,22.4584],[120.7644,22.4954],[120.7608,22.5034],[120.74,22.5584],[120.744,22.5696],[120.7542,22.6],[120.7612,22.6298],[120.7864,22.663],[120.7864,22.6722],[120.7868,22.6924],[120.8094,22.6884],[120.8368,22.697],[120.8488,22.717],[120.8836,22.717],[120.8912,22.729],[120.8922,22.764],[120.9034,22.7776],[120.9034,22.7998],[120.8912,22.8116],[120.8686,22.8168],[120.8646,22.843],[120.833,22.8662],[120.823,22.8658],[120.78,22.8354],[120.7742,22.838],[120.7622,22.8568],[120.7426,22.8736],[120.725,22.8808],[120.7038,22.8802],[120.6768,22.8572],[120.6612,22.8596],[120.649,22.877],[120.6476,22.8796],[120.6314,22.8802],[120.6204,22.8756],[120.6018,22.8702],[120.5952,22.8636],[120.5854,22.8564],[120.5714,22.845],[120.5666,22.8384],[120.5464,22.829],[120.5052,22.8314],[120.5004,22.8312],[120.4802,22.8376],[120.473,22.8354],[120.469,22.8286],[120.4674,22.8188],[120.4664,22.8142],[120.4558,22.7784],[120.4544,22.7718],[120.4542,22.7516],[120.4542,22.7506],[120.455,22.7388],[120.4556,22.7338],[120.4558,22.7196],[120.452,22.7022],[120.45,22.6944],[120.448,22.6894],[120.443,22.685],[120.4428,22.6848],[120.4396,22.672],[120.4378,22.667],[120.4362,22.6622],[120.436,22.6596],[120.436,22.6516],[120.4352,22.6398],[120.4354,22.6356],[120.4352,22.6288]]],[[[120.3796,22.356],[120.361,22.337],[120.3608,22.3366],[120.3552,22.323],[120.3688,22.3278],[120.3804,22.3378],[120.3876,22.351],[120.383,22.3534],[120.3796,22.356]]]]},"properties":{"name":"屏東縣","county":"10013"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[121.1936,22.819],[121.1874,22.8292],[121.192,22.8504],[121.209,22.8632],[121.2334,22.8644],[121.2472,22.8814],[121.2728,22.9178],[121.2828,22.9474],[121.3112,22.9744],[121.322,23.0018],[121.3364,23.0194],[121.3458,23.0516],[121.3582,23.086],[121.3872,23.1042],[121.4112,23.124],[121.3998,23.1356],[121.4076,23.1622],[121.3978,23.1896],[121.3962,23.2012],[121.41,23.2136],[121.4274,23.2724],[121.439,23.2964],[121.462,23.3126],[121.4678,23.3432],[121.4748,23.3866],[121.4818,23.397],[121.496,23.4348],[121.4472,23.4438],[121.4174,23.4128],[121.403,23.389],[121.4,23.3862],[121.4048,23.367],[121.423,23.3596],[121.4032,23.3362],[121.3998,23.3232],[121.3904,23.3206],[121.3778,23.2982],[121.3772,23.2836],[121.3778,23.2696],[121.3594,23.2528],[121.3568,23.2372],[121.3526,23.2312],[121.3466,23.2172],[121.3466,23.209],[121.3434,23.201],[121.335,23.178],[121.328,23.1792],[121.3174,23.1644],[121.3242,23.155],[121.322,23.1322],[121.3158,23.1098],[121.3034,23.1112],[121.2786,23.1012],[121.2644,23.1038],[121.256,23.1272],[121.2336,23.1356],[121.23,23.1396],[121.2296,23.1396],[121.212,23.1442],[121.1894,23.2038],[121.1756,23.2102],[121.154,23.199],[121.1398,23.2016],[121.1294,23.2234],[121.1088,23.2236],[121.0792,23.2328],[121.0624,23.2658],[121.0564,23.2904],[121.0282,23.2972],[120.986,23.2804],[120.9702,23.2806],[120.9378,23.245],[120.9154,23.2374],[120.9118,23.2282],[120.9064,23.1966],[120.9124,23.1868],[120.8958,23.1706],[120.8766,23.1508],[120.8878,23.1364],[120.8892,23.1004],[120.8692,23.06],[120.8796,23.048],[120.8634,23.0322],[120.8606,23.008],[120.8294,22.9752],[120.8302,22.9704],[120.821,22.961],[120.822,22.935],[120.8332,22.9122],[120.8286,22.9052],[120.842,22.8812],[120.8598,22.8784],[120.8694,22.858],[120.8646,22.843],[120.8686,22.8168],[120.8912,22.8116],[120.9034,22.7998],[120.9034,22.7776],[120.8922,22.764],[120.8912,22.729],[120.8836,22.717],[120.8488,22.717],[120.8368,22.697],[120.8094,22.6884],[120.7868,22.6924],[120.7864,22.6722],[120.7864,22.663],[120.7612,22.6298],[120.7542,22.6],[120.744,22.5696],[120.74,22.5584],[120.7608,22.5034],[120.7644,22.4954],[120.7516,22.4584],[120.7764,22.449],[120.7822,22.4342],[120.7848,22.4288],[120.7804,22.4094],[120.7538,22.405],[120.7434,22.3672],[120.7632,22.359],[120.768,22.3474],[120.7856,22.3434],[120.7924,22.3304],[120.7968,22.3184],[120.7886,22.294],[120.7988,22.2606],[120.8166,22.2624],[120.8356,22.2454],[120.8372,22.2448],[120.8586,22.2408],[120.8664,22.2298],[120.8962,22.2464],[120.8918,22.2916],[120.8946,22.3326],[120.8984,22.3426],[120.9098,22.3646],[120.9274,22.4142],[120.9466,22.4574],[120.9594,22.5048],[120.9686,22.528],[120.9786,22.5572],[120.9856,22.5694],[121.0094,22.5898],[121.0134,22.6216],[121.0176,22.6368],[121.0316,22.6636],[121.0466,22.673],[121.0654,22.6834],[121.0762,22.6946],[121.104,22.7066],[121.1284,22.7198],[121.1358,22.7278],[121.145,22.7344],[121.148,22.7384],[121.1548,22.7454],[121.1602,22.7492],[121.1778,22.762],[121.1814,22.783],[121.201,22.796],[121.1936,22.819]]],[[[121.478,22.6742],[121.4656,22.676],[121.4892,22.6416],[121.5088,22.6538],[121.51,22.677],[121.478,22.6742]]],[[[121.5664,22.0842],[121.5134,22.0804],[121.505,22.0848],[121.5108,22.0496],[121.5258,22.0372],[121.5386,22.0244],[121.5622,22.0174],[121.5698,22.004],[121.5884,21.9998],[121.603,22.0186],[121.568,22.0408],[121.5708,22.0648],[121.5664,22.0842]]]]},"properties":{"name":"臺東縣","county":"10014"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.6334,23.9876],[121.6364,23.993],[121.636,23.9976],[121.6478,24.009],[121.6416,24.0208],[121.6334,24.027],[121.6204,24.0496],[121.6162,24.0786],[121.6206,24.0928],[121.6464,24.1146],[121.6564,24.124],[121.6638,24.1346],[121.6584,24.1718],[121.6634,24.1942],[121.6928,24.2182],[121.717,24.2428],[121.744,24.2612],[121.7482,24.2798],[121.7696,24.3026],[121.774,24.3152],[121.7144,24.3268],[121.6874,24.3348],[121.631,24.3706],[121.6254,24.3688],[121.6202,24.3454],[121.6064,24.33],[121.607,24.3126],[121.56,24.3226],[121.556,24.3312],[121.5222,24.343],[121.4982,24.3392],[121.452,24.3646],[121.4356,24.3472],[121.435,24.3226],[121.4226,24.3078],[121.3804,24.2794],[121.3852,24.2552],[121.367,24.2522],[121.343,24.2236],[121.3492,24.1996],[121.3258,24.1962],[121.2982,24.1796],[121.2862,24.1774],[121.2828,24.1418],[121.3158,24.1164],[121.3228,24.0844],[121.3046,24.0684],[121.2832,24.0542],[121.2858,24.0398],[121.2766,24.0246],[121.26,23.9924],[121.2632,23.9788],[121.2778,23.966],[121.2746,23.9266],[121.2678,23.907],[121.2684,23.8838],[121.2528,23.8674],[121.2398,23.841],[121.235,23.8182],[121.2254,23.7982],[121.2284,23.7852],[121.2054,23.7712],[121.2132,23.7576],[121.2326,23.7506],[121.2296,23.7302],[121.2394,23.7244],[121.2408,23.7046],[121.2326,23.6762],[121.2354,23.6614],[121.2134,23.6002],[121.1946,23.6006],[121.178,23.5826],[121.1532,23.5866],[121.1604,23.5678],[121.1476,23.553],[121.147,23.5272],[121.135,23.515],[121.1204,23.521],[121.0922,23.5148],[121.0686,23.5184],[121.054,23.4902],[121.039,23.4744],[121.059,23.4618],[121.0518,23.4508],[121.0152,23.4354],[121.0292,23.4228],[121.0226,23.4002],[121.0078,23.3846],[120.9882,23.3706],[121.0104,23.3458],[121.0482,23.326],[121.0464,23.3092],[121.0282,23.2972],[121.0564,23.2904],[121.0624,23.2658],[121.0792,23.2328],[121.1088,23.2236],[121.1294,23.2234],[121.1398,23.2016],[121.154,23.199],[121.1756,23.2102],[121.1894,23.2038],[121.212,23.1442],[121.2296,23.1396],[121.23,23.1396],[121.2336,23.1356],[121.256,23.1272],[121.2644,23.1038],[121.2786,23.1012],[121.3034,23.1112],[121.3158,23.1098],[121.322,23.1322],[121.3242,23.155],[121.3174,23.1644],[121.328,23.1792],[121.335,23.178],[121.3434,23.201],[121.3466,23.209],[121.3466,23.2172],[121.3526,23.2312],[121.3568,23.2372],[121.3594,23.2528],[121.3778,23.2696],[121.3772,23.2836],[121.3778,23.2982],[121.3904,23.3206],[121.3998,23.3232],[121.4032,23.3362],[121.423,23.3596],[121.4048,23.367],[121.4,23.3862],[121.403,23.389],[121.4174,23.4128],[121.4472,23.4438],[121.496,23.4348],[121.5018,23.46],[121.514,23.4872],[121.5066,23.4916],[121.5044,23.5222],[121.5114,23.5516],[121.522,23.567],[121.5304,23.6132],[121.5358,23.6456],[121.5466,23.674],[121.5534,23.6984],[121.5492,23.7118],[121.5676,23.7462],[121.5708,23.7824],[121.5778,23.8122],[121.5982,23.857],[121.6118,23.9334],[121.6096,23.9442],[121.607,23.9528],[121.6096,23.963],[121.6112,23.9652],[121.6144,23.9702],[121.616,23.9734],[121.6176,23.975],[121.6214,23.9774],[121.6276,23.9826],[121.6334,23.9876]]]},"properties":{"name":"花蓮縣","county":"10015"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[119.5648,23.5626],[119.569,23.5652],[119.5694,23.566],[119.5736,23.5672],[119.5768,23.5658],[119.5796,23.5634],[119.5784,23.5622],[119.5794,23.5486],[119.5888,23.5514],[119.5932,23.5502],[119.6024,23.5472],[119.6032,23.5404],[119.5998,23.5312],[119.5948,23.5268],[119.58,23.5252],[119.5758,23.52],[119.5548,23.5304],[119.5568,23.538],[119.5508,23.5406],[119.5478,23.5516],[119.5414,23.5432],[119.548,23.5394],[119.5542,23.5302],[119.574,23.5178],[119.582,23.5092],[119.6056,23.5166],[119.6086,23.5298],[119.61,23.5324],[119.6144,23.538],[119.6346,23.551],[119.6404,23.557],[119.6546,23.5608],[119.67,23.5614],[119.6828,23.5684],[119.68,23.5862],[119.6782,23.5896],[119.6716,23.599],[119.6676,23.5912],[119.6642,23.5906],[119.6598,23.593],[119.6554,23.5984],[119.6484,23.594],[119.6338,23.592],[119.6282,23.5804],[119.6266,23.5804],[119.6262,23.5828],[119.6246,23.5912],[119.6178,23.6012],[119.6126,23.606],[119.6058,23.621],[119.598,23.6384],[119.6006,23.6458],[119.6066,23.649],[119.607,23.6576],[119.59,23.672],[119.5824,23.6776],[119.5564,23.6686],[119.5448,23.6466],[119.5358,23.639],[119.52,23.644],[119.5196,23.6478],[119.5244,23.6512],[119.524,23.6558],[119.518,23.6546],[119.5194,23.648],[119.5028,23.6316],[119.5088,23.6118],[119.5042,23.588],[119.5034,23.579],[119.4922,23.57],[119.4834,23.5754],[119.4796,23.564],[119.4942,23.5674],[119.5136,23.5726],[119.5128,23.5918],[119.5148,23.5944],[119.5232,23.6018],[119.5198,23.62],[119.5248,23.63],[119.5318,23.6322],[119.545,23.6464],[119.5708,23.662],[119.5814,23.6612],[119.5874,23.6476],[119.5888,23.6454],[119.595,23.6374],[119.592,23.6242],[119.6022,23.624],[119.6054,23.6204],[119.6122,23.606],[119.6048,23.602],[119.6072,23.5928],[119.6062,23.5852],[119.5974,23.5732],[119.5966,23.5692],[119.586,23.573],[119.5762,23.5858],[119.565,23.5798],[119.5674,23.5748],[119.5632,23.5718],[119.56,23.5674],[119.5648,23.5626]]],[[[119.5412,23.496],[119.5294,23.4958],[119.5288,23.4866],[119.5412,23.496]]],[[[119.5206,23.515],[119.5172,23.5148],[119.5144,23.51],[119.522,23.5102],[119.5206,23.515]]],[[[119.6124,23.756],[119.5974,23.7418],[119.6238,23.7436],[119.6124,23.756]]],[[[119.6644,23.6696],[119.6618,23.6636],[119.6664,23.662],[119.6644,23.6696]]],[[[119.6344,23.6514],[119.6316,23.6502],[119.6316,23.6464],[119.6362,23.648],[119.6344,23.6514]]],[[[119.5708,23.6178],[119.5698,23.6214],[119.567,23.6178],[119.5708,23.6178]]],[[[119.5078,23.364],[119.5082,23.372],[119.508,23.3904],[119.4924,23.3814],[119.4946,23.3662],[119.4974,23.3546],[119.5078,23.364]]],[[[119.5372,23.3752],[119.5332,23.367],[119.5426,23.3672],[119.5372,23.3752]]],[[[119.5198,23.2646],[119.514,23.2622],[119.5162,23.2566],[119.5196,23.2608],[119.5198,23.2646]]],[[[119.5068,23.2726],[119.505,23.2682],[119.511,23.2672],[119.511,23.2708],[119.5068,23.2726]]],[[[119.6774,23.264],[119.6668,23.2614],[119.6664,23.2502],[119.6782,23.2564],[119.6774,23.264]]],[[[119.3198,23.4116],[119.3148,23.3998],[119.3276,23.4008],[119.3198,23.4116]]],[[[119.4336,23.2204],[119.415,23.2162],[119.42,23.204],[119.4206,23.2004],[119.4324,23.1994],[119.4426,23.2054],[119.4336,23.2204]]]]},"properties":{"name":"澎湖縣","county":"10016"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[121.7428,25.1314],[121.7418,25.1306],[121.7404,25.1316],[121.7418,25.1354],[121.741,25.1402],[121.7422,25.1414],[121.7536,25.1452],[121.7492,25.1488],[121.743,25.1572],[121.7126,25.1656],[121.7092,25.165],[121.7096,25.1766],[121.691,25.166],[121.6828,25.1594],[121.6776,25.1558],[121.6692,25.1538],[121.6512,25.1472],[121.6402,25.1456],[121.6268,25.1396],[121.643,25.1278],[121.6518,25.098],[121.652,25.098],[121.6586,25.0916],[121.674,25.083],[121.6774,25.0858],[121.6812,25.0844],[121.681,25.077],[121.6888,25.0716],[121.699,25.068],[121.7002,25.0674],[121.7124,25.068],[121.7282,25.055],[121.7302,25.0534],[121.7476,25.0538],[121.7486,25.0554],[121.7624,25.057],[121.7756,25.07],[121.7592,25.084],[121.7584,25.0944],[121.759,25.101],[121.7568,25.102],[121.7576,25.103],[121.75,25.1096],[121.7518,25.111],[121.7716,25.118],[121.7736,25.1202],[121.7834,25.1166],[121.7856,25.1182],[121.795,25.1126],[121.7972,25.1142],[121.7946,25.1264],[121.803,25.122],[121.8028,25.1352],[121.8034,25.1362],[121.8056,25.1488],[121.795,25.1416],[121.7854,25.1462],[121.7692,25.1536],[121.7682,25.1528],[121.765,25.1512],[121.7614,25.1478],[121.7538,25.1412],[121.7496,25.1386],[121.7494,25.1384],[121.7478,25.1374],[121.7428,25.1314]]],[[[121.7662,25.1542],[121.7766,25.158],[121.7702,25.1604],[121.7676,25.162],[121.7622,25.1634],[121.7592,25.1546],[121.7642,25.1544],[121.7662,25.1542]]]]},"properties":{"name":"基隆市","county":"10017"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.007,24.8168],[120.999,24.8224],[120.9966,24.823],[120.991,24.824],[120.983,24.831],[120.9812,24.8312],[120.9712,24.8314],[120.963,24.8326],[120.953,24.836],[120.9448,24.841],[120.944,24.844],[120.9412,24.8492],[120.9316,24.8526],[120.9252,24.8548],[120.9158,24.8438],[120.912,24.8358],[120.9058,24.8284],[120.8992,24.814],[120.8966,24.8074],[120.8922,24.793],[120.8932,24.7802],[120.8978,24.7646],[120.8936,24.7616],[120.8878,24.7536],[120.8746,24.7384],[120.8938,24.7324],[120.9058,24.7406],[120.9124,24.7316],[120.9138,24.7172],[120.9222,24.7152],[120.9342,24.7132],[120.9354,24.7126],[120.945,24.7444],[120.9572,24.7484],[120.9608,24.751],[120.9708,24.7656],[120.9818,24.7672],[120.9878,24.7682],[120.9866,24.777],[121.01,24.7734],[121.0104,24.7732],[121.0136,24.7708],[121.0196,24.7584],[121.02,24.7574],[121.0264,24.7576],[121.0264,24.7808],[121.0266,24.7808],[121.023,24.7852],[121.0246,24.7886],[121.0214,24.8018],[121.0212,24.802],[121.0184,24.807],[121.0114,24.8126],[121.007,24.8168]],[[120.94,24.8138],[120.933,24.8082],[120.9288,24.8148],[120.9316,24.8238],[120.9316,24.832],[120.9372,24.8376],[120.9414,24.8352],[120.9486,24.8328],[120.9546,24.8284],[120.9524,24.821],[120.9484,24.8166],[120.94,24.8138]]]},"properties":{"name":"新竹市","county":"10018"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.4338,23.5098],[120.4256,23.5074],[120.4132,23.502],[120.4084,23.4984],[120.4088,23.5066],[120.39,23.4994],[120.3944,23.4896],[120.394,23.4876],[120.397,23.4802],[120.3942,23.4626],[120.4014,23.4634],[120.412,23.4646],[120.422,23.461],[120.4244,23.4612],[120.4292,23.461],[120.4312,23.4516],[120.4326,23.4504],[120.436,23.4442],[120.4396,23.4396],[120.4496,23.4434],[120.4596,23.4544],[120.4686,23.4616],[120.4712,23.4618],[120.488,23.4534],[120.4952,23.4528],[120.5004,23.4604],[120.5094,23.473],[120.5014,23.4898],[120.4854,23.4942],[120.4838,23.496],[120.4832,23.5054],[120.4666,23.4988],[120.4626,23.5008],[120.4616,23.5044],[120.4616,23.5046],[120.4548,23.5158],[120.4534,23.5158],[120.4482,23.5182],[120.4408,23.5182],[120.4326,23.5134],[120.4338,23.5098]]]},"properties":{"name":"嘉義市","county":"10020"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.5318,25.0086],[121.5326,25.0062],[121.531,24.9994],[121.5306,24.998],[121.5314,24.9954],[121.5318,24.9906],[121.5334,24.9922],[121.535,24.995],[121.537,24.991],[121.5398,24.9878],[121.5422,24.988],[121.5448,24.9838],[121.55,24.9844],[121.5506,24.987],[121.5528,24.9864],[121.5536,24.9832],[121.5532,24.9796],[121.5552,24.9764],[121.5598,24.9666],[121.5648,24.9642],[121.5786,24.9666],[121.5968,24.9606],[121.6092,24.964],[121.62,24.9692],[121.6172,24.9712],[121.5996,24.9778],[121.5984,24.995],[121.5994,25.0028],[121.596,25.0042],[121.596,25.0044],[121.5972,25.0144],[121.6158,25.0196],[121.6214,25.0178],[121.628,25.0196],[121.6402,25.0236],[121.6606,25.0234],[121.6634,25.023],[121.6658,25.03],[121.6502,25.0276],[121.6318,25.0356],[121.6234,25.0394],[121.6204,25.042],[121.6194,25.0432],[121.6164,25.0486],[121.6162,25.049],[121.6208,25.0548],[121.6242,25.0554],[121.6162,25.064],[121.618,25.0662],[121.6178,25.0676],[121.6206,25.0726],[121.6206,25.0732],[121.6276,25.0844],[121.6282,25.086],[121.626,25.0964],[121.6172,25.1014],[121.5994,25.1086],[121.5956,25.1142],[121.6044,25.1258],[121.6078,25.1302],[121.5894,25.1526],[121.5898,25.1638],[121.577,25.1672],[121.5832,25.1776],[121.5762,25.1954],[121.5592,25.2102],[121.5428,25.1894],[121.5358,25.1866],[121.5218,25.1792],[121.519,25.1694],[121.5028,25.1734],[121.4938,25.1614],[121.4922,25.16],[121.4868,25.151],[121.48,25.1464],[121.479,25.1456],[121.476,25.1424],[121.4708,25.1368],[121.4644,25.124],[121.4616,25.1234],[121.4588,25.123],[121.461,25.1162],[121.459,25.1128],[121.4578,25.1066],[121.4626,25.1032],[121.4842,25.0994],[121.4954,25.0912],[121.4986,25.0884],[121.5016,25.0844],[121.5034,25.0812],[121.5046,25.0782],[121.5066,25.0722],[121.507,25.0688],[121.5068,25.0656],[121.5066,25.0636],[121.5056,25.0604],[121.506,25.0568],[121.5062,25.054],[121.5046,25.0498],[121.502,25.0468],[121.5002,25.045],[121.4936,25.0428],[121.489,25.0428],[121.4852,25.0392],[121.4836,25.0354],[121.4842,25.0334],[121.4846,25.0324],[121.4866,25.0284],[121.4872,25.0274],[121.4876,25.027],[121.4886,25.0236],[121.4886,25.0218],[121.4884,25.0208],[121.4886,25.0192],[121.4886,25.0166],[121.4886,25.0158],[121.494,25.0092],[121.4954,25.0094],[121.5036,25.016],[121.506,25.0186],[121.5124,25.0218],[121.5162,25.0208],[121.5196,25.0194],[121.5206,25.0186],[121.5244,25.0136],[121.5274,25.0108],[121.5318,25.0086]]]},"properties":{"name":"臺北市","county":"63000"}}, +{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[120.2904,22.6188],[120.2924,22.6168],[120.292,22.616],[120.2914,22.615],[120.2966,22.6094],[120.2818,22.61],[120.2974,22.5846],[120.3068,22.5868],[120.3092,22.5718],[120.318,22.5612],[120.3276,22.5546],[120.331,22.5502],[120.3588,22.5326],[120.3222,22.5506],[120.3076,22.5452],[120.3218,22.5278],[120.3364,22.5256],[120.338,22.518],[120.3454,22.5134],[120.3542,22.5066],[120.359,22.5008],[120.3676,22.4956],[120.3766,22.4894],[120.3814,22.4868],[120.3918,22.4802],[120.3966,22.4766],[120.3982,22.4758],[120.4104,22.4708],[120.4142,22.4704],[120.4244,22.4688],[120.4242,22.4824],[120.4244,22.4846],[120.4248,22.4888],[120.4252,22.492],[120.4256,22.4986],[120.4228,22.5178],[120.4236,22.5212],[120.4258,22.5306],[120.4274,22.5342],[120.4302,22.5416],[120.4336,22.546],[120.4398,22.5562],[120.4408,22.5576],[120.4444,22.5706],[120.4452,22.577],[120.4464,22.5834],[120.4468,22.5922],[120.4468,22.5934],[120.4462,22.597],[120.4424,22.6036],[120.4408,22.605],[120.4352,22.6122],[120.4336,22.619],[120.4352,22.6288],[120.4354,22.6356],[120.4352,22.6398],[120.436,22.6516],[120.436,22.6596],[120.4362,22.6622],[120.4378,22.667],[120.4396,22.672],[120.4428,22.6848],[120.443,22.685],[120.448,22.6894],[120.45,22.6944],[120.452,22.7022],[120.4558,22.7196],[120.4556,22.7338],[120.455,22.7388],[120.4542,22.7506],[120.4542,22.7516],[120.4544,22.7718],[120.4558,22.7784],[120.4664,22.8142],[120.4674,22.8188],[120.469,22.8286],[120.473,22.8354],[120.4802,22.8376],[120.5004,22.8312],[120.5052,22.8314],[120.5464,22.829],[120.5666,22.8384],[120.5714,22.845],[120.5854,22.8564],[120.5952,22.8636],[120.6018,22.8702],[120.6204,22.8756],[120.6314,22.8802],[120.6476,22.8796],[120.649,22.877],[120.6612,22.8596],[120.6768,22.8572],[120.7038,22.8802],[120.725,22.8808],[120.7426,22.8736],[120.7622,22.8568],[120.7742,22.838],[120.78,22.8354],[120.823,22.8658],[120.833,22.8662],[120.8646,22.843],[120.8694,22.858],[120.8598,22.8784],[120.842,22.8812],[120.8286,22.9052],[120.8332,22.9122],[120.822,22.935],[120.821,22.961],[120.8302,22.9704],[120.8294,22.9752],[120.8606,23.008],[120.8634,23.0322],[120.8796,23.048],[120.8692,23.06],[120.8892,23.1004],[120.8878,23.1364],[120.8766,23.1508],[120.8958,23.1706],[120.9124,23.1868],[120.9064,23.1966],[120.9118,23.2282],[120.9154,23.2374],[120.9378,23.245],[120.9702,23.2806],[120.986,23.2804],[121.0282,23.2972],[121.0464,23.3092],[121.0482,23.326],[121.0104,23.3458],[120.9882,23.3706],[121.0078,23.3846],[121.0226,23.4002],[121.0292,23.4228],[121.0152,23.4354],[121.0158,23.4516],[120.9998,23.4622],[120.9668,23.4718],[120.9576,23.4696],[120.9284,23.4568],[120.8968,23.4508],[120.8872,23.4352],[120.8492,23.419],[120.8286,23.375],[120.8046,23.3708],[120.8032,23.3696],[120.7832,23.3422],[120.7586,23.3372],[120.7478,23.322],[120.7302,23.3106],[120.7122,23.3088],[120.6946,23.2844],[120.6562,23.2934],[120.652,23.2912],[120.6394,23.2706],[120.6492,23.247],[120.6534,23.2246],[120.6514,23.2084],[120.6366,23.1902],[120.6362,23.1752],[120.6166,23.1632],[120.5966,23.137],[120.5854,23.1106],[120.5758,23.0958],[120.5724,23.0888],[120.5414,23.0622],[120.5238,23.0502],[120.5118,23.0366],[120.5054,23.0306],[120.5022,23.0276],[120.499,23.0256],[120.4826,23.0156],[120.4798,23.0026],[120.4604,23.0034],[120.4554,22.9912],[120.4426,22.9774],[120.4364,22.961],[120.4352,22.9594],[120.4308,22.9486],[120.4294,22.9444],[120.4284,22.9404],[120.4088,22.9124],[120.3994,22.922],[120.3802,22.9184],[120.3724,22.9126],[120.3718,22.9108],[120.351,22.8882],[120.3344,22.8894],[120.3324,22.8892],[120.3172,22.8976],[120.3164,22.8984],[120.3028,22.9004],[120.2782,22.8962],[120.2748,22.8952],[120.2698,22.8966],[120.2588,22.8954],[120.251,22.8956],[120.2388,22.9044],[120.2304,22.9166],[120.226,22.9156],[120.222,22.9108],[120.2152,22.9102],[120.204,22.9148],[120.192,22.9212],[120.1878,22.9202],[120.1846,22.9184],[120.1776,22.913],[120.1748,22.9118],[120.1756,22.9076],[120.1766,22.906],[120.1786,22.9004],[120.179,22.8994],[120.1792,22.8986],[120.1798,22.8972],[120.18,22.896],[120.1806,22.8944],[120.1812,22.8934],[120.182,22.8918],[120.1828,22.89],[120.1848,22.8854],[120.1954,22.8502],[120.1982,22.8438],[120.2154,22.8034],[120.2204,22.7912],[120.2268,22.7774],[120.2326,22.7632],[120.2432,22.744],[120.2458,22.737],[120.2476,22.7332],[120.2492,22.73],[120.2496,22.7288],[120.2564,22.7186],[120.2572,22.7138],[120.2748,22.7048],[120.2714,22.688],[120.2576,22.6688],[120.25,22.6508],[120.266,22.6186],[120.2696,22.6238],[120.2698,22.623],[120.27,22.6202],[120.2762,22.619],[120.28,22.6196],[120.2844,22.6182],[120.286,22.6174],[120.2904,22.6188]],[[120.2654,22.7702],[120.2588,22.7702],[120.255,22.7826],[120.2536,22.7868],[120.2524,22.7896],[120.2564,22.7954],[120.2614,22.797],[120.2648,22.7988],[120.2684,22.7908],[120.2682,22.7822],[120.2652,22.7748],[120.2654,22.7702]]],[[[120.2644,22.6114],[120.266,22.6092],[120.266,22.609],[120.2654,22.6068],[120.2672,22.5988],[120.2684,22.5968],[120.2732,22.5906],[120.2828,22.5804],[120.2898,22.5732],[120.3072,22.553],[120.3176,22.5554],[120.3032,22.5722],[120.3012,22.5736],[120.2982,22.5772],[120.2916,22.5866],[120.282,22.5966],[120.2786,22.6024],[120.273,22.6094],[120.2712,22.6124],[120.2694,22.6142],[120.2644,22.6114]]]]},"properties":{"name":"高雄市","county":"64000"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.4122,25.0194],[121.409,25.0182],[121.4044,25.0172],[121.4042,25.0172],[121.3976,25.0162],[121.4,25.0058],[121.4032,24.9996],[121.3942,24.9936],[121.384,24.9954],[121.3856,24.9864],[121.3826,24.9842],[121.369,24.9768],[121.3668,24.978],[121.3542,24.9778],[121.3426,24.9824],[121.3414,24.9806],[121.339,24.9806],[121.33,24.9792],[121.3298,24.979],[121.324,24.9714],[121.3258,24.9714],[121.3282,24.9726],[121.3288,24.9694],[121.3284,24.9658],[121.329,24.9604],[121.3288,24.9578],[121.328,24.9552],[121.3302,24.9444],[121.3244,24.9434],[121.3158,24.9384],[121.3274,24.929],[121.3398,24.9284],[121.3176,24.9164],[121.3262,24.9086],[121.3324,24.8998],[121.3528,24.8768],[121.3538,24.8724],[121.345,24.867],[121.3452,24.8668],[121.3524,24.849],[121.3358,24.845],[121.3468,24.8458],[121.3728,24.8338],[121.3876,24.842],[121.4088,24.8406],[121.43,24.815],[121.4382,24.7954],[121.4504,24.791],[121.4506,24.7906],[121.4506,24.7902],[121.4234,24.7632],[121.4336,24.736],[121.4504,24.7056],[121.4742,24.6962],[121.48,24.6738],[121.4928,24.6732],[121.5244,24.6838],[121.5368,24.6884],[121.5432,24.7056],[121.587,24.7202],[121.5968,24.7292],[121.59,24.7518],[121.5976,24.7726],[121.5922,24.7878],[121.6014,24.7886],[121.6236,24.7944],[121.63,24.809],[121.6688,24.8168],[121.6894,24.8174],[121.6978,24.8342],[121.7076,24.8388],[121.711,24.8412],[121.7326,24.8558],[121.7464,24.8532],[121.7474,24.8538],[121.777,24.8694],[121.7858,24.8908],[121.7934,24.8998],[121.822,24.9042],[121.832,24.905],[121.8538,24.928],[121.8398,24.9422],[121.8456,24.9592],[121.8612,24.9636],[121.8884,24.9632],[121.9076,24.9758],[121.9156,24.9794],[121.9186,24.9788],[121.9436,24.9872],[121.9604,24.9882],[121.966,24.983],[121.9838,24.9906],[122.007,25.0108],[121.999,25.0196],[121.9692,25.0248],[121.9472,25.021],[121.9308,25.0384],[121.9306,25.053],[121.9166,25.076],[121.9144,25.0898],[121.9266,25.1082],[121.9226,25.1224],[121.8948,25.1204],[121.8732,25.1248],[121.8646,25.1238],[121.8594,25.1248],[121.8418,25.1288],[121.8278,25.1222],[121.8192,25.1294],[121.8034,25.1362],[121.8028,25.1352],[121.803,25.122],[121.7946,25.1264],[121.7972,25.1142],[121.795,25.1126],[121.7856,25.1182],[121.7834,25.1166],[121.7736,25.1202],[121.7716,25.118],[121.7518,25.111],[121.75,25.1096],[121.7576,25.103],[121.7568,25.102],[121.759,25.101],[121.7584,25.0944],[121.7592,25.084],[121.7756,25.07],[121.7624,25.057],[121.7486,25.0554],[121.7476,25.0538],[121.7302,25.0534],[121.7282,25.055],[121.7124,25.068],[121.7002,25.0674],[121.699,25.068],[121.6888,25.0716],[121.681,25.077],[121.6812,25.0844],[121.6774,25.0858],[121.674,25.083],[121.6586,25.0916],[121.652,25.098],[121.6518,25.098],[121.643,25.1278],[121.6268,25.1396],[121.6402,25.1456],[121.6512,25.1472],[121.6692,25.1538],[121.6776,25.1558],[121.6828,25.1594],[121.691,25.166],[121.7096,25.1766],[121.689,25.1842],[121.6956,25.2032],[121.6706,25.2028],[121.6582,25.2112],[121.6502,25.2228],[121.6526,25.227],[121.641,25.232],[121.6356,25.2528],[121.6208,25.2758],[121.6048,25.2856],[121.5876,25.293],[121.5854,25.2944],[121.5656,25.2932],[121.5578,25.2922],[121.5474,25.2918],[121.5458,25.2924],[121.5268,25.2864],[121.5076,25.2828],[121.4934,25.2762],[121.4764,25.2648],[121.4734,25.2582],[121.4526,25.2528],[121.4458,25.2418],[121.4444,25.2356],[121.44,25.2258],[121.4316,25.2162],[121.4268,25.2102],[121.4188,25.1988],[121.4186,25.1778],[121.4174,25.1756],[121.41,25.1662],[121.4008,25.1598],[121.3896,25.1476],[121.3658,25.1396],[121.3468,25.1298],[121.33,25.1252],[121.318,25.124],[121.2834,25.1178],[121.2918,25.1026],[121.302,25.0976],[121.3252,25.0924],[121.3334,25.0866],[121.3366,25.085],[121.3548,25.0654],[121.3552,25.0652],[121.3638,25.065],[121.3684,25.0652],[121.3686,25.0652],[121.3774,25.066],[121.3802,25.0652],[121.3834,25.0628],[121.3874,25.0552],[121.3912,25.0536],[121.403,25.0454],[121.3918,25.0426],[121.401,25.0342],[121.3986,25.0314],[121.4012,25.0266],[121.4104,25.021],[121.4122,25.0194]],[[121.4872,25.0274],[121.4866,25.0284],[121.4846,25.0324],[121.4842,25.0334],[121.4836,25.0354],[121.4852,25.0392],[121.472,25.0394],[121.4662,25.0386],[121.4664,25.0412],[121.471,25.0432],[121.476,25.0454],[121.4784,25.0522],[121.477,25.056],[121.4656,25.0656],[121.4698,25.0686],[121.4702,25.0684],[121.4794,25.0616],[121.4814,25.0578],[121.4826,25.0554],[121.4844,25.0518],[121.485,25.051],[121.4934,25.0516],[121.4948,25.0528],[121.4972,25.0548],[121.501,25.0578],[121.5018,25.0586],[121.504,25.063],[121.5044,25.064],[121.5046,25.0672],[121.5044,25.069],[121.504,25.0704],[121.5036,25.072],[121.5028,25.0746],[121.5018,25.0774],[121.4986,25.0828],[121.4984,25.0834],[121.4982,25.0838],[121.4974,25.0848],[121.4962,25.0862],[121.4956,25.087],[121.4886,25.0922],[121.4896,25.0934],[121.4766,25.0978],[121.4666,25.0994],[121.4612,25.0996],[121.4626,25.1032],[121.4578,25.1066],[121.459,25.1128],[121.461,25.1162],[121.4588,25.123],[121.4542,25.1398],[121.4462,25.158],[121.4516,25.1598],[121.4576,25.1422],[121.4578,25.1378],[121.4578,25.135],[121.4582,25.1306],[121.4616,25.1234],[121.4644,25.124],[121.4708,25.1368],[121.476,25.1424],[121.479,25.1456],[121.48,25.1464],[121.4868,25.151],[121.4922,25.16],[121.4938,25.1614],[121.5028,25.1734],[121.519,25.1694],[121.5218,25.1792],[121.5358,25.1866],[121.5428,25.1894],[121.5592,25.2102],[121.5762,25.1954],[121.5832,25.1776],[121.577,25.1672],[121.5898,25.1638],[121.5894,25.1526],[121.6078,25.1302],[121.6044,25.1258],[121.5956,25.1142],[121.5994,25.1086],[121.6172,25.1014],[121.626,25.0964],[121.6282,25.086],[121.6276,25.0844],[121.6206,25.0732],[121.6206,25.0726],[121.6178,25.0676],[121.618,25.0662],[121.6162,25.064],[121.6242,25.0554],[121.6208,25.0548],[121.6162,25.049],[121.6164,25.0486],[121.6194,25.0432],[121.6204,25.042],[121.6234,25.0394],[121.6318,25.0356],[121.6502,25.0276],[121.6658,25.03],[121.6634,25.023],[121.6606,25.0234],[121.6402,25.0236],[121.628,25.0196],[121.6214,25.0178],[121.6158,25.0196],[121.5972,25.0144],[121.596,25.0044],[121.596,25.0042],[121.5994,25.0028],[121.5984,24.995],[121.5996,24.9778],[121.6172,24.9712],[121.62,24.9692],[121.6092,24.964],[121.5968,24.9606],[121.5786,24.9666],[121.5648,24.9642],[121.5598,24.9666],[121.5552,24.9764],[121.5532,24.9796],[121.5536,24.9832],[121.5528,24.9864],[121.5506,24.987],[121.55,24.9844],[121.5448,24.9838],[121.5422,24.988],[121.5398,24.9878],[121.537,24.991],[121.535,24.995],[121.5334,24.9922],[121.5318,24.9906],[121.5314,24.9954],[121.5282,24.9954],[121.5286,24.9978],[121.5288,24.9988],[121.5288,25.0018],[121.5272,25.0058],[121.5252,25.0088],[121.525,25.009],[121.524,25.0104],[121.5218,25.0138],[121.5204,25.0154],[121.52,25.016],[121.5188,25.017],[121.5154,25.0182],[121.5126,25.0182],[121.5116,25.018],[121.5076,25.0162],[121.5068,25.0154],[121.5046,25.0134],[121.4984,25.0088],[121.494,25.0092],[121.4886,25.0158],[121.4886,25.0166],[121.4886,25.0192],[121.4884,25.0208],[121.4886,25.0218],[121.4886,25.0236],[121.4876,25.027],[121.4872,25.0274]]]},"properties":{"name":"新北市","county":"65000"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.8174,24.3076],[120.8114,24.3118],[120.7778,24.3206],[120.7646,24.3258],[120.7546,24.3318],[120.7244,24.354],[120.7182,24.3558],[120.7164,24.3562],[120.7072,24.3578],[120.6916,24.3696],[120.6786,24.387],[120.6642,24.4016],[120.66,24.405],[120.658,24.4068],[120.643,24.4168],[120.6396,24.4278],[120.6328,24.432],[120.6218,24.4402],[120.6146,24.4292],[120.6114,24.4268],[120.5972,24.4064],[120.5912,24.4004],[120.5836,24.3898],[120.5792,24.384],[120.5704,24.3698],[120.569,24.3666],[120.5624,24.3608],[120.5592,24.3514],[120.5516,24.334],[120.548,24.313],[120.546,24.3078],[120.5282,24.3138],[120.5186,24.3054],[120.5266,24.284],[120.5226,24.2814],[120.525,24.2774],[120.5238,24.265],[120.5214,24.2618],[120.5212,24.261],[120.5108,24.2614],[120.51,24.261],[120.5094,24.2596],[120.5042,24.2328],[120.5038,24.2322],[120.4826,24.2368],[120.4688,24.2144],[120.4566,24.2072],[120.507,24.1882],[120.508,24.1874],[120.5126,24.177],[120.5174,24.1658],[120.5198,24.1614],[120.5226,24.1554],[120.523,24.1546],[120.5248,24.1432],[120.5236,24.1414],[120.5312,24.1284],[120.5368,24.1248],[120.5434,24.1194],[120.545,24.1168],[120.5496,24.114],[120.5562,24.1126],[120.5628,24.1108],[120.566,24.1098],[120.5818,24.1096],[120.5832,24.1096],[120.5964,24.105],[120.6018,24.1038],[120.6026,24.103],[120.6124,24.1024],[120.6158,24.083],[120.6252,24.0694],[120.6256,24.062],[120.6258,24.0468],[120.6264,24.0298],[120.6266,24.0298],[120.6322,24.0304],[120.652,24.0286],[120.6556,24.0306],[120.6764,24.0156],[120.6786,24.014],[120.691,24.0084],[120.7036,24.0056],[120.7086,24.006],[120.7318,24.009],[120.7482,23.9998],[120.7704,24.0104],[120.7796,24.02],[120.7818,24.0228],[120.7864,24.0294],[120.7916,24.0352],[120.7966,24.0404],[120.8154,24.069],[120.8292,24.0742],[120.8286,24.0946],[120.8378,24.1178],[120.8726,24.1168],[120.8814,24.1006],[120.8786,24.0852],[120.8916,24.0986],[120.8962,24.1164],[120.9142,24.1078],[120.9318,24.1122],[120.951,24.1276],[120.957,24.1242],[120.9874,24.1196],[120.9986,24.127],[121.0154,24.156],[121.0476,24.16],[121.0526,24.1548],[121.0914,24.1828],[121.1012,24.1946],[121.1034,24.1958],[121.1354,24.1962],[121.1478,24.2128],[121.1676,24.2254],[121.1808,24.2122],[121.2032,24.2218],[121.2198,24.2292],[121.238,24.2198],[121.2604,24.2454],[121.2858,24.2292],[121.3112,24.235],[121.343,24.2236],[121.367,24.2522],[121.3852,24.2552],[121.3804,24.2794],[121.4226,24.3078],[121.435,24.3226],[121.4356,24.3472],[121.452,24.3646],[121.437,24.383],[121.4018,24.3796],[121.3736,24.3682],[121.3648,24.389],[121.3384,24.39],[121.325,24.407],[121.328,24.434],[121.3176,24.4416],[121.3058,24.4326],[121.2602,24.429],[121.2438,24.42],[121.2436,24.4058],[121.2314,24.3838],[121.2134,24.382],[121.2036,24.3976],[121.1746,24.3738],[121.168,24.3608],[121.141,24.3596],[121.1254,24.342],[121.0866,24.3176],[121.0816,24.324],[121.0556,24.3106],[121.0384,24.2964],[121.02,24.3092],[121.0058,24.3306],[120.991,24.3298],[120.9378,24.3418],[120.917,24.3358],[120.9222,24.3028],[120.9098,24.294],[120.9058,24.2926],[120.8748,24.2948],[120.8502,24.2886],[120.8324,24.2914],[120.825,24.2972],[120.8232,24.2992],[120.8174,24.3076]],[[120.6428,24.2706],[120.6416,24.266],[120.6332,24.2592],[120.61,24.2656],[120.6064,24.2666],[120.6136,24.2828],[120.6218,24.2904],[120.6288,24.2902],[120.6302,24.2702],[120.6428,24.2706]]]},"properties":{"name":"臺中市","county":"66000"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[120.2608,23.3444],[120.263,23.3372],[120.252,23.3298],[120.2468,23.3272],[120.2384,23.3272],[120.2362,23.3246],[120.2282,23.3098],[120.2282,23.3096],[120.2124,23.2918],[120.2118,23.2926],[120.1908,23.3008],[120.184,23.2904],[120.1734,23.3004],[120.1626,23.31],[120.1528,23.3132],[120.1444,23.3228],[120.118,23.3402],[120.1108,23.3104],[120.0958,23.2982],[120.095,23.2816],[120.095,23.2804],[120.0922,23.26],[120.0832,23.2412],[120.0816,23.2204],[120.0798,23.2082],[120.0694,23.1834],[120.0634,23.1706],[120.0556,23.1362],[120.053,23.1314],[120.0422,23.1154],[120.0278,23.0752],[120.0626,23.044],[120.109,23.0196],[120.1106,23.0186],[120.1394,22.9974],[120.1482,22.9866],[120.1554,22.9654],[120.1706,22.9526],[120.1738,22.9428],[120.1748,22.9356],[120.175,22.9298],[120.1748,22.9262],[120.174,22.9224],[120.1748,22.9118],[120.1776,22.913],[120.1846,22.9184],[120.1878,22.9202],[120.192,22.9212],[120.204,22.9148],[120.2152,22.9102],[120.222,22.9108],[120.226,22.9156],[120.2304,22.9166],[120.2388,22.9044],[120.251,22.8956],[120.2588,22.8954],[120.2698,22.8966],[120.2748,22.8952],[120.2782,22.8962],[120.3028,22.9004],[120.3164,22.8984],[120.3172,22.8976],[120.3324,22.8892],[120.3344,22.8894],[120.351,22.8882],[120.3718,22.9108],[120.3724,22.9126],[120.3802,22.9184],[120.3994,22.922],[120.4088,22.9124],[120.4284,22.9404],[120.4294,22.9444],[120.4308,22.9486],[120.4352,22.9594],[120.4364,22.961],[120.4426,22.9774],[120.4554,22.9912],[120.4604,23.0034],[120.4798,23.0026],[120.4826,23.0156],[120.499,23.0256],[120.5022,23.0276],[120.5054,23.0306],[120.5118,23.0366],[120.5238,23.0502],[120.5414,23.0622],[120.5724,23.0888],[120.5758,23.0958],[120.5854,23.1106],[120.5966,23.137],[120.6166,23.1632],[120.6362,23.1752],[120.6366,23.1902],[120.6514,23.2084],[120.6534,23.2246],[120.6282,23.2294],[120.6098,23.2228],[120.5926,23.2398],[120.5782,23.2148],[120.5548,23.2176],[120.5194,23.2396],[120.5322,23.2552],[120.5206,23.2716],[120.521,23.2796],[120.522,23.2874],[120.5226,23.3118],[120.5354,23.3236],[120.5338,23.3364],[120.5048,23.3462],[120.51,23.3536],[120.501,23.3678],[120.496,23.384],[120.4952,23.3932],[120.4794,23.3876],[120.459,23.4048],[120.4382,23.4134],[120.4304,23.4066],[120.4298,23.4064],[120.4196,23.4038],[120.4186,23.406],[120.408,23.4134],[120.3894,23.4056],[120.3868,23.4048],[120.3822,23.4038],[120.3786,23.4034],[120.3618,23.4028],[120.3558,23.4018],[120.345,23.3998],[120.336,23.3886],[120.3146,23.3884],[120.3112,23.3838],[120.3106,23.3778],[120.3028,23.376],[120.2846,23.3636],[120.2862,23.3502],[120.2768,23.348],[120.2662,23.3526],[120.2608,23.3444]]]},"properties":{"name":"臺南市","county":"67000"}}, +{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[121.3298,24.979],[121.33,24.9792],[121.339,24.9806],[121.3414,24.9806],[121.3426,24.9824],[121.3542,24.9778],[121.3668,24.978],[121.369,24.9768],[121.3826,24.9842],[121.3856,24.9864],[121.384,24.9954],[121.3942,24.9936],[121.4032,24.9996],[121.4,25.0058],[121.3976,25.0162],[121.4042,25.0172],[121.4044,25.0172],[121.409,25.0182],[121.4122,25.0194],[121.4104,25.021],[121.4012,25.0266],[121.3986,25.0314],[121.401,25.0342],[121.3918,25.0426],[121.403,25.0454],[121.3912,25.0536],[121.3874,25.0552],[121.3834,25.0628],[121.3802,25.0652],[121.3774,25.066],[121.3686,25.0652],[121.3684,25.0652],[121.3638,25.065],[121.3552,25.0652],[121.3548,25.0654],[121.3366,25.085],[121.3334,25.0866],[121.3252,25.0924],[121.302,25.0976],[121.2918,25.1026],[121.2834,25.1178],[121.2748,25.119],[121.2484,25.1196],[121.207,25.1072],[121.1872,25.0972],[121.1722,25.0918],[121.155,25.0838],[121.1318,25.078],[121.1204,25.075],[121.0968,25.0646],[121.094,25.0628],[121.0696,25.0498],[121.0576,25.0468],[121.0404,25.0324],[121.0196,25.0074],[121.0172,24.9984],[121.0098,24.9894],[121.01,24.975],[120.996,24.9568],[120.982,24.94],[120.9902,24.9358],[121.001,24.9402],[121.007,24.9462],[121.0242,24.941],[121.034,24.9448],[121.0462,24.9424],[121.0584,24.9368],[121.0576,24.9306],[121.0592,24.9272],[121.0604,24.9186],[121.0576,24.906],[121.0606,24.9036],[121.0922,24.8934],[121.109,24.8978],[121.122,24.8802],[121.1254,24.8802],[121.1438,24.881],[121.1582,24.8754],[121.1572,24.8722],[121.1614,24.8594],[121.15,24.8444],[121.1756,24.8322],[121.1738,24.8276],[121.1792,24.8264],[121.1962,24.818],[121.2028,24.81],[121.2216,24.7996],[121.226,24.8016],[121.2342,24.8042],[121.2432,24.8088],[121.2512,24.7944],[121.2774,24.771],[121.2932,24.7654],[121.3012,24.7632],[121.3076,24.7552],[121.2982,24.7332],[121.3076,24.7198],[121.3032,24.693],[121.3266,24.6936],[121.3532,24.6664],[121.3524,24.6436],[121.3658,24.6318],[121.3588,24.6174],[121.3728,24.5938],[121.3914,24.5864],[121.403,24.5918],[121.4162,24.6022],[121.4354,24.6222],[121.4594,24.6732],[121.48,24.6738],[121.4742,24.6962],[121.4504,24.7056],[121.4336,24.736],[121.4234,24.7632],[121.4506,24.7902],[121.4506,24.7906],[121.4504,24.791],[121.4382,24.7954],[121.43,24.815],[121.4088,24.8406],[121.3876,24.842],[121.3728,24.8338],[121.3468,24.8458],[121.3358,24.845],[121.3524,24.849],[121.3452,24.8668],[121.345,24.867],[121.3538,24.8724],[121.3528,24.8768],[121.3324,24.8998],[121.3262,24.9086],[121.3176,24.9164],[121.3398,24.9284],[121.3274,24.929],[121.3158,24.9384],[121.3244,24.9434],[121.3302,24.9444],[121.328,24.9552],[121.3288,24.9578],[121.329,24.9604],[121.3284,24.9658],[121.3288,24.9694],[121.3282,24.9726],[121.3258,24.9714],[121.324,24.9714],[121.3298,24.979]]]},"properties":{"name":"桃園市","county":"68000"}} +]} \ No newline at end of file diff --git a/web/scripts/build-map-context.mjs b/web/scripts/build-map-context.mjs new file mode 100644 index 0000000..418b63d --- /dev/null +++ b/web/scripts/build-map-context.mjs @@ -0,0 +1,29 @@ +// 產生全台縣市界線(簡化),給開始畫面選縣市、以及各縣市地圖周邊的底圖用;不含任何選舉資料。 +// 來源:後端全國資料包的鄉鎮界線(內政部國土測繪中心,政府資料開放授權條款)。 +// 執行:node scripts/build-map-context.mjs +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const backend = fileURLToPath(new URL("../../backend/", import.meta.url)); +const out = fileURLToPath(new URL("../public/maps/taiwan-counties.json", import.meta.url)); +const NAMES = { + "63000": "臺北市", "64000": "高雄市", "65000": "新北市", "66000": "臺中市", "67000": "臺南市", "68000": "桃園市", + "10002": "宜蘭縣", "10004": "新竹縣", "10005": "苗栗縣", "10007": "彰化縣", "10008": "南投縣", "10009": "雲林縣", + "10010": "嘉義縣", "10013": "屏東縣", "10014": "臺東縣", "10015": "花蓮縣", "10016": "澎湖縣", "10017": "基隆市", + "10018": "新竹市", "10020": "嘉義市", "09007": "連江縣", "09020": "金門縣", +}; + +execFileSync( + "npx", + [ + "mapshaper", + "-i", "data/build/packs/00000/topology.json", + "-target", "towns", + "-each", `county=townCode.slice(0,5), name=(${JSON.stringify(NAMES)})[townCode.slice(0,5)] || ''`, + "-filter", "name !== ''", + "-dissolve", "county", "copy-fields=name", + "-simplify", "2.5%", "keep-shapes", + "-o", out, "format=geojson", "precision=0.0002", + ], + { cwd: backend, stdio: "inherit" }, +); diff --git a/web/scripts/sync-fixtures.mjs b/web/scripts/sync-fixtures.mjs new file mode 100644 index 0000000..6dea752 --- /dev/null +++ b/web/scripts/sync-fixtures.mjs @@ -0,0 +1,22 @@ +// 從後端複製已產出的資料包到 public/fixtures,前端開發時不需要跑整套後端(docs/16)。 +// 用法:pnpm sync-fixtures [縣市代碼...](預設 68000) +import { cpSync, existsSync, mkdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const backendPacks = process.env.BACKEND_PACKS ?? join(root, "..", "backend", "data", "build", "packs"); +const counties = process.argv.slice(2).length ? process.argv.slice(2) : ["68000"]; + +for (const county of counties) { + const src = join(backendPacks, county); + if (!existsSync(src)) { + process.stderr.write(`找不到 ${src};請先在後端執行 election-data pack --county ${county}\n`); + process.exitCode = 1; + continue; + } + const dest = join(root, "public", "fixtures", "packs", county); + mkdirSync(dest, { recursive: true }); + cpSync(src, dest, { recursive: true, filter: (p) => !p.endsWith("report.md") }); + process.stdout.write(`已複製 ${county} → ${dest}\n`); +} diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 0000000..a1b8036 --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,66 @@ +import { lazy, Suspense, useEffect, useState } from "react"; +import { HomeScreen } from "./game/home/HomeScreen.tsx"; +import { RogueScreen } from "./game/rogue/RogueScreen.tsx"; +import "./game/game.css"; +import "./game/art/art.css"; +import "./game/screens.css"; +import "./theme/campaign.css"; + +// 首頁和選戰卡牌一開始就載入;捏人物、圖鑑、政治生涯、資料檢視器等用到才下載,手機開首頁比較快 +const DataViewer = lazy(() => import("./viewer/DataViewer.tsx").then((m) => ({ default: m.DataViewer }))); +const ArtGallery = lazy(() => import("./game/art/ArtGallery.tsx").then((m) => ({ default: m.ArtGallery }))); +const FaceGallery = lazy(() => import("./game/art/FaceGallery.tsx").then((m) => ({ default: m.FaceGallery }))); +const CreatorScreen = lazy(() => import("./game/creator/CreatorScreen.tsx").then((m) => ({ default: m.CreatorScreen }))); +const RogueCollection = lazy(() => import("./game/rogue/Collection.tsx").then((m) => ({ default: m.RogueCollection }))); +const RogueCareer = lazy(() => import("./game/rogue/Career.tsx").then((m) => ({ default: m.RogueCareer }))); +const IslandScreen = lazy(() => import("./game/island/IslandScreen.tsx").then((m) => ({ default: m.IslandScreen }))); +const MiniGameLobby = lazy(() => import("./game/minigames/MiniGameLobby.tsx").then((m) => ({ default: m.MiniGameLobby }))); +const PeopleScreen = lazy(() => import("./game/people/PeopleScreen.tsx").then((m) => ({ default: m.PeopleScreen }))); +const TermPreview = lazy(() => import("./game/career/term/TermPreview.tsx").then((m) => ({ default: m.TermPreview }))); +const ShopScreen = lazy(() => import("./game/shop/ShopScreen.tsx").then((m) => ({ default: m.ShopScreen }))); +const AvatarCheck = lazy(() => import("./game/art/AvatarCheck.tsx").then((m) => ({ default: m.AvatarCheck }))); + +function useHash(): string { + const [hash, setHash] = useState(location.hash); + useEffect(() => { + const update = () => setHash(location.hash); + addEventListener("hashchange", update); + return () => removeEventListener("hashchange", update); + }, []); + return hash; +} + +/** + * 簡單的 hash 路由:#/ 首頁(選戰卡牌)、#/rogue 選戰卡牌大廳、#/rogue/:id 一局、#/rogue/career 政治生涯、#/rogue/collection 圖鑑與成就、 + * #/create 捏人物、#/shop 服裝店(小鎮幣買外觀)、#/avatar-check 頭像部件檢查頁、#/viewer 資料檢視器、#/island 政策島(#/island/workshop 政策工坊)、#/minigames 小遊戲大廳(#/minigames/<遊戲> 進遊戲)、#/term 任期小遊戲試玩、#/people 歷屆參選人與客觀資歷分數。經典模式(十週行程版)2026-10-26 依使用者要求刪除,舊網址回首頁。 + */ +export function App() { + const hash = useHash(); + return 讀取中…}>{route(hash)}; +} + +function route(hash: string) { + if (hash.startsWith("#/avatar-check")) return ; + if (hash.startsWith("#/shop")) { + const q = new URLSearchParams(hash.split("?")[1] ?? ""); + return ; + } + if (hash.startsWith("#/viewer")) return ; + if (hash.startsWith("#/art")) return ; + if (hash.startsWith("#/faces")) return ; + if (hash.startsWith("#/island")) return ; + if (hash.startsWith("#/minigames")) return ; + if (hash.startsWith("#/term")) return ; + if (hash.startsWith("#/people")) return ; + if (hash.startsWith("#/create")) { + const q = new URLSearchParams(hash.split("?")[1] ?? ""); + return ; + } + const run = /^#\/rogue\/([0-9a-f-]{36})$/.exec(hash); + if (run) return ; + if (hash.startsWith("#/rogue/collection")) return ; + if (hash.startsWith("#/rogue/career")) return ; + // 選戰大廳就是首頁的標題畫面(朋友的挑戰連結 #/rogue?challenge=… 也在這裡接) + if (hash.startsWith("#/rogue")) return ; + return ; +} diff --git a/web/src/data/loadPack.ts b/web/src/data/loadPack.ts new file mode 100644 index 0000000..c45141e --- /dev/null +++ b/web/src/data/loadPack.ts @@ -0,0 +1,43 @@ +import { + CellsFile, + DataPackManifest, + HistoryFile, + TownsFile, + VillagesFile, + type CellsBlock, + type DataPackManifest as Manifest, + type HistoryBlock, + type TownRecord, + type VillageRecord, +} from "@election2026/protocol"; +import type { Topology } from "topojson-specification"; + +export interface DataPack { + manifest: Manifest; + villages: VillageRecord[]; + towns: TownRecord[]; + cells: CellsBlock; + history: HistoryBlock; + topology: Topology; +} + +async function getJson(url: string): Promise { + const res = await fetch(url); + if (!res.ok) { + throw new Error(`讀取 ${url} 失敗(HTTP ${res.status})。請先執行 pnpm sync-fixtures。`); + } + return res.json(); +} + +/** 讀取資料包,並用協定的 Zod 定義驗證:格式不符時立刻報錯,而不是畫出錯的地圖。 */ +export async function loadPack(base: string): Promise { + const manifest = DataPackManifest.parse(await getJson(`${base}/manifest.json`)); + const [villages, towns, cells, history, topology] = await Promise.all([ + getJson(`${base}/${manifest.files.villages}`).then((d) => VillagesFile.parse(d).villages), + getJson(`${base}/${manifest.files.towns}`).then((d) => TownsFile.parse(d).towns), + getJson(`${base}/${manifest.files.cells}`).then((d) => CellsFile.parse(d).cells), + getJson(`${base}/${manifest.files.history}`).then((d) => HistoryFile.parse(d).history), + getJson(`${base}/${manifest.files.topology}`) as Promise, + ]); + return { manifest, villages, towns, cells, history, topology }; +} diff --git a/web/src/game/PartyFlag.tsx b/web/src/game/PartyFlag.tsx new file mode 100644 index 0000000..e48a0fc --- /dev/null +++ b/web/src/game/PartyFlag.tsx @@ -0,0 +1,309 @@ +/** + * 政黨旗幟:以向量自行重繪,不使用官方圖檔(docs/14)。 + * 台灣本島輪廓由內政部村里界線(packs/00000 topology)合併、簡化而成。 + * 2026-10-27 查證(維基百科、維基共享資源、Flags of the World):有黨旗的政黨都畫;只有黨徽、沒有黨旗的不畫(顯示灰色)。 + * 例外是台灣民眾黨:沒有正式黨旗,用官方黨色 #28c8c8 加白色「眾」字黨徽,因為它是選票模型裡的三黨之一。 + * 勞動黨(一顆黃色五角星)、台灣主義黨(紅底一圈白色小星星)有星星,等使用者決定要不要畫。 + * 書法字(新黨的孫中山題字等)用粗宋體字代替。 + */ + +/** 台灣本島,寬 52.8、高 100 */ +const TAIWAN = + "M49.4 19.3 48.9 13.4 50.6 10.7 52.7 9.2 51.5 5.1 47.3 4.2 46.6 4.9 42.9 0.3 39.8 0.5 37.0 4.4 27.5 7.8 22.5 17.6 18.8 20.5 13.3 29.4 12.9 31.5 10.6 33.4 3.5 44.8 4.8 45.0 2.6 49.0 3.9 53.5 3.5 56.9 1.8 59.3 0.0 65.9 3.9 69.5 6.7 76.9 6.0 78.5 9.0 82.0 8.0 81.5 8.0 82.2 16.5 88.5 18.7 95.1 18.1 97.5 19.4 100.0 19.7 99.3 21.5 99.8 23.6 96.6 23.6 87.9 27.3 78.1 31.3 75.2 31.7 72.6 33.2 71.7 37.0 65.0 43.7 38.6 43.3 35.7 44.5 32.7 46.7 30.7 50.2 22.4 50.5 20.6Z"; + +const KMT_BLUE = "#000095"; +const DPP_GREEN = "#1b9431"; +const TPP_TEAL = "#28c8c8"; + +/** 青天白日:十二道光芒的星形,內側頂點藏在藍圈底下(rays 可以改,綠黨的向日葵用 20 瓣) */ +function sunRays(cx: number, cy: number, outer: number, inner: number, rays = 12): string { + const points: string[] = []; + for (let k = 0; k < rays * 2; k++) { + const r = k % 2 === 0 ? outer : inner; + const angle = ((k * 180) / rays - 90) * (Math.PI / 180); + points.push(`${(cx + r * Math.cos(angle)).toFixed(2)},${(cy + r * Math.sin(angle)).toFixed(2)}`); + } + return points.join(" "); +} + +function Kmt() { + return ( + <> + + + + + + ); +} + +function Dpp() { + return ( + <> + + + + + + + ); +} + +/** 民眾黨:青綠底、白色「眾」字黨徽(照官方黨徽 SVG 簡化) */ +function Tpp() { + return ( + <> + + + + + + + + + + ); +} + +/** 旗上的字(粗宋體);vertical 是直排 */ +function Words({ text, x, y, size, fill, vertical }: { text: string; x: number; y: number; size: number; fill: string; vertical?: boolean }) { + return ( + + {text} + + ); +} + +/** 新黨:黃底、深藍「新黨」 */ +function NewParty() { + return ( + <> + + + + ); +} + +/** 親民黨:橘底、白字黨名(維基百科上的旗;Flags of the World 說黨章沒有規定黨旗) */ +function Pfp() { + return ( + <> + + + + PEOPLE FIRST PARTY + + + ); +} + +/** 建國黨:上淺藍、下綠,中間一個金色三角形,上面黨名 */ +function Taip() { + return ( + <> + + + + + + ); +} + +/** 無黨團結聯盟:白底、灰紅太極形黨徽、黨名、底下一條紅線 */ +function Npsu() { + return ( + <> + + + + + + + ); +} + +/** 綠黨:旗桿那側彩虹、其餘綠色、黃色向日葵(只有一張照片可以對照,彩虹順序沒有確認) */ +function Green() { + const rainbow = ["#7b3fa0", "#2f6fd6", "#2fa84f", "#f3d21b", "#f08a1c", "#e0322b"]; + return ( + <> + + {rainbow.map((c, i) => ( + + ))} + + + + ); +} + +/** 喜樂島聯盟:薄荷綠底、右下白色斜角、一隻往上揚的黑鯨魚(直幅旗改成橫的) */ +function Formosa() { + return ( + <> + + + + + + + + + ); +} + +/** 國會政黨聯盟:紅黃綠橫條、中間同心圓 */ +function Cpu() { + return ( + <> + + + + + + + + ); +} + +/** 台澎黨:四塊色角(原旗是漸層,這裡用平塗)、白色圓盤、灰色台灣和澎湖 */ +function Ssfp() { + return ( + <> + + + + + + + + + + ); +} + +/** 客家黨:藍白綠直條、中間紅字直排黨名 */ +function Hakka() { + return ( + <> + + + + + + ); +} + +/** 紅黨:紅底、白色圓盤(「日正當中」) */ +function Red() { + return ( + <> + + + + ); +} + +/** 台灣農民黨:白底,中間台灣、兩邊藍綠兩塊在中間握手、山丘,黨名,底下三條波浪(簡化) */ +function Farmers() { + return ( + <> + + + + + + + {[ + ["#14594d", 53.5], + ["#0c65b2", 56.5], + ["#419e0c", 59.5], + ].map(([c, y]) => ( + + ))} + + ); +} + +/** 民國黨:金黃底、中間中華民國國徽(藍圈白日) */ +function Minkuotang() { + return ( + <> + + + + + + + ); +} + +/** 台灣工黨:綠底、黃色「井」字 */ +function Labour() { + return ( + <> + + + + + + + + + ); +} + +/** 中國青年黨:黃、藍、白、紅、黃橫條 */ +function Youth() { + const bands: [string, number, number][] = [ + ["#fce61e", 0, 17.14], + ["#08639c", 17.14, 25.71], + ["#fff", 25.71, 34.29], + ["#db000f", 34.29, 42.86], + ["#fce61e", 42.86, 60], + ]; + return ( + <> + {bands.map(([c, y0, y1]) => ( + + ))} + + ); +} + +const FLAGS: Record React.JSX.Element> = { + 中國國民黨: Kmt, + 民主進步黨: Dpp, + 台灣民眾黨: Tpp, + 新黨: NewParty, + 親民黨: Pfp, + 建國黨: Taip, + 無黨團結聯盟: Npsu, + // 同一個黨改過名 + 綠黨: Green, + 台灣綠黨: Green, + 綠色本土清新黨: Green, + 喜樂島聯盟: Formosa, + 國會政黨聯盟: Cpu, + 台澎黨: Ssfp, + 客家黨: Hakka, + 紅黨: Red, + 台灣農民黨: Farmers, + 民國黨: Minkuotang, + 台灣工黨: Labour, + 中國青年黨: Youth, +}; + +/** 這個政黨有沒有畫黨旗 */ +export const hasPartyFlag = (party: string | null): boolean => !!party && party in FLAGS; + +export function PartyFlag({ party, height = 20 }: { party: string | null; height?: number }) { + const Flag = party ? FLAGS[party] : undefined; + if (!Flag) return null; + return ( + + + + + ); +} diff --git a/web/src/game/api.ts b/web/src/game/api.ts new file mode 100644 index 0000000..0d27010 --- /dev/null +++ b/web/src/game/api.ts @@ -0,0 +1,101 @@ +import { ApiError, RogueArea, RogueCatalog, RogueView, ScenarioSummary, type CareerAbilities, type CustomCandidate, type IslandPerk, type PolicySpec, RogueVillageList, type MiniGameKind } from "@election2026/protocol"; +import type { Topology } from "topojson-specification"; + +/** 遊戲 API:所有回應都用協定的 Zod 定義驗證,格式不符就報錯(docs/16) */ +async function request(url: string, schema: { parse(x: unknown): T }, body?: unknown): Promise { + const init: RequestInit = body === undefined ? {} : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }; + let res: Response; + try { + res = await fetch(url, init); + } catch { + throw new Error("連不上遊戲伺服器。請確認 backend 的伺服器有在跑(pnpm --filter @election2026/server start)。"); + } + const json: unknown = await res.json().catch(() => null); + if (!res.ok) { + const err = ApiError.safeParse(json); + throw new Error(err.success ? [err.data.error, ...(err.data.details ?? [])].join(":") : `伺服器錯誤(HTTP ${res.status})`); + } + return schema.parse(json); +} + +const TopologyShape = { + parse(x: unknown): Topology { + if (typeof x !== "object" || x === null || (x as { type?: unknown }).type !== "Topology") throw new Error("地圖格式不正確"); + return x as Topology; + }, +}; + +const CreateRogueResponse = { + parse(x: unknown): { runId: string; view: RogueView } { + const o = x as { runId?: unknown; view?: unknown }; + if (typeof o?.runId !== "string") throw new Error("開局回應格式不正確"); + return { runId: o.runId, view: RogueView.parse(o.view) }; + }, +}; + +/** 選戰卡牌(新玩法試玩版):規則在伺服器,每出一張牌拿回新的畫面狀態 */ +export interface RogueCreateOptions { + /** 逆風難度 0–10 */ + ascension?: number; + /** 勢均力敵:雙方開局底盤拉平 */ + even?: boolean; + /** 每日一戰的日期(YYYY-MM-DD) */ + daily?: string; + seed?: number; + /** 政治生涯:自創角色、第幾關、帶過來的幕僚和牌 */ + custom?: CustomCandidate; + career?: { stage: number }; + carry?: { advisors: string[]; cards: { id: string; up: boolean }[]; money: number; momentum?: number }; + /** 政治生涯的地方選舉:里長(不指定里就隨機挑)、議員(那個里所在的議員選區) */ + local?: { kind: "village"; village: string | null } | { kind: "council"; village: string }; + /** 政治生涯的角色能力、政策島的建築、帶進這一局的政策 */ + abilities?: CareerAbilities; + perks?: IslandPerk[]; + policies?: PolicySpec[]; +} + +export const rogueApi = { + create: (scenarioId: string, candidateId: string, options: RogueCreateOptions = {}) => request("/api/rogue/runs", CreateRogueResponse, { scenarioId, candidateId, ...options }), + tutorial: () => request("/api/rogue/tutorial", CreateRogueResponse, {}), + catalog: () => request("/api/rogue/catalog", RogueCatalog), + get: (id: string) => request(`/api/rogue/runs/${encodeURIComponent(id)}`, RogueView), + /** 選區範圍:立委選區內的村里代碼;縣市長、總統是 null */ + area: (id: string) => request(`/api/rogue/runs/${encodeURIComponent(id)}/area`, RogueArea), + /** 政治生涯里長關:縣市長劇本那個縣市的區和里 */ + villages: (scenarioId: string) => request(`/api/rogue/villages/${encodeURIComponent(scenarioId)}`, RogueVillageList), + play: (id: string, uid: string, target: string | null) => request(`/api/rogue/runs/${encodeURIComponent(id)}/play`, RogueView, { uid, target }), + endWeek: (id: string) => request(`/api/rogue/runs/${encodeURIComponent(id)}/end-week`, RogueView, {}), + /** 放大絕招:玩完小遊戲把分數送出(掃街馬拉松帶挑的區) */ + ultimate: (id: string, kind: MiniGameKind, score: number, towns?: string[]) => request(`/api/rogue/runs/${encodeURIComponent(id)}/ultimate`, RogueView, { kind, score, towns }), + /** 劇情、下一站、站內的選擇;target 是要升級或拿掉的牌;option 是門上直接選的選項(選門+選項一次完成) */ + choose: (id: string, pick: number | "skip", target: string | null = null, option?: number) => + request(`/api/rogue/runs/${encodeURIComponent(id)}/choose`, RogueView, option === undefined ? { pick, target } : { pick, target, option }), +}; + +export const api = { + scenarios: () => request("/api/scenarios", ScenarioSummary.array()), + topology: (packId: string) => request(`/api/packs/${encodeURIComponent(packId)}/topology`, TopologyShape), +}; + +// ── 政治人物資料庫(#/people):歷屆縣市長、議員的選舉紀錄與資歷分數 ── +// import 放在這裡(ES 模組的 import 會提升),避免和其他功能同時改檔頭的 import +import { PeopleListResponse, PersonRecordResponse, type ElectionOffice } from "@election2026/protocol"; + +export interface PeopleQuery { + county?: string; + office?: ElectionOffice; + year?: number; + q?: string; + page?: number; +} + +export const peopleApi = { + /** 每頁 50 人;縣市、選舉種類、年份要同一次參選都符合 */ + list: (query: PeopleQuery = {}) => { + const params = new URLSearchParams(); + for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== "") params.set(k, String(v)); + const qs = params.toString(); + return request(`/api/people${qs ? `?${qs}` : ""}`, PeopleListResponse); + }, + get: (id: string) => request(`/api/people/${encodeURIComponent(id)}`, PersonRecordResponse), +}; diff --git a/web/src/game/art/ArtGallery.tsx b/web/src/game/art/ArtGallery.tsx new file mode 100644 index 0000000..f858592 --- /dev/null +++ b/web/src/game/art/ArtGallery.tsx @@ -0,0 +1,28 @@ +import { Avatar, avatarFromSeed } from "./Avatar.tsx"; +import { SCENE_LIST, Scene } from "./scenes/index.tsx"; + +/** 美術總覽(#/art):所有場景與人物一次看,方便檢查風格 */ +export function ArtGallery() { + const seeds = ["anchor-a", "anchor-b", "staff-1", "staff-2", "staff-3", "staff-4", "staff-5", "staff-6", "reporter", "village-chief", "elder", "youth"]; + return ( +
+

美術總覽

+
+ {seeds.map((s) => ( +
+ +
{s}
+
+ ))} +
+
+ {SCENE_LIST.map((k) => ( +
+ +
{k.label}
+
+ ))} +
+
+ ); +} diff --git a/web/src/game/art/Avatar.tsx b/web/src/game/art/Avatar.tsx new file mode 100644 index 0000000..497d05c --- /dev/null +++ b/web/src/game/art/Avatar.tsx @@ -0,0 +1,196 @@ +import { isAvatarStyle, type AvatarSpecData } from "@election2026/protocol"; +import { useId } from "react"; +import { useSettings } from "../audio/settings.ts"; +import { mix, type Look } from "./avatar/builtin.tsx"; +import { AvatarFigure, AvatarFrame } from "./avatar/layers.tsx"; +import type { PartCtx } from "./avatar/parts.tsx"; +import { PixelFigure } from "./avatar/pixel.tsx"; +import { HAIR, SHIRT, SKIN, SUIT, TIE, pickFrom, seeded } from "./palette.ts"; + +/** + * Q 版漫畫肖像:部件組合,會眨眼、說話時嘴巴會動。 + * 臉型、臉寬臉長、耳朵、眉毛、眼型、眼鏡款式、鼻子、嘴型、髮線都能調, + * 用來畫虛構人物,也用來替政治人物畫「抓招牌特徵」的卡通頭像(不是照片、不是 AI 生成)。 + * + * 部件照目錄(@election2026/protocol 的部件目錄,docs/24)一層一層疊:舊部件是程式畫的(avatar/builtin.tsx), + * 新部件(帽子、彩帶、手持物、外框…)是部件圖(avatar/parts.tsx)。同一套部件可以換四種畫風: + * 漫畫(預設)、Q 版大頭、復刻像素、平面貼紙;畫風看 style 參數 → 角色自己的 spec.style → 全遊戲設定。 + */ + +/** 頭像資料:就是前後端共用的格式(髮型、服裝…是目錄裡的代號) */ +export type AvatarSpec = AvatarSpecData; +/** 髮型代號(目錄裡 hair 部位的部件代號) */ +export type HairStyle = string; +export type AvatarStyle = "comic" | "chibi" | "pixel" | "sticker"; + +const MALE_HAIR: HairStyle[] = ["short", "side", "buzz", "bald", "curly", "receding", "slick", "crew"]; +const FEMALE_HAIR: HairStyle[] = ["bob", "long", "bun", "curly", "bobSide", "shortBob", "perm"]; +const BG = ["#dfe8f0", "#f1e4d3", "#e3eedf", "#efe0e6", "#e6e2f3"]; +const FACES = ["oval", "round", "long", "square", "heart"] as const; + +export function avatarFromSeed(seed: string, overrides: Partial & { female?: boolean } = {}): AvatarSpec { + const r = seeded(seed); + const female = overrides.female ?? r() < 0.5; + const hair = pickFrom(female ? FEMALE_HAIR : MALE_HAIR, r()); + const older = r() < 0.25; + const { female: _f, ...rest } = overrides; + return { + skin: pickFrom(SKIN, r()), + hair, + hairColor: older ? HAIR[4] : pickFrom(HAIR.slice(0, 4), r()), + outfit: female ? (r() < 0.6 ? "blouse" : "suit") : r() < 0.7 ? "suit" : r() < 0.5 ? "vest" : "polo", + suit: pickFrom(SUIT, r()), + shirt: pickFrom(SHIRT, r()), + tie: pickFrom(TIE, r()), + glasses: r() < 0.35, + beard: !female && r() < 0.15, + bg: pickFrom(BG, r()), + face: pickFrom(FACES, r()), + faceW: 0.92 + r() * 0.16, + faceH: 0.94 + r() * 0.12, + ears: r() < 0.2 ? "big" : "normal", + brows: female ? "thin" : r() < 0.3 ? "thick" : "normal", + browAngle: (r() - 0.5) * 0.8, + eyes: pickFrom(["round", "narrow", "smile", "round"] as const, r()), + nose: "normal", + mouth: pickFrom(["smile", "smile", "closed", "teeth"] as const, r()), + lines: older ? 1 : 0, + part: r() < 0.5 ? "left" : "right", + ...rest, + }; +} + +/** 政黨槽位的顏色(頭像是「圖」,淺色深色模式都用同一套;tokens.css 淺色版的政黨色)。無黨籍、其他政黨用競選紅 */ +export const PARTY_HEX: Record<"a" | "b" | "c" | "other", string> = { a: "#1b9431", b: "#2349b8", c: "#16a3a6", other: "#d61f2c" }; + +/** 這個頭像實際用哪種畫風:參數 → 角色自己的 → 全遊戲設定 */ +export function resolveStyle(spec: AvatarSpec, override: string | undefined, global: string): AvatarStyle { + const pick = [override, spec.style, global].find((s) => isAvatarStyle(s)); + return (pick ?? "comic") as AvatarStyle; +} + +/** 背景:競選看板那種放射狀光芒(淺一階的同色),小圖只留平塗底色 */ +function PosterBackground({ id, fill, rays, rx }: { id: string; fill: string; rays: boolean; rx: number }) { + const n = 12; + let d = ""; + for (let i = 0; i < n; i++) { + const a0 = ((i * 2) / (n * 2)) * Math.PI * 2; + const a1 = ((i * 2 + 1) / (n * 2)) * Math.PI * 2; + d += `M100 96 L${(100 + Math.cos(a0) * 260).toFixed(1)} ${(96 + Math.sin(a0) * 260).toFixed(1)} L${(100 + Math.cos(a1) * 260).toFixed(1)} ${(96 + Math.sin(a1) * 260).toFixed(1)} Z`; + } + return ( + <> + + {rays && ( + <> + + + + + + )} + + ); +} + +/** 平面貼紙:粗白邊+細黑邊(濾鏡,單位跟著畫布縮放) */ +function StickerFilter({ id }: { id: string }) { + return ( + + + + + + + + + + + + + + ); +} + +export function Avatar({ + spec, + size = 96, + talking = false, + background = true, + className, + label, + style: styleOverride, + partyColor, + print, + frame, +}: { + spec: AvatarSpec; + size?: number; + talking?: boolean; + background?: boolean; + className?: string; + label?: string; + /** 指定畫風(試穿、部件檢查頁);沒給就看角色自己的、再看全遊戲設定 */ + style?: string; + /** 政黨色(#RRGGBB):部件預設跟政黨色的(競選背心、鴨舌帽…)用它;沒給用競選紅 */ + partyColor?: string; + /** 部件上印的號次、名字 */ + print?: { name?: string | null; number?: number | null }; + /** 畫不畫頭像外框;預設跟 background 一樣 */ + frame?: boolean; +}) { + const settings = useSettings(); + const style = resolveStyle(spec, styleOverride, settings.avatarStyle); + const uid = useId().replace(/:/g, ""); + const small = size < 64; + // 細節多少:小圖線條加粗、省略網點和皺紋;像素風縮成小點陣,網點只會變成雜點 + const detail = small ? 0 : style === "pixel" ? 1 : size >= 120 ? 2 : 1; + const look: Look = { chibi: style === "chibi", flat: style === "sticker", raster: style === "pixel", detail }; + const ctx: PartCtx = { + party: partyColor ?? PARTY_HEX.other, + skin: spec.skin, + suit: spec.suit, + shirt: spec.shirt, + tint: spec.tint, + name: print?.name ?? null, + number: print?.number ?? null, + text: !small && style !== "pixel", + }; + const showFrame = frame ?? background; + const figure = ; + const frameLayer = showFrame ? : null; + let body = ( + <> + {figure} + {frameLayer} + + ); + if (style === "sticker") { + body = ( + <> + + + + {figure} + {frameLayer} + + ); + } else if (style === "pixel") { + const key = JSON.stringify([spec, ctx.party, small, showFrame]); + body = {body}; + } + return ( + + {background && } + {body} + + ); +} diff --git a/web/src/game/art/AvatarCheck.tsx b/web/src/game/art/AvatarCheck.tsx new file mode 100644 index 0000000..4b96310 --- /dev/null +++ b/web/src/game/art/AvatarCheck.tsx @@ -0,0 +1,101 @@ +import { AVATAR_CATALOG, avatarStyles, wearSlots, type AvatarItem } from "@election2026/protocol"; +import { useState } from "react"; +import { Avatar, avatarFromSeed, type AvatarSpec } from "./Avatar.tsx"; +import { RARITY_TEXT } from "../shop/unlocks.ts"; +import "./avatar-check.css"; + +/** + * 部件檢查頁(#/avatar-check,docs/24 第 1 節):每件部件套在不同臉型、最寬最窄的臉、不同髮型上, + * 再用 28/96/320 像素各畫一次,一眼看出有沒有歪掉、小圖有沒有糊掉。上面可以切換畫風。 + * 新加部件後跑 pnpm avatar:build,再打開這一頁看一次。 + */ + +const BASE = avatarFromSeed("avatar-check", { female: false, outfit: "suit", glasses: false, beard: false, eyes: "round", mouth: "smile" }); +const FACES: { label: string; patch: Partial }[] = [ + { label: "鵝蛋臉・短髮", patch: { face: "oval", faceW: 1, faceH: 1, hair: "short" } }, + { label: "圓臉・捲髮", patch: { face: "round", faceW: 1.05, faceH: 1, hair: "curly", glasses: true, glassesStyle: "round" } }, + { label: "長臉・長髮", patch: { face: "long", faceW: 0.95, faceH: 1.08, hair: "long", outfit: "blouse" } }, + { label: "方臉・蓬鬆旁分", patch: { face: "square", faceW: 1, faceH: 1, hair: "volume", outfit: "polo" } }, + { label: "瓜子臉・包頭", patch: { face: "heart", faceW: 0.96, faceH: 1, hair: "bun", outfit: "blouse" } }, + { label: "最寬最矮・燙髮", patch: { face: "round", faceW: 1.25, faceH: 0.85, hair: "perm", glasses: true, glassesStyle: "black" } }, + { label: "最窄最長・側分鮑伯", patch: { face: "long", faceW: 0.8, faceH: 1.25, hair: "bobSide", outfit: "vest" } }, +]; +const PRINT = { name: "王小明", number: 3 }; +const PARTY = "#2349b8"; + +const getText = (i: AvatarItem): string => { + const g = i.get; + if (g.type === "free") return "免費"; + if (g.type === "shop") return `商店 ${g.price} 幣${g.shelf === "always" ? "(常駐)" : ""}${i.available?.months ? `(每年 ${i.available.months.join("、")} 月)` : ""}`; + return g.text; +}; + +export function AvatarCheck() { + const [style, setStyle] = useState("comic"); + const [slot, setSlot] = useState("all"); + const slots = wearSlots(); + const items = AVATAR_CATALOG.items.filter((i) => !i.art.startsWith("builtin:") && (slot === "all" || i.slot === slot)); + return ( +
+
+

頭像部件檢查

+

+ 目錄第 {AVATAR_CATALOG.catalogVersion} 版,新部件 {AVATAR_CATALOG.items.filter((i) => !i.art.startsWith("builtin:")).length} 件、舊部件{" "} + {AVATAR_CATALOG.items.filter((i) => i.art.startsWith("builtin:")).length} 件。部件圖都經過 pnpm avatar:build 檢查(沒有 script、外部連結、文字,沒有超出畫布)。 + 每件套在 7 種臉、3 種大小上畫一次;28 像素的小圖會自動省略胸前、手持物、外框和字。 +

+
+
+ {avatarStyles().map((s) => ( + + ))} +
+
+ + {slots.map((s) => ( + + ))} +
+
+
+
    + {items.map((it) => ( +
  1. +
    + {it.name} + {it.id} + + {RARITY_TEXT[it.rarity]}・{getText(it)} + + {it.realPersonOk ? "真實人物可以穿" : "只給自創角色"} +
    +
    + +
    +
    + {FACES.map((f) => ( +
    + +
    {f.label}
    +
    + ))} +
    + + + + +
    28 像素
    +
    +
    +
  2. + ))} +
+
+ ); +} diff --git a/web/src/game/art/Badge.tsx b/web/src/game/art/Badge.tsx new file mode 100644 index 0000000..29e4a84 --- /dev/null +++ b/web/src/game/art/Badge.tsx @@ -0,0 +1,27 @@ +import type { CandidatePublic } from "@election2026/protocol"; +import { slotColor } from "../format.ts"; +import { Avatar, PARTY_HEX, type AvatarSpec } from "./Avatar.tsx"; +import { candidateAvatar } from "./candidateAvatar.ts"; + +/** 候選人徽章:政黨色圓底+Q 版頭像(太小時只放號次)。地圖棋子、名單、開票都用它 */ +export function CandidateBadge({ + candidate, + size = 28, +}: { + candidate: Pick & { avatar?: AvatarSpec | null; gender?: "m" | "f" | null }; + size?: number; +}) { + if (size >= 24) { + return ( + + + {size >= 30 && {candidate.number}} + + ); + } + return ( + + {candidate.number} + + ); +} diff --git a/web/src/game/art/BallotStamp.tsx b/web/src/game/art/BallotStamp.tsx new file mode 100644 index 0000000..7920090 --- /dev/null +++ b/web/src/game/art/BallotStamp.tsx @@ -0,0 +1,9 @@ +/** 選票上的圈選章「卜」:遊戲的標誌,也用在送出按鈕與當選章 */ +export function BallotStamp({ size = 28, color = "var(--stamp)" }: { size?: number; color?: string }) { + return ( + + + + + ); +} diff --git a/web/src/game/art/CardArt.tsx b/web/src/game/art/CardArt.tsx new file mode 100644 index 0000000..eb024a1 --- /dev/null +++ b/web/src/game/art/CardArt.tsx @@ -0,0 +1,17 @@ +import { useState } from "react"; +import { actionIcon } from "./actionIcons.ts"; + +/** 卡牌插圖:本機生成的一般場景(art/cards.tsv),不畫真實人物;圖讀不到時用圖示代替 */ +export function CardArt({ actionId, className }: { actionId: string; className?: string }) { + const [missing, setMissing] = useState(false); + const Icon = actionIcon(actionId); + return ( + + {missing ? ( + + ) : ( + setMissing(true)} /> + )} + + ); +} diff --git a/web/src/game/art/FaceGallery.tsx b/web/src/game/art/FaceGallery.tsx new file mode 100644 index 0000000..4af50a8 --- /dev/null +++ b/web/src/game/art/FaceGallery.tsx @@ -0,0 +1,34 @@ +import { Avatar } from "./Avatar.tsx"; +import { defaultAvatar } from "./candidateAvatar.ts"; +import { LIKENESS } from "./likeness.ts"; +import { LIKENESS_2024 } from "./likeness-2024.ts"; + +/** 頭像對照(#/faces):所有照公開肖像設定特徵的政治人物,一次看 */ +export function FaceGallery() { + const groups: { title: string; names: string[] }[] = [ + { title: "重要政治人物", names: Object.keys(LIKENESS) }, + { title: "第 11 屆立法委員(2024 年選上,看立法院官方照片)", names: Object.keys(LIKENESS_2024).filter((n) => !(n in LIKENESS)) }, + ]; + const total = groups.reduce((n, g) => n + g.names.length, 0); + return ( +
+

政治人物 Q 版頭像

+

依公開官方肖像的招牌特徵畫成卡通,不是照片、不是 AI 生成。共 {total} 位。

+ {groups.map((g) => ( +
+

+ {g.title}({g.names.length} 位) +

+
    + {g.names.map((n) => ( +
  • + + {n.replace(/ .*$/, "")} +
  • + ))} +
+
+ ))} +
+ ); +} diff --git a/web/src/game/art/Person.tsx b/web/src/game/art/Person.tsx new file mode 100644 index 0000000..442b74a --- /dev/null +++ b/web/src/game/art/Person.tsx @@ -0,0 +1,178 @@ +import { CROWD, HAIR, SKIN, SUIT, pickFrom, seeded } from "./palette.ts"; + +/** + * 場景裡的全身小人。(x, y) 是腳底的位置,身高約 110 × s。 + * silhouette:真實候選人一律畫成剪影,只有競選彩帶與號次,不畫五官(docs/17)。 + */ +export type Pose = "stand" | "wave" | "cheer" | "shake" | "hold" | "kneel" | "point"; + +interface PersonProps { + x: number; + y: number; + s?: number; + pose?: Pose; + skin?: string; + hair?: string; + top?: string; + bottom?: string; + silhouette?: boolean; + sash?: { color: string; number: number }; + flag?: string; + female?: boolean; + flip?: boolean; + className?: string; +} + +const ARMS: Record = { + stand: [ + [-20, -46], + [20, -46], + ], + wave: [ + [-20, -46], + [26, -106], + ], + cheer: [ + [-26, -106], + [26, -106], + ], + shake: [ + [-20, -46], + [32, -62], + ], + hold: [ + [-20, -46], + [24, -72], + ], + point: [ + [-20, -46], + [34, -86], + ], + kneel: [ + [-22, -40], + [22, -40], + ], +}; + +export function Person({ x, y, s = 1, pose = "stand", skin = SKIN[1], hair = HAIR[0], top = SUIT[0], bottom = "#2b2b33", silhouette, sash, flag, female, flip, className }: PersonProps) { + const dark = "#2a2d35"; + const fill = (c: string) => (silhouette ? dark : c); + const kneel = pose === "kneel"; + const [left, right] = ARMS[pose]; + const lift = kneel ? 26 : 0; + return ( + + + {kneel ? ( + + + + + + ) : ( + + + + + )} + + + + + + + + {flag && ( + + + + + )} + + {sash && ( + + + + {sash.number}號 + + + )} + + + {!silhouette && ( + <> + + + + + + )} + + + ); +} + +/** 一群人:頭與肩膀,部分人揮旗或拿螢光棒;同一個 seed 每次畫出來一樣 */ +export function Crowd({ + x, + y, + width, + rows = 3, + seed, + flags = [], + lights = false, + density = 1, + className = "art-crowd", +}: { + x: number; + y: number; + width: number; + rows?: number; + seed: string; + flags?: string[]; + lights?: boolean; + density?: number; + className?: string; +}) { + const r = seeded(seed); + const people: { cx: number; cy: number; s: number; shirt: string; skin: string; hair: string; flag?: string; light?: boolean; delay: number }[] = []; + for (let row = 0; row < rows; row++) { + const s = 0.75 + row * 0.18; + const gap = 26 * s / density; + const count = Math.floor(width / gap); + for (let i = 0; i < count; i++) { + const roll = r(); + people.push({ + cx: x + i * gap + (row % 2) * gap * 0.5 + (r() - 0.5) * 6, + cy: y + row * 18, + s, + shirt: pickFrom(CROWD, r()), + skin: pickFrom(SKIN, r()), + hair: pickFrom(HAIR.slice(0, 4), r()), + flag: flags.length && roll < 0.22 ? pickFrom(flags, r()) : undefined, + light: lights && roll > 0.7, + delay: Math.round(r() * 900), + }); + } + } + return ( + + {people.map((p, i) => ( + + + {p.flag && ( + + + + + )} + {p.light && } + + + + + + ))} + + ); +} diff --git a/web/src/game/art/Poster.tsx b/web/src/game/art/Poster.tsx new file mode 100644 index 0000000..b29f5a8 --- /dev/null +++ b/web/src/game/art/Poster.tsx @@ -0,0 +1,30 @@ +import type { CandidatePublic } from "@election2026/protocol"; +import { slotColor } from "../format.ts"; +import { PartyFlag } from "../PartyFlag.tsx"; +import { Avatar, PARTY_HEX, type AvatarSpec } from "./Avatar.tsx"; +import { candidateAvatar } from "./candidateAvatar.ts"; + +type PosterCandidate = Pick & { avatar?: AvatarSpec | null; gender?: "m" | "f" | null }; + +const AVATAR_SIZE = { sm: 46, md: 74, lg: 118 } as const; + +/** + * 競選看板風格的候選人卡:大號次、姓名、黨旗,右邊是 Q 版頭像。 + * 頭像是卡通,不是照真人長相畫的(不用照片、不用 AI 生成真人);自創角色顯示玩家捏的頭像。 + */ +export function Poster({ candidate, size = "md" }: { candidate: PosterCandidate; size?: "sm" | "md" | "lg" }) { + const spec = candidateAvatar(candidate); + return ( +
+ {candidate.number} + {candidate.name} + + + + + + + {candidate.party ?? "無黨籍"} +
+ ); +} diff --git a/web/src/game/art/StaffAvatar.tsx b/web/src/game/art/StaffAvatar.tsx new file mode 100644 index 0000000..3a66d76 --- /dev/null +++ b/web/src/game/art/StaffAvatar.tsx @@ -0,0 +1,10 @@ +import { Avatar, avatarFromSeed } from "./Avatar.tsx"; + +/** 幕僚的圓形頭像。幕僚是虛構角色,同一個陣營的同一位幕僚每次長得一樣 */ +export function StaffAvatar({ owner, staffId, size = 28, talking }: { owner: string; staffId: string; size?: number; talking?: boolean }) { + return ( + + + + ); +} diff --git a/web/src/game/art/actionIcons.ts b/web/src/game/art/actionIcons.ts new file mode 100644 index 0000000..5a0d33d --- /dev/null +++ b/web/src/game/art/actionIcons.ts @@ -0,0 +1,149 @@ +import { + Award, + Banknote, + BookOpen, + CalendarHeart, + Church, + Drama, + Dumbbell, + Eye, + FileText, + Flag, + Gavel, + Gift, + HeartCrack, + Home, + Moon, + MessagesSquare, + Mic, + Music, + Newspaper, + PhoneCall, + PhoneOff, + Plane, + Radio, + Scale, + ShieldCheck, + Swords, + UserMinus, + Vault, + Video, + Bed, + Bot, + Building2, + ClipboardList, + Factory, + Flame, + HandCoins, + Handshake, + Landmark, + Megaphone, + MicVocal, + PartyPopper, + Phone, + PiggyBank, + Printer, + ScrollText, + Search, + Shield, + Smartphone, + Store, + Footprints, + Truck, + Tv, + UserPlus, + Users, + Utensils, + Wallet, + Zap, + type LucideIcon, +} from "lucide-react"; + +/** 行動 → 圖示。沒有對應的行動用通用圖示,不會壞掉 */ +const ICONS: Record = { + street_canvass: Footprints, + market_visit: Store, + temple_visit: Landmark, + factory_visit: Factory, + sound_truck: Truck, + rally: MicVocal, + open_office: Building2, + recruit_machine: Handshake, + hire_staff: UserPlus, + recruit_volunteers: Users, + print_flyers: Printer, + tv_ad: Tv, + online_ad: Smartphone, + talk_show: Megaphone, + announce_policy: ScrollText, + fundraiser_dinner: Utensils, + small_donations: HandCoins, + self_fund: Wallet, + expose_press: Flame, + rebuttal_press: Shield, + investigate: Search, + internal_poll: ClipboardList, + vote_buying: Banknote, + troll_army: Bot, + rest: Bed, + eve_rally: PartyPopper, + kneel: Zap, + eve_phone_bank: Phone, + eve_online_ad: Smartphone, + eve_vote_buying: Banknote, + night_market: Moon, + grassroots_walk: Footprints, + facebook_live: Smartphone, + volunteer_calls: PhoneCall, + street_interview: Mic, + door_to_door: Home, + pilgrimage: Flag, + church_visit: Church, + weddings_funerals: CalendarHeart, + banquet: Utensils, + concert: Music, + flags_billboards: Flag, + phone_banking: Phone, + homecoming: Plane, + radio_ad: Radio, + short_video: Video, + line_groups: MessagesSquare, + influencer_live: Mic, + press_conference: Newspaper, + interview: Mic, + forum: Users, + visit_associations: Handshake, + endorsement: Award, + party_elder: Landmark, + gifts: Gift, + councilor_allies: Users, + big_donor: Building2, + party_fund: Vault, + white_paper: FileText, + lawsuit: Gavel, + report_prosecutor: Scale, + protest_government: Megaphone, + protest_hq: Swords, + crisis_pr: Shield, + fact_check: ShieldCheck, + promise_bribe: Handshake, + smear: Flame, + impersonate: PhoneOff, + frame_vote_buying: Eye, + staged_attack: HeartCrack, + buyout: Banknote, + slush_fund: Vault, + fake_poll: ClipboardList, + chicken_oath: Drama, + invite_oath: Swords, + live_pledge: Video, + workout: Dumbbell, + study: BookOpen, + debate_training: MicVocal, + media_training: Mic, + fire_staff: UserMinus, +}; + +export function actionIcon(actionId: string): LucideIcon { + return ICONS[actionId] ?? PiggyBank; +} diff --git a/web/src/game/art/art.css b/web/src/game/art/art.css new file mode 100644 index 0000000..c95370e --- /dev/null +++ b/web/src/game/art/art.css @@ -0,0 +1,65 @@ +/* 插畫的動畫:只動 transform 與 opacity;減少動態時全部停住 */ +.scene { display: block; width: 100%; height: auto; } +.art-flag { transform-box: fill-box; transform-origin: left center; animation: art-flag 900ms ease-in-out infinite alternate; } +@keyframes art-flag { to { transform: skewY(-8deg) scaleX(0.9); } } +.art-bob { animation: art-bob 1400ms ease-in-out infinite alternate; } +@keyframes art-bob { to { transform: translateY(-3px); } } +.art-drift { animation: art-drift 14s ease-in-out infinite alternate; } +@keyframes art-drift { to { transform: translateX(24px); } } +.art-sway { animation: art-sway 2.4s ease-in-out infinite alternate; } +@keyframes art-sway { from { transform: rotate(-4deg); } to { transform: rotate(4deg); } } +.art-smoke { animation: art-smoke 3s ease-out infinite; } +@keyframes art-smoke { from { opacity: 0.65; transform: translateY(6px); } to { opacity: 0; transform: translateY(-26px); } } +.art-glow { animation: art-glow 1.2s ease-in-out infinite alternate; } +@keyframes art-glow { from { opacity: 0.45; } to { opacity: 1; } } +.art-twinkle { animation: art-glow 1.8s ease-in-out infinite alternate; } +.art-pulse { animation: art-glow 500ms steps(2) infinite; } +.art-pop { transform-box: fill-box; transform-origin: center; animation: art-pop 700ms var(--ease-out) both; } +@keyframes art-pop { from { opacity: 0; transform: scale(0.7) rotate(-8deg); } } +.art-drive { animation: art-drive 6s linear infinite; } +@keyframes art-drive { from { transform: translateX(-380px); } to { transform: translateX(420px); } } +.art-beam { animation: art-beam 3.2s ease-in-out infinite alternate; transform: rotate(calc(var(--beam-angle) * -1)); } +@keyframes art-beam { to { transform: rotate(var(--beam-angle)); } } +.art-rain line { animation: art-rain 700ms linear infinite; } +@keyframes art-rain { from { transform: translate(0, -40px); } to { transform: translate(-12px, 40px); } } +.art-spark { animation: art-spark 900ms ease-out infinite; } +@keyframes art-spark { from { opacity: 1; } to { opacity: 0; transform: translateY(6px); } } +.art-flash { animation: art-flash 2.6s steps(1) infinite; } +@keyframes art-flash { 0%, 100% { opacity: 0; } 8% { opacity: 0.9; } 12% { opacity: 0; } 55% { opacity: 0; } 58% { opacity: 0.8; } 61% { opacity: 0; } } +.art-blink-light { animation: art-glow 400ms steps(2) infinite; } + +/* 人物:眨眼、說話 */ +.avatar .av-eyes { transform-box: fill-box; transform-origin: center; animation: av-blink 5s infinite; } +@keyframes av-blink { 0%, 95%, 100% { transform: scaleY(1); } 97% { transform: scaleY(0.1); } } +.avatar .av-mouth-open { opacity: 0; } +.avatar.is-talking .av-mouth-open { animation: av-talk 260ms steps(1) infinite; } +.avatar.is-talking .av-mouth-closed { animation: av-talk 260ms steps(1) infinite reverse; } +@keyframes av-talk { 0% { opacity: 1; } 50% { opacity: 0; } } + +@media (prefers-reduced-motion: reduce) { + .scene *, .avatar * { animation: none !important; } + .avatar.is-talking .av-mouth-open { opacity: 1; } +} + +/* 美術總覽 */ +.gallery { padding: 20px; display: grid; gap: 16px; max-width: 1400px; margin: 0 auto; } +.gallery h1 { font-family: var(--font-serif); margin: 0; } +.gallery figure { margin: 0; display: grid; gap: 4px; font-size: 13px; color: var(--muted); } +.gallery-avatars { display: flex; flex-wrap: wrap; gap: 12px; } +.gallery-scenes { display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 16px; } +.gallery-scenes .scene { border-radius: 12px; overflow: hidden; } + +.art-firework { animation: art-firework 2.1s var(--ease-out) infinite; } +@keyframes art-firework { 0% { opacity: 0; transform: scale(0.2); } 15% { opacity: 1; } 70% { opacity: 0.9; transform: scale(1); } 100% { opacity: 0; transform: scale(1.1); } } +.art-screen { animation: art-glow 1.6s ease-in-out infinite alternate; } +.art-confetti { animation: art-confetti 2.4s linear infinite; } +@keyframes art-confetti { from { transform: translateY(-20px) rotate(0deg); } to { transform: translateY(380px) rotate(360deg); } } +.art-float { animation: art-floaty 2.4s ease-out infinite; } +@keyframes art-floaty { from { opacity: 0; transform: translateY(10px); } 30% { opacity: 1; } to { opacity: 0; transform: translateY(-50px); } } +.art-fill { transform-box: fill-box; transform-origin: left center; animation: art-fill 2.4s var(--ease-out) infinite; } +@keyframes art-fill { from { transform: scaleX(0.1); } to { transform: scaleX(0.85); } } + +/* 頭像對照頁 */ +.face-gallery { max-width: 1100px; margin: 0 auto; padding: 24px 16px; } +.face-gallery ul { list-style: none; margin: 16px 0 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 14px; } +.face-gallery li { display: grid; justify-items: center; gap: 6px; padding: 8px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface); } diff --git a/web/src/game/art/avatar-check.css b/web/src/game/art/avatar-check.css new file mode 100644 index 0000000..222767b --- /dev/null +++ b/web/src/game/art/avatar-check.css @@ -0,0 +1,33 @@ +/* 部件檢查頁(AvatarCheck.tsx):工具頁,可以往下捲 */ +.avc { max-width: 1280px; margin: 0 auto; padding: 24px 16px 60px; color: var(--ink); } +.avc-head { display: grid; gap: 8px; margin-bottom: 18px; } +.avc-head h1 { margin: 0; font-family: var(--font-serif); } +.avc-head p { margin: 0; max-width: 80ch; } +.avc-controls { display: grid; gap: 8px; } +.avc-controls > div { display: flex; flex-wrap: wrap; gap: 6px; } +.avc-controls button { + min-height: 44px; padding: 4px 14px; border: 2px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); + font: inherit; font-weight: 800; cursor: pointer; +} +.avc-controls button.is-on { background: var(--signal); color: var(--signal-ink); } +.avc-controls button:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +.avc-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 16px; } +.avc-row { + display: grid; grid-template-columns: 180px auto minmax(0, 1fr); align-items: start; gap: 14px; + padding: 12px; border: 3px solid var(--ink); border-radius: 16px; background: var(--surface); box-shadow: 4px 4px 0 var(--shadow-ink); +} +.avc-meta { display: grid; gap: 4px; font-size: 13px; } +.avc-meta b { font-family: var(--font-serif); font-size: 18px; } +.avc-meta code { font-size: 12px; color: var(--muted); } +.avc-big .avatar { display: block; border-radius: 16px; } +.avc-faces { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; } +.avc-faces figure { margin: 0; display: grid; justify-items: center; gap: 4px; } +.avc-faces figcaption { font-size: 11px; color: var(--muted); font-weight: 700; } +.avc-small { grid-template-columns: auto auto; align-items: center; column-gap: 8px; } +.avc-small figcaption { grid-column: 1 / -1; } +.avc-chip { width: 28px; height: 28px; display: grid; place-items: center; overflow: hidden; border-radius: 50%; background: var(--slot-b); } +.avc-chip .avatar { width: 28px; height: auto; } +@media (max-width: 820px) { + .avc-row { grid-template-columns: minmax(0, 1fr); } + .avc-big .avatar { width: 100%; height: auto; max-width: 320px; } +} diff --git a/web/src/game/art/avatar/builtin.tsx b/web/src/game/art/avatar/builtin.tsx new file mode 100644 index 0000000..f45de4f --- /dev/null +++ b/web/src/game/art/avatar/builtin.tsx @@ -0,0 +1,863 @@ +import type { AvatarSpecData } from "@election2026/protocol"; +import type { SVGProps } from "react"; +import { HAIR } from "../palette.ts"; +import { CX, EY, cap, type Head } from "./geometry.ts"; +import { shade } from "./parts.tsx"; + +/** + * 舊部件的程式畫法(髮型、五官、眼鏡、衣服):依臉型即時算出來,目錄裡登記成 builtin:xxx。 + * 海報漫畫風(docs/24 畫風):每塊形狀都有粗墨線外框、平塗色塊;暗面是「形狀減掉往左上挪一點的自己」剩下的一彎, + * 一般大小用深一階的平塗色,大圖改成網點;不用半透明黑色。黑髮的高光是藍灰色的筆觸。 + * look.chibi:Q 版大頭(大眼睛加兩個反光點、小鼻子、腮紅深一點);look.flat:平面貼紙(去掉陰影)。 + * look.detail:0 是 64 像素以下的小圖(線更粗,省略皺紋、網點、鼻孔),1 一般,2 大圖(陰影改網點)。 + */ +export interface Look { + chibi: boolean; + flat: boolean; + /** 要轉成像素圖(沒有 CSS 動畫):只畫閉著的嘴 */ + raster?: boolean; + detail?: 0 | 1 | 2; +} +type P = { spec: AvatarSpecData; h: Head; look: Look; uid: string }; + +/** 墨線的顏色 */ +export const INK = "#1d1714"; + +/** 墨線粗細(畫布單位):小圖要更粗才看得到 */ +export function inkWidth(look: Look): number { + return look.detail === 0 ? 5.2 : look.detail === 2 ? 3 : 3.6; +} +const detailOf = (look: Look) => look.detail ?? 1; + +/** 兩個顏色照比例混合(t=0 是 a,t=1 是 b) */ +export function mix(a: string, b: string, t: number): string { + const x = Number.parseInt(a.slice(1), 16); + const y = Number.parseInt(b.slice(1), 16); + if (!Number.isFinite(x) || !Number.isFinite(y)) return a; + const c = (s: number) => { + const u = (x >> s) & 255; + return Math.round(u + (((y >> s) & 255) - u) * t) + .toString(16) + .padStart(2, "0"); + }; + return `#${c(16)}${c(8)}${c(0)}`; +} + +const luma = (hex: string) => { + const n = Number.parseInt(hex.slice(1), 16); + return Number.isFinite(n) ? 0.3 * ((n >> 16) & 255) + 0.59 * ((n >> 8) & 255) + 0.11 * (n & 255) : 128; +}; + +/** 頭髮的高光:黑髮用藍灰色的筆觸,淺色頭髮往白色調 */ +const shineOf = (hair: string) => (luma(hair) < 70 ? mix(hair, "#9fb4cc", 0.5) : mix(hair, "#ffffff", 0.45)); + +/** 網點遮罩、部件外框濾鏡(每張頭像一份,id 帶 uid) */ +export function InkDefs({ uid, look }: { uid: string; look: Look }) { + const lw = inkWidth(look); + return ( + + + + + + + + + + + + + + + + + + + + + + + + ); +} + +/** 一塊形狀:路徑字串,或圓(cx, cy, r) */ +type Sh = string | readonly [number, number, number]; +function shapeEl(s: Sh, key: number, props: SVGProps = {}) { + return typeof s === "string" ? : ; +} + +/** 幾塊形狀合起來描一圈墨線(先畫兩倍粗的墨、再蓋上顏色),形狀之間不會留下內線 */ +function Inked({ shapes, fill, lw, mask }: { shapes: readonly Sh[]; fill: string; lw: number; mask?: string }) { + return ( + <> + + {shapes.map((s, i) => shapeEl(s, i))} + + + {shapes.map((s, i) => shapeEl(s, i))} + + + ); +} + +/** 剪裁用的形狀 */ +function Clip({ id, shapes }: { id: string; shapes: readonly Sh[] }) { + return {shapes.map((s, i) => shapeEl(s, i))}; +} + +/** + * 暗面:形狀減掉往左上挪 (dx, dy) 的自己,剩下右下的一彎。 + * dots 有給就改成網點(範圍寬一倍),沒給就是深一階的平塗色。 + */ +function Shade({ id, d, base, dark, dx, dy, dots }: { id: string; d: string; base: string; dark: string; dx: number; dy: number; dots?: string }) { + const k = dots ? 2 : 1; + return ( + <> + + + + + + + + + ); +} + +// ── 頭髮 ── + +interface HairArt { + shapes: Sh[]; + /** 頭髮裡面的墨線(分線、髮流),會剪在頭髮形狀裡,不會跑出去 */ + lines?: string[]; + /** 高光筆觸,也剪在頭髮裡 */ + shine?: string[]; +} + +function backHair(spec: AvatarSpecData, h: Head): HairArt | null { + const { w, top, chin } = h; + switch (spec.hair) { + case "bob": + case "bobSide": + return { shapes: [`M${CX - w - 9} ${EY} C${CX - w - 12} ${top - 6} ${CX + w + 12} ${top - 6} ${CX + w + 9} ${EY} L${CX + w + 10} ${chin - 6} C${CX + w - 6} ${chin + 2} ${CX - w + 6} ${chin + 2} ${CX - w - 10} ${chin - 6} Z`] }; + case "shortBob": + return { shapes: [`M${CX - w - 7} ${EY} C${CX - w - 10} ${top - 6} ${CX + w + 10} ${top - 6} ${CX + w + 7} ${EY} L${CX + w + 6} ${EY + 26} C${CX + w - 8} ${EY + 32} ${CX - w + 8} ${EY + 32} ${CX - w - 6} ${EY + 26} Z`] }; + case "longWavy": { + // 長波浪:兩側的外緣一彎一彎,到肩膀 + const wave = (s: number, i: number) => [CX + s * (w + 12 + (i % 2) * 5), EY + i * 21 + 21] as const; + let d = `M${CX - w - 10} ${EY} C${CX - w - 14} ${top - 8} ${CX + w + 14} ${top - 8} ${CX + w + 10} ${EY}`; + for (let i = 0; i < 5; i++) d += ` Q${CX + w + 22} ${EY + i * 21 + 10} ${wave(1, i).join(" ")}`; + d += ` C${CX + w - 10} 208 ${CX - w + 10} 208 ${wave(-1, 4).join(" ")}`; + for (let i = 4; i >= 0; i--) d += ` Q${CX - w - 22} ${EY + i * 21 + 10} ${i > 0 ? wave(-1, i - 1).join(" ") : `${CX - w - 10} ${EY}`}`; + return { + shapes: [`${d} Z`], + lines: [`M${CX - w - 6} ${EY + 24} Q${CX - w - 14} ${EY + 46} ${CX - w - 6} ${EY + 70} Q${CX - w} ${EY + 88} ${CX - w - 8} 196`, `M${CX + w + 6} ${EY + 24} Q${CX + w + 14} ${EY + 46} ${CX + w + 6} ${EY + 70} Q${CX + w} ${EY + 88} ${CX + w + 8} 196`], + }; + } + case "long": + case "longMiddle": + case "longBangs": + return { + shapes: [`M${CX - w - 8} ${EY} C${CX - w - 12} ${top - 8} ${CX + w + 12} ${top - 8} ${CX + w + 8} ${EY} L${CX + w + 14} 198 C${CX + w - 10} 206 ${CX - w + 10} 206 ${CX - w - 14} 198 Z`], + lines: [`M${CX - w - 4} ${EY + 30} L${CX - w - 7} 196`, `M${CX + w + 4} ${EY + 30} L${CX + w + 7} 196`], + }; + case "ponytail": { + // 馬尾:頭後面一圈,加上從分線那一側垂到肩膀的一束 + const s = spec.part === "right" ? 1 : -1; + return { + shapes: [ + `M${CX - w - 6} ${EY} C${CX - w - 9} ${top - 6} ${CX + w + 9} ${top - 6} ${CX + w + 6} ${EY} L${CX + w + 4} ${EY + 12} L${CX - w - 4} ${EY + 12} Z`, + `M${CX + s * (w - 4)} ${EY - 4} C${CX + s * (w + 16)} ${EY + 10} ${CX + s * (w + 20)} ${EY + 44} ${CX + s * (w + 8)} ${EY + 74} C${CX + s * (w + 2)} ${EY + 56} ${CX + s * (w - 2)} ${EY + 30} ${CX + s * (w - 10)} ${EY + 10} Z`, + ], + lines: [`M${CX + s * (w + 2)} ${EY + 8} C${CX + s * (w + 12)} ${EY + 26} ${CX + s * (w + 12)} ${EY + 46} ${CX + s * (w + 7)} ${EY + 64}`], + }; + } + case "bun": + return { shapes: [[CX, top - 6, 17]], shine: [`M${CX - 10} ${top - 12} Q${CX - 6} ${top - 19} ${CX + 2} ${top - 20}`] }; + case "perm": + return { shapes: [-1, -0.6, -0.2, 0.2, 0.6, 1].map((k) => [CX + k * (w + 6), EY + 6 - Math.abs(k) * 2, 13] as const) }; + default: + return null; + } +} + +function frontHair(spec: AvatarSpecData, h: Head): HairArt | null { + const { w, top } = h; + const dir = spec.part === "right" ? 1 : -1; + const partX = CX + dir * w * 0.42; + /** 鬢角:上寬下尖 */ + const burn = (s: number) => `M${CX + s * (w + 1)} ${h.templeY - 2} L${CX + s * (w - 7)} ${h.templeY - 2} Q${CX + s * (w - 5)} ${EY - 8} ${CX + s * (w - 2)} ${EY + 4} L${CX + s * (w + 1)} ${EY + 4} Z`; + const burns = [burn(-1), burn(1)]; + /** 頭頂左上一道高光,再一小段 */ + const shine = (lift: number) => [`M${CX - w * 0.66} ${top + 9} Q${CX - w * 0.52} ${top - lift} ${CX - w * 0.16} ${top - lift - 1}`, `M${CX - w * 0.02} ${top - lift - 1.5} L${CX + w * 0.1} ${top - lift - 1.2}`]; + const curls = (pts: readonly (readonly [number, number, number])[]) => pts.map(([x, y]) => `M${x - 7} ${y + 3} Q${x - 1} ${y - 6} ${x + 6} ${y + 1}`); + switch (spec.hair) { + case "short": + case "crew": { + const thick = spec.hair === "crew" ? 5 : 7; + return { shapes: [cap(h, thick, 0.19), ...burns], shine: shine(thick * 0.5) }; + } + case "side": + case "volume": { + const thick = spec.hair === "volume" ? 14 : 8; + // 瀏海往另一側梳過去 + const bang = `M${partX} ${top + 4} C${partX - dir * 18} ${top + 12} ${CX - dir * w * 0.7} ${top + 22} ${CX - dir * (w + 4)} ${h.templeY + 4} L${CX - dir * (w + 6)} ${h.templeY - 8} C${CX - dir * w * 0.6} ${top - thick + 2} ${partX - dir * 10} ${top - thick + 2} ${partX} ${top - 2} Z`; + return { + shapes: [cap(h, thick, 0.2, { partX, dip: 6 }), bang, ...burns], + lines: [`M${partX} ${top - thick - 2} L${partX + dir * 2} ${top + 14}`, `M${partX - dir * 4} ${top + 1} C${partX - dir * 18} ${top + 4} ${CX - dir * w * 0.62} ${top + 10} ${CX - dir * (w + 2)} ${h.templeY - 2}`], + shine: shine(thick * 0.55), + }; + } + case "slick": + return { + shapes: [cap(h, 7, 0.19), ...burns], + shine: [`M${CX - w * 0.5} ${top + 6} Q${CX - w * 0.2} ${top - 4} ${CX + w * 0.3} ${top + 2}`, `M${CX - w * 0.3} ${top + 12} Q${CX} ${top + 2} ${CX + w * 0.5} ${top + 8}`, `M${CX - w * 0.72} ${top + 14} Q${CX - w * 0.6} ${top + 4} ${CX - w * 0.45} ${top}`], + }; + case "receding": + return { shapes: [cap(h, 5, 0.27, { dip: -9 }), ...burns], shine: shine(2) }; + case "ponytail": + // 頭髮往後綁:服貼的一頂,髮線清楚 + return { shapes: [cap(h, 6, 0.21, { partX, dip: 5 })], lines: [`M${partX} ${top - 8} L${partX + dir * 2} ${top + 10}`], shine: shine(3) }; + case "pixie": { + // 女性露耳短髮:短短一頂,斜瀏海掃到眉毛上方 + const fringe = `M${partX} ${top + 2} C${partX - dir * 14} ${top + 14} ${CX - dir * w * 0.55} ${EY - 26} ${CX - dir * (w + 3)} ${EY - 14} L${CX - dir * (w + 6)} ${h.templeY - 6} C${CX - dir * w * 0.6} ${top - 8} ${partX - dir * 8} ${top - 8} ${partX} ${top - 3} Z`; + return { + shapes: [cap(h, 8, 0.22, { partX, dip: 6 }), fringe, burn(-1), burn(1)], + lines: [`M${partX - dir * 4} ${top + 4} C${partX - dir * 16} ${top + 14} ${CX - dir * w * 0.5} ${EY - 28} ${CX - dir * (w - 2)} ${EY - 17}`, `M${partX - dir * 12} ${top + 2} C${CX - dir * w * 0.3} ${top + 14} ${CX - dir * w * 0.7} ${EY - 30} ${CX - dir * (w + 2)} ${EY - 24}`], + shine: shine(4), + }; + } + case "fringe": { + // 瀏海短髮:頭髮往前蓋住半個額頭,瀏海尾端一撮一撮 + const n = 6; + const hl = top + (h.chin - top) * 0.3; + let bangs = `M${CX - w - 4} ${h.templeY + 4} C${CX - w - 6} ${top - 8} ${CX + w + 6} ${top - 8} ${CX + w + 4} ${h.templeY + 4}`; + for (let i = n; i > 0; i--) { + const x0 = CX - w * 0.95 + ((2 * w * 0.95) * i) / n; + const x1 = CX - w * 0.95 + ((2 * w * 0.95) * (i - 1)) / n; + bangs += ` L${(x0 + x1) / 2} ${hl + 4} L${x1} ${hl - 3}`; + } + bangs += " Z"; + return { shapes: [bangs, ...burns], lines: [-0.5, -0.1, 0.3].map((k) => `M${CX + k * w} ${top + 2} L${CX + k * w - 2} ${hl - 4}`), shine: shine(4) }; + } + case "spiky": { + // 抓立短髮:頭頂一撮一撮往上翹 + const n = 7; + let crown = `M${CX - w - 3} ${top + 12}`; + for (let i = 0; i < n; i++) { + const x0 = CX - w - 3 + ((2 * w + 6) * i) / n; + const x1 = CX - w - 3 + ((2 * w + 6) * (i + 1)) / n; + const lift = 14 - Math.abs(i - (n - 1) / 2) * 2.6; + crown += ` L${(x0 + x1) / 2 + 2} ${top - lift} L${x1} ${top - 2 + Math.abs(i - (n - 1) / 2) * 1.5}`; + } + crown += ` L${CX + w + 3} ${top + 12} Z`; + return { shapes: [cap(h, 6, 0.19), crown, ...burns], shine: shine(3) }; + } + case "pompadour": + // 高聳背頭:往後梳、頭頂很高,髮流往後 + return { + shapes: [cap(h, 17, 0.14, { dip: 4 }), ...burns], + shine: [`M${CX - w * 0.55} ${top + 4} Q${CX - w * 0.3} ${top - 14} ${CX + w * 0.35} ${top - 12}`, `M${CX - w * 0.3} ${top + 9} Q${CX} ${top - 6} ${CX + w * 0.55} ${top - 4}`], + lines: [`M${CX - w * 0.75} ${top + 10} Q${CX - w * 0.5} ${top - 10} ${CX + w * 0.1} ${top - 15}`, `M${CX + w * 0.75} ${top + 10} Q${CX + w * 0.6} ${top - 6} ${CX + w * 0.25} ${top - 13}`], + }; + case "flatTop": + // 平頭板寸:頭頂削平、往上站 + return { + shapes: [cap(h, 6, 0.18), `M${CX - w - 2} ${top + 10} Q${CX - w} ${top - 9} ${CX - w + 6} ${top - 11} L${CX + w - 6} ${top - 11} Q${CX + w} ${top - 9} ${CX + w + 2} ${top + 10} Z`, ...burns], + lines: [-0.45, -0.15, 0.15, 0.45].map((k) => `M${CX + k * w * 1.4} ${top - 11} L${CX + k * w * 1.4} ${top - 7}`), + shine: [`M${CX - w * 0.6} ${top - 7} L${CX + w * 0.1} ${top - 7}`], + }; + case "longMiddle": + case "middle": { + // 中分:分線在正中間,兩片瀏海往兩邊梳 + const bang = (s: number) => `M${CX} ${top + 2} C${CX + s * 10} ${top + 12} ${CX + s * w * 0.7} ${top + 18} ${CX + s * (w + 4)} ${h.templeY + 4} L${CX + s * (w + 6)} ${h.templeY - 8} C${CX + s * w * 0.6} ${top - 7} ${CX + s * 8} ${top - 7} ${CX} ${top - 3} Z`; + return { + shapes: [cap(h, 8, 0.24, { dip: -8 }), bang(-1), bang(1), ...burns], + lines: [`M${CX} ${top - 12} L${CX} ${top + 6}`, `M${CX - 3} ${top + 2} C${CX - 14} ${top + 6} ${CX - w * 0.62} ${top + 10} ${CX - w - 2} ${h.templeY - 2}`, `M${CX + 3} ${top + 2} C${CX + 14} ${top + 6} ${CX + w * 0.62} ${top + 10} ${CX + w + 2} ${h.templeY - 2}`], + shine: shine(4), + }; + } + case "combover": { + // 側梳地中海:兩側濃,頭頂只剩幾根髮絲(HairFront 另外畫),中間露出頭皮 + const side = (s: number) => `M${CX + s * (w + 3)} ${h.templeY - 10} C${CX + s * (w + 5)} ${h.templeY} ${CX + s * (w + 3)} ${EY - 2} ${CX + s * (w - 1)} ${EY + 4} L${CX + s * (w - 6)} ${EY + 4} Q${CX + s * (w - 5)} ${h.templeY + 4} ${CX + s * (w - 7)} ${h.templeY - 6} Z`; + return { shapes: [side(-1), side(1)] }; + } + case "curly": { + const pts = [-0.85, -0.45, 0, 0.45, 0.85].map((k, i) => [CX + k * w, top + (i % 2 ? 2 : 8) + Math.abs(k) * 10, 15] as const); + return { shapes: pts, lines: curls(pts) }; + } + case "perm": { + const pts = [-0.8, -0.4, 0, 0.4, 0.8].map((k, i) => [CX + k * w, top + (i % 2 ? 4 : 10) + Math.abs(k) * 8, 13] as const); + return { shapes: pts, lines: curls(pts) }; + } + case "bob": + case "longBangs": + return { + shapes: [`M${CX - w - 6} ${h.templeY + 8} C${CX - w - 8} ${top - 8} ${CX + w + 8} ${top - 8} ${CX + w + 6} ${h.templeY + 8} C${CX + w * 0.6} ${top + 24} ${CX - w * 0.6} ${top + 24} ${CX - w - 6} ${h.templeY + 8} Z`], + lines: [`M${CX - w * 0.2} ${top + 16} L${CX - w * 0.24} ${top + 22}`, `M${CX + w * 0.25} ${top + 16} L${CX + w * 0.3} ${top + 21}`], + shine: shine(4), + }; + case "bobSide": + case "shortBob": + case "longWavy": + case "long": { + // 側分的瀏海:分線那一側髮線高,往另一側斜斜蓋過額頭 + const near = CX + dir * (w + 7); + const far = CX - dir * (w + 7); + const hairline = top + (h.chin - top) * 0.2; + return { + shapes: [ + `M${near} ${h.templeY + 6} C${near + dir * 2} ${top - 8} ${CX - dir * w * 0.3} ${top - 10} ${CX - dir * w * 0.7} ${top - 2} C${far} ${top + 8} ${far} ${h.templeY} ${far} ${h.templeY + 18} C${CX - dir * w * 0.55} ${hairline + 8} ${CX} ${hairline + 2} ${partX} ${top + 8} C${partX + dir * 8} ${top + 16} ${near - dir * 3} ${h.templeY - 2} ${near} ${h.templeY + 6} Z`, + ], + lines: [`M${partX} ${top - 8} L${partX} ${top + 8}`, `M${partX - dir * 4} ${top + 2} C${CX - dir * w * 0.2} ${top + 4} ${CX - dir * w * 0.6} ${top + 10} ${far + dir * 2} ${h.templeY + 10}`], + shine: shine(4), + }; + } + case "bun": + return { shapes: [cap(h, 4, 0.2)], shine: shine(2) }; + default: + return null; + } +} + +function HairLayer({ art, color, look, id }: { art: HairArt; color: string; look: Look; id: string }) { + const lw = inkWidth(look); + const d = detailOf(look); + const inside = (art.lines?.length || art.shine?.length) && d > 0; + return ( + + + {inside && ( + <> + + + {art.shine && ( + + {art.shine.map((s, i) => shapeEl(s, i))} + + )} + {art.lines && ( + + {art.lines.map((s, i) => shapeEl(s, i))} + + )} + + + )} + + ); +} + +export function HairBack({ spec, h, look, uid }: P) { + const art = backHair(spec, h); + return art ? : null; +} + +export function HairFront({ spec, h, look, uid }: P) { + const c = spec.hairColor; + const lw = inkWidth(look); + const d = detailOf(look); + const { w, top } = h; + if (spec.hair === "bald") { + // 光頭:兩邊剩一點頭髮(網點),頭頂一塊反光 + const tufts = [ + `M${CX - w + 1} ${h.templeY + 6} L${CX - w + 6} ${h.templeY + 4} L${CX - w + 5} ${EY + 4} L${CX - w + 1} ${EY + 4} Z`, + `M${CX + w - 1} ${h.templeY + 6} L${CX + w - 6} ${h.templeY + 4} L${CX + w - 5} ${EY + 4} L${CX + w - 1} ${EY + 4} Z`, + ]; + return ( + + 0 ? c : mix(spec.skin, c, 0.35)} mask={d > 0 ? `url(#stub-${uid})` : undefined}> + {tufts.map((s, i) => shapeEl(s, i))} + + + + ); + } + if (spec.hair === "buzz") { + // 平頭:頭髮是網點,邊緣一條細墨線 + const s = cap(h, 2, 0.17); + return ( + + + 0 ? c : mix(spec.skin, c, 0.6)} mask={d > 0 ? `url(#stub-${uid})` : undefined} /> + + ); + } + const art = frontHair(spec, h); + if (!art) return null; + if (spec.hair === "combover") { + // 地中海:頭皮一塊反光,再從分線那邊梳幾根髮絲過去(墨線包著頭髮色) + const dir = spec.part === "right" ? 1 : -1; + const strands = [0, 7, 14].map((lift) => `M${CX + dir * (w + 2)} ${h.templeY - 6 + lift * 0.3} C${CX + dir * w * 0.4} ${top - 4 + lift} ${CX - dir * w * 0.4} ${top - 3 + lift} ${CX - dir * (w - 2)} ${h.templeY - 2 + lift * 0.4}`); + return ( + + + + + + {strands.map((s, i) => shapeEl(s, i))} + + + {strands.map((s, i) => shapeEl(s, i))} + + + + ); + } + return ; +} + +// ── 五官 ── + +export function Brows({ spec, h, look }: P) { + const bushy = spec.brows === "bushy"; + const t = (bushy ? 7.5 : spec.brows === "thick" ? 7 : spec.brows === "thin" ? 3.2 : 4.8) * (look.detail === 0 ? 1.25 : 1); + const a = (spec.browAngle ?? 0) * 4; + const y = EY - 15; + const dx = h.eyeDx; + const color = spec.hair === "bald" ? "#3b2f28" : spec.hairColor === HAIR[4] ? "#6f6a66" : shade(spec.hairColor, 0.7); + // 一頭粗(眉頭)一頭細(眉尾)的實心筆觸 + const brow = (s: number) => { + const ox = CX + s * (dx + 10); + const ix = CX + s * (dx - 9); + const oy = y - a; + const iy = y + a * 0.6; + const cx = CX + s * dx; + const cy = y - 5 - a * 0.3; + return `M${ox} ${oy - t * 0.22} Q${cx} ${cy - t * 0.6} ${ix} ${iy - t * 0.5} L${ix} ${iy + t * 0.5} Q${cx} ${cy + t * 0.4} ${ox} ${oy + t * 0.22} Z`; + }; + /** 粗濃眉:沿著眉毛往上翹的一撮一撮毛 */ + const tufts = (s: number) => { + const ix = CX + s * (dx - 9); + const iy = y + a * 0.6; + const ox = CX + s * (dx + 10); + const oy = y - a; + const cx = CX + s * dx; + const cy = y - 5 - a * 0.3; + return [0.08, 0.28, 0.48, 0.68, 0.88].map((k) => { + const px = (1 - k) ** 2 * ix + 2 * (1 - k) * k * cx + k ** 2 * ox; + const py = (1 - k) ** 2 * iy + 2 * (1 - k) * k * cy + k ** 2 * oy - t * 0.35; + return `M${px} ${py + 1} L${px + s * 2.2} ${py - 3.6}`; + }); + }; + return ( + + + + {bushy && look.detail !== 0 && ( + + {[...tufts(-1), ...tufts(1)].map((d, i) => ( + + ))} + + )} + + ); +} + +export function Eyes({ spec, h, look }: P) { + const dx = h.eyeDx; + const lw = inkWidth(look); + const d = detailOf(look); + const kind = spec.eyes ?? "round"; + if (kind === "smile") { + return ( + + + + + ); + } + if (kind === "dot") { + const r = look.chibi ? 4.8 : d === 0 ? 4.4 : 3.6; + return ( + + {[-1, 1].map((s) => ( + + + {look.chibi && } + + ))} + + ); + } + const narrow = kind === "narrow"; + const droopy = kind === "droopy"; + const wide = kind === "wide"; + /** 下垂眼的眼尾往下掉多少(s 是左右:眼尾在外側) */ + const droop = droopy ? 3.5 : 0; + if (look.chibi) { + // Q 版:大眼睛、大瞳孔、兩個反光點 + const ry = narrow ? 6.2 : wide ? 9.4 : 8.4; + return ( + + {[-1, 1].map((s) => { + const x = CX + s * dx; + return ( + + + + + + + + ); + })} + + ); + } + if (d === 0) { + // 小圖:一顆瞳孔加一條上眼皮,白眼球在這個大小只會糊成一團 + return ( + + {[-1, 1].map((s) => { + const x = CX + s * dx; + return ( + + + + + ); + })} + + ); + } + const ry = narrow ? 3.4 : wide ? 6.8 : 5.2; + const rx = wide ? 8.2 : 7.4; + return ( + + {[-1, 1].map((s) => { + const x = CX + s * dx; + // 眼白:一般是橢圓,下垂眼是眼尾往下的杏仁形 + const white = droopy ? ( + + ) : ( + + ); + const lidY = narrow ? 0.5 : wide ? 0.4 : 1; + const lidTop = narrow ? 6.4 : wide ? 10.4 : droopy ? 8.6 : 8.4; + return ( + + {white} + + + {/* 上眼皮:粗墨線,眼尾往外多拉一點;下垂眼的眼皮厚、眼尾往下 */} + + {droopy && } + + ); + })} + + ); +} + +export function Glasses({ spec, h, look }: P) { + const style = spec.glassesStyle ?? "black"; + const color = spec.glassesColor ?? (style === "metal" ? "#a8874f" : style === "rimless" ? "#9aa3ad" : "#22252a"); + const dx = h.eyeDx; + const d = detailOf(look); + const lw = inkWidth(look); + const lens = (s: number) => { + const x = CX + s * dx; + switch (style) { + case "round": + return ; + case "black": + return ; + case "halfRim": + case "browline": + return ; + default: + return ; + } + }; + // 眼鏡是很多人的招牌特徵:小圖加粗,才不會不見 + // 眉框:上緣粗黑框、下緣細金屬框(顏色是下緣的金屬色) + const base = style === "black" ? 4 : style === "rimless" ? 1.4 : style === "halfRim" || style === "browline" ? 2 : 2.2; + const width = d === 0 ? base + 1.4 : base; + return ( + + {lens(-1)} + {lens(1)} + {(style === "halfRim" || style === "browline") && ( + + + + + )} + + + + {/* 鏡片反光 */} + {d > 0 && style !== "rimless" && ( + + + + + )} + + ); +} + +export function Nose({ spec, look }: P) { + const lw = inkWidth(look); + const d = detailOf(look); + if (look.chibi) return ; + const kind = spec.nose ?? "normal"; + const line = { fill: "none", stroke: INK, strokeWidth: lw * 0.6, strokeLinecap: "round" as const, strokeLinejoin: "round" as const }; + const under = d > 0 && !look.flat && ; + if (kind === "round") + return ( + + {under} + {/* 圓鼻頭:一顆鼻球、反光、兩個鼻孔 */} + + {d > 0 && } + {d > 0 && ( + + + + + )} + + ); + if (d === 0) return ; + if (kind === "small") + return ( + + {under} + + + + ); + if (kind === "big") + return ( + + {under} + {/* 大鼻頭:一圈鼻球加兩邊鼻翼 */} + + + + + + ); + return ( + + {under} + {/* 一側鼻樑線+兩個鼻孔 */} + + + + + ); +} + +const MOUTH = "#7a3a32"; +const MOUTH_INK = "#3a1712"; + +export function Mouth({ spec, h, look }: P) { + const y = h.mouthY; + const lw = inkWidth(look); + const d = detailOf(look); + const kind = spec.mouth ?? "smile"; + const stroke = { fill: "none", stroke: MOUTH_INK, strokeLinecap: "round" as const }; + /** 嘴角的小勾,笑起來才有表情 */ + const ticks = (x: number, yy: number) => + d > 0 && ( + + + + + ); + const lip = d > 0 && !look.flat && ; + const closed = + kind === "teeth" ? ( + + + + {ticks(14, y - 2)} + + ) : kind === "grin" ? ( + + + {ticks(16, y - 3)} + + ) : kind === "smirk" ? ( + + {/* 嘴角上揚:一邊高一邊平 */} + + {d > 0 && } + + ) : kind === "laugh" ? ( + + {/* 開懷大笑:張大的嘴、上排牙齒、舌頭 */} + + + {d > 0 && } + {ticks(15, y - 3)} + + ) : kind === "closed" ? ( + + ) : ( + + + {ticks(12, y - 2)} + + ); + return ( + + {lip} + {closed} + {!look.raster && } + + ); +} + +// ── 身體 ── + +/** 脖子和衣服 */ +export function Clothes({ spec, h, look, uid }: P) { + const lw = inkWidth(look); + const d = detailOf(look); + const neckTop = h.chin - 14; + const body = "M16 220 C20 182 52 166 100 164 C148 166 180 182 184 220 Z"; + const line = { stroke: INK, strokeWidth: lw, strokeLinejoin: "round" as const }; + const thin = { stroke: INK, strokeWidth: lw * 0.75, strokeLinejoin: "round" as const }; + const shadows = !look.flat && d > 0; + /** 身體的顏色:只穿襯衫的是襯衫色,其他是外套(或上衣)色 */ + const top = spec.outfit === "shirt" ? spec.shirt : spec.suit; + return ( + + + {/* 下巴在脖子上的影子(Q 版頭和身體分開縮放,對不準,改成一小塊) */} + {shadows && + (look.chibi ? ( + + ) : ( + <> + + + + + + ))} + + {shadows && } + + {spec.outfit === "shirt" ? ( + + {/* 只穿襯衫:身體是襯衫色,尖領、門襟、扣子 */} + + + {d > 0 && ( + + + + + + )} + + ) : spec.outfit === "polo" ? ( + + + {d > 0 && } + + ) : spec.outfit === "blouse" ? ( + + ) : ( + + + {/* 西裝翻領 */} + {d > 0 && ( + + + + + )} + {spec.outfit === "suit" && ( + + + + + )} + + )} + + ); +} + +/** 耳朵、臉、臉的暗面、鬍渣 */ +export function FaceBase({ spec, h, look, uid }: P) { + const lw = inkWidth(look); + const d = detailOf(look); + const earR = spec.ears === "big" ? 11 : spec.ears === "small" ? 6 : 8; + const skin = spec.skin; + return ( + <> + {[-1, 1].map((s) => { + const ex = CX + s * (h.w + 1); + const ey = EY + 4; + return ( + + + {d > 0 && } + + ); + })} + + {!look.flat && d > 0 && } + {/* 鬍渣:網點 */} + {spec.beard && ( + 0 ? 0.65 : 0.4)} + mask={d > 0 ? `url(#stub-${uid})` : undefined} + /> + )} + + + ); +} + +/** 皺紋、眼袋、腮紅、小鬍子 */ +export function FaceMarks({ spec, h, look }: P) { + const lines = spec.lines ?? 0; + const lw = inkWidth(look); + const d = detailOf(look); + const blush = (s: number) => ; + return ( + <> + {lines > 0 && d > 0 && ( + + + + {lines > 1 && ( + <> + + + + + )} + + )} + {/* 腮紅:淡淡的平塗(網點腮紅看起來像起疹子),小圖只有 Q 版畫 */} + {(d > 0 || look.chibi) && ( + + {blush(-1)} + {blush(1)} + + )} + {/* 大下巴:一條雙下巴線 */} + {spec.face === "jowl" && d > 0 && } + {spec.mustache && } + + ); +} diff --git a/web/src/game/art/avatar/geometry.ts b/web/src/game/art/avatar/geometry.ts new file mode 100644 index 0000000..f600aa4 --- /dev/null +++ b/web/src/game/art/avatar/geometry.ts @@ -0,0 +1,116 @@ +import type { AvatarSpecData } from "@election2026/protocol"; + +/** + * 頭像的幾何(docs/24 第 1 節「錨點」):200×220 的畫布、臉的形狀、頭頂和眼睛那條線在哪。 + * 部件圖都畫在「標準臉」(鵝蛋臉、臉寬臉長 1)上,這裡算出實際的臉,把部件移過去、縮放到合適大小。 + */ +export const CX = 100; +export const EY = 96; +export const W = 200; +export const H = 220; +/** 標準臉的頭寬一半、頭頂、下巴(部件圖照這張臉畫) */ +export const STD = { w: 42, top: EY - 58, chin: EY + 52 } as const; + +export interface Head { + w: number; + top: number; + chin: number; + templeY: number; + path: string; + mouthY: number; + eyeDx: number; + /** 臉長倍率(含臉型) */ + fh: number; +} + +type FaceShape = { t: number; c: number; j: number; jy: number; h: number }; +const SHAPES: Record = { + oval: { t: 0.93, c: 1.0, j: 0.74, jy: 18, h: 1 }, + round: { t: 0.96, c: 1.07, j: 0.88, jy: 14, h: 0.96 }, + long: { t: 0.9, c: 0.95, j: 0.74, jy: 20, h: 1.08 }, + square: { t: 0.96, c: 1.0, j: 0.97, jy: 12, h: 1 }, + heart: { t: 1.02, c: 0.98, j: 0.62, jy: 22, h: 1 }, + /** 大下巴:下顎比顴骨還寬,另外畫一條雙下巴線(builtin.tsx 的 FaceMarks) */ + jowl: { t: 0.92, c: 1.03, j: 1.04, jy: 9, h: 1.02 }, +}; + +/** 一圈點 → 平滑的封閉曲線(Catmull-Rom 轉三次貝茲) */ +export function smooth(points: readonly [number, number][]): string { + const n = points.length; + const p = (i: number) => points[(i + n) % n]!; + let d = `M${p(0)[0].toFixed(1)} ${p(0)[1].toFixed(1)}`; + for (let i = 0; i < n; i++) { + const [x0, y0] = p(i - 1); + const [x1, y1] = p(i); + const [x2, y2] = p(i + 1); + const [x3, y3] = p(i + 2); + d += ` C${(x1 + (x2 - x0) / 6).toFixed(1)} ${(y1 + (y2 - y0) / 6).toFixed(1)} ${(x2 - (x3 - x1) / 6).toFixed(1)} ${(y2 - (y3 - y1) / 6).toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`; + } + return `${d} Z`; +} + +export function headOf(spec: AvatarSpecData): Head { + const shape = SHAPES[spec.face ?? "oval"] ?? SHAPES.oval!; + const w = 42 * (spec.faceW ?? 1); + const fh = (spec.faceH ?? 1) * shape.h; + const top = EY - 58 * fh; + const chin = EY + 52 * fh; + const templeY = top + (chin - top) * 0.3; + const cheekY = EY + 14; + const jawY = chin - shape.jy * fh; + const pts: [number, number][] = [ + [CX, top], + [CX + w * 0.72, top + 10 * fh], + [CX + w * shape.t, templeY], + [CX + w * shape.c, cheekY], + [CX + w * shape.j, jawY], + [CX + w * 0.3, chin - 3], + [CX, chin], + [CX - w * 0.3, chin - 3], + [CX - w * shape.j, jawY], + [CX - w * shape.c, cheekY], + [CX - w * shape.t, templeY], + [CX - w * 0.72, top + 10 * fh], + ]; + return { w, top, chin, templeY, path: smooth(pts), mouthY: EY + 30 * fh, eyeDx: 17 * (spec.faceW ?? 1), fh }; +} + +/** 頭頂的一頂「帽子」形狀的頭髮:外緣沿頭形外擴 thick,內緣是髮線 */ +export function cap(h: Head, thick: number, hairline: number, opts: { sideTo?: number; dip?: number; partX?: number } = {}): string { + const { w, top, templeY } = h; + const hl = top + (h.chin - top) * hairline; + const side = opts.sideTo ?? templeY + 6; + const L = CX - w - thick * 0.7; + const R = CX + w + thick * 0.7; + const dip = opts.dip ?? 0; + const px = opts.partX ?? CX; + return [ + `M${L} ${side}`, + `C${L - 2} ${top + 4} ${CX - w * 0.6} ${top - thick} ${CX} ${top - thick}`, + `C${CX + w * 0.6} ${top - thick} ${R + 2} ${top + 4} ${R} ${side}`, + `L${CX + w * 0.96} ${side}`, + `C${CX + w * 0.92} ${hl + 2} ${px + w * 0.4} ${hl - dip} ${px} ${hl + dip * 0.3}`, + `C${px - w * 0.4} ${hl - dip} ${CX - w * 0.92} ${hl + 2} ${CX - w * 0.96} ${side}`, + "Z", + ].join(" "); +} + +/** 部件圖從標準臉移到實際的臉:回傳 SVG transform(none 不用動) */ +export function anchorTransform(anchor: "none" | "headTop" | "face", h: Head): string | undefined { + if (anchor === "none") return undefined; + const s = h.w / STD.w; + if (anchor === "headTop") return `translate(${CX} ${h.top}) scale(${s}) translate(${-CX} ${-STD.top})`; + return `translate(${CX} ${EY}) scale(${s} ${h.fh}) translate(${-CX} ${-EY})`; +} + +/** 標準畫布上的一條水平線(例如帽子壓住頭髮的那條線)換到實際的臉上 */ +export function anchorY(anchor: "none" | "headTop" | "face", y: number, h: Head): number { + if (anchor === "headTop") return h.top + (y - STD.top) * (h.w / STD.w); + if (anchor === "face") return EY + (y - EY) * h.fh; + return y; +} + +// ── Q 版大頭:頭放大、身體縮小(部件跟著頭、身體走) ── +export const CHIBI = { head: 1.2, headDy: 9, body: 0.86 } as const; +export const chibiHead = `translate(0 ${CHIBI.headDy}) translate(${CX} ${EY}) scale(${CHIBI.head}) translate(${-CX} ${-EY})`; +export const chibiBody = `translate(${CX} ${H}) scale(${CHIBI.body}) translate(${-CX} ${-H})`; diff --git a/web/src/game/art/avatar/layers.tsx b/web/src/game/art/avatar/layers.tsx new file mode 100644 index 0000000..c6c5e6b --- /dev/null +++ b/web/src/game/art/avatar/layers.tsx @@ -0,0 +1,105 @@ +import { AVATAR_CATALOG, wearItem, type AvatarItem, type AvatarSpecData } from "@election2026/protocol"; +import { useId } from "react"; +import { Brows, Clothes, Eyes, FaceBase, FaceMarks, Glasses, HairBack, HairFront, InkDefs, Mouth, Nose, type Look } from "./builtin.tsx"; +import { anchorTransform, anchorY, chibiBody, chibiHead, headOf, type Head } from "./geometry.ts"; +import { WornPart, type PartCtx } from "./parts.tsx"; + +/** + * 照目錄一層一層疊(docs/24 第 2 節圖層順序,由後到前): + * 部件的後層 → 後髮 → 衣服 → 外套層、彩帶、胸前(body)→ 耳朵、臉、鬍子 → 前髮 → 眉眼、眼鏡、鼻子、皺紋、腮紅、嘴 → + * 口罩(face)→ 帽子(head)→ 手持物(hand)→ 外框(canvas,另外畫,見 AvatarFrame)。 + * Q 版大頭:頭那一組放大、身體那一組縮小,部件靠錨點跟著走。64 像素以下(small)省略胸前、手持物、外框和字。 + */ + +type Layer = "body" | "face" | "head" | "hand" | "canvas"; +interface Worn { + item: AvatarItem; + layer: Layer; +} + +const LAYER_OF = new Map(AVATAR_CATALOG.slots.filter((s) => s.layer).map((s) => [s.id, s])); +const SLOT_ORDER = new Map(AVATAR_CATALOG.slots.map((s, i) => [s.id, i])); + +/** 這個頭像穿了哪些新部件(目錄裡沒有的代號不畫、不報錯) */ +export function wornItems(spec: AvatarSpecData, small: boolean): Worn[] { + const out: Worn[] = []; + for (const [slot, id] of Object.entries(spec.wear ?? {})) { + const s = LAYER_OF.get(slot); + const item = wearItem(id); + if (!s?.layer || !item || item.slot !== slot) continue; + if (small && s.small === "hide") continue; + out.push({ item, layer: s.layer }); + } + return out.sort((a, b) => (SLOT_ORDER.get(a.item.slot) ?? 0) - (SLOT_ORDER.get(b.item.slot) ?? 0)); +} + +export function AvatarFigure({ spec, look, small, ctx }: { spec: AvatarSpecData; look: Look; small: boolean; ctx: PartCtx }) { + const uid = useId().replace(/:/g, ""); + const h = headOf(spec); + const worn = wornItems(spec, small); + const on = (layer: Layer) => worn.filter((w) => w.layer === layer); + const headT = look.chibi ? chibiHead : undefined; + const bodyT = look.chibi ? chibiBody : undefined; + const hat = on("head").find((w) => w.item.hideHairAbove !== undefined); + const hairClip = hat ? `hair-${uid}` : undefined; + const hairCut = hat ? anchorY(hat.item.anchor, hat.item.hideHairAbove!, h) : 0; + const masked = on("face").length > 0; + const p = { spec, h, look, uid }; + // 新部件也描一圈墨線,跟程式畫的部件一樣是海報風 + const part = (w: Worn, side: "back" | "front", head: Head) => ( + + ); + const headBack = worn.filter((w) => w.layer !== "canvas" && w.item.anchor !== "none"); + const bodyBack = worn.filter((w) => w.layer !== "canvas" && w.item.anchor === "none"); + return ( + <> + + {bodyBack.length > 0 && {bodyBack.map((w) => part(w, "back", h))}} + + {headBack.map((w) => part(w, "back", h))} + {hairClip && ( + + + + )} + + + + + + + {on("body").map((w) => part(w, "front", h))} + + + + + + + + + {spec.glasses && !masked && } + + + + {on("face").map((w) => part(w, "front", h))} + {spec.glasses && masked && } + {on("head").map((w) => part(w, "front", h))} + + {on("hand").length > 0 && {on("hand").map((w) => part(w, "front", h))}} + + ); +} + +/** 頭像外框(最上面一層,不跟著畫風變形) */ +export function AvatarFrame({ spec, small, ctx }: { spec: AvatarSpecData; small: boolean; ctx: PartCtx }) { + const frames = wornItems(spec, small).filter((w) => w.layer === "canvas"); + if (frames.length === 0) return null; + return ( + <> + {frames.map((w) => ( + + ))} + + ); +} + diff --git a/web/src/game/art/avatar/parts.tsx b/web/src/game/art/avatar/parts.tsx new file mode 100644 index 0000000..07588c7 --- /dev/null +++ b/web/src/game/art/avatar/parts.tsx @@ -0,0 +1,123 @@ +import { MAGIC_COLORS, type ArtShape, type AvatarItem, type AvatarTextDef, type MagicRole } from "@election2026/protocol"; +import { AVATAR_ART } from "@election2026/protocol/avatar-art"; +import { createElement, type ReactNode } from "react"; + +/** + * 新部件(帽子、彩帶、手持物…)的畫法:照部件圖(只有形狀和顏色的資料,由 SVG 轉來)一個一個畫出來, + * 魔術色換成玩家選的顏色(沒選就用部件的預設,常常是政黨色),再印上號次、名字。 + */ +export interface PartCtx { + /** 政黨色(#RRGGBB);部件預設色寫 party 的就用它 */ + party: string; + skin: string; + suit: string; + shirt: string; + tint: Readonly> | undefined; + name?: string | null; + number?: number | null; + /** 印字(64 像素以下的小圖、像素風不印) */ + text: boolean; +} + +/** 顏色加深(暗面) */ +export function shade(hex: string, k = 0.78): string { + const n = Number.parseInt(hex.slice(1), 16); + if (!Number.isFinite(n)) return hex; + const c = (v: number) => Math.round(v * k).toString(16).padStart(2, "0"); + return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`; +} + +export function tintOf(item: AvatarItem, key: string, ctx: PartCtx): string { + const picked = ctx.tint?.[`${item.slot}.${key}`]; + if (picked) return picked; + const def = item.tints.find((t) => t.key === key)?.default; + return !def || def === "party" ? ctx.party : def; +} + +function colorsFor(item: AvatarItem, ctx: PartCtx): Record { + const main = tintOf(item, "main", ctx); + const accent = item.tints.some((t) => t.key === "accent") ? tintOf(item, "accent", ctx) : main; + return { + main, + mainShade: shade(main), + accent, + accentShade: shade(accent), + skin: ctx.skin, + skinShade: shade(ctx.skin, 0.7), + suit: ctx.suit, + suitShade: shade(ctx.suit), + shirt: ctx.shirt, + }; +} + +const paint = (v: string | undefined, colors: Record) => (v && v in MAGIC_COLORS ? colors[MAGIC_COLORS[v as keyof typeof MAGIC_COLORS]] : v); + +function Shapes({ list, colors }: { list: readonly ArtShape[]; colors: Record }): ReactNode { + return list.map((s, i) => + createElement( + s.t, + { key: i, ...s.a, fill: paint(s.a.fill, colors), stroke: paint(s.a.stroke, colors) }, + s.c ? : undefined, + ), + ); +} + +/** 部件上印的字 */ +export function textOf(def: AvatarTextDef, ctx: Pick): string { + const name = ctx.name?.trim() || ""; + const n = ctx.number ?? null; + switch (def.kind) { + case "number": + // 沒有號次印「勝」(不用星星:單顆紅星看起來像中國的符號) + return n !== null ? String(n) : "勝"; + case "name": + return name || "候選人"; + case "numberName": + return n !== null && name ? `${n}號 ${name}` : name || (n !== null ? `${n} 號` : "候選人"); + case "plea": + return n !== null ? `請支持 ${n} 號` : name ? `請支持${name}` : "請支持"; + default: + return def.value ?? ""; + } +} + +const FILL: Record = { ink: "#111419", white: "#ffffff", gold: "#ffd23f" }; + +function PartText({ def, colors, ctx }: { def: AvatarTextDef; colors: Record; ctx: PartCtx }) { + const text = textOf(def, ctx); + if (!text) return null; + const fill = def.fill === "main" ? colors.main : def.fill === "accent" ? colors.accent : (FILL[def.fill] ?? def.fill); + const wide = [...text].reduce((w, ch) => w + (ch.charCodeAt(0) < 128 ? 0.6 : 1) * def.size, 0); + return ( + def.width ? { textLength: def.width, lengthAdjust: "spacingAndGlyphs" as const } : {})} + > + {text} + + ); +} + +/** 畫一件新部件的某一層(back 畫在頭和身體後面;front 是自己的圖層);outline 是描墨線外框的濾鏡 id */ +export function WornPart({ item, side, ctx, transform, outline }: { item: AvatarItem; side: "back" | "front"; ctx: PartCtx; transform?: string; outline?: string }) { + const art = AVATAR_ART[item.art]; + const list = art?.[side]; + if (!list?.length) return null; + const colors = colorsFor(item, ctx); + return ( + + + + + {side === "front" && ctx.text && item.text.map((t, i) => )} + + ); +} diff --git a/web/src/game/art/avatar/pixel.tsx b/web/src/game/art/avatar/pixel.tsx new file mode 100644 index 0000000..77f4620 --- /dev/null +++ b/web/src/game/art/avatar/pixel.tsx @@ -0,0 +1,233 @@ +import { useEffect, useReducer, useRef, type ReactNode } from "react"; + +/** + * 復刻像素風(致敬 1994 年原作的 72×90、16 色頭像):把畫好的頭像縮成小點陣、 + * 套 16 色(從這張頭像自己的顏色挑)、外圍描一圈深色邊,再用方塊放大畫回來(每種顏色一條 path,任何大小都銳利)。 + * 同一個頭像只算一次(快取);瀏覽器不讓讀畫布時退回一般畫法。 + */ +export const GRID_W = 64; +export const GRID_H = 70; +const COLORS = 16; +const OUTLINE = "#1f1a24"; +const MAX_CACHE = 400; + +export interface PixelArt { + layers: { fill: string; d: string }[]; +} + +const cache = new Map(); +const pending = new Map>(); + +function remember(key: string, v: PixelArt | "fail") { + cache.set(key, v); + if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value!); +} + +function loadImage(url: string): Promise { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("頭像轉圖失敗")); + img.src = url; + }); +} + +const hex = (r: number, g: number, b: number) => `#${[r, g, b].map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`; + +/** 每個像素格先用 4×4 的小點取樣(挑格子裡的顏色,不是平均:細細的眼睛、嘴巴才不會被糊掉) */ +const SUB = 4; + +/** 把一張頭像(SVG 字串)變成像素圖 */ +export async function pixelate(inner: string): Promise { + const [w, h] = [GRID_W * SUB, GRID_H * SUB]; + const svg = `${inner}`; + const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" })); + try { + const img = await loadImage(url); + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const g = canvas.getContext("2d", { willReadFrequently: true }); + if (!g) throw new Error("沒有畫布"); + g.drawImage(img, 0, 0, w, h); + return quantize(sampleBlocks(g.getImageData(0, 0, w, h).data, GRID_W, GRID_H), GRID_W, GRID_H); + } finally { + URL.revokeObjectURL(url); + } +} + +const luma = (r: number, g: number, b: number) => 0.3 * r + 0.59 * g + 0.11 * b; + +/** + * 4×4 取一格:蓋到的不到 6 點就是透明;否則取最多的顏色,但格子裡有夠多(3 點以上)明顯更深的顏色時取深色 + * (像素畫家會優先保留輪廓、眼睛、嘴巴)。 + */ +export function sampleBlocks(src: Uint8ClampedArray, gw: number, gh: number): Uint8ClampedArray { + const sw = gw * SUB; + const out = new Uint8ClampedArray(gw * gh * 4); + for (let gy = 0; gy < gh; gy++) { + for (let gx = 0; gx < gw; gx++) { + const groups = new Map(); + let solid = 0; + for (let y = 0; y < SUB; y++) { + for (let x = 0; x < SUB; x++) { + const i = ((gy * SUB + y) * sw + gx * SUB + x) * 4; + if (src[i + 3]! < 128) continue; + solid += 1; + const [r, g, b] = [src[i]!, src[i + 1]!, src[i + 2]!]; + const k = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3); + const e = groups.get(k) ?? { n: 0, r: 0, g: 0, b: 0 }; + e.n += 1; + e.r += r; + e.g += g; + e.b += b; + groups.set(k, e); + } + } + const o = (gy * gw + gx) * 4; + if (solid < 6) continue; + const list = [...groups.values()].map((e) => ({ n: e.n, r: e.r / e.n, g: e.g / e.n, b: e.b / e.n })); + let pick = list.reduce((a, b) => (b.n > a.n ? b : a)); + const dark = list.filter((e) => e.n >= 3 && luma(e.r, e.g, e.b) < luma(pick.r, pick.g, pick.b) - 50).sort((a, b) => luma(a.r, a.g, a.b) - luma(b.r, b.g, b.b))[0]; + if (dark) pick = dark; + out[o] = pick.r; + out[o + 1] = pick.g; + out[o + 2] = pick.b; + out[o + 3] = 255; + } + } + return out; +} + +/** 16 色量化(k-means)+外圍描邊+每種顏色一條 path */ +export function quantize(data: Uint8ClampedArray, w: number, h: number): PixelArt { + const n = w * h; + const solid = new Uint8Array(n); + const px: number[] = []; + for (let i = 0; i < n; i++) { + if (data[i * 4 + 3]! >= 110) { + solid[i] = 1; + px.push(i); + } + } + // 起始色:最常出現的 16 種(每個顏色取 4 位元分桶) + const buckets = new Map(); + for (const i of px) { + const [r, g, b] = [data[i * 4]!, data[i * 4 + 1]!, data[i * 4 + 2]!]; + const k = ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4); + const e = buckets.get(k) ?? { n: 0, r: 0, g: 0, b: 0 }; + e.n += 1; + e.r += r; + e.g += g; + e.b += b; + buckets.set(k, e); + } + let centers = [...buckets.values()] + .sort((a, b) => b.n - a.n) + .slice(0, COLORS) + .map((e) => [e.r / e.n, e.g / e.n, e.b / e.n] as [number, number, number]); + const assign = new Uint8Array(n); + const near = (r: number, g: number, b: number) => { + let best = 0; + let bd = Infinity; + for (let c = 0; c < centers.length; c++) { + const [cr, cg, cb] = centers[c]!; + const d = 0.3 * (r - cr) ** 2 + 0.59 * (g - cg) ** 2 + 0.11 * (b - cb) ** 2; + if (d < bd) { + bd = d; + best = c; + } + } + return best; + }; + for (let iter = 0; iter < 4; iter++) { + const sum = centers.map(() => [0, 0, 0, 0]); + for (const i of px) { + const [r, g, b] = [data[i * 4]!, data[i * 4 + 1]!, data[i * 4 + 2]!]; + const c = near(r, g, b); + assign[i] = c; + const s = sum[c]!; + s[0]! += r; + s[1]! += g; + s[2]! += b; + s[3]! += 1; + } + centers = centers.map((c, k) => (sum[k]![3]! ? [sum[k]![0]! / sum[k]![3]!, sum[k]![1]! / sum[k]![3]!, sum[k]![2]! / sum[k]![3]!] : c)); + } + const fills = centers.map(([r, g, b]) => hex(r, g, b)); + const color: (string | null)[] = new Array(n).fill(null); + for (const i of px) color[i] = fills[assign[i]!]!; + // 外圍一圈深色邊(像素角色的輪廓) + for (let i = 0; i < n; i++) { + if (solid[i]) continue; + const x = i % w; + const y = Math.floor(i / w); + if ((x > 0 && solid[i - 1]) || (x < w - 1 && solid[i + 1]) || (y > 0 && solid[i - w]) || (y < h - 1 && solid[i + w])) color[i] = OUTLINE; + } + const paths = new Map(); + for (let y = 0; y < h; y++) { + let x = 0; + while (x < w) { + const c = color[y * w + x]; + if (!c) { + x += 1; + continue; + } + let end = x + 1; + while (end < w && color[y * w + end] === c) end += 1; + const list = paths.get(c) ?? []; + list.push(`M${x} ${y}h${end - x}v1h${x - end}z`); + paths.set(c, list); + x = end; + } + } + return { layers: [...paths].map(([fill, d]) => ({ fill, d: d.join("") })) }; +} + +/** + * 像素風的頭像身體:第一次先把一般畫法畫在看不見的地方,讀出來轉成像素圖,之後直接用快取。 + * key 要能代表這張頭像(同一個 key 一定長得一樣)。 + */ +export function PixelFigure({ cacheKey, children }: { cacheKey: string; children: ReactNode }) { + const ref = useRef(null); + const [, bump] = useReducer((n: number) => n + 1, 0); + const hit = cache.get(cacheKey); + useEffect(() => { + if (cache.has(cacheKey)) return; + let alive = true; + let job = pending.get(cacheKey); + if (!job) { + const node = ref.current?.firstElementChild; + if (!node || typeof XMLSerializer === "undefined") { + remember(cacheKey, "fail"); + bump(); + return; + } + const markup = new XMLSerializer().serializeToString(node); + job = pixelate(markup).then( + (art) => remember(cacheKey, art), + () => remember(cacheKey, "fail"), + ); + pending.set(cacheKey, job); + void job.finally(() => pending.delete(cacheKey)); + } + void job.then(() => alive && bump()); + return () => { + alive = false; + }; + }, [cacheKey]); + if (hit === "fail") return <>{children}; + if (hit) + return ( + + {hit.layers.map((l) => ( + + ))} + + ); + return ( + + {children} + + ); +} diff --git a/web/src/game/art/candidateAvatar.ts b/web/src/game/art/candidateAvatar.ts new file mode 100644 index 0000000..557dbbe --- /dev/null +++ b/web/src/game/art/candidateAvatar.ts @@ -0,0 +1,50 @@ +import { parseAvatarLoose } from "@election2026/protocol"; +import { avatarFromSeed, type AvatarSpec } from "./Avatar.tsx"; +import { likenessOf } from "./likeness.ts"; + +/** + * 候選人的 Q 版頭像。每位候選人依名字固定產生一個卡通頭像(性別來自中選會資料), + * 不是照真人長相畫的;以前在這台瀏覽器改過的頭像照樣套用。自創角色用玩家捏的頭像。 + * 真實人物的頭像只能穿正式類部件(realPersonOk),讀存檔和存檔時都照部件目錄清洗(docs/24)。 + */ +export interface AvatarCandidate { + name: string; + gender?: "m" | "f" | null; + avatar?: AvatarSpec | null; +} + +const KEY = "tongsuan.avatars"; + +function load(): Record { + try { + const raw = localStorage.getItem(KEY); + const all: unknown = raw ? JSON.parse(raw) : {}; + if (!all || typeof all !== "object" || Array.isArray(all)) return {}; + const out: Record = {}; + for (const [name, v] of Object.entries(all as Record)) { + const spec = parseAvatarLoose(v, { realPerson: true }); + if (spec) out[name] = spec; + } + return out; + } catch { + return {}; + } +} + +const overrides = load(); + +/** 同一個人的不同時期(「韓國瑜(2018)」)用同一個頭像 */ +const person = (name: string) => name.replace(/(\d{4})$/, ""); + +export function defaultAvatar(c: AvatarCandidate): AvatarSpec { + const female = c.gender === "f" ? true : c.gender === "m" ? false : undefined; + // 候選人都穿正式一點:男生西裝,女生襯衫或西裝 + const base = avatarFromSeed(`cand:${person(c.name)}`, { ...(female !== undefined ? { female } : {}), ...(female === false ? { outfit: "suit" as const } : {}) }); + // 有照著公開肖像設定招牌特徵的政治人物,用那些特徵 + const like = likenessOf(c.name); + return like ? { ...base, ...like } : base; +} + +export function candidateAvatar(c: AvatarCandidate): AvatarSpec { + return c.avatar ?? overrides[person(c.name)] ?? defaultAvatar(c); +} diff --git a/web/src/game/art/likeness-2024.ts b/web/src/game/art/likeness-2024.ts new file mode 100644 index 0000000..bedb543 --- /dev/null +++ b/web/src/game/art/likeness-2024.ts @@ -0,0 +1,590 @@ +import type { Likeness } from "./likeness.ts"; + +/** + * 第 11 屆立法委員(2024 年選上)的卡通頭像特徵:看立法院網站的委員官方照片(ref),只記招牌特徵, + * 由頭像系統畫成卡通。不使用照片、也不是 AI 生圖;遊戲不會載入照片。判讀規則見 docs/24「1f」。 + * 同名同姓、在歷屆資料裡不只一個人的(吳宗憲、李柏毅、林月琴、林淑芬)先不放,免得套到別人身上。 + * 每筆後面的註解是招牌特徵,方便之後核對;confidence 不是 high 的也寫在註解裡。 + */ +export const LIKENESS_2024: Readonly> = { + // 深褐色旁分短髮、寬方臉、白襯衫露齒笑 + 丁學忠: { + ref: "https://www.ly.gov.tw/Images/Legislators/110001.jpg", + spec: { face: "square", faceW: 1.08, faceH: 1.0, hair: "side", hairColor: "#4a372b", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "polo", suit: "#f4f6f8", shirt: "#f4f6f8", tie: "#f4f6f8" }, + }, + // 厚斜瀏海黑長直髮、駝色外套、開朗露齒笑 + "伍麗華 Saidhai.Tahovecahe": { + ref: "https://www.ly.gov.tw/Images/Legislators/110008.jpg", + spec: { face: "round", faceW: 1.05, faceH: 1.0, hair: "long", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "blouse", suit: "#e6cfa3", shirt: "#b9c4c0", tie: "#e6cfa3" }, + }, + // 斜瀏海及下巴鮑伯頭、露齒笑、淺灰外套 + 何欣純: { + ref: "https://www.ly.gov.tw/Images/Legislators/110010.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: false, nose: "small", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#d9d6d8", shirt: "#f7f7f7", tie: "#d9d6d8" }, + }, + // 圓臉、蓬鬆旁分黑髮、紅領帶配露齒笑(判讀信心:medium) + 傅崐萁: { + ref: "https://www.ly.gov.tw/Images/Legislators/110076.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "smile", glasses: false, nose: "round", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#1c1a22", shirt: "#f4f2f0", tie: "#c8302c" }, + }, + // 下巴一撮山羊鬍、方框金屬眼鏡、蓬鬆旁分 + 劉建國: { + ref: "https://www.ly.gov.tw/Images/Legislators/110093.jpg", + spec: { face: "square", faceW: 1.04, faceH: 1.02, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#5a4a40", nose: "normal", mouth: "teeth", lines: 1, beard: true, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#101820", shirt: "#f4f4f2", tie: "#101820" }, + }, + // 側分斜瀏海短鮑伯、圓臉、米色西裝外套 + 劉書彬: { + ref: "https://www.ly.gov.tw/Images/Legislators/110116.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "bobSide", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#d2c0b0", shirt: "#f2eeea", tie: "#d2c0b0" }, + }, + // 及下巴的黑色側分鮑伯頭、張嘴開懷大笑、淡紫色西裝外套 + 吳思瑤: { + ref: "https://www.ly.gov.tw/Images/Legislators/110014.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "laugh", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#d9c9dc", shirt: "#f2ece8", tie: "#f2ece8" }, + }, + // 抓立短髮、無框眼鏡、長臉 + 吳春城: { + ref: "https://www.ly.gov.tw/Images/Legislators/110015.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.06, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#2b2a2e", shirt: "#b8662e", tie: "#2b2a2e" }, + }, + // 中分往後紮的黑髮配兩側垂下的細鬢髮、大眼、淡紫色西裝外套(判讀信心:medium) + 吳沛憶: { + ref: "https://www.ly.gov.tw/Images/Legislators/110011.jpg", + spec: { face: "heart", faceW: 0.96, faceH: 1.04, hair: "ponytail", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "wide", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#ddd3ec", shirt: "#f8f8f8", tie: "#ddd3ec" }, + }, + // 濃密蓬鬆的旁分黑髮、寬圓臉、瞇眼露齒笑 + 吳琪銘: { + ref: "https://www.ly.gov.tw/Images/Legislators/110016.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#8a8e9c", shirt: "#8a8e9c", tie: "#8a8e9c" }, + }, + // 寬圓臉、細金屬框眼鏡、灰西裝露齒笑 + 吳秉叡: { + ref: "https://www.ly.gov.tw/Images/Legislators/110013.jpg", + spec: { face: "round", faceW: 1.1, faceH: 1.0, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#a8a294", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#686c6e", shirt: "#f4f4f6", tie: "#2a3560" }, + }, + // 蓬鬆厚斜瀏海鮑伯頭、瞇眼露齒大笑、白色襯衫 + 呂玉玲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110017.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "bobSide", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f5f3f0", shirt: "#f5f3f0", tie: "#f5f3f0" }, + }, + // 兩側推短、頭頂高聳的背頭、濃眉、露齒笑 + 廖偉翔: { + ref: "https://www.ly.gov.tw/Images/Legislators/110092.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.2, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#26303f", shirt: "#f0f4f8", tie: "#26303f" }, + }, + // 深色粗框方眼鏡、黑短髮、露齒笑、藍襯衫 + 廖先翔: { + ref: "https://www.ly.gov.tw/Images/Legislators/110091.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#2a3040", nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#8aaae8", shirt: "#8aaae8", tie: "#8aaae8" }, + }, + // 無框眼鏡、蓬鬆旁分黑髮、寬鼻翼與明顯皺紋 + 張啓楷: { + ref: "https://www.ly.gov.tw/Images/Legislators/110053.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.05, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "big", mouth: "smile", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#1f2030", shirt: "#a6a2a4", tie: "#1f2030" }, + }, + // 往後梳綁的深棕髮(腦後馬尾)、紅唇露齒笑、淡黃色外套 + 張嘉郡: { + ref: "https://www.ly.gov.tw/Images/Legislators/110056.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "ponytail", hairColor: "#4a372b", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#fbf6dc", shirt: "#ffffff", tie: "#ffffff" }, + }, + // 抓亂的黑色短髮、深色粗框長方眼鏡、瞇眼露齒大笑 + 張宏陸: { + ref: "https://www.ly.gov.tw/Images/Legislators/110052.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#4a2b26", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#050608", shirt: "#e4dae4", tie: "#7b9aae" }, + }, + // 往上梳的蓬鬆黑髮、黑色粗框眼鏡、圓臉配白襯衫 + 張智倫: { + ref: "https://www.ly.gov.tw/Images/Legislators/110054.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#22252a", nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "shirt", suit: "#f2f4fa", shirt: "#f2f4fa", tie: "#f2f4fa" }, + }, + // 髮尾漸層淺棕的黑長直髮、圓臉、露齒笑 + 張雅琳: { + ref: "https://www.ly.gov.tw/Images/Legislators/110055.jpg", + spec: { face: "round", faceW: 1.03, faceH: 1.0, hair: "long", hairColor: "#2f2520", part: "left", ears: "normal", brows: "normal", browAngle: 0.05, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#f4f2f0", shirt: "#f4f2f0", tie: "#f4f2f0" }, + }, + // 深色方框眼鏡、旁分短髮、方下巴 + 徐富癸: { + ref: "https://www.ly.gov.tw/Images/Legislators/110047.jpg", + spec: { face: "square", faceW: 1.05, faceH: 1.0, hair: "side", hairColor: "#2f2520", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#3a3a3f", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "suit", suit: "#2a2526", shirt: "#f2f0f0", tie: "#262a48" }, + }, + // 及肩的深色側分鮑伯、瞇眼露齒笑、白色西裝外套 + 徐巧芯: { + ref: "https://www.ly.gov.tw/Images/Legislators/110045.jpg", + spec: { face: "oval", faceW: 0.96, faceH: 1.04, hair: "bobSide", hairColor: "#2f2520", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: false, nose: "small", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#fafafa", shirt: "#fafafa", tie: "#fafafa" }, + }, + // 黑色側分及下巴鮑伯、無框眼鏡、露齒笑 + 徐欣瑩: { + ref: "https://www.ly.gov.tw/Images/Legislators/110046.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#0c1219", shirt: "#f2f5fc", tie: "#f2f5fc" }, + }, + // 無框眼鏡、短碎髮、露齒笑 + 李坤城: { + ref: "https://www.ly.gov.tw/Images/Legislators/110018.jpg", + spec: { face: "oval", faceW: 1.04, faceH: 1.04, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "suit", suit: "#1a1f33", shirt: "#f5f5f5", tie: "#1f2c55" }, + }, + // 及肩的棕色中分直髮、尖下巴大眼、淺粉色襯衫 + 李彥秀: { + ref: "https://www.ly.gov.tw/Images/Legislators/110020.jpg", + spec: { face: "heart", faceW: 0.94, faceH: 1.04, hair: "longMiddle", hairColor: "#6b4f3a", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "wide", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#ebdfe0", shirt: "#ebdfe0", tie: "#ebdfe0" }, + }, + // 深色細方框眼鏡、露齒笑、墨綠色休閒夾克(黃色滾邊領) + 李昆澤: { + ref: "https://www.ly.gov.tw/Images/Legislators/110019.jpg", + spec: { face: "oval", faceW: 0.96, faceH: 1.06, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#3a3b40", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "polo", suit: "#1f5566", shirt: "#f2f3f5", tie: "#1f5566" }, + }, + // 側分鮑伯頭、圓臉、微笑 + 李貞秀: { + ref: "https://www.ly.gov.tw/Images/Legislators/110122.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "small", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#3a3a3a", shirt: "#b04a4a", tie: "#b04a4a" }, + }, + // 蓬鬆旁分黑髮、細長眼、黑西裝配淡紫色領帶 + 林俊憲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110028.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.06, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#151417", shirt: "#f5f5f5", tie: "#8e78b8" }, + }, + // 深褐色層次斜瀏海短髮、咖啡色西裝外套、條紋襯衫 + 林倩綺: { + ref: "https://www.ly.gov.tw/Images/Legislators/110030.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "shortBob", hairColor: "#4a372b", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#78452e", shirt: "#d8ccc0", tie: "#78452e" }, + }, + // 圓臉、半框眼鏡、露齒笑 + 林國成: { + ref: "https://www.ly.gov.tw/Images/Legislators/110031.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "halfRim", glassesColor: "#5a5a66", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#24324a", shirt: "#f7f5f0", tie: "#2c5aa0" }, + }, + // 斜瀏海的深棕色長波浪髮、露齒笑、灰色外套配白襯衫 + 林宜瑾: { + ref: "https://www.ly.gov.tw/Images/Legislators/110026.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.02, hair: "longWavy", hairColor: "#4a372b", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "round", glasses: false, nose: "small", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#919396", shirt: "#f5f5f5", tie: "#f5f5f5" }, + }, + // 露耳的黑色極短髮、米白外套配芥末黃上衣、溫和微笑 + 林岱樺: { + ref: "https://www.ly.gov.tw/Images/Legislators/110027.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.04, hair: "pixie", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#e2ded6", shirt: "#f2ae4e", tie: "#f2ae4e" }, + }, + // 烏黑側梳的大波浪髮、金屬框眼鏡、寬大下顎與明顯皺紋 + 林德福: { + ref: "https://www.ly.gov.tw/Images/Legislators/110034.jpg", + spec: { face: "jowl", faceW: 1.06, faceH: 1.06, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", nose: "big", mouth: "smile", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#12161a", shirt: "#b8d0e6", tie: "#1c3a4f" }, + }, + // 濃密蓬鬆的黑髮、細金屬框眼鏡、深藍細條紋西裝 + 林思銘: { + ref: "https://www.ly.gov.tw/Images/Legislators/110029.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#8a8f96", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#282a48", shirt: "#c4c4dd", tie: "#0b1024" }, + }, + // 長波浪捲髮、白外套 + 林憶君: { + ref: "https://www.ly.gov.tw/Images/Legislators/110035.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "longWavy", hairColor: "#4a372b", part: "left", ears: "small", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f1c7a5", outfit: "blouse", suit: "#f3f1ec", shirt: "#1c1c1c", tie: "#1c1c1c" }, + }, + // 頭頂蓬起的黑長髮、大眼露齒笑、紅色西裝外套 + 林楚茵: { + ref: "https://www.ly.gov.tw/Images/Legislators/110033.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "long", hairColor: "#2f2520", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "wide", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#d8231a", shirt: "#f4f4f4", tie: "#d8231a" }, + }, + // 兩側推短的高聳背頭、濃眉、黑西裝開領白襯衫 + 林沛祥: { + ref: "https://www.ly.gov.tw/Images/Legislators/110025.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.06, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.2, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#121214", shirt: "#f4f4f4", tie: "#121214" }, + }, + // 上唇小鬍子、髮線後退的高額頭、細金屬框眼鏡 + 柯建銘: { + ref: "https://www.ly.gov.tw/Images/Legislators/110041.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "receding", hairColor: "#5e5a57", ears: "normal", brows: "normal", browAngle: 0.2, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#9aa3ad", nose: "round", mouth: "teeth", lines: 2, beard: false, mustache: true, skin: "#eebd98", outfit: "suit", suit: "#232e31", shirt: "#e6e9f2", tie: "#b8bcc8" }, + }, + // 及下巴的黑色側分鮑伯頭、尖下巴、黑色上衣 + 柯志恩: { + ref: "https://www.ly.gov.tw/Images/Legislators/110040.jpg", + spec: { face: "heart", faceW: 0.98, faceH: 1.02, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#28242c", shirt: "#28242c", tie: "#28242c" }, + }, + // 濃密小平頭、半框眼鏡、長臉抿嘴、白色細條紋POLO衫 + 楊曜: { + ref: "https://www.ly.gov.tw/Images/Legislators/110086.jpg", + spec: { face: "long", faceW: 0.97, faceH: 1.08, hair: "crew", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: true, glassesStyle: "halfRim", glassesColor: "#6a6a70", nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "polo", suit: "#ecebee", shirt: "#ecebee", tie: "#ecebee" }, + }, + // 蓬鬆的耳下短髮配斜瀏海、圓臉、紅唇抿嘴笑 + 楊瓊瓔: { + ref: "https://www.ly.gov.tw/Images/Legislators/110087.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "shortBob", hairColor: "#2f2520", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1e1c24", shirt: "#1e1c24", tie: "#1e1c24" }, + }, + // 粗黑方框眼鏡、前額抓立短髮、銀灰色領帶 + 江啟臣: { + ref: "https://www.ly.gov.tw/Images/Legislators/110009.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.06, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#1c1c1e", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#1a2438", shirt: "#f4f4f6", tie: "#a7aebd" }, + }, + // 蓬亂大捲髮、細框圓眼鏡、露齒大笑 + 沈伯洋: { + ref: "https://www.ly.gov.tw/Images/Legislators/110022.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "curly", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "round", glassesColor: "#9a958c", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "polo", suit: "#f2f2f2", shirt: "#f2f2f2", tie: "#f2f2f2" }, + }, + // 長方框眼鏡、蓋額頭的短瀏海、露齒笑 + 沈發惠: { + ref: "https://www.ly.gov.tw/Images/Legislators/110023.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#4a4a4f", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#f4f6f8", shirt: "#f4f6f8", tie: "#5e6369" }, + }, + // 兩側推短的高背頭、灰色眉框眼鏡、招風耳配露齒笑 + 洪孟楷: { + ref: "https://www.ly.gov.tw/Images/Legislators/110043.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.06, hair: "pompadour", hairColor: "#1f1b18", ears: "big", brows: "normal", browAngle: 0.15, eyes: "smile", glasses: true, glassesStyle: "browline", glassesColor: "#555a60", nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "polo", suit: "#f4f4f6", shirt: "#f4f4f6", tie: "#f4f4f6" }, + }, + // 酒紅色圓框眼鏡、蓬鬆微捲旁分、方臉 + 洪毓祥: { + ref: "https://www.ly.gov.tw/Images/Legislators/110117.jpg", + spec: { face: "square", faceW: 1.06, faceH: 1.02, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "round", glassesColor: "#5a2a2a", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#1e2329", shirt: "#c4d6f2", tie: "#1e2329" }, + }, + // 下巴山羊鬍配上唇小鬍、高聳背頭、寬圓臉 + 洪申翰: { + ref: "https://www.ly.gov.tw/Images/Legislators/110042.jpg", + spec: { face: "round", faceW: 1.1, faceH: 1.0, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "big", mouth: "closed", lines: 1, beard: true, mustache: true, skin: "#d9a079", outfit: "vest", suit: "#1b2436", shirt: "#f5f5f5", tie: "#1b2436" }, + }, + // 寬方下顎、上揚的濃劍眉、露齒大笑 + 涂權吉: { + ref: "https://www.ly.gov.tw/Images/Legislators/110048.jpg", + spec: { face: "square", faceW: 1.08, faceH: 1.0, hair: "side", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thick", browAngle: 0.3, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#a9cdee", shirt: "#a9cdee", tie: "#a9cdee" }, + }, + // 髮線後退的高額頭、細金屬框眼鏡、露齒笑與深笑紋 + 游錫堃: { + ref: "https://www.ly.gov.tw/Images/Legislators/110077.jpg", + spec: { face: "long", faceW: 0.97, faceH: 1.08, hair: "receding", hairColor: "#2f2520", ears: "normal", brows: "normal", browAngle: -0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#8a8f96", nose: "big", mouth: "teeth", lines: 2, beard: false, mustache: false, skin: "#d9a079", outfit: "suit", suit: "#14192e", shirt: "#9cb8e0", tie: "#1f3a75" }, + }, + // 小平頭、寬圓臉、粉紅襯衫露齒笑 + 游顥: { + ref: "https://www.ly.gov.tw/Images/Legislators/110078.jpg", + spec: { face: "round", faceW: 1.1, faceH: 1.0, hair: "crew", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "polo", suit: "#f6cfd8", shirt: "#f6cfd8", tie: "#f6cfd8" }, + }, + // 垂到額頭的蓬鬆斜瀏海、笑瞇眼、大大露齒笑 + 牛煦庭: { + ref: "https://www.ly.gov.tw/Images/Legislators/110002.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "fringe", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#1a1a1c", shirt: "#f5f5f5", tie: "#1a1a1c" }, + }, + // 蓋過耳朵往後梳的中長黑髮、寬圓臉、淺藍襯衫配深色領帶(判讀信心:medium) + 王世堅: { + ref: "https://www.ly.gov.tw/Images/Legislators/110003.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.02, hair: "slick", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "big", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#161a1e", shirt: "#a9c2dc", tie: "#1c2630" }, + }, + // 蓬鬆往後梳的背頭、長臉、米色西裝配條紋領帶 + 王安祥: { + ref: "https://www.ly.gov.tw/Images/Legislators/110119.jpg", + spec: { face: "long", faceW: 0.94, faceH: 1.08, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#b5ad9c", shirt: "#f2f2f2", tie: "#4a2a2e" }, + }, + // 兩鬢灰白的高聳背頭、招風耳、露齒笑配藍白直條紋襯衫 + 王定宇: { + ref: "https://www.ly.gov.tw/Images/Legislators/110005.jpg", + spec: { face: "square", faceW: 1.04, faceH: 1.02, hair: "pompadour", hairColor: "#5e5a57", ears: "big", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#161a26", shirt: "#8fa8d0", tie: "#1e2f5a" }, + }, + // 濃密灰白中分髮、槍色長方框眼鏡、紅色條紋領帶 + 王正旭: { + ref: "https://www.ly.gov.tw/Images/Legislators/110114.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.06, hair: "middle", hairColor: "#9a9a9a", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#4a4a4f", nose: "normal", mouth: "smile", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#14171c", shirt: "#d1dced", tie: "#9a2a3a" }, + }, + // 齊瀏海鮑伯頭、深色圓框眼鏡、額頭上的痣 + 王美惠: { + ref: "https://www.ly.gov.tw/Images/Legislators/110006.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "bob", hairColor: "#2f2520", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "round", glassesColor: "#2a2a2e", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#6b655c", shirt: "#f5f5f7", tie: "#6b655c" }, + }, + // 大圓臉、黑粗框方眼鏡、往後梳的服貼短髮 + 王義川: { + ref: "https://www.ly.gov.tw/Images/Legislators/110115.jpg", + spec: { face: "round", faceW: 1.1, faceH: 1.0, hair: "slick", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.05, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#22252a", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#2f353d", shirt: "#f8f4f4", tie: "#2f353d" }, + }, + // 蓬鬆內彎的側分鮑伯、紅唇露齒笑、黑外套白內搭 + 王育敏: { + ref: "https://www.ly.gov.tw/Images/Legislators/110004.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.04, hair: "bobSide", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thin", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1a1a1e", shirt: "#f8f8f8", tie: "#1a1a1e" }, + }, + // 側分黑色鮑伯頭、黃色西裝外套、露齒笑 + 王鴻薇: { + ref: "https://www.ly.gov.tw/Images/Legislators/110007.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "small", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f2cf6a", shirt: "#f7f5f0", tie: "#f2cf6a" }, + }, + // 寬圓臉、濃劍眉、醫師白袍配藍色刷手服(判讀信心:medium) + 盧縣一: { + ref: "https://www.ly.gov.tw/Images/Legislators/110099.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "crew", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.2, eyes: "narrow", glasses: false, nose: "round", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "vest", suit: "#eef0f6", shirt: "#8fb8e8", tie: "#eef0f6" }, + }, + // 霧灰色韓系蓋額瀏海、圓臉露齒笑、米色西裝外套配白T + 羅廷瑋: { + ref: "https://www.ly.gov.tw/Images/Legislators/110108.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "fringe", hairColor: "#8d9096", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "vest", suit: "#cdbcab", shirt: "#eeedec", tie: "#cdbcab" }, + }, + // 無框眼鏡、整齊的黑短髮、露齒笑 + 羅明才: { + ref: "https://www.ly.gov.tw/Images/Legislators/110109.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.02, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#141826", shirt: "#f4f4f6", tie: "#8a8c94" }, + }, + // M字後退髮線、深藍粗框方眼鏡、手捏領帶結的姿勢 + 羅智強: { + ref: "https://www.ly.gov.tw/Images/Legislators/110111.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "receding", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#2c3a5a", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#10111c", shirt: "#f4f4f6", tie: "#2c3451" }, + }, + // 紅褐色側分長髮、髮尾大捲、米色西裝外套 + 羅美玲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110110.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "longWavy", hairColor: "#4a372b", part: "left", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#d8cfc4", shirt: "#1a1f33", tie: "#d8cfc4" }, + }, + // 齊瀏海鮑伯頭、無框眼鏡、淺藍條紋上衣 + 翁曉玲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110049.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "bob", hairColor: "#2f2520", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#9a7a8a", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#c8d4e0", shirt: "#eef2f6", tie: "#c8d4e0" }, + }, + // 斜碎瀏海蓋到眉毛的黑色層次短髮、紅唇抿笑、白色上衣 + 范雲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110044.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "pixie", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f7f6f8", shirt: "#f7f6f8", tie: "#f7f6f8" }, + }, + // 抓立的黑色短髮、寬圓臉、瞇眼露齒大笑 + 莊瑞雄: { + ref: "https://www.ly.gov.tw/Images/Legislators/110057.jpg", + spec: { face: "round", faceW: 1.1, faceH: 1.0, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.2, eyes: "smile", glasses: false, nose: "round", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "suit", suit: "#2c5080", shirt: "#e8eaf5", tie: "#3a4a70" }, + }, + // 中分過肩黑長直髮、細長眼、黑色外套 + 萬美玲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110088.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.05, hair: "longMiddle", hairColor: "#1f1b18", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1c1c22", shirt: "#1c1c22", tie: "#1c1c22" }, + }, + // 往上撥的蓬鬆旁分、一撮瀏海垂到額前、露齒笑、淺藍條紋襯衫 + 葉元之: { + ref: "https://www.ly.gov.tw/Images/Legislators/110089.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.05, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#78a8e2", shirt: "#78a8e2", tie: "#78a8e2" }, + }, + // 兩側推短的往後梳背頭、深色粗框眼鏡、寬下顎 + 葛如鈞: { + ref: "https://www.ly.gov.tw/Images/Legislators/110090.jpg", + spec: { face: "square", faceW: 1.06, faceH: 1.0, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.05, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#3a3a3e", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#141a34", shirt: "#f4f0f0", tie: "#141a34" }, + }, + // 大寬臉帶雙下巴、細銀框方眼鏡、厚密短髮 + 蔡易餘: { + ref: "https://www.ly.gov.tw/Images/Legislators/110095.jpg", + spec: { face: "jowl", faceW: 1.12, faceH: 1.02, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#a0a4a8", nose: "round", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#22262a", shirt: "#f4f6f8", tie: "#4a4a4a" }, + }, + // 水鑽髮箍、往後收的及肩直黑髮、露齒笑 + 蔡春綢: { + ref: "https://www.ly.gov.tw/Images/Legislators/110118.jpg", + spec: { face: "oval", faceW: 0.97, faceH: 1.04, hair: "longMiddle", hairColor: "#1f1b18", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#1d1d3a", shirt: "#ece9e4", tie: "#ece9e4" }, + }, + // 及下巴的黑色側分鮑伯、無框細眼鏡、露齒笑 + 蘇巧慧: { + ref: "https://www.ly.gov.tw/Images/Legislators/110112.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#b89a66", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#141214", shirt: "#f6f6f4", tie: "#141214" }, + }, + // 長臉、側梳的濃密黑髮、細金屬方框眼鏡、紅領帶 + 蘇清泉: { + ref: "https://www.ly.gov.tw/Images/Legislators/110113.jpg", + spec: { face: "long", faceW: 0.97, faceH: 1.08, hair: "side", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#8a8a90", nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#20292f", shirt: "#f4f4f4", tie: "#9a2a2e" }, + }, + // 及肩側分直髮、圓臉紅唇微笑、深藍外套配珠飾領口 + 許宇甄: { + ref: "https://www.ly.gov.tw/Images/Legislators/110058.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "long", hairColor: "#2f2520", part: "left", ears: "normal", brows: "normal", browAngle: 0.05, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#273041", shirt: "#fafafa", tie: "#273041" }, + }, + // 黑白參半的蓬鬆旁分、金色無框眼鏡、寬方臉 + 許忠信: { + ref: "https://www.ly.gov.tw/Images/Legislators/110123.jpg", + spec: { face: "square", faceW: 1.08, faceH: 1.02, hair: "volume", hairColor: "#5e5a57", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#b89a66", nose: "normal", mouth: "smile", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#252935", shirt: "#f2f2f5", tie: "#5e7a8e" }, + }, + // 抓立刺蝟短髮、細金屬框眼鏡、露齒笑 + 許智傑: { + ref: "https://www.ly.gov.tw/Images/Legislators/110059.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.04, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#9aa3ad", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#1e3266", shirt: "#f4f4f6", tie: "#1e3266" }, + }, + // 薄瀏海的及肩直鮑伯、瓜子臉、灰色西裝外套 + 謝衣鳯: { + ref: "https://www.ly.gov.tw/Images/Legislators/110103.jpg", + spec: { face: "heart", faceW: 0.96, faceH: 1.02, hair: "bob", hairColor: "#2f2520", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: false, nose: "small", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#41455a", shirt: "#22283c", tie: "#41455a" }, + }, + // 頭頂高高膨起的大旁分黑髮、長臉、半框眼鏡 + 謝龍介: { + ref: "https://www.ly.gov.tw/Images/Legislators/110104.jpg", + spec: { face: "long", faceW: 0.97, faceH: 1.08, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "halfRim", glassesColor: "#8a7f6a", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#0c2340", shirt: "#d4e2ee", tie: "#1e3a8a" }, + }, + // 細圓框眼鏡、大耳朵、皺紋明顯的笑臉、藍白格紋襯衫 + 賴士葆: { + ref: "https://www.ly.gov.tw/Images/Legislators/110100.jpg", + spec: { face: "long", faceW: 0.98, faceH: 1.06, hair: "side", hairColor: "#2f2520", part: "right", ears: "big", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "round", glassesColor: "#5a5048", nose: "normal", mouth: "smile", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#6a8fc8", shirt: "#6a8fc8", tie: "#6a8fc8" }, + }, + // 深褐色側分鮑伯、露齒笑、淺藍西裝外套配深藍內搭 + 賴惠員: { + ref: "https://www.ly.gov.tw/Images/Legislators/110101.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "bobSide", hairColor: "#4a372b", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#bcd4f0", shirt: "#1a2a4e", tie: "#bcd4f0" }, + }, + // 往上梳的蓬鬆旁分黑髮、細金屬方框眼鏡、淺藍襯衫抿嘴笑 + 賴瑞隆: { + ref: "https://www.ly.gov.tw/Images/Legislators/110102.jpg", + spec: { face: "square", faceW: 1.02, faceH: 1.04, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#4a4a4f", nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#a4cbea", shirt: "#a4cbea", tie: "#a4cbea" }, + }, + // 蓋住額頭的蓬鬆黑髮瀏海、細框長方形眼鏡、窄長臉 + 邱志偉: { + ref: "https://www.ly.gov.tw/Images/Legislators/110036.jpg", + spec: { face: "oval", faceW: 0.95, faceH: 1.06, hair: "fringe", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#4a4a4f", nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "suit", suit: "#141218", shirt: "#efeefa", tie: "#b8acc8" }, + }, + // 耳際極短髮配斜瀏海、圓臉、直條紋襯衫 + 邱慧洳: { + ref: "https://www.ly.gov.tw/Images/Legislators/110120.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "pixie", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "round", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#4a5068", shirt: "#f2f2f2", tie: "#4a5068" }, + }, + // 圓臉、及肩側分黑髮、白襯衫露齒笑 + 邱若華: { + ref: "https://www.ly.gov.tw/Images/Legislators/110037.jpg", + spec: { face: "round", faceW: 1.05, faceH: 0.98, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: false, nose: "small", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f8f8f8", shirt: "#f8f8f8", tie: "#f8f8f8" }, + }, + // 斜瀏海的黑色及下巴鮑伯頭、大眼、露齒笑 + 邱議瑩: { + ref: "https://www.ly.gov.tw/Images/Legislators/110039.jpg", + spec: { face: "oval", faceW: 0.96, faceH: 1.04, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "wide", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#ede5da", shirt: "#f8f0f0", tie: "#f8f0f0" }, + }, + // 往上吹高的深褐色波浪背頭、淺灰藍休閒西裝不打領帶、露齒笑 + 邱鎮軍: { + ref: "https://www.ly.gov.tw/Images/Legislators/110038.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "pompadour", hairColor: "#4a372b", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#7a8ea5", shirt: "#a5c0d2", tie: "#a5c0d2" }, + }, + // 厚實方正的黑色短髮、細金屬框眼鏡、抿嘴 + 郭國文: { + ref: "https://www.ly.gov.tw/Images/Legislators/110061.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#8a8079", nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#0e2030", shirt: "#d8e6f2", tie: "#404c53" }, + }, + // 紅棕色中分八字瀏海鮑伯、大圈圈耳環、白皙 + 郭昱晴: { + ref: "https://www.ly.gov.tw/Images/Legislators/110060.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "bobSide", hairColor: "#8a4a2c", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f4dcd8", shirt: "#f4dcd8", tie: "#f4dcd8" }, + }, + // 銀色金屬框眼鏡、旁分黑髮、原住民彩色織紋背心 + "鄭天財 Sra‧Kacaw": { + ref: "https://www.ly.gov.tw/Images/Legislators/110096.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.06, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#9aa3ad", nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#5a6a2a", shirt: "#dfeffc", tie: "#b95a5d" }, + }, + // 粗黑框方眼鏡、深褐色蓬鬆側瀏海、招風耳、露齒笑 + 鄭正鈐: { + ref: "https://www.ly.gov.tw/Images/Legislators/110097.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.04, hair: "volume", hairColor: "#4a372b", part: "right", ears: "big", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#2a2522", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#1c1c20", shirt: "#f0eeee", tie: "#1c1c20" }, + }, + // 兩側推短的側梳短髮、玳瑁色粗框眼鏡、長臉露齒笑 + 鍾佳濱: { + ref: "https://www.ly.gov.tw/Images/Legislators/110105.jpg", + spec: { face: "long", faceW: 0.96, faceH: 1.06, hair: "side", hairColor: "#2f2520", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#5a3a2a", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#2a2834", shirt: "#f4f4f4", tie: "#2a2834" }, + }, + // 側掃瀏海的棕色耳下短髮、尖下巴、深色外套配白襯衫 + 陳亭妃: { + ref: "https://www.ly.gov.tw/Images/Legislators/110065.jpg", + spec: { face: "heart", faceW: 0.96, faceH: 1.04, hair: "shortBob", hairColor: "#4a372b", part: "left", ears: "normal", brows: "normal", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1c272b", shirt: "#eeeef2", tie: "#eeeef2" }, + }, + // 濃密的側分黑髮、寬方下顎、細長眼 + 陳俊宇: { + ref: "https://www.ly.gov.tw/Images/Legislators/110066.jpg", + spec: { face: "square", faceW: 1.06, faceH: 1.02, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#0a1626", shirt: "#d8dbe0", tie: "#bcb5c9" }, + }, + // 濃密蓬鬆的黑短髮、年輕白淨的鵝蛋臉、藍色西裝外套配白T + 陳冠廷: { + ref: "https://www.ly.gov.tw/Images/Legislators/110067.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.04, hair: "short", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "vest", suit: "#33598a", shirt: "#f2f0f0", tie: "#33598a" }, + }, + // 淺銀細框圓眼鏡、黑色側分鮑伯、圓臉露齒笑 + 陳培瑜: { + ref: "https://www.ly.gov.tw/Images/Legislators/110070.jpg", + spec: { face: "round", faceW: 1.06, faceH: 0.98, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "round", glasses: true, glassesStyle: "round", glassesColor: "#b8bcc4", nose: "normal", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1a2340", shirt: "#e8ecf0", tie: "#1a2340" }, + }, + // 厚斜瀏海的深褐層次長髮、白色薄外套配深藍花上衣、淺笑 + 陳昭姿: { + ref: "https://www.ly.gov.tw/Images/Legislators/110068.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.03, hair: "long", hairColor: "#4a372b", part: "left", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#ededed", shirt: "#262c4e", tie: "#ededed" }, + }, + // 灰白後梳短髮與後退髮線、明顯大耳、下垂眼 + 陳永康: { + ref: "https://www.ly.gov.tw/Images/Legislators/110062.jpg", + spec: { face: "square", faceW: 1.04, faceH: 1.04, hair: "receding", hairColor: "#5e5a57", ears: "big", brows: "thin", browAngle: 0.0, eyes: "droopy", glasses: false, nose: "normal", mouth: "closed", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#2b2c31", shirt: "#f0f0f2", tie: "#9cabc6" }, + }, + // 長方形槍色金屬框眼鏡、尖下巴、露齒笑 + 陳清龍: { + ref: "https://www.ly.gov.tw/Images/Legislators/110121.jpg", + spec: { face: "heart", faceW: 0.96, faceH: 1.06, hair: "side", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#4a4a4f", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#3a3b45", shirt: "#f2f0f0", tie: "#8e6e94" }, + }, + // 碎層次的棕色側分鮑伯、圓臉大眼、灰藍色圍巾 + 陳玉珍: { + ref: "https://www.ly.gov.tw/Images/Legislators/110063.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "bobSide", hairColor: "#4a372b", part: "right", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "wide", glasses: false, nose: "normal", mouth: "closed", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#081a32", shirt: "#eef2f6", tie: "#eef2f6" }, + }, + // 及胸黑長直髮、露齒笑、原住民織紋背心配藍白條紋襯衫(判讀信心:medium) + 陳瑩: { + ref: "https://www.ly.gov.tw/Images/Legislators/110074.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "long", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "smile", glasses: false, nose: "small", mouth: "teeth", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#1c1c1e", shirt: "#dfe6f2", tie: "#1c1c1e" }, + }, + // 黑髮往後綁成低馬尾、垂在臉側的長斜瀏海、瞇眼露齒笑 + 陳秀寳: { + ref: "https://www.ly.gov.tw/Images/Legislators/110064.jpg", + spec: { face: "oval", faceW: 0.98, faceH: 1.02, hair: "ponytail", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#bcb5b7", shirt: "#f2e9e8", tie: "#f2e9e8" }, + }, + // 碎瀏海層次短髮、無框眼鏡、露齒笑 + 陳素月: { + ref: "https://www.ly.gov.tw/Images/Legislators/110069.jpg", + spec: { face: "round", faceW: 1.04, faceH: 1.0, hair: "pixie", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#1c2333", shirt: "#f5f5f5", tie: "#1c2333" }, + }, + // 紅棕色不對稱長斜瀏海短髮、尖下巴、白西裝外套 + 陳菁徽: { + ref: "https://www.ly.gov.tw/Images/Legislators/110072.jpg", + spec: { face: "heart", faceW: 0.95, faceH: 1.04, hair: "pixie", hairColor: "#8a4a2c", part: "left", ears: "normal", brows: "thin", browAngle: 0.2, eyes: "round", glasses: false, nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#f4f6f8", shirt: "#b8d0ec", tie: "#f4f6f8" }, + }, + // 眉框眼鏡、往後梳的黑髮配高額頭、露齒大笑、白襯衫不穿外套 + 陳超明: { + ref: "https://www.ly.gov.tw/Images/Legislators/110073.jpg", + spec: { face: "long", faceW: 0.98, faceH: 1.08, hair: "receding", hairColor: "#1f1b18", ears: "big", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "browline", glassesColor: "#2a2522", nose: "big", mouth: "teeth", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#e2e8ee", shirt: "#e2e8ee", tie: "#e2e8ee" }, + }, + // 寬方臉、厚重側分黑髮、金黃色領帶 + 陳雪生: { + ref: "https://www.ly.gov.tw/Images/Legislators/110071.jpg", + spec: { face: "square", faceW: 1.08, faceH: 1.02, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", brows: "normal", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "big", mouth: "closed", lines: 2, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#1e2533", shirt: "#f3eccf", tie: "#d9c070" }, + }, + // 兩側推短的小平頭、寬方臉、濃平眉 + 顏寬恒: { + ref: "https://www.ly.gov.tw/Images/Legislators/110107.jpg", + spec: { face: "square", faceW: 1.08, faceH: 1.0, hair: "crew", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.05, eyes: "narrow", glasses: false, nose: "normal", mouth: "smile", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "shirt", suit: "#c4d0ec", shirt: "#c4d0ec", tie: "#c4d0ec" }, + }, + // 過肩的深色斜瀏海長直髮、圓臉、湖水藍上衣 + 馬文君: { + ref: "https://www.ly.gov.tw/Images/Legislators/110050.jpg", + spec: { face: "round", faceW: 1.08, faceH: 1.0, hair: "long", hairColor: "#2f2520", part: "right", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "small", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#88def0", shirt: "#88def0", tie: "#88def0" }, + }, + // 中分的棕色長直髮、尖下巴、白色襯衫 + 高金素梅: { + ref: "https://www.ly.gov.tw/Images/Legislators/110051.jpg", + spec: { face: "heart", faceW: 0.95, faceH: 1.04, hair: "longMiddle", hairColor: "#4a372b", ears: "normal", brows: "thin", browAngle: 0.1, eyes: "narrow", glasses: false, nose: "small", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#fdfafd", shirt: "#fdfafd", tie: "#fdfafd" }, + }, + // 高聳油亮背頭、濃眉、白襯衫 + 魯明哲: { + ref: "https://www.ly.gov.tw/Images/Legislators/110098.jpg", + spec: { face: "oval", faceW: 1.02, faceH: 1.02, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.15, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "polo", suit: "#f6f6f6", shirt: "#f6f6f6", tie: "#f6f6f6" }, + }, + // 中分長直髮、瓜子臉 + 麥玉珍: { + ref: "https://www.ly.gov.tw/Images/Legislators/110075.jpg", + spec: { face: "oval", faceW: 0.95, faceH: 1.06, hair: "longMiddle", hairColor: "#1f1b18", ears: "small", brows: "thin", browAngle: 0.0, eyes: "narrow", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#1c1c1c", shirt: "#f2f2f2", tie: "#1c1c1c" }, + }, + // 一撮撮往上抓的刺蝟短髮、方臉、黑色桃紅領夾克配黃黑條紋領帶 + 黃仁: { + ref: "https://www.ly.gov.tw/Images/Legislators/110079.jpg", + spec: { face: "square", faceW: 1.06, faceH: 1.04, hair: "spiky", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.2, eyes: "narrow", glasses: false, nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#d9a079", outfit: "suit", suit: "#1a1a1c", shirt: "#f3efe0", tie: "#d4aa22" }, + }, + // 玳瑁色粗框眼鏡、兩側推短的蓬鬆旁分、圓臉 + 黃健豪: { + ref: "https://www.ly.gov.tw/Images/Legislators/110083.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#4a2c22", nose: "normal", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#1c2133", shirt: "#f4f4f6", tie: "#4b3a6b" }, + }, + // 往後梳的高背頭、長臉、劍眉 + 黃國昌: { + ref: "https://www.ly.gov.tw/Images/Legislators/110084.jpg", + spec: { face: "long", faceW: 0.95, faceH: 1.1, hair: "pompadour", hairColor: "#1f1b18", ears: "normal", brows: "thick", browAngle: 0.3, eyes: "narrow", glasses: false, nose: "normal", mouth: "closed", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "suit", suit: "#1f2a44", shirt: "#f7f5f0", tie: "#2c3e66" }, + }, + // 蓬亂厚重的側瀏海、多角形細金屬框眼鏡、露齒大笑 + 黃建賓: { + ref: "https://www.ly.gov.tw/Images/Legislators/110081.jpg", + spec: { face: "round", faceW: 1.06, faceH: 1.0, hair: "volume", hairColor: "#2f2520", part: "left", ears: "big", brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#b0a07a", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "vest", suit: "#9c8d7e", shirt: "#f0f0ee", tie: "#9c8d7e" }, + }, + // 厚齊瀏海的黑長直髮、兩側粉紅色挑染、白色西裝外套 + 黃捷: { + ref: "https://www.ly.gov.tw/Images/Legislators/110085.jpg", + spec: { face: "heart", faceW: 0.95, faceH: 1.02, hair: "longBangs", hairColor: "#1f1b18", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "wide", glasses: false, nose: "small", mouth: "smile", lines: 0, beard: false, mustache: false, skin: "#f6d3b7", outfit: "blouse", suit: "#eeeeec", shirt: "#f4f4f2", tie: "#eeeeec" }, + }, + // 細圓框眼鏡、及下巴的側分黑鮑伯、露齒大笑 + 黃秀芳: { + ref: "https://www.ly.gov.tw/Images/Legislators/110080.jpg", + spec: { face: "oval", faceW: 1.0, faceH: 1.02, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "normal", brows: "thin", browAngle: 0.0, eyes: "smile", glasses: true, glassesStyle: "round", glassesColor: "#4a4a4f", nose: "normal", mouth: "teeth", lines: 1, beard: false, mustache: false, skin: "#eebd98", outfit: "blouse", suit: "#d6c0b2", shirt: "#f4f2ee", tie: "#d6c0b2" }, + }, +}; diff --git a/web/src/game/art/likeness.ts b/web/src/game/art/likeness.ts new file mode 100644 index 0000000..bb5427e --- /dev/null +++ b/web/src/game/art/likeness.ts @@ -0,0 +1,359 @@ +import type { AvatarSpec } from "./Avatar.tsx"; +import { LIKENESS_2024 } from "./likeness-2024.ts"; + +/** + * 政治人物的 Q 版頭像特徵:看公開的官方肖像(維基共享資源),只記招牌特徵 + * (臉型、髮型、髮色、眼鏡、眉眼、笑容、常見穿著),由頭像系統畫成卡通。不使用照片、也不是 AI 生成。 + * ref 是參考的照片頁面,方便之後核對;遊戲不會載入照片。 + */ +export interface Likeness { + spec: Partial; + ref: string; +} + +export const LIKENESS: Readonly> = { + 韓國瑜: { + ref: "https://commons.wikimedia.org/wiki/File:立法院長韓國瑜.jpg", + spec: { + face: "oval", faceW: 0.98, faceH: 1.1, hair: "bald", hairColor: "#2a2420", ears: "big", + brows: "thin", browAngle: -0.1, eyes: "narrow", nose: "normal", mouth: "smile", lines: 1, + skin: "#eebd98", glasses: false, outfit: "polo", suit: "#9cc3e6", shirt: "#bcd8f0", + }, + }, + 蔡英文: { + ref: "https://commons.wikimedia.org/wiki/File:蔡英文官方元首肖像照.png", + spec: { + face: "round", faceW: 1.06, faceH: 0.98, hair: "bobSide", hairColor: "#3a2a22", part: "left", ears: "small", + brows: "thin", browAngle: -0.2, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", + nose: "small", mouth: "teeth", lines: 1, skin: "#f1c7a5", outfit: "blouse", suit: "#1c1c1c", shirt: "#f1ead8", + }, + }, + 賴清德: { + ref: "https://commons.wikimedia.org/wiki/File:賴清德總統_1.jpg", + spec: { + face: "long", faceW: 0.93, faceH: 1.14, hair: "volume", hairColor: "#1f1b18", part: "right", ears: "normal", + brows: "normal", browAngle: 0.2, eyes: "narrow", nose: "normal", mouth: "smile", lines: 1, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#1f2a3d", shirt: "#f7f5f0", tie: "#4a2b45", + }, + }, + 蕭美琴: { + ref: "https://commons.wikimedia.org/wiki/File:蕭美琴副總統_1.jpg", + spec: { + face: "oval", faceW: 0.96, faceH: 1.06, hair: "shortBob", hairColor: "#2a2420", part: "left", ears: "small", + brows: "thin", browAngle: 0.1, eyes: "narrow", nose: "small", mouth: "teeth", lines: 1, beard: false, + skin: "#f1c7a5", glasses: false, outfit: "blouse", suit: "#1f2a44", shirt: "#f7f5f0", + }, + }, + 侯友宜: { + ref: "https://commons.wikimedia.org/wiki/File:新北市長侯友宜.jpg", + spec: { + face: "square", faceW: 1.0, faceH: 1.05, hair: "crew", hairColor: "#1f1b18", ears: "big", + brows: "normal", browAngle: 0.3, eyes: "narrow", nose: "normal", mouth: "smile", lines: 1, beard: false, + skin: "#d9a079", glasses: false, outfit: "vest", suit: "#1c1c1e", shirt: "#f7f5f0", + }, + }, + 趙少康: { + ref: "https://commons.wikimedia.org/wiki/File:趙少康副總統候選人.jpg", + spec: { + face: "long", faceW: 0.98, faceH: 1.08, hair: "slick", hairColor: "#1f1b18", ears: "big", + brows: "thin", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "halfRim", glassesColor: "#4a4a4f", + nose: "big", mouth: "closed", lines: 2, beard: false, skin: "#eebd98", outfit: "polo", suit: "#1e2b5c", shirt: "#151515", + }, + }, + 柯文哲: { + ref: "https://commons.wikimedia.org/wiki/File:民眾黨創黨主席柯文哲2026年照片.jpg", + spec: { + face: "round", faceW: 1.06, faceH: 1.0, hair: "side", hairColor: "#8b8682", part: "right", ears: "normal", + brows: "normal", browAngle: -0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#8e9196", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "vest", suit: "#24324a", shirt: "#cfe0f2", + }, + }, + 吳欣盈: { + ref: "https://commons.wikimedia.org/wiki/File:吳欣盈肖像.jpg", + spec: { + face: "oval", faceW: 0.95, faceH: 1.05, hair: "long", hairColor: "#2f2520", part: "right", ears: "small", + brows: "thin", browAngle: 0.25, eyes: "narrow", nose: "small", mouth: "closed", lines: 0, beard: false, + skin: "#eebd98", glasses: false, outfit: "blouse", suit: "#f3f1ec", shirt: "#eebd98", + }, + }, + 宋楚瑜: { + ref: "https://commons.wikimedia.org/wiki/File:James_Soong_election_infobox.jpg", + spec: { + face: "square", faceW: 1.08, faceH: 1.08, hair: "receding", hairColor: "#1f1b18", ears: "big", + brows: "normal", browAngle: 0.1, eyes: "narrow", nose: "big", mouth: "closed", lines: 2, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#3a3d44", shirt: "#f7f5f0", tie: "#c4232c", + }, + }, + 余湘: { + ref: "https://commons.wikimedia.org/wiki/File:第15任總統副總統選舉候選人余湘.jpg", + spec: { + face: "round", faceW: 1.0, faceH: 1.0, hair: "shortBob", hairColor: "#1f1b18", part: "right", ears: "small", + brows: "thin", browAngle: 0, eyes: "round", glasses: true, glassesStyle: "round", glassesColor: "#1a1a1a", + nose: "small", mouth: "teeth", lines: 1, beard: false, skin: "#f1c7a5", outfit: "blouse", suit: "#1c1c1c", shirt: "#f1ead8", + }, + }, + 張善政: { + ref: "https://commons.wikimedia.org/wiki/File:桃園市長張善政.jpg", + spec: { + face: "long", faceW: 0.98, faceH: 1.08, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.2, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#3d3f45", + nose: "normal", mouth: "teeth", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1f2a44", shirt: "#f7f5f0", tie: "#a9a79c", + }, + }, + 朱立倫: { + ref: "https://commons.wikimedia.org/wiki/File:Eric_Chu_Chopped_2017.png", + spec: { + face: "long", faceW: 0.95, faceH: 1.1, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0, eyes: "smile", nose: "normal", mouth: "teeth", lines: 1, beard: false, + skin: "#eebd98", glasses: false, outfit: "polo", suit: "#24365c", shirt: "#2e4470", + }, + }, + 王如玄: { + ref: "https://commons.wikimedia.org/wiki/File:王如玄.jpg", + spec: { + face: "oval", faceW: 0.95, faceH: 1.02, hair: "long", hairColor: "#2a2420", part: "left", ears: "small", + brows: "thin", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", + nose: "small", mouth: "teeth", lines: 0, beard: false, skin: "#f1c7a5", outfit: "blouse", suit: "#f4f1ea", shirt: "#2a2a2a", + }, + }, + 陳建仁: { + ref: "https://commons.wikimedia.org/wiki/File:陳建仁院長_2.jpg", + spec: { + face: "round", faceW: 1.04, faceH: 1.0, hair: "volume", hairColor: "#9a9a9a", part: "left", ears: "normal", + brows: "normal", browAngle: -0.1, eyes: "smile", glasses: true, glassesStyle: "black", glassesColor: "#1e1e22", + nose: "normal", mouth: "teeth", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#26272c", shirt: "#f7f5f0", tie: "#c96f6a", + }, + }, + 馬英九: { + ref: "https://commons.wikimedia.org/wiki/File:中華民國第12、13任總統馬英九先生官方肖像照.jpg", + spec: { + face: "long", faceW: 0.95, faceH: 1.1, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.3, eyes: "narrow", nose: "normal", mouth: "smile", lines: 1, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#1c1d22", shirt: "#f7f5f0", tie: "#2c3e78", + }, + }, + 吳敦義: { + ref: "https://commons.wikimedia.org/wiki/File:Wu_Den-yih.jpg", + spec: { + face: "oval", faceW: 1.04, faceH: 1.04, hair: "receding", hairColor: "#b3b3b0", ears: "big", + brows: "thin", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#a8957a", + nose: "normal", mouth: "smile", lines: 2, beard: false, skin: "#f1c7a5", outfit: "suit", suit: "#1f2026", shirt: "#f7f5f0", tie: "#8d8d8d", + }, + }, + 謝長廷: { + ref: "https://commons.wikimedia.org/wiki/File:謝長廷代表.jpg", + spec: { + face: "long", faceW: 0.95, faceH: 1.08, hair: "side", hairColor: "#4a4642", part: "left", ears: "big", + brows: "thin", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#a8874f", + nose: "normal", mouth: "closed", lines: 2, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1c2333", shirt: "#f7f5f0", tie: "#9cc0e6", + }, + }, + 蘇貞昌: { + ref: "https://commons.wikimedia.org/wiki/File:行政院院長蘇貞昌肖像.jpg", + spec: { + face: "round", faceW: 1.05, faceH: 1.02, hair: "bald", hairColor: "#2a2420", ears: "big", + brows: "normal", browAngle: 0, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", + nose: "big", mouth: "teeth", lines: 2, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1d2230", shirt: "#f7f5f0", tie: "#3f5d9a", + }, + }, + 蕭萬長: { + ref: "https://commons.wikimedia.org/wiki/File:Vincent_Siew_(chopped).jpg", + spec: { + face: "round", faceW: 1.08, faceH: 1.0, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#b8a070", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1f2a4a", shirt: "#f7f5f0", tie: "#d9a93a", + }, + }, + 陳水扁: { + ref: "https://commons.wikimedia.org/wiki/File:陳水扁總統_1.jpg", + spec: { + face: "square", faceW: 1.02, faceH: 1.05, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b5a47e", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#3a3d44", shirt: "#f7f5f0", tie: "#8fb3c9", + }, + }, + 呂秀蓮: { + ref: "https://commons.wikimedia.org/wiki/File:副總統呂秀蓮女士玉照_(國民大會實錄).jpg", + spec: { + face: "round", faceW: 1.02, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "right", ears: "small", + brows: "thin", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#c9b38a", + nose: "small", mouth: "teeth", lines: 1, beard: false, skin: "#f1c7a5", outfit: "blouse", suit: "#c8a27a", shirt: "#e6cfa8", + }, + }, + 連戰: { + ref: "https://commons.wikimedia.org/wiki/File:連戰副總統.jpg", + spec: { + face: "square", faceW: 1.1, faceH: 1.05, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", + nose: "big", mouth: "closed", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1c2235", shirt: "#f7f5f0", tie: "#24345e", + }, + }, + 許信良: { + ref: "https://commons.wikimedia.org/wiki/File:2026.05.20_Hsu_Hsin-liang_at_ROC_President_Office_(cropped).jpg", + spec: { + face: "round", faceW: 1.04, faceH: 1.05, hair: "bald", hairColor: "#c9c9c9", ears: "big", + brows: "thin", browAngle: -0.1, eyes: "smile", nose: "normal", mouth: "teeth", lines: 2, beard: false, + skin: "#f1c7a5", glasses: false, outfit: "suit", suit: "#26272c", shirt: "#f7f5f0", tie: "#7a95b8", + }, + }, + 李敖: { + ref: "https://commons.wikimedia.org/wiki/File:第六屆立法委員_李敖.jpg", + spec: { + face: "long", faceW: 0.98, faceH: 1.06, hair: "side", hairColor: "#1f1b18", part: "right", ears: "normal", + brows: "normal", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#1c1c1c", + nose: "normal", mouth: "closed", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#c75b4a", shirt: "#3d5a85", tie: "#b3262d", + }, + }, + 李登輝: { + ref: "https://commons.wikimedia.org/wiki/File:李總統登輝先生玉照_(cropped).jpg", + spec: { + face: "long", faceW: 0.98, faceH: 1.15, hair: "slick", hairColor: "#9a9a9a", ears: "big", + brows: "normal", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", + nose: "big", mouth: "smile", lines: 2, beard: false, skin: "#f1c7a5", outfit: "suit", suit: "#1f2440", shirt: "#f3ead8", tie: "#6a2a35", + }, + }, + 彭明敏: { + ref: "https://commons.wikimedia.org/wiki/File:彭明敏出席著作簽書分享會.jpg", + spec: { + face: "long", faceW: 0.95, faceH: 1.08, hair: "receding", hairColor: "#8a8580", ears: "big", + brows: "thin", browAngle: -0.1, eyes: "smile", nose: "normal", mouth: "smile", lines: 2, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#3a3d48", shirt: "#dfe9f3", tie: "#7a95b8", + }, + }, + 林洋港: { + ref: "https://commons.wikimedia.org/wiki/File:林洋港省主席.jpg", + spec: { + face: "square", faceW: 1.08, faceH: 1.05, hair: "slick", hairColor: "#2f2a26", ears: "normal", + brows: "thick", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#1a1a1a", + nose: "big", mouth: "closed", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1f1f22", shirt: "#bcd3ef", tie: "#2a3550", + }, + }, + 郝柏村: { + ref: "https://commons.wikimedia.org/wiki/File:郝柏村院長.jpg", + spec: { + face: "square", faceW: 1.1, faceH: 1.06, hair: "slick", hairColor: "#1f1b18", ears: "big", + brows: "thick", browAngle: 0.2, eyes: "narrow", nose: "big", mouth: "closed", lines: 2, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#3a3f4c", shirt: "#f7f5f0", tie: "#b3262d", + }, + }, + 陳履安: { + ref: "https://commons.wikimedia.org/wiki/File:前監察院長陳履安.jpg", + spec: { + face: "long", faceW: 0.95, faceH: 1.1, hair: "side", hairColor: "#c9c9c9", part: "left", ears: "big", + brows: "thin", browAngle: -0.1, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", + nose: "normal", mouth: "smile", lines: 2, beard: false, skin: "#f1c7a5", outfit: "suit", suit: "#1d2230", shirt: "#f7f5f0", tie: "#2c3e78", + }, + }, + 王清峰: { + ref: "https://commons.wikimedia.org/wiki/File:Wang_Ching-feng.jpg", + spec: { + face: "oval", faceW: 0.98, faceH: 1.0, hair: "bobSide", hairColor: "#1f1b18", part: "left", ears: "small", + brows: "thin", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "metal", glassesColor: "#b89a66", + nose: "small", mouth: "closed", lines: 1, beard: false, skin: "#f1c7a5", outfit: "blouse", suit: "#f2cfd2", shirt: "#f7f5f0", + }, + }, + 蔣萬安: { + ref: "https://commons.wikimedia.org/wiki/File:蔣萬安市長_(cropped).jpg", + spec: { + face: "long", faceW: 0.95, faceH: 1.08, hair: "volume", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.2, eyes: "narrow", nose: "normal", mouth: "smile", lines: 0, beard: false, + skin: "#f1c7a5", glasses: false, outfit: "suit", suit: "#cfe0f2", shirt: "#dfeaf6", tie: "#7f9cc6", + }, + }, + 盧秀燕: { + ref: "https://commons.wikimedia.org/wiki/File:臺中市長盧秀燕.jpg", + spec: { + face: "round", faceW: 1.06, faceH: 0.98, hair: "shortBob", hairColor: "#1f1b18", part: "left", ears: "small", + brows: "thin", browAngle: 0.1, eyes: "narrow", nose: "small", mouth: "smile", lines: 0, beard: false, + skin: "#f1c7a5", glasses: false, outfit: "blouse", suit: "#3f6fc0", shirt: "#bcd3ef", + }, + }, + 陳其邁: { + ref: "https://commons.wikimedia.org/wiki/File:Chen_Chi-mai_election_infobox.jpg", + spec: { + face: "long", faceW: 0.98, faceH: 1.1, hair: "side", hairColor: "#1f1b18", part: "right", ears: "normal", + brows: "normal", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "black", glassesColor: "#3a2a22", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#2a2c33", shirt: "#f7f5f0", tie: "#9cc0e6", + }, + }, + 黃偉哲: { + ref: "https://commons.wikimedia.org/wiki/File:黃偉哲市長.jpg", + spec: { + face: "oval", faceW: 1.0, faceH: 1.05, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", + nose: "normal", mouth: "teeth", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1f2a4a", shirt: "#dfe9f3", tie: "#24345e", + }, + }, + 林佳龍: { + ref: "https://commons.wikimedia.org/wiki/File:林佳龍部長.jpg", + spec: { + face: "oval", faceW: 1.0, faceH: 1.06, hair: "side", hairColor: "#1f1b18", part: "left", ears: "normal", + brows: "normal", browAngle: 0.1, eyes: "smile", glasses: true, glassesStyle: "metal", glassesColor: "#8e9196", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "suit", suit: "#1f2a4a", shirt: "#f7f5f0", tie: "#3f6b48", + }, + }, + 陳時中: { + ref: "https://commons.wikimedia.org/wiki/File:陳時中部長肖像.jpg", + spec: { + face: "oval", faceW: 1.0, faceH: 1.06, hair: "side", hairColor: "#6f6a66", part: "left", ears: "normal", + brows: "normal", browAngle: 0, eyes: "narrow", nose: "normal", mouth: "closed", lines: 1, beard: false, + skin: "#eebd98", glasses: false, outfit: "suit", suit: "#3a3d44", shirt: "#f7f5f0", tie: "#5a5d63", + }, + }, + 黃珊珊: { + ref: "https://commons.wikimedia.org/wiki/File:黃珊珊委員.jpg", + spec: { + face: "round", faceW: 1.02, faceH: 1.0, hair: "shortBob", hairColor: "#3a2a22", part: "left", ears: "small", + brows: "thin", browAngle: 0, eyes: "smile", nose: "small", mouth: "teeth", lines: 0, beard: false, + skin: "#f1c7a5", glasses: false, outfit: "blouse", suit: "#f4f2ee", shirt: "#f1c7a5", + }, + }, + 高虹安: { + ref: "https://commons.wikimedia.org/wiki/File:新竹市長高虹安.jpg", + spec: { + face: "oval", faceW: 0.95, faceH: 1.04, hair: "long", hairColor: "#1f1b18", part: "left", ears: "small", + brows: "thin", browAngle: 0.1, eyes: "narrow", nose: "small", mouth: "teeth", lines: 0, beard: false, + skin: "#f6d3b7", glasses: false, outfit: "blouse", suit: "#8e9196", shirt: "#f7f5f0", + }, + }, + 鄭運鵬: { + ref: "https://commons.wikimedia.org/wiki/File:Cheng_Yun-Peng-2-by_Ring_Chang_(cropped).jpg", + spec: { + face: "oval", faceW: 0.98, faceH: 1.06, hair: "short", hairColor: "#1f1b18", ears: "normal", + brows: "normal", browAngle: 0.1, eyes: "narrow", glasses: true, glassesStyle: "rimless", glassesColor: "#9aa3ad", + nose: "normal", mouth: "smile", lines: 0, beard: false, skin: "#eebd98", outfit: "vest", suit: "#2a2c33", shirt: "#e6e3f2", + }, + }, + 蔡其昌: { + ref: "https://commons.wikimedia.org/wiki/File:立法院副院長蔡其昌_(cropped).jpg", + spec: { + face: "round", faceW: 1.08, faceH: 1.02, hair: "crew", hairColor: "#1f1b18", ears: "big", + brows: "normal", browAngle: 0, eyes: "narrow", glasses: true, glassesStyle: "halfRim", glassesColor: "#5f7a66", + nose: "normal", mouth: "smile", lines: 1, beard: false, skin: "#eebd98", outfit: "polo", suit: "#f5f5f2", shirt: "#e4e4df", + }, + }, +}; + +const person = (name: string) => name.replace(/(\d{4})$/, ""); + +/** + * 漫畫誇張:臉寬、臉長偏離標準多少,畫的時候再放大 2.2 倍(夾在協定允許的範圍裡),每個人才不會長得都差不多。 + * 眉毛角度只放大 1.5 倍,放太大每個人都像在生氣。 + */ +const push = (v: number | undefined, lo: number, hi: number, mid = 1, k = 2.2) => (v === undefined ? undefined : Math.min(hi, Math.max(lo, Math.round((mid + (v - mid) * k) * 100) / 100))); + +export function caricature(spec: Partial): Partial { + const out = { ...spec }; + const faceW = push(spec.faceW, 0.8, 1.25); + const faceH = push(spec.faceH, 0.85, 1.25); + const browAngle = push(spec.browAngle, -1, 1, 0, 1.5); + if (faceW !== undefined) out.faceW = faceW; + if (faceH !== undefined) out.faceH = faceH; + if (browAngle !== undefined) out.browAngle = browAngle; + return out; +} + +export function likenessOf(name: string): Partial | null { + const like = LIKENESS[person(name)] ?? LIKENESS_2024[person(name)]; + return like ? caricature(like.spec) : null; +} diff --git a/web/src/game/art/palette.ts b/web/src/game/art/palette.ts new file mode 100644 index 0000000..06ff7ca --- /dev/null +++ b/web/src/game/art/palette.ts @@ -0,0 +1,31 @@ +/** + * 插畫用的固定色盤(場景是「圖」,淺色、深色模式都用同一套顏色)。 + * 人物都是虛構的遊戲角色;真實候選人在場景裡只畫剪影加競選彩帶(docs/17)。 + */ +export const SKIN = ["#f6d3b7", "#eebd98", "#d9a079", "#b97b55"] as const; +export const HAIR = ["#1f1b18", "#2f2520", "#4a372b", "#6b4f3a", "#9a9a9a"] as const; +export const SUIT = ["#24324a", "#363b44", "#4b3a2f", "#1d3a3a", "#5a2d34", "#2e2f5a"] as const; +export const SHIRT = ["#f7f5f0", "#dfe9f3", "#f3e6d8", "#e7f0e3"] as const; +export const TIE = ["#b3262d", "#2c5aa0", "#2f7d4f", "#d08b1a", "#6c3d91"] as const; +export const CROWD = ["#d9534f", "#f0ad4e", "#5bc0de", "#5cb85c", "#7a6fd1", "#e88ab0", "#8d6e63", "#455a64", "#ffd166", "#26a69a"] as const; + +export const SKY = { + day: ["#a9d6ec", "#e9f4f1"], + dusk: ["#f2a477", "#fbe0bf"], + night: ["#0f1a33", "#26365e"], + studio: ["#0d1b36", "#1d3767"], +} as const; + +/** 由字串產生穩定的亂數(同一個人每次畫出來都一樣) */ +export function seeded(seed: string): () => number { + let h = 2166136261; + for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619); + return () => { + h = Math.imul(h ^ (h >>> 15), 2246822507); + h = Math.imul(h ^ (h >>> 13), 3266489909); + h ^= h >>> 16; + return (h >>> 0) / 4294967296; + }; +} + +export const pickFrom = (list: readonly T[], r: number): T => list[Math.floor(r * list.length) % list.length]!; diff --git a/web/src/game/art/scenes/dark.tsx b/web/src/game/art/scenes/dark.tsx new file mode 100644 index 0000000..9890fa0 --- /dev/null +++ b/web/src/game/art/scenes/dark.tsx @@ -0,0 +1,179 @@ +import { SKIN, SUIT } from "../palette.ts"; +import { Person } from "../Person.tsx"; +import { Banner, Cloud, Ground, H, Rain, SceneSvg, Shophouse, Sky, Stars, W } from "./kit.tsx"; +import type { SceneProps } from "./ground.tsx"; + +/** 黑暗面:深夜巷弄塞信封(cash)、網軍工作室(trolls)、徵信社跟監(spy) */ +export function ShadowScene({ id, color, variant = "cash" }: SceneProps) { + if (variant === "trolls") { + return ( + + + {[0, 1, 2].map((row) => + [0, 1, 2, 3].map((col) => { + const x = 70 + col * 150; + const y = 110 + row * 90; + return ( + + + + {[0, 1, 2].map((k) => ( + + ))} + + + ); + }), + )} + + #爆料 + #黑心 + #轉傳 + + + (外包網軍,約 12% 機率被查核中心揭露) + + + ); + } + if (variant === "spy") { + return ( + + + + {[0, 1, 2, 3, 4, 5, 6].map((i) => ( + + ))} + + + + + + + + + + + + + + + ); + } + return ( + + + + + + {[90, 160, 230].map((y) => ( + + ))} + + + + + + + + + + + + (違反選罷法:知情的人越多,越容易有人檢舉) + + + + ); +} + +/** 檢調約談:地檢署門口、警示燈、記者包圍 */ +export function InvestigationScene({ id }: SceneProps) { + return ( + + + + + {[150, 230, 310, 390, 470].map((x) => ( + + ))} + + + + + + + + + + + + + + + {[180, 220, 420, 460].map((x, i) => ( + + 320} female={i % 2 === 0} /> + 320 ? -24 : 24)} cy="262" r="24" fill={`url(#${id}-glow)`} style={{ animationDelay: `${i * 380}ms` }} /> + 320 ? -24 : 24)} cy="262" r="8" fill="#fff" style={{ animationDelay: `${i * 380}ms` }} /> + + ))} + + ); +} + +/** 颱風:烏雲、強風、雨、被吹歪的樹與傘 */ +export function TyphoonScene({ id }: SceneProps) { + return ( + + + + + + + + {[0, 1, 2, 3, 4, 5, 6].map((i) => ( + + ))} + + + + + + + + + + + + + + + + 颱風逼近,戶外活動效果打折 + + + ); +} + +/** 全國風向/民調:電視上的趨勢圖 */ +export function NationalScene({ id }: SceneProps) { + return ( + + + + + + + {[100, 150, 200, 250].map((y) => ( + + ))} + + + 中央政局動態 + + + + ); +} + diff --git a/web/src/game/art/scenes/events.tsx b/web/src/game/art/scenes/events.tsx new file mode 100644 index 0000000..c4cfa41 --- /dev/null +++ b/web/src/game/art/scenes/events.tsx @@ -0,0 +1,237 @@ +import { CROWD, SKIN, SUIT } from "../palette.ts"; +import { Crowd, Person } from "../Person.tsx"; +import { Beam, Cloud, Ground, H, Lanterns, Rain, SceneSvg, Shophouse, Sky, Sparks, Stars, Sun, W } from "./kit.tsx"; +import type { SceneProps } from "./ground.tsx"; + +/** 造勢晚會:夜空、舞台桁架、大螢幕、聚光燈、揮旗的人群;variant = eve(選前之夜,加煙火)、kneel(下跪) */ +export function RallyScene({ id, color, number, variant }: SceneProps) { + const eve = variant === "eve" || variant === "kneel"; + return ( + + + + {eve && ( + + {[ + [120, 70, "#ffd166"], + [520, 56, "#ff6b8a"], + [330, 40, "#7ee0ff"], + ].map(([x, y, c], i) => ( + + {Array.from({ length: 12 }, (_, k) => { + const a = (k / 12) * Math.PI * 2; + return ; + })} + + ))} + + )} + + + {/* 舞台 */} + + + + + + {Array.from({ length: 14 }, (_, i) => ( + + ))} + + + + + + {number} + + + {variant === "kneel" ? "拜託" : "凍蒜"} + + + {eve ? "最後一夜 全力拚" : "感謝鄉親 支持"} + + + + + + + + {variant === "kneel" && ( + + (台下支持者淚灑會場) + + )} + + + + ); +} + +/** 募款餐會(辦桌):紅棚、圓桌紅桌巾、上菜、台上致詞 */ +export function BanquetScene({ id, color, number }: SceneProps) { + const tables = [ + [110, 268], + [320, 262], + [530, 268], + [210, 318], + [430, 318], + ]; + return ( + + + + + {Array.from({ length: 11 }, (_, i) => ( + + ))} + `Q${i * 32 + 16} 134 ${(i + 1) * 32} 120`).join(" ")}`} fill="#c4161c" /> + + + + {number}號 募款餐會 + + + 感謝各界鄉親熱情贊助 + + + + + {tables.map(([x, y], i) => ( + + {[-56, -34, 34, 56].map((dx, k) => ( + + + + + ))} + + + {[-30, -6, 18, 38].map((dx, k) => ( + + ))} + + + + + + ))} + + ); +} + +/** 競選服務處成立:店面、大看板、花籃、剪綵、鞭炮 */ +export function OfficeScene({ id, color, number }: SceneProps) { + return ( + + + + + + + + + + 競選服務處 + + + + {number} + + + 為民服務 傾聽心聲 + + + + + + + + {[110, 160, 440, 490].map((x, i) => ( + + + + + + + 恭賀 + + + ))} + + + + + + + + + {Array.from({ length: 8 }, (_, i) => ( + + ))} + + + + ); +} + +/** 當選:謝票車隊、鞭炮、彩帶 */ +export function VictoryScene({ id, color, number }: SceneProps) { + return ( + + + + {[0, 1, 2, 3, 4, 5, 6].map((i) => ( + + ))} + + + + + + + + 感謝鄉親 {number}號當選 謝票 + + + + + + + + {Array.from({ length: 40 }, (_, i) => ( + + ))} + + + + + ); +} + +/** 落選:雨夜、空蕩的服務處、收起的椅子 */ +export function DefeatScene({ id, color, number }: SceneProps) { + return ( + + + + + + {number}號 競選總部 + + + + {Array.from({ length: 7 }, (_, i) => ( + + + + + + ))} + + + + + + + ); +} diff --git a/web/src/game/art/scenes/ground.tsx b/web/src/game/art/scenes/ground.tsx new file mode 100644 index 0000000..6040e9a --- /dev/null +++ b/web/src/game/art/scenes/ground.tsx @@ -0,0 +1,191 @@ +import { CROWD, SKIN, SUIT } from "../palette.ts"; +import { Person } from "../Person.tsx"; +import { Banner, Cloud, Ground, H, Lanterns, SceneSvg, Scooter, Shophouse, Sky, Stall, Sun, W } from "./kit.tsx"; + +export interface SceneProps { + id: string; + /** 自己陣營的政黨色(CSS 顏色或變數) */ + color: string; + number: number; + variant?: string; + /** 對手(撞場用) */ + rival?: { color: string; number: number }; +} + +/** 掃街拜票:騎樓街屋、機車、候選人揮手、幕僚發面紙;variant = truck 是宣傳車,clash 是撞場 */ +export function StreetScene({ id, color, number, variant, rival }: SceneProps) { + return ( + + + + + + {[0, 1, 2, 3, 4, 5, 6].map((i) => ( + + ))} + + + + + + + + + {variant === "truck" ? ( + + + + + + + + + + {number}號 拜託 + + + + + + + + ) : ( + + + + + + {variant === "clash" && rival && ( + + + + + 撞場! + + + )} + + )} + + ); +} + +/** 菜市場拜票:條紋攤位、攤商、長輩,候選人握手 */ +export function MarketScene({ id, color, number }: SceneProps) { + return ( + + + + + {[0, 1, 2, 3, 4, 5, 6, 7].map((i) => ( + + ))} + + {[80, 260, 440, 600].map((x) => ( + + + + + + ))} + + + + + + + + + + + + + + + + ); +} + +/** 宮廟參拜:燕尾屋脊、紅柱、香爐冒煙、燈籠 */ +export function TempleScene({ id, color, number }: SceneProps) { + return ( + + + + + + + + + + + + {[150, 210, 410, 470].map((x) => ( + + ))} + + + + + + + + 福德宮 + + + + + + + + + + + + + + + + + + + + + ); +} + +/** 工業區拜票:鋸齒屋頂的廠房、煙囪、工人換班 */ +export function FactoryScene({ id, color, number }: SceneProps) { + return ( + + + + + + + + + + + + + + + + {[40, 110, 180, 250, 320].map((x) => ( + + ))} + {[440, 500, 560].map((x) => ( + + ))} + + + + + {[300, 350, 400, 452, 500].map((x, i) => ( + + ))} + + + ); +} diff --git a/web/src/game/art/scenes/index.tsx b/web/src/game/art/scenes/index.tsx new file mode 100644 index 0000000..928fbfb --- /dev/null +++ b/web/src/game/art/scenes/index.tsx @@ -0,0 +1,81 @@ +import type { ComponentType } from "react"; +import { BanquetScene, DefeatScene, OfficeScene, RallyScene, VictoryScene } from "./events.tsx"; +import { InvestigationScene, NationalScene, ShadowScene, TyphoonScene } from "./dark.tsx"; +import { FactoryScene, MarketScene, StreetScene, TempleScene, type SceneProps } from "./ground.tsx"; +import { AdScene, CallCenterScene, PressScene, TalkShowScene } from "./media.tsx"; + +export type SceneKind = + | "street" + | "market" + | "temple" + | "factory" + | "rally" + | "banquet" + | "office" + | "press" + | "talkshow" + | "ad" + | "callcenter" + | "shadow" + | "investigation" + | "typhoon" + | "national" + | "victory" + | "defeat"; + +const SCENES: Record> = { + street: StreetScene, + market: MarketScene, + temple: TempleScene, + factory: FactoryScene, + rally: RallyScene, + banquet: BanquetScene, + office: OfficeScene, + press: PressScene, + talkshow: TalkShowScene, + ad: AdScene, + callcenter: CallCenterScene, + shadow: ShadowScene, + investigation: InvestigationScene, + typhoon: TyphoonScene, + national: NationalScene, + victory: VictoryScene, + defeat: DefeatScene, +}; + +export function Scene({ kind, ...props }: SceneProps & { kind: SceneKind }) { + const Component = SCENES[kind]; + return ; +} + +/** 美術總覽用:每個場景與變化 */ +export const SCENE_LIST: { key: string; kind: SceneKind; variant?: string; label: string }[] = [ + { key: "street", kind: "street", label: "掃街拜票" }, + { key: "truck", kind: "street", variant: "truck", label: "宣傳車" }, + { key: "clash", kind: "street", variant: "clash", label: "撞場" }, + { key: "market", kind: "market", label: "菜市場" }, + { key: "temple", kind: "temple", label: "宮廟" }, + { key: "factory", kind: "factory", label: "工業區" }, + { key: "rally", kind: "rally", label: "造勢晚會" }, + { key: "eve", kind: "rally", variant: "eve", label: "選前之夜" }, + { key: "kneel", kind: "rally", variant: "kneel", label: "下跪拜票" }, + { key: "banquet", kind: "banquet", label: "募款餐會" }, + { key: "office", kind: "office", label: "服務處成立" }, + { key: "press-policy", kind: "press", variant: "policy", label: "政見記者會" }, + { key: "press-expose", kind: "press", variant: "expose", label: "爆料記者會" }, + { key: "talkshow", kind: "talkshow", label: "政論節目" }, + { key: "gaffe", kind: "talkshow", variant: "gaffe", label: "政論失言" }, + { key: "ad-tv", kind: "ad", variant: "tv", label: "電視廣告" }, + { key: "ad-online", kind: "ad", variant: "online", label: "網路廣告" }, + { key: "ad-donate", kind: "ad", variant: "donate", label: "小額募款" }, + { key: "poll", kind: "callcenter", variant: "poll", label: "內參民調" }, + { key: "phone", kind: "callcenter", variant: "phone", label: "電話催票" }, + { key: "cash", kind: "shadow", variant: "cash", label: "買票(黑暗面)" }, + { key: "trolls", kind: "shadow", variant: "trolls", label: "網軍(黑暗面)" }, + { key: "spy", kind: "shadow", variant: "spy", label: "打探對手" }, + { key: "investigation", kind: "investigation", label: "檢調約談" }, + { key: "typhoon", kind: "typhoon", label: "颱風" }, + { key: "national", kind: "national", label: "全國政情" }, + { key: "victory", kind: "victory", label: "當選謝票" }, + { key: "defeat", kind: "defeat", label: "落選" }, +]; diff --git a/web/src/game/art/scenes/kit.tsx b/web/src/game/art/scenes/kit.tsx new file mode 100644 index 0000000..229d985 --- /dev/null +++ b/web/src/game/art/scenes/kit.tsx @@ -0,0 +1,224 @@ +import type { ReactNode } from "react"; +import { SKY, seeded } from "../palette.ts"; + +/** 場景的共用畫框與零件。畫布 640 × 360(16:9) */ +export const W = 640; +export const H = 360; + +export function SceneSvg({ id, label, children, className }: { id: string; label: string; children: ReactNode; className?: string }) { + return ( + + + + + + + + + + + + + + + + + + + + + + + + {children} + + ); +} + +export function Sky({ id, time = "day" }: { id: string; time?: "day" | "dusk" | "night" }) { + return ; +} + +export function Stars({ seed = "stars", count = 40 }: { seed?: string; count?: number }) { + const r = seeded(seed); + return ( + + {Array.from({ length: count }, (_, i) => ( + + ))} + + ); +} + +export function Cloud({ x, y, s = 1, className = "art-drift" }: { x: number; y: number; s?: number; className?: string }) { + return ( + + + + + + ); +} + +export function Sun({ x, y }: { x: number; y: number }) { + return ( + + + + + ); +} + +export function Ground({ y, color = "#cdbfa8", line = "#b5a68e" }: { y: number; color?: string; line?: string }) { + return ( + + + + + ); +} + +const SIGNS = ["藥局", "飲料", "機車行", "早餐", "麵店", "眼鏡", "五金", "茶行", "電器", "書局", "水果", "便當"]; + +/** 台灣街屋:三樓、騎樓、直立招牌、冷氣、鐵窗 */ +export function Shophouse({ x, w = 96, floors = 3, color = "#e8d9c4", seed }: { x: number; w?: number; floors?: number; color?: string; seed: string }) { + const r = seeded(seed); + const top = 300 - floors * 62; + const sign = SIGNS[Math.floor(r() * SIGNS.length)]!; + const signColor = ["#c4161c", "#1d5fa8", "#e8a317", "#2f7d4f"][Math.floor(r() * 4)]!; + return ( + + + + {Array.from({ length: floors - 1 }, (_, f) => ( + + + + {Array.from({ length: 6 }, (_, i) => ( + + ))} + + + + ))} + {/* 騎樓 */} + + + + + + + {sign.split("").map((ch, i) => ( + + {ch} + + ))} + + + ); +} + +export function Scooter({ x, y, color = "#d64545", flip }: { x: number; y: number; color?: string; flip?: boolean }) { + return ( + + + + + + + + ); +} + +/** 一串燈籠 */ +export function Lanterns({ x1, x2, y, count = 7, color = "#d8262d" }: { x1: number; x2: number; y: number; count?: number; color?: string }) { + const step = (x2 - x1) / (count - 1); + return ( + + + {Array.from({ length: count }, (_, i) => { + const t = i / (count - 1); + const cx = x1 + i * step; + const cy = y + 22 * 4 * t * (1 - t) * 0.5 + 6; + return ( + + + + + + + ); + })} + + ); +} + +/** 攤位:條紋遮雨棚與菜籃 */ +export function Stall({ x, w = 130, stripe = "#c4161c", seed }: { x: number; w?: number; stripe?: string; seed: string }) { + const r = seeded(seed); + const produce = ["#e85d3f", "#f2b632", "#5aa54b", "#8e4b8f", "#f28c28", "#3f9d55"]; + return ( + + + + + {Array.from({ length: 6 }, (_, i) => ( + + ))} + + + + {Array.from({ length: 12 }, (_, i) => ( + + ))} + + ); +} + +/** 舞台聚光燈的光束(會擺動) */ +export function Beam({ id, x, angle, delay = 0 }: { id: string; x: number; angle: number; delay?: number }) { + return ( + + + + ); +} + +export function Rain({ seed = "rain", count = 70 }: { seed?: string; count?: number }) { + const r = seeded(seed); + return ( + + {Array.from({ length: count }, (_, i) => { + const x = r() * (W + 80); + const y = r() * H; + return ; + })} + + ); +} + +/** 鞭炮的火花 */ +export function Sparks({ x, y, seed }: { x: number; y: number; seed: string }) { + const r = seeded(seed); + return ( + + {Array.from({ length: 14 }, (_, i) => { + const a = r() * Math.PI * 2; + const d = 10 + r() * 22; + return ; + })} + + ); +} + +/** 寫著字的布條(直書或橫書) */ +export function Banner({ x, y, w, h, color, text, fontSize = 22, textColor = "#fff" }: { x: number; y: number; w: number; h: number; color: string; text: string; fontSize?: number; textColor?: string }) { + return ( + + + + {text} + + + ); +} diff --git a/web/src/game/art/scenes/media.tsx b/web/src/game/art/scenes/media.tsx new file mode 100644 index 0000000..3160513 --- /dev/null +++ b/web/src/game/art/scenes/media.tsx @@ -0,0 +1,255 @@ +import { Avatar, avatarFromSeed } from "../Avatar.tsx"; +import { CROWD, SKIN, SUIT } from "../palette.ts"; +import { Person } from "../Person.tsx"; +import { H, SceneSvg, W } from "./kit.tsx"; +import type { SceneProps } from "./ground.tsx"; + +const PRESS_TEXT: Record = { policy: "政見發表記者會", expose: "揭弊記者會", rebuttal: "澄清記者會" }; +/** 麥克風上的台標都是虛構的 */ +const MIC = [ + ["#c4161c", "TY"], + ["#1d5fa8", "快報"], + ["#e8a317", "新聞"], + ["#2f7d4f", "台"], + ["#6c3d91", "NEWS"], +] as const; + +/** 記者會:背板、講台、一排麥克風、記者與閃光燈;variant = policy / expose / rebuttal */ +export function PressScene({ id, color, number, variant = "policy" }: SceneProps) { + return ( + + + + + {Array.from({ length: 5 }, (_, r) => + Array.from({ length: 6 }, (_, c) => ( + + {number}號 + + )), + )} + + + + {PRESS_TEXT[variant] ?? "記者會"} + + {variant === "expose" && ( + + + {Array.from({ length: 6 }, (_, i) => ( + + ))} + + + )} + + + + {MIC.map(([c, t], i) => ( + + + + + {t} + + + + ))} + + {[60, 140, 500, 580].map((x, i) => ( + + 320} female={i % 2 === 1} /> + 320 ? -26 : 26)} 272)`}> + + + + + + + ))} + + ); +} + +/** 政論節目:攝影棚、長桌、主持人(虛構)、背後螢幕 */ +export function TalkShowScene({ id, color, number, variant }: SceneProps) { + const host = avatarFromSeed("talkshow-host", { female: false, glasses: true, hair: "side", outfit: "suit" }); + const guest = avatarFromSeed("talkshow-guest", { female: true, hair: "bob", outfit: "blouse" }); + const gaffe = variant === "gaffe"; + return ( + + + + {[0, 1, 2].map((i) => ( + + + + + ))} + + {number}號 專訪 + + + 桃園大未來 + + + 選戰觀察 + + + + + + LIVE + + + + + + + + + + + + + {gaffe && ( + + + + 失言了!網路炸鍋 + + + )} + + ); +} + +/** 廣告:客廳電視(tv)、手機社群(online)、網路小額募款(donate) */ +export function AdScene({ id, color, number, variant = "tv" }: SceneProps) { + if (variant === "tv") { + return ( + + + + + + + + {number} + + + 桃園向前行 + + + 投 {number} 號 改變看得見 + + + + + + + ); + } + return ( + + + + + + + + {number}號 官方帳號 + + {variant === "donate" ? ( + + + 小額捐款 一起凍蒜 + + + + {[0, 1, 2, 3].map((i) => ( + + + + + + +{[100, 500, 200, 1000][i]} + + + ))} + + ) : ( + + + + + {number} + + + 年輕人 + + + 回家投票 + + {[0, 1, 2].map((i) => ( + + + + + + ))} + + )} + + {["👍", "❤️", "🔥", "👏"].map((e, i) => ( + + {e} + + ))} + + ); +} + +/** 電話中心:內參民調、電話催票、招募義工、找幕僚(variant = poll / phone / volunteers / hire) */ +export function CallCenterScene({ id, color, number, variant = "poll" }: SceneProps) { + const title = { poll: "內參民調中心", phone: "電話催票", volunteers: "義工招募中", hire: "競選總部" }[variant] ?? "競選總部"; + return ( + + + + + {variant === "poll" ? ( + + {[0.42, 0.35, 0.08, 0.05].map((v, i) => ( + + ))} + + ) : ( + + {title} + + )} + + + {number}號 {variant === "volunteers" ? "需要你" : "加油"} + + {[0, 1, 2].map((row) => + [0, 1, 2, 3].map((col) => { + const x = 90 + col * 150; + const y = 200 + row * 62; + const spec = avatarFromSeed(`callcenter-${row}-${col}`); + return ( + + + + + {variant !== "volunteers" && } + + + + ); + }), + )} + + ); +} diff --git a/web/src/game/audio/engine.ts b/web/src/game/audio/engine.ts new file mode 100644 index 0000000..b60c337 --- /dev/null +++ b/web/src/game/audio/engine.ts @@ -0,0 +1,88 @@ +/** + * 共用的 Web Audio 環境:音效與音樂都走這裡。 + * 瀏覽器規定要等玩家第一次點擊或按鍵之後才能出聲,unlock() 會在那時候被呼叫。 + */ +let ctx: AudioContext | null = null; +const buffers = new Map>(); +const unlockers = new Set<() => void>(); +let unlocked = false; + +export function audioContext(): AudioContext | null { + try { + ctx ??= new AudioContext(); + if (ctx.state === "suspended" && unlocked) void ctx.resume(); + return ctx; + } catch { + return null; + } +} + +export const isUnlocked = () => unlocked; + +/** 第一次互動之後要做的事(例如開始播首頁音樂) */ +export function onUnlock(fn: () => void): () => void { + if (unlocked) { + fn(); + return () => {}; + } + unlockers.add(fn); + return () => unlockers.delete(fn); +} + +function unlock() { + if (unlocked) return; + unlocked = true; + const a = audioContext(); + if (a?.state === "suspended") void a.resume(); + unlockers.forEach((fn) => fn()); + unlockers.clear(); + removeEventListener("pointerdown", unlock); + removeEventListener("keydown", unlock); +} +if (typeof window !== "undefined") { + addEventListener("pointerdown", unlock); + addEventListener("keydown", unlock); +} + +/** 支援 OGG 的瀏覽器用 OGG(迴圈比較無縫),其他(Safari)用 MP3 */ +const ext = (() => { + try { + return typeof Audio !== "undefined" && new Audio().canPlayType('audio/ogg; codecs="vorbis"') ? "ogg" : "mp3"; + } catch { + return "mp3"; + } +})(); +/** 只有 MP3 的檔案(素材本身就是 MP3) */ +const MP3_ONLY = new Set([ + "music/news-intro", + "music/victory-triumphant", + "sfx/applause", + "sfx/channel-switch", + "sfx/crowd-cheer-fireworks", + "sfx/crowd-rally", + "sfx/drumroll", + "sfx/firecrackers", + "sfx/paper-crumple", + "sfx/paper-rip", + "sfx/paper-rustle-1", + "sfx/paper-rustle-2", + "sfx/tv-static", + "sfx/tv-static-loop", +]); + +/** 讀取並解碼音檔(快取);失敗回傳 null,呼叫的人改用合成音 */ +export function loadBuffer(name: string): Promise { + let p = buffers.get(name); + if (!p) { + const a = audioContext(); + const file = `/assets/${name}.${MP3_ONLY.has(name) ? "mp3" : ext}`; + p = a + ? fetch(file) + .then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(file)))) + .then((b) => a.decodeAudioData(b)) + .catch(() => null) + : Promise.resolve(null); + buffers.set(name, p); + } + return p; +} diff --git a/web/src/game/audio/music.ts b/web/src/game/audio/music.ts new file mode 100644 index 0000000..609e051 --- /dev/null +++ b/web/src/game/audio/music.ts @@ -0,0 +1,64 @@ +import { audioContext, isUnlocked, loadBuffer, onUnlock } from "./engine.ts"; +import { getSettings, subscribeSettings } from "./settings.ts"; + +/** + * 背景音樂:同時只放一首,換歌時交叉淡入淡出。音量刻意壓低,不蓋過音效。 + * 素材都是 CC0(web/public/assets/LICENSES.md)。 + */ +export type Track = "theme-march" | "planning-loop" | "election-night-tension" | "party-disco-loop" | "news-bed"; + +const VOLUME: Record = { + "theme-march": 0.32, + "planning-loop": 0.22, + "election-night-tension": 0.3, + "party-disco-loop": 0.3, + "news-bed": 0.18, +}; +const FADE = 0.8; + +let wanted: Track | null = null; +let playing: { track: Track; src: AudioBufferSourceNode; gain: GainNode } | null = null; +let token = 0; + +function stopCurrent(a: AudioContext) { + if (!playing) return; + const { src, gain } = playing; + gain.gain.cancelScheduledValues(a.currentTime); + gain.gain.setValueAtTime(gain.gain.value, a.currentTime); + gain.gain.linearRampToValueAtTime(0.0001, a.currentTime + FADE); + src.stop(a.currentTime + FADE + 0.05); + playing = null; +} + +async function apply() { + const a = audioContext(); + if (!a || !isUnlocked()) return; + const track = getSettings().music ? wanted : null; + if (playing?.track === track) return; + const my = ++token; + stopCurrent(a); + if (!track) return; + const buffer = await loadBuffer(`music/${track}`); + if (!buffer || my !== token) return; + const src = a.createBufferSource(); + src.buffer = buffer; + src.loop = true; + const gain = a.createGain(); + gain.gain.setValueAtTime(0.0001, a.currentTime); + gain.gain.linearRampToValueAtTime(VOLUME[track], a.currentTime + FADE); + src.connect(gain).connect(a.destination); + src.start(); + playing = { track, src, gain }; +} + +/** 現在想放的背景音樂(小遊戲的節奏關卡先停音樂,玩完再換回來) */ +export const currentMusic = (): Track | null => wanted; + +/** 換背景音樂(null 是停掉);還沒互動過就等第一次點擊再開始 */ +export function setMusic(track: Track | null): void { + wanted = track; + if (isUnlocked()) void apply(); +} + +onUnlock(() => void apply()); +subscribeSettings(() => void apply()); diff --git a/web/src/game/audio/settings.ts b/web/src/game/audio/settings.ts new file mode 100644 index 0000000..5be7cbe --- /dev/null +++ b/web/src/game/audio/settings.ts @@ -0,0 +1,61 @@ +import { useSyncExternalStore } from "react"; + +/** 玩家偏好:音效、背景音樂、主播語音、全遊戲的頭像畫風。存在瀏覽器裡,讀寫失敗(私密模式)就用預設值 */ +export interface Settings { + sound: boolean; + /** 背景音樂 */ + music: boolean; + voice: boolean; + /** 畫面震動(被大幅拉票、爆分時);容易頭暈的人可以關掉 */ + shake: boolean; + /** 全遊戲的頭像畫風(comic 漫畫、chibi Q 版大頭、pixel 復刻像素、sticker 平面貼紙;docs/24);自創角色可以各自選 */ + avatarStyle: string; +} + +const KEY = "tongsuan.settings"; +const DEFAULTS: Settings = { sound: true, music: true, voice: true, shake: true, avatarStyle: "comic" }; +const AVATAR_STYLES = ["comic", "chibi", "pixel", "sticker"]; +const listeners = new Set<() => void>(); + +function load(): Settings { + try { + const raw = localStorage.getItem(KEY); + const merged: Settings = raw ? { ...DEFAULTS, ...(JSON.parse(raw) as Partial) } : DEFAULTS; + return AVATAR_STYLES.includes(merged.avatarStyle) ? merged : { ...merged, avatarStyle: DEFAULTS.avatarStyle }; + } catch { + return DEFAULTS; + } +} + +let current = load(); + +export function getSettings(): Settings { + return current; +} + +export function updateSettings(patch: Partial): void { + current = { ...current, ...patch }; + try { + localStorage.setItem(KEY, JSON.stringify(current)); + } catch { + // 存不了就只在這次有效 + } + listeners.forEach((l) => l()); +} + +export function useSettings(): Settings { + return useSyncExternalStore( + (l) => { + listeners.add(l); + return () => listeners.delete(l); + }, + getSettings, + getSettings, + ); +} + +/** 設定改變時通知(非 React 的模組用,例如背景音樂) */ +export function subscribeSettings(fn: () => void): () => void { + listeners.add(fn); + return () => listeners.delete(fn); +} diff --git a/web/src/game/audio/sfx.ts b/web/src/game/audio/sfx.ts new file mode 100644 index 0000000..05649c7 --- /dev/null +++ b/web/src/game/audio/sfx.ts @@ -0,0 +1,191 @@ +import { audioContext, loadBuffer, onUnlock } from "./engine.ts"; +import { getSettings } from "./settings.ts"; + +/** + * 音效:用 CC0 音檔(web/public/assets/sfx,出處見 LICENSES.md); + * 音檔讀不到時退回 Web Audio 即時合成的版本。只在玩家互動之後播放(瀏覽器的自動播放規則)。 + */ +function audio(): AudioContext | null { + return getSettings().sound ? audioContext() : null; +} + +/** 播一個音檔;names 有好幾個時隨機挑一個,讓重複的動作聽起來不單調 */ +function play(names: string | readonly string[], volume = 0.6, fallback?: (a: AudioContext) => void, rate = 1) { + const a = audio(); + if (!a) return; + const list = typeof names === "string" ? [names] : names; + const name = list[Math.floor(Math.random() * list.length)]!; + void loadBuffer(name).then((buffer) => { + if (!buffer) { + fallback?.(a); + return; + } + const src = a.createBufferSource(); + src.buffer = buffer; + src.playbackRate.value = rate; + const g = a.createGain(); + g.gain.value = volume; + src.connect(g).connect(a.destination); + src.start(); + }); +} + +// 常用的音效先讀進來,第一次播放才不會慢半拍 +onUnlock(() => { + ["sfx/ui-click", "sfx/card-deal-1", "sfx/card-deal-2", "sfx/card-place", "sfx/stamp-thump", "sfx/paper-rustle-1", "sfx/channel-switch", "sfx/news-three-tone"].forEach((n) => void loadBuffer(n)); +}); + +function tone(a: AudioContext, freq: number, start: number, dur: number, type: OscillatorType = "sine", gain = 0.12, endFreq?: number) { + const osc = a.createOscillator(); + const g = a.createGain(); + osc.type = type; + osc.frequency.setValueAtTime(freq, a.currentTime + start); + if (endFreq) osc.frequency.exponentialRampToValueAtTime(endFreq, a.currentTime + start + dur); + g.gain.setValueAtTime(0.0001, a.currentTime + start); + g.gain.exponentialRampToValueAtTime(gain, a.currentTime + start + 0.01); + g.gain.exponentialRampToValueAtTime(0.0001, a.currentTime + start + dur); + osc.connect(g).connect(a.destination); + osc.start(a.currentTime + start); + osc.stop(a.currentTime + start + dur + 0.05); +} + +function noise(a: AudioContext, start: number, dur: number, gain = 0.08, band = 1800, q = 0.8) { + const buffer = a.createBuffer(1, Math.ceil(a.sampleRate * dur), a.sampleRate); + const data = buffer.getChannelData(0); + for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1; + const src = a.createBufferSource(); + src.buffer = buffer; + const filter = a.createBiquadFilter(); + filter.type = "bandpass"; + filter.frequency.value = band; + filter.Q.value = q; + const g = a.createGain(); + g.gain.setValueAtTime(0.0001, a.currentTime + start); + g.gain.exponentialRampToValueAtTime(gain, a.currentTime + start + dur * 0.3); + g.gain.exponentialRampToValueAtTime(0.0001, a.currentTime + start + dur); + src.connect(filter).connect(g).connect(a.destination); + src.start(a.currentTime + start); +} + +export const sfx = { + /** 蓋章:低沉的一聲 */ + stamp() { + play("sfx/stamp-thump", 0.9, (a) => { + tone(a, 140, 0, 0.18, "sine", 0.35, 45); + noise(a, 0, 0.06, 0.12, 900, 0.6); + }); + }, + /** 錢進來 */ + coin() { + play("sfx/coins-small", 0.6, (a) => { + tone(a, 988, 0, 0.09, "triangle", 0.1); + tone(a, 1319, 0.08, 0.22, "triangle", 0.1); + }); + }, + /** 新聞片頭 */ + jingle() { + play("sfx/news-three-tone", 0.55, (a) => { + [523, 659, 784].forEach((f, i) => tone(a, f, i * 0.16, 0.3, "triangle", 0.09)); + }); + }, + /** 群眾歡呼 */ + cheer() { + play("sfx/crowd-rally", 0.45, (a) => { + noise(a, 0, 1.4, 0.06, 1400, 0.5); + noise(a, 0.2, 1.1, 0.04, 2600, 0.7); + }); + }, + /** 鞭炮 */ + firecracker() { + play("sfx/firecrackers", 0.5, (a) => { + for (let i = 0; i < 18; i++) noise(a, i * 0.07 + Math.random() * 0.04, 0.05, 0.14, 2500 + Math.random() * 2000, 1.5); + }); + }, + /** 快訊 */ + alert() { + play("sfx/bell-ding", 0.5, (a) => { + tone(a, 880, 0, 0.12, "square", 0.05); + tone(a, 660, 0.18, 0.25, "square", 0.05); + }); + }, + /** 翻報紙 */ + paper() { + play(["sfx/paper-rustle-1", "sfx/paper-rustle-2"], 0.5, (a) => noise(a, 0, 0.25, 0.05, 3500, 0.4)); + }, + /** 發牌、抽牌 */ + card() { + play(["sfx/card-deal-1", "sfx/card-deal-2"], 0.5); + }, + /** 把牌放到桌上 */ + place() { + play("sfx/card-place", 0.6); + }, + /** 翻牌 */ + flip() { + play("sfx/card-flip", 0.55); + }, + /** 洗牌(新的一週發新手牌) */ + shuffle() { + play("sfx/card-shuffle", 0.45); + }, + /** 擲骰(看運氣的選項) */ + dice() { + play(["sfx/dice-roll-1", "sfx/dice-roll-2"], 0.55); + }, + /** 轉台 */ + channel() { + play("sfx/channel-switch", 0.4); + }, + /** 好結果 */ + good() { + play(["sfx/chime-positive-1", "sfx/chime-positive-2"], 0.5); + }, + /** 壞結果 */ + bad() { + play("sfx/buzz-negative", 0.4); + }, + /** 一般按鈕 */ + click() { + play("sfx/ui-click", 0.35); + }, + /** 掌聲 */ + applause() { + play("sfx/applause", 0.5); + }, + /** 開票前的鼓聲 */ + drumroll() { + play("sfx/drumroll", 0.5); + }, + /** 鑼聲(週轉場) */ + gong() { + play("sfx/gong-bright", 0.35); + }, + /** 觀眾驚呼(醜聞) */ + ooh() { + play("sfx/crowd-ooh", 0.45); + }, + /** 組合拳、連續加成:level 越高音越高(選戰卡牌的爆分) */ + combo(level: number) { + const rate = 1 + 0.12 * Math.min(8, Math.max(0, level)); + play( + "sfx/chime-positive-1", + 0.45, + (a) => { + tone(a, 660 * rate, 0, 0.14, "triangle", 0.09); + tone(a, 990 * rate, 0.06, 0.2, "triangle", 0.07); + }, + rate, + ); + }, + /** 插旗、翻轉 */ + flag() { + play("sfx/bell-ding", 0.55, (a) => { + tone(a, 784, 0, 0.12, "triangle", 0.1); + tone(a, 1175, 0.1, 0.3, "triangle", 0.1); + }, 1.15); + }, + /** 棋子跳一下 */ + hop() { + play(["sfx/piece-hop-1", "sfx/piece-hop-2"], 0.45); + }, +}; diff --git a/web/src/game/board3d/BoardStage.tsx b/web/src/game/board3d/BoardStage.tsx new file mode 100644 index 0000000..5c7f00a --- /dev/null +++ b/web/src/game/board3d/BoardStage.tsx @@ -0,0 +1,209 @@ +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import type { StageGeometry } from "../stage/geometry.ts"; +import { MapStage, type FloatText, type StageMarker, type StageToken } from "../stage/MapStage.tsx"; +import { BoardScene, LAND_H, webglAvailable, type PawnSpec } from "./scene.ts"; +import "./board3d.css"; + +interface Props { + geometry: StageGeometry; + /** 區代碼 → 底色 */ + townFills: ReadonlyMap; + /** 村里代碼 → 底色(開票夜逐里上色);有值時蓋過區的底色 */ + villageFills?: ReadonlyMap; + selected?: string | null; + onSelect?: (townCode: string) => void; + highlight?: ReadonlySet; + offices?: ReadonlySet; + markers?: readonly StageMarker[]; + tokens?: readonly StageToken[]; + floats?: readonly FloatText[]; + showLandmarks?: boolean; + ariaLabel?: string; + /** 出牌時選到要打在某一區的牌:游標變成準星 */ + highlightAll?: boolean; + /** 各區成年人口:小鎮裝飾依密度長出店面、住家或樹 */ + townAdults?: ReadonlyMap | null; + /** 播放時要在盤面上演出的行動(同一個 key 只演一次) */ + effects?: readonly { key: string; townCode: string; actionId: string }[]; +} + +const MAX_ICONS = 4; +const NO_SET: ReadonlySet = new Set(); +const NO_EFFECTS: readonly { key: string; townCode: string; actionId: string }[] = []; +/** 同一區有好幾個棋子時,左右排開的間距(舞台座標) */ +const PAWN_GAP = 20; + +/** + * 立體桌遊盤(docs/17):和平面地圖 MapStage 一樣的 props,可以直接替換。 + * 地形、棋子用 three.js;區名、行程圖示、浮字用 HTML 疊在上面,字才清楚。 + * 瀏覽器不支援 WebGL 時退回平面地圖。 + */ +export function BoardStage(props: Props) { + const [webgl] = useState(webglAvailable); + return webgl ? : ; +} + +function Board3D({ + geometry: g, + townFills, + villageFills, + selected = null, + onSelect, + highlight = NO_SET, + offices = NO_SET, + markers = [], + tokens = [], + floats = [], + showLandmarks = true, + ariaLabel = "地圖", + highlightAll = false, + townAdults = null, + effects = NO_EFFECTS, +}: Props) { + const canvasRef = useRef(null); + const overlayRef = useRef(null); + const [scene, setScene] = useState(null); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + const townAdultsRef = useRef(townAdults); + townAdultsRef.current = townAdults; + const towns = useMemo(() => new Map(g.towns.map((t) => [t.code, t])), [g]); + + // 換地圖才重建整個場景;其他 props 只更新狀態 + useEffect(() => { + const canvas = canvasRef.current; + const overlay = overlayRef.current; + if (!canvas || !overlay) return; + const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; + const s = new BoardScene(canvas, overlay, g, { reduceMotion, townAdults: townAdultsRef.current, onSelect: (code) => onSelectRef.current?.(code) }); + const ro = new ResizeObserver(() => s.resize()); + ro.observe(canvas); + s.resize(); + // 主題切換:系統深淺色,或設定裡的 data-theme + const media = matchMedia("(prefers-color-scheme: dark)"); + const retheme = () => requestAnimationFrame(() => s.applyTheme()); + media.addEventListener("change", retheme); + const mo = new MutationObserver(retheme); + mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "class", "style"] }); + setScene(s); + return () => { + ro.disconnect(); + mo.disconnect(); + media.removeEventListener("change", retheme); + setScene(null); + s.dispose(); + }; + }, [g]); + + useEffect(() => { + scene?.setFills( + (code, town) => villageFills?.get(code) ?? townFills.get(town) ?? "var(--neutral)", + (code) => townFills.get(code), + ); + }, [scene, townFills, villageFills]); + useEffect(() => scene?.setSelected(selected), [scene, selected]); + useEffect(() => scene?.setHighlight(highlight), [scene, highlight]); + useEffect(() => scene?.setClickable(!!onSelect), [scene, onSelect]); + + // 棋子:同一區的棋子左右排開 + const pawns = useMemo(() => { + const byTown = new Map(); + for (const t of tokens) byTown.set(t.townCode, [...(byTown.get(t.townCode) ?? []), t]); + return tokens.flatMap((tok) => { + const town = towns.get(tok.townCode); + if (!town) return []; + const group = byTown.get(tok.townCode)!; + const i = group.indexOf(tok); + // 棋子站在區名和行程圖示的下方,不擋字 + return [{ key: tok.key, x: town.cx + (i - (group.length - 1) / 2) * PAWN_GAP, y: town.cy + 46, color: tok.color ?? "var(--ink)" }]; + }); + }, [tokens, towns]); + useEffect(() => scene?.setPawns(pawns), [scene, pawns]); + useEffect(() => { + for (const e of effects) scene?.playEffect(e.key, e.townCode, e.actionId); + }, [scene, effects]); + + // 每次重繪後,讓場景重新抓要跟著地圖走的 HTML + useLayoutEffect(() => scene?.refreshAnchors()); + + const markersByTown = useMemo(() => { + const map = new Map(); + for (const m of markers) map.set(m.townCode, [...(map.get(m.townCode) ?? []), m]); + return map; + }, [markers]); + const anchor = (x: number, y: number, h: number) => `${x},${y},${h}`; + + return ( +
+ +
+ {g.seas.map((s) => ( +
+ {s.name} +
+ ))} + {g.context + .filter((c) => c.rings.length > 0 && c.cx > 20 && c.cx < g.width - 20 && c.cy > 20 && c.cy < g.height - 20) + .map((c) => ( +
+ {c.name} +
+ ))} + {showLandmarks && + g.landmarks.map((l) => { + const Icon = l.icon; + return ( +
+ + + +
+ ); + })} + {[...markersByTown].map(([code, list]) => { + const t = towns.get(code); + if (!t) return null; + return ( +
+ + {list.slice(0, MAX_ICONS).map((m) => { + const Icon = m.icon; + return ( + + + + ); + })} + {list.length > MAX_ICONS && +{list.length - MAX_ICONS}} + +
+ ); + })} + {tokens.map((tok) => ( +
+ + {tok.node} + +
+ ))} + {g.towns.map((t) => ( +
+ + {offices.has(t.code) ? "⚑" : ""} + {t.name.replace(/區$/, "")} + +
+ ))} + {floats.map((f) => { + const t = towns.get(f.townCode); + if (!t) return null; + return ( +
+ {f.text} +
+ ); + })} +
+
+ ); +} diff --git a/web/src/game/board3d/board3d.css b/web/src/game/board3d/board3d.css new file mode 100644 index 0000000..40bc9b0 --- /dev/null +++ b/web/src/game/board3d/board3d.css @@ -0,0 +1,60 @@ +/* 立體桌遊盤:canvas 畫地形,上面一層 HTML 放區名、行程圖示、棋子徽章、浮字 */ +.b3 { position: relative; width: 100%; aspect-ratio: 760 / 640; max-width: 100%; container-type: inline-size; } +.b3-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; } +.b3-overlay { position: absolute; inset: 0; pointer-events: none; overflow: hidden; } +/* 位置由 BoardScene 每幀寫進 transform;子元素再依自己的錨點對齊 */ +.b3-anchor { position: absolute; left: 0; top: 0; will-change: transform; transform-origin: 0 0; } +.b3-anchor > * { position: absolute; left: 0; top: 0; white-space: nowrap; transform: translate(-50%, -50%); } + +.b3-label { + transform: translate(-50%, calc(-100% - 4px)); + font-size: 13px; font-weight: 700; color: var(--ink); letter-spacing: 0.02em; + text-shadow: 0 0 2px var(--paper), 0 0 2px var(--paper), 0 0 3px var(--paper), 1px 1px 0 var(--paper), -1px -1px 0 var(--paper); +} +.b3-label.is-selected { font-size: 15px; } +.b3-sea { font-family: var(--font-serif); font-size: 17px; font-weight: 700; letter-spacing: 0.6em; color: var(--sea-line); } +.b3-neighbor { font-size: 12px; color: var(--muted); letter-spacing: 0.3em; text-shadow: 0 0 2px var(--land-neighbor); } +.b3-landmark { + display: grid; place-items: center; width: 17px; height: 17px; border-radius: 50%; + transform: translate(-50%, -100%); + background: var(--paper); border: 1px solid var(--landmark-line); color: var(--landmark-ink); + box-shadow: 0 1px 2px rgb(0 0 0 / 0.25); +} + +.b3-markers { display: flex; gap: 2px; align-items: center; transform: translate(-50%, 6px); } +.b3-marker { + display: grid; place-items: center; width: 19px; height: 19px; border-radius: 50%; + border: 1.5px solid var(--paper); box-shadow: 0 1px 3px rgb(0 0 0 / 0.35); +} +.b3-marker.is-fresh { animation: b3-pop 260ms var(--ease-out) both; } +.b3-more { font-size: 11px; font-weight: 700; color: var(--ink); text-shadow: 0 0 2px var(--paper), 0 0 2px var(--paper); } +@keyframes b3-pop { from { opacity: 0; transform: scale(0.6); } } + +/* 棋子頭上的徽章 */ +.b3-token { transform: translate(-50%, -100%); filter: drop-shadow(0 2px 3px rgb(0 0 0 / 0.35)); } + +/* 浮字:translate 屬性和定位用的 transform 分開,動畫才不會互相蓋掉 */ +.b3-float { + transform: translate(-50%, calc(-100% - 22px)); + font-size: 15px; font-weight: 900; + text-shadow: 0 0 2px var(--paper), 0 0 2px var(--paper), 0 0 4px var(--paper); + animation: b3-float-up 1000ms var(--ease-out) both; +} +.b3-float.tone-good { color: var(--good); } +.b3-float.tone-bad { color: var(--stamp); } +.b3-float.tone-neutral { color: var(--ink); } +@keyframes b3-float-up { from { opacity: 0; translate: 0 8px; } 30% { opacity: 1; } to { opacity: 1; translate: 0 -6px; } } + +/* 手機寬度:地標和海名先收起來,區名才看得清楚 */ +@container (max-width: 520px) { + .b3-landmark, .b3-sea { display: none; } +} + +@media (prefers-reduced-motion: reduce) { + .b3-marker.is-fresh, .b3-float { animation: b3-fade 200ms ease-out both; } +} +@keyframes b3-fade { from { opacity: 0; } } + +/* #/board 開發預覽 */ + +.b3.is-targeting .b3-canvas { cursor: crosshair; } diff --git a/web/src/game/board3d/colors.ts b/web/src/game/board3d/colors.ts new file mode 100644 index 0000000..d1b6c83 --- /dev/null +++ b/web/src/game/board3d/colors.ts @@ -0,0 +1,94 @@ +/** + * CSS 顏色 → 畫布與 three.js 能用的 rgb。 + * 遊戲的顏色多半是 var(--slot-a)、color-mix(...),畫布和 three.js 都看不懂, + * 所以交給瀏覽器算出實際顏色,再轉成 rgb()。同一個字串只算一次(換主題時清空)。 + */ +export interface Rgb { + r: number; + g: number; + b: number; + a: number; +} + +export class ColorResolver { + private readonly cache = new Map(); + private readonly probe: HTMLSpanElement; + private readonly pixel: CanvasRenderingContext2D | null; + + constructor(host: HTMLElement) { + this.probe = document.createElement("span"); + this.probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none"; + this.probe.setAttribute("aria-hidden", "true"); + host.appendChild(this.probe); + const c = document.createElement("canvas"); + c.width = c.height = 1; + this.pixel = c.getContext("2d", { willReadFrequently: true }); + } + + /** 主題換了,舊的顏色都不算數 */ + clear(): void { + this.cache.clear(); + } + + dispose(): void { + this.probe.remove(); + } + + rgb(value: string): Rgb { + const hit = this.cache.get(value); + if (hit) return hit; + this.probe.style.color = ""; + this.probe.style.color = value; + const computed = getComputedStyle(this.probe).color; + const out = parseComputed(computed) ?? this.viaCanvas(computed) ?? { r: 128, g: 128, b: 128, a: 1 }; + this.cache.set(value, out); + return out; + } + + /** 畫布用的字串 */ + css(value: string): string { + const { r, g, b, a } = this.rgb(value); + return a >= 1 ? `rgb(${r} ${g} ${b})` : `rgb(${r} ${g} ${b} / ${a})`; + } + + /** three.js 用的 0xRRGGBB */ + hex(value: string): number { + const { r, g, b } = this.rgb(value); + return (r << 16) | (g << 8) | b; + } + + private viaCanvas(computed: string): Rgb | null { + const ctx = this.pixel; + if (!ctx) return null; + ctx.clearRect(0, 0, 1, 1); + ctx.fillStyle = "#000"; + ctx.fillStyle = computed; + ctx.fillRect(0, 0, 1, 1); + const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data; + return { r: r!, g: g!, b: b!, a: a! / 255 }; + } +} + +/** 解析 getComputedStyle 回傳的 rgb()/rgba()/color(srgb …) */ +export function parseComputed(text: string): Rgb | null { + const rgb = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)$/.exec(text); + if (rgb) return { r: Math.round(+rgb[1]!), g: Math.round(+rgb[2]!), b: Math.round(+rgb[3]!), a: alpha(rgb[4]) }; + const srgb = /^color\(srgb\s+([-\d.e]+)\s+([-\d.e]+)\s+([-\d.e]+)(?:\s*\/\s*([\d.]+%?))?\s*\)$/.exec(text); + if (srgb) { + const c = (v: string) => Math.round(Math.min(1, Math.max(0, +v)) * 255); + return { r: c(srgb[1]!), g: c(srgb[2]!), b: c(srgb[3]!), a: alpha(srgb[4]) }; + } + return null; +} + +function alpha(v: string | undefined): number { + if (v === undefined) return 1; + return v.endsWith("%") ? +v.slice(0, -1) / 100 : +v; +} + +/** 調暗(地形側面用) */ +export function shade({ r, g, b, a }: Rgb, k: number): Rgb { + return { r: Math.round(r * k), g: Math.round(g * k), b: Math.round(b * k), a }; +} + +export const toHex = ({ r, g, b }: Rgb): number => (r << 16) | (g << 8) | b; diff --git a/web/src/game/board3d/effects.ts b/web/src/game/board3d/effects.ts new file mode 100644 index 0000000..44350c8 --- /dev/null +++ b/web/src/game/board3d/effects.ts @@ -0,0 +1,260 @@ +import * as THREE from "three"; +import { GLTFLoader, type GLTF } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { clone as cloneSkinned } from "three/examples/jsm/utils/SkeletonUtils.js"; + +/** + * 每週播放時在桌遊盤上的演出:打出一張牌,那一區就跳出對應的小場面。 + * 造勢、拜票:一群 Q 版小人跳起來歡呼(加彩帶);募款:金幣往上飛;宣傳車:車子開過去; + * 插旗、發傳單:旗子插滿;媒體、網路:星星和愛心冒出來。模型都是 CC0(Kenney;web/public/assets/LICENSES.md)。 + */ + +const A = "/assets/3d/"; +type Kind = "crowd" | "coins" | "truck" | "flags" | "media"; + +const KIND_OF: Record = { + rally: "crowd", eve_rally: "crowd", concert: "crowd", night_market: "crowd", market_visit: "crowd", street_canvass: "crowd", + grassroots_walk: "crowd", street_interview: "crowd", temple_visit: "crowd", pilgrimage: "crowd", door_to_door: "crowd", + banquet: "crowd", weddings_funerals: "crowd", factory_visit: "crowd", church_visit: "crowd", homecoming: "crowd", forum: "crowd", + councilor_allies: "crowd", party_elder: "crowd", endorsement: "crowd", recruit_machine: "crowd", visit_associations: "crowd", kneel: "crowd", protest_government: "crowd", + fundraiser_dinner: "coins", small_donations: "coins", big_donor: "coins", party_fund: "coins", self_fund: "coins", vote_buying: "coins", eve_vote_buying: "coins", + sound_truck: "truck", eve_phone_bank: "media", + flags_billboards: "flags", print_flyers: "flags", open_office: "flags", recruit_volunteers: "flags", + tv_ad: "media", online_ad: "media", eve_online_ad: "media", short_video: "media", facebook_live: "media", line_groups: "media", + talk_show: "media", interview: "media", press_conference: "media", influencer_live: "media", radio_ad: "media", +}; +/** 造勢晚會、選前之夜加彩帶 */ +const CONFETTI = new Set(["rally", "eve_rally", "concert", "open_office"]); +const PALETTE = ["#d61f2c", "#ffd23f", "#1d4fa3", "#ffffff", "#0f8a4a", "#ff8a3d"]; +const FIGURE_H = 34; +const DURATION = 2600; + +interface Assets { + people: GLTF[]; + coin: THREE.Object3D; + star: THREE.Object3D; + heart: THREE.Object3D; + flag: THREE.Object3D; + truck: THREE.Object3D; +} + +let cache: Promise | null = null; +function loadAssets(): Promise { + cache ??= (async () => { + const loader = new GLTFLoader(); + const load = (p: string) => loader.loadAsync(`${A}${p}.glb`); + try { + const [people, coin, star, heart, flag, truck] = await Promise.all([ + Promise.all(["character-female-b", "character-male-b", "character-female-d", "character-male-d", "character-female-f", "character-male-f"].map((n) => load(`characters/${n}`))), + load("props/coin-gold"), + load("props/star"), + load("props/heart"), + load("props/flag"), + load("vehicles/truck"), + ]); + return { people, coin: coin.scene, star: star.scene, heart: heart.scene, flag: flag.scene, truck: truck.scene }; + } catch { + return null; + } + })(); + return cache; +} + +/** 縮放到指定高度(或寬度)、底部貼齊 y=0,包一層 group 方便擺放 */ +function fit(obj: THREE.Object3D, size: number, by: "height" | "width" = "height"): THREE.Group { + const box = new THREE.Box3().setFromObject(obj); + const dim = box.getSize(new THREE.Vector3()); + obj.scale.multiplyScalar(size / (by === "height" ? dim.y : Math.max(dim.x, dim.z))); + const after = new THREE.Box3().setFromObject(obj); + obj.position.y -= after.min.y; + const g = new THREE.Group(); + g.add(obj); + return g; +} + +interface Running { + group: THREE.Group; + start: number; + mixers: THREE.AnimationMixer[]; + tick: (t: number, dt: number) => void; +} + +export class EffectPlayer { + private running: Running[] = []; + private played = new Set(); + private assets: Assets | null = null; + + constructor( + private readonly scene: THREE.Scene, + private readonly shadows: boolean, + ) { + void loadAssets().then((a) => (this.assets = a)); + } + + get active(): boolean { + return this.running.length > 0; + } + + /** 在某一點演出某個行動;同一個 key 只演一次 */ + play(key: string, at: THREE.Vector3, actionId: string): void { + if (this.played.has(key) || !this.assets) return; + this.played.add(key); + const kind = KIND_OF[actionId] ?? "media"; + const group = new THREE.Group(); + group.position.copy(at); + this.scene.add(group); + const run: Running = { group, start: performance.now(), mixers: [], tick: () => {} }; + const a = this.assets; + const pop = (obj: THREE.Object3D, t: number, delay: number) => { + // 彈出來、待一下、縮回去 + const local = Math.max(0, t - delay); + const s = local < 0.15 ? local / 0.15 : t > 0.85 ? Math.max(0, (1 - t) / 0.15) : 1; + obj.scale.setScalar(Math.max(0.001, s)); + }; + const shadowed = (o: THREE.Object3D) => o.traverse((m) => ((m as THREE.Mesh).isMesh ? ((m.castShadow = this.shadows), (m.raycast = () => {})) : null)); + + if (kind === "crowd") { + const n = CONFETTI.has(actionId) ? 7 : 5; + const people = Array.from({ length: n }, (_, i) => { + const src = a.people[i % a.people.length]!; + const p = fit(cloneSkinned(src.scene), FIGURE_H * (0.9 + (i % 3) * 0.06)); + const ang = (i / n) * Math.PI * 2 + 0.4; + p.position.set(Math.cos(ang) * 30, 0, Math.sin(ang) * 22); + p.rotation.y = Math.atan2(-p.position.x, -p.position.z) + Math.PI; + shadowed(p); + group.add(p); + const mixer = new THREE.AnimationMixer(p.children[0]!); + const clip = THREE.AnimationClip.findByName(src.animations, i % 2 ? "jump" : "emote-yes") ?? src.animations[0]; + if (clip) { + const act = mixer.clipAction(clip); + act.time = (i * 0.23) % clip.duration; + act.play(); + } + run.mixers.push(mixer); + return p; + }); + const bits = CONFETTI.has(actionId) ? this.confetti(group) : null; + run.tick = (t, dt) => { + people.forEach((p, i) => pop(p, t, i * 0.03)); + bits?.(t, dt); + }; + } else if (kind === "coins") { + const coins = Array.from({ length: 6 }, (_, i) => { + const c = fit(a.coin.clone(), 12); + c.position.set((i % 3) * 12 - 12, 0, Math.floor(i / 3) * 12 - 6); + shadowed(c); + group.add(c); + return c; + }); + run.tick = (t) => { + coins.forEach((c, i) => { + const local = Math.max(0, t - i * 0.06); + c.position.y = local * 70; + c.rotation.y = local * 14; + pop(c, t, i * 0.06); + }); + }; + } else if (kind === "truck") { + const truck = fit(a.truck.clone(), 34, "width"); + shadowed(truck); + group.add(truck); + run.tick = (t) => { + truck.position.x = -70 + t * 140; + truck.position.y = Math.abs(Math.sin(t * 40)) * 1.2; + truck.rotation.y = Math.PI / 2; + pop(truck, t, 0); + }; + } else if (kind === "flags") { + const flags = Array.from({ length: 6 }, (_, i) => { + const f = fit(a.flag.clone(), 26); + const ang = (i / 6) * Math.PI * 2; + f.position.set(Math.cos(ang) * 26, 0, Math.sin(ang) * 18); + f.rotation.y = -ang; + shadowed(f); + group.add(f); + return f; + }); + const bits = CONFETTI.has(actionId) ? this.confetti(group) : null; + run.tick = (t, dt) => { + flags.forEach((f, i) => { + pop(f, t, i * 0.05); + f.rotation.z = Math.sin(t * 20 + i) * 0.06; + }); + bits?.(t, dt); + }; + } else { + const items = Array.from({ length: 6 }, (_, i) => { + const o = fit((i % 2 ? a.heart : a.star).clone(), 11); + o.position.set(Math.cos(i) * 18, 0, Math.sin(i * 1.7) * 14); + group.add(o); + return o; + }); + run.tick = (t) => { + items.forEach((o, i) => { + const local = Math.max(0, t - i * 0.08); + o.position.y = 12 + local * 50; + o.rotation.y = local * 8; + pop(o, t, i * 0.08); + }); + }; + } + this.running.push(run); + } + + /** 彩帶:一團小紙片噴上去再落下 */ + private confetti(group: THREE.Group): (t: number, dt: number) => void { + const n = 90; + const mesh = new THREE.InstancedMesh(new THREE.PlaneGeometry(2.6, 1.6), new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, toneMapped: false }), n); + const color = new THREE.Color(); + const bits = Array.from({ length: n }, (_, i) => { + mesh.setColorAt(i, color.set(PALETTE[i % PALETTE.length]!)); + return { p: new THREE.Vector3(0, 20, 0), v: new THREE.Vector3((Math.random() - 0.5) * 70, 60 + Math.random() * 50, (Math.random() - 0.5) * 50), r: new THREE.Euler(), w: Math.random() * 10 }; + }); + mesh.raycast = () => {}; + group.add(mesh); + const dummy = new THREE.Object3D(); + return (_t, dt) => { + bits.forEach((b, i) => { + b.v.y -= 90 * dt; + b.v.multiplyScalar(0.985); + b.p.addScaledVector(b.v, dt); + b.r.x += b.w * dt; + b.r.y += b.w * 0.7 * dt; + dummy.position.copy(b.p); + dummy.rotation.copy(b.r); + dummy.scale.setScalar(b.p.y < 0 ? 0.001 : 1); + dummy.updateMatrix(); + mesh.setMatrixAt(i, dummy.matrix); + }); + mesh.instanceMatrix.needsUpdate = true; + }; + } + + /** 每一幀:推進動畫,演完的移除;回傳是否還有東西在動 */ + update(now: number, dt: number): boolean { + for (const r of [...this.running]) { + const t = (now - r.start) / DURATION; + if (t >= 1) { + this.scene.remove(r.group); + r.group.traverse((o) => { + const m = o as THREE.Mesh; + if (m.geometry && (o as THREE.InstancedMesh).isInstancedMesh) m.geometry.dispose(); + }); + this.running = this.running.filter((x) => x !== r); + continue; + } + for (const m of r.mixers) m.update(dt); + r.tick(t, dt); + } + return this.running.length > 0; + } + + /** 新的一週:之前演過的 key 可以重來 */ + reset(): void { + this.played.clear(); + } + + dispose(): void { + for (const r of this.running) this.scene.remove(r.group); + this.running = []; + } +} diff --git a/web/src/game/board3d/scene.ts b/web/src/game/board3d/scene.ts new file mode 100644 index 0000000..1d20244 --- /dev/null +++ b/web/src/game/board3d/scene.ts @@ -0,0 +1,686 @@ +import * as THREE from "three"; +import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { clone as cloneSkinned } from "three/examples/jsm/utils/SkeletonUtils.js"; +import { buildTownDecor } from "./town.ts"; +import { EffectPlayer } from "./effects.ts"; +import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; +import type { StageGeometry, StagePolygons } from "../stage/geometry.ts"; +import { ColorResolver, shade, toHex } from "./colors.ts"; +import { MapPainter, waveTexture, woodTexture } from "./textures.ts"; + +/** 地形的高度(舞台寬 760 時):夠立體、又不會擋住後面的區 */ +export const LAND_H = 9; +const NEIGHBOR_H = 2.5; +const FRAME_W = 26; +const FRAME_TOP = 5; +const FRAME_BOTTOM = -16; +const SELECT_LIFT = 4; +const HOVER_LIFT = 1.5; +const PAWN_H = 24; +/** 預設視角和垂直方向的夾角(弧度):約 36 度,像坐在桌邊看桌遊 */ +const TILT = 0.62; + +interface Region { + code: string; + mesh: THREE.Mesh; + lift: number; +} + +interface Pawn { + /** 棋子整組(底座+人偶);mesh 是底座,顏色是候選人的政黨色 */ + group: THREE.Group; + mesh: THREE.Mesh; + from: THREE.Vector3; + to: THREE.Vector3; + start: number; +} + +export interface PawnSpec { + key: string; + x: number; + y: number; + color: string; +} + +export interface BoardOptions { + reduceMotion: boolean; + /** 各區成年人口:決定小鎮裝飾是市區、郊區還是鄉下 */ + townAdults?: ReadonlyMap | null; + onSelect: (code: string) => void; +} + +const stageToWorld = (g: StageGeometry, x: number, y: number, h = 0) => new THREE.Vector3(x - g.width / 2, h, y - g.height / 2); + +/** 舞台座標的多邊形 → three.js 形狀(擠出後再轉成躺平,所以 y 要反過來) */ +function shapesOf(g: StageGeometry, polys: StagePolygons): THREE.Shape[] { + const v = ([x, y]: [number, number]) => new THREE.Vector2(x - g.width / 2, g.height / 2 - y); + return polys.map(([outer, ...holes]) => { + const shape = new THREE.Shape(outer!.map(v)); + shape.holes = holes.map((h) => new THREE.Path(h.map(v))); + return shape; + }); +} + +function extrude(g: StageGeometry, polys: StagePolygons, depth: number): THREE.ExtrudeGeometry { + const geo = new THREE.ExtrudeGeometry(shapesOf(g, polys), { depth, bevelEnabled: false, curveSegments: 1 }); + geo.rotateX(-Math.PI / 2); + return geo; +} + +function roundedRect(w: number, h: number, r: number, cx = 0, cy = 0): THREE.Shape { + const s = new THREE.Shape(); + const x = cx - w / 2; + const y = cy - h / 2; + s.moveTo(x + r, y); + s.lineTo(x + w - r, y); + s.quadraticCurveTo(x + w, y, x + w, y + r); + s.lineTo(x + w, y + h - r); + s.quadraticCurveTo(x + w, y + h, x + w - r, y + h); + s.lineTo(x + r, y + h); + s.quadraticCurveTo(x, y + h, x, y + h - r); + s.lineTo(x, y + r); + s.quadraticCurveTo(x, y, x + r, y); + return s; +} + +/** + * 棋子上的 Q 版小人(CC0,Kenney Mini Characters;web/public/assets/LICENSES.md)。 + * 只是不具名的棋子,不代表候選人的長相。所有棋盤共用一份模型,讀不到就只用傳統的兵。 + */ +const FIGURES = ["character-male-a", "character-female-a", "character-male-c", "character-female-c", "character-male-e", "character-female-e"]; +let figureCache: Promise | null = null; +function loadFigures(): Promise { + figureCache ??= Promise.all( + FIGURES.map( + (n) => + new Promise((resolve, reject) => + new GLTFLoader().load(`/assets/3d/characters/${n}.glb`, (g) => resolve(g.scene), undefined, reject), + ), + ), + ).catch(() => []); + return figureCache; +} +const FIGURE_H = 58; +/** 棋子的底座:矮圓柱 */ +const BASE_GEO = new THREE.CylinderGeometry(13, 14.5, 4, 32); +BASE_GEO.translate(0, 2, 0); + +/** 棋子:和桌遊的兵一樣的剖面,繞一圈 */ +function pawnGeometry(): THREE.LatheGeometry { + const k = PAWN_H / 3.2; + const profile = [ + [0, 0], [1.1, 0], [1.1, 0.3], [0.7, 0.5], [0.45, 1.6], [0.7, 1.9], [0.55, 2.1], [0.75, 2.5], [0.6, 2.95], [0.3, 3.15], [0, 3.2], + ].map(([x, y]) => new THREE.Vector2(x! * k, y! * k)); + return new THREE.LatheGeometry(profile, 28); +} + +/** + * 立體桌遊盤:木框、海、各區的地形塊、鄰近縣市、離島小框、棋子。 + * 只管 three.js 的部分;文字、圖示用 HTML 疊在上面(BoardStage),由這裡每幀換算位置。 + */ +export class BoardScene { + private readonly renderer: THREE.WebGLRenderer; + private readonly scene = new THREE.Scene(); + private readonly camera = new THREE.PerspectiveCamera(32, 1, 1, 6000); + private readonly controls: OrbitControls; + private readonly colors: ColorResolver; + private readonly painter: MapPainter; + private readonly regions: Region[] = []; + private readonly regionByMesh = new Map(); + private readonly pawns = new Map(); + private readonly pawnGeo = pawnGeometry(); + private figures: THREE.Object3D[] = []; + private disposed = false; + private readonly effects: EffectPlayer; + private lastFrame = performance.now(); + /** 播放演出時鏡頭拉近的目標;演完拉回原本的視角 */ + private cinematic: { target: THREE.Vector3; dist: number; returning: boolean } | null = null; + private readonly disposables: { dispose(): void }[] = []; + private readonly ray = new THREE.Raycaster(); + private readonly materials: Record<"sea" | "frame" | "base" | "neighbor" | "tray", THREE.MeshStandardMaterial>; + private readonly trayLines: THREE.LineDashedMaterial; + private anchors: HTMLElement[] = []; + private selected: string | null = null; + private hovered: string | null = null; + private highlight = new Set(); + private clickable = false; + private dirty = true; + private raf = 0; + private visible = true; + private userMoved = false; + private down: { x: number; y: number } | null = null; + private fillOf: (code: string, town: string) => string = () => "var(--neutral)"; + private readonly fitCorners: THREE.Vector3[]; + private readonly cleanup: (() => void)[] = []; + private home: { target: THREE.Vector3; dist: number } | null = null; + /** HTML 標籤的縮放:畫面窄時字跟著變小,避免擠成一團 */ + private labelScale = 1; + + constructor( + private readonly canvas: HTMLCanvasElement, + private readonly overlay: HTMLElement, + private readonly g: StageGeometry, + private readonly options: BoardOptions, + ) { + this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: "high-performance" }); + this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); + this.renderer.shadowMap.enabled = true; + this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; + this.colors = new ColorResolver(overlay); + this.painter = new MapPainter(g, this.colors); + this.disposables.push(this.painter, this.pawnGeo); + + this.materials = { + sea: new THREE.MeshStandardMaterial({ roughness: 0.75 }), + frame: new THREE.MeshStandardMaterial({ roughness: 0.65 }), + base: new THREE.MeshStandardMaterial({ roughness: 0.9 }), + neighbor: new THREE.MeshStandardMaterial({ roughness: 0.95 }), + tray: new THREE.MeshStandardMaterial({ roughness: 0.8 }), + }; + this.trayLines = new THREE.LineDashedMaterial({ dashSize: 6, gapSize: 4 }); + this.disposables.push(...Object.values(this.materials), this.trayLines); + + this.buildLights(); + this.buildBoard(); + this.buildNeighbors(); + this.buildInsets(); + this.buildRegions(); + this.applyTheme(); + this.decorate(); + this.effects = new EffectPlayer(this.scene, true); + + const halfW = g.width / 2 + FRAME_W; + const halfH = g.height / 2 + FRAME_W; + this.fitCorners = [-1, 1].flatMap((sx) => [-1, 1].flatMap((sz) => [FRAME_BOTTOM, LAND_H].map((y) => new THREE.Vector3(sx * halfW, y, sz * halfH)))); + + this.controls = new OrbitControls(this.camera, canvas); + this.controls.enableDamping = true; + this.controls.dampingFactor = 0.12; + this.controls.minPolarAngle = 0.05; + this.controls.maxPolarAngle = 1.18; + this.controls.screenSpacePanning = false; + this.controls.addEventListener("change", () => { + // 平移不能把盤面拖出畫面:注視點限制在盤面範圍內 + const t = this.controls.target; + const limX = this.g.width / 2; + const limZ = this.g.height / 2; + t.x = Math.max(-limX, Math.min(limX, t.x)); + t.z = Math.max(-limZ, Math.min(limZ, t.z)); + t.y = 0; + this.dirty = true; + }); + // 真的拖曳、縮放過才算玩家自己動了鏡頭(點一下選區不算) + let startPos: THREE.Vector3 | null = null; + this.controls.addEventListener("start", () => (startPos = this.camera.position.clone())); + this.controls.addEventListener("end", () => { + if (startPos && startPos.distanceTo(this.camera.position) > 1) { + this.userMoved = true; + this.cinematic = null; + } + startPos = null; + }); + this.listen(); + this.fit(); + this.loop(); + } + + // ── 建場景 ── + + private buildLights(): void { + const hemi = new THREE.HemisphereLight(0xffffff, 0xb8a888, 1.9); + const sun = new THREE.DirectionalLight(0xfff6e8, 1.5); + sun.position.set(-260, 520, 300); + sun.castShadow = true; + sun.shadow.mapSize.set(2048, 2048); + sun.shadow.bias = -0.0004; + const r = Math.max(this.g.width, this.g.height) / 2 + 80; + Object.assign(sun.shadow.camera, { left: -r, right: r, top: r, bottom: -r, near: 100, far: 1400 }); + this.scene.add(hemi, sun); + } + + private buildBoard(): void { + const { width: w, height: h } = this.g; + // 外框:圓角矩形挖掉中間,擠出成一圈木框 + const outer = roundedRect(w + FRAME_W * 2, h + FRAME_W * 2, 22); + outer.holes = [new THREE.Path(roundedRect(w, h, 6).getPoints(8))]; + const frameGeo = new THREE.ExtrudeGeometry(outer, { depth: FRAME_TOP - FRAME_BOTTOM, bevelEnabled: true, bevelThickness: 2, bevelSize: 2, bevelSegments: 2, curveSegments: 6 }); + frameGeo.rotateX(-Math.PI / 2); + frameGeo.translate(0, FRAME_BOTTOM, 0); + const frame = new THREE.Mesh(frameGeo, this.materials.frame); + frame.castShadow = true; + frame.receiveShadow = true; + // 底座:讓海面下面不是空的 + const baseGeo = new THREE.BoxGeometry(w + 2, -FRAME_BOTTOM - 1, h + 2); + baseGeo.translate(0, FRAME_BOTTOM / 2 - 0.5, 0); + const base = new THREE.Mesh(baseGeo, this.materials.base); + const seaGeo = new THREE.PlaneGeometry(w + 4, h + 4); + seaGeo.rotateX(-Math.PI / 2); + const sea = new THREE.Mesh(seaGeo, this.materials.sea); + sea.receiveShadow = true; + this.scene.add(frame, base, sea); + this.disposables.push(frameGeo, baseGeo, seaGeo); + } + + private buildNeighbors(): void { + for (const c of this.g.context) { + if (c.rings.length === 0) continue; + const geo = extrude(this.g, c.rings, NEIGHBOR_H); + const mesh = new THREE.Mesh(geo, this.materials.neighbor); + mesh.receiveShadow = true; + this.scene.add(mesh); + this.disposables.push(geo); + } + } + + private buildInsets(): void { + for (const i of this.g.insets) { + const cx = i.x + i.w / 2 - this.g.width / 2; + const cy = this.g.height / 2 - (i.y + i.h / 2); + const shape = roundedRect(i.w, i.h, 8, cx, cy); + const geo = new THREE.ExtrudeGeometry(shape, { depth: 1.2, bevelEnabled: false, curveSegments: 4 }); + geo.rotateX(-Math.PI / 2); + const tray = new THREE.Mesh(geo, this.materials.tray); + tray.receiveShadow = true; + const pts = shape.getPoints(6).map((p) => new THREE.Vector3(p.x, 1.4, -p.y)); + const lineGeo = new THREE.BufferGeometry().setFromPoints([...pts, pts[0]!]); + const line = new THREE.Line(lineGeo, this.trayLines); + line.computeLineDistances(); + this.scene.add(tray, line); + this.disposables.push(geo, lineGeo); + } + } + + private buildRegions(): void { + for (const t of this.g.towns) { + if (t.rings.length === 0) continue; + const geo = extrude(this.g, t.rings, LAND_H); + const cap = new THREE.MeshStandardMaterial({ map: this.painter.texture, roughness: 0.82, metalness: 0 }); + const side = new THREE.MeshStandardMaterial({ roughness: 0.9 }); + const mesh = new THREE.Mesh(geo, [cap, side]); + mesh.castShadow = true; + mesh.receiveShadow = true; + const region: Region = { code: t.code, mesh, lift: 0 }; + this.regions.push(region); + this.regionByMesh.set(mesh, region); + this.scene.add(mesh); + this.disposables.push(geo, cap, side); + } + } + + /** 在某一區演出一個行動(每週播放用);減少動態時不演 */ + playEffect(key: string, code: string, actionId: string): void { + if (this.options.reduceMotion) return; + const town = this.g.towns.find((t) => t.code === code); + if (!town) return; + const lift = this.regions.find((r) => r.code === code)?.lift ?? 0; + const at = stageToWorld(this.g, town.cx, town.cy + 18, LAND_H + lift); + this.effects.play(key, at, actionId); + // 鏡頭拉近演出的那一區(玩家自己轉過鏡頭就不搶) + if (this.home && !this.userMoved) this.cinematic = { target: new THREE.Vector3(at.x, 0, at.z), dist: this.home.dist * 0.55, returning: false }; + this.dirty = true; + } + + /** 每一區長出店面、住家、樹(讀模型要一點時間,讀好再掛上去) */ + private decorate(): void { + void buildTownDecor(this.g, this.options.townAdults ?? null, LAND_H, true).then((decor) => { + if (this.disposed) { + decor.dispose(); + return; + } + for (const r of this.regions) { + const group = decor.groups.get(r.code); + if (group) r.mesh.add(group); + } + this.disposables.push({ dispose: decor.dispose }); + this.dirty = true; + }); + } + + // ── 主題與顏色 ── + + applyTheme(): void { + this.colors.clear(); + const c = (v: string) => this.colors.css(v); + const wave = waveTexture(c("var(--sea)"), c("var(--sea-line)")); + wave.repeat.set(this.g.width / 112, this.g.height / 48); + const wood = woodTexture(c("var(--board-wood)"), c("var(--board-wood-grain)")); + wood.repeat.set(3, 3); + for (const old of [this.materials.sea.map, this.materials.frame.map]) old?.dispose(); + this.materials.sea.map = wave; + this.materials.frame.map = wood; + // 真的木頭貼圖(CC0)讀到之後換掉畫出來的木紋 + new THREE.TextureLoader().load("/assets/textures/wood-oak-light-diff.jpg", (t) => { + t.colorSpace = THREE.SRGBColorSpace; + t.wrapS = t.wrapT = THREE.RepeatWrapping; + t.repeat.set(4, 4); + this.materials.frame.map?.dispose(); + this.materials.frame.map = t; + this.materials.frame.color.setHex(0xffffff); + this.materials.frame.needsUpdate = true; + this.dirty = true; + }); + this.materials.base.color.setHex(this.colors.hex("var(--sea-line)")); + this.materials.neighbor.color.setHex(this.colors.hex("var(--land-neighbor)")); + this.materials.tray.color.setHex(toHex(shade(this.colors.rgb("var(--sea)"), 0.94))); + this.trayLines.color.setHex(this.colors.hex("var(--muted)")); + for (const m of Object.values(this.materials)) m.needsUpdate = true; + this.painter.paintLines({ neutral: "var(--neutral)", districtLine: "var(--district-line)", countyLine: "var(--county-line)" }); + this.painter.paintFills(this.fillOf, true); + this.paintSides(); + this.dirty = true; + } + + /** 每個里的顏色;回傳的字串可以是 var()、color-mix() */ + setFills(fillOf: (code: string, town: string) => string, townColor: (code: string) => string | undefined): void { + this.fillOf = fillOf; + this.townColor = townColor; + this.painter.paintFills(fillOf); + this.paintSides(); + this.dirty = true; + } + + private townColor: (code: string) => string | undefined = () => undefined; + + private paintSides(): void { + for (const r of this.regions) { + const base = this.colors.rgb(this.townColor(r.code) ?? "var(--neutral)"); + r.mesh.material[1]!.color.setHex(toHex(shade(base, 0.72))); + } + } + + // ── 狀態 ── + + setSelected(code: string | null): void { + this.selected = code; + this.dirty = true; + } + + setHighlight(codes: ReadonlySet): void { + this.highlight = new Set(codes); + this.dirty = true; + } + + setClickable(on: boolean): void { + this.clickable = on; + if (!on) this.setHover(null); + } + + setPawns(specs: readonly PawnSpec[]): void { + const keep = new Set(specs.map((s) => s.key)); + for (const [key, pawn] of this.pawns) { + if (keep.has(key)) continue; + this.scene.remove(pawn.group); + pawn.mesh.material.dispose(); + this.pawns.delete(key); + } + const now = performance.now(); + for (const s of specs) { + const to = stageToWorld(this.g, s.x, s.y, LAND_H); + const pawn = this.pawns.get(s.key); + if (pawn) { + pawn.mesh.material.color.setHex(this.colors.hex(s.color)); + if (pawn.to.distanceTo(to) > 0.01) { + pawn.from = pawn.group.position.clone(); + pawn.to = to; + pawn.start = this.options.reduceMotion ? 0 : now; + } + continue; + } + const group = new THREE.Group(); + const material = new THREE.MeshStandardMaterial({ color: this.colors.hex(s.color), roughness: 0.35, metalness: 0.05 }); + const figure = this.figureFor(s.key); + const mesh = new THREE.Mesh(figure ? BASE_GEO : this.pawnGeo, material); + mesh.castShadow = true; + group.add(mesh); + if (figure) group.add(figure); + group.position.copy(to); + this.scene.add(group); + this.pawns.set(s.key, { group, mesh, from: to.clone(), to, start: 0 }); + } + this.dirty = true; + // 人偶還沒讀進來:讀好之後把傳統的兵換成底座+人偶 + if (this.figures.length === 0) { + void loadFigures().then((figs) => { + if (figs.length === 0 || this.figures.length > 0) return; + this.figures = figs; + for (const [key, pawn] of this.pawns) { + const figure = this.figureFor(key); + if (!figure) continue; + pawn.mesh.geometry = BASE_GEO; + pawn.group.add(figure); + } + this.dirty = true; + }); + } + } + + /** 依棋子的 key 固定挑一個人偶,縮放到棋子的高度、站在底座上 */ + private figureFor(key: string): THREE.Object3D | null { + if (this.figures.length === 0) return null; + let h = 0; + for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) >>> 0; + // 人偶有骨架,要用 SkeletonUtils 複製,不然骨頭還指向原本那份、畫不出來 + const fig = cloneSkinned(this.figures[h % this.figures.length]!); + const box = new THREE.Box3().setFromObject(fig); + const size = box.getSize(new THREE.Vector3()); + const k = FIGURE_H / size.y; + fig.scale.multiplyScalar(k); + fig.position.y = 4 - box.min.y * k; + fig.traverse((o) => { + if ((o as THREE.Mesh).isMesh) o.castShadow = true; + }); + return fig; + } + + /** BoardStage 每次重繪後呼叫:重新收集要跟著地圖移動的 HTML */ + refreshAnchors(): void { + this.anchors = [...this.overlay.querySelectorAll("[data-b3], [data-b3-pawn]")]; + this.dirty = true; + } + + // ── 鏡頭 ── + + /** + * 把整張桌遊盤放進畫面:斜看時遠端會縮小、近端會放大, + * 所以同時調距離和注視點(往近端移),直到盤面的八個角剛好塞滿畫面、上下置中。 + */ + private fit(): void { + const target = new THREE.Vector3(0, 0, 0); + const dir = new THREE.Vector3(0, Math.cos(TILT), Math.sin(TILT)).normalize(); + const halfTan = Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2)); + let dist = Math.max(this.g.width, this.g.height) * 1.6; + const place = () => { + this.camera.position.copy(target).addScaledVector(dir, dist); + this.camera.lookAt(target); + this.camera.updateMatrixWorld(); + }; + for (let i = 0; i < 10; i++) { + place(); + const ndc = this.fitCorners.map((p) => p.clone().project(this.camera)); + const xs = ndc.map((v) => v.x); + const ys = ndc.map((v) => v.y); + const cy = (Math.min(...ys) + Math.max(...ys)) / 2; + const span = Math.max((Math.max(...xs) - Math.min(...xs)) / 2, (Math.max(...ys) - Math.min(...ys)) / 2); + target.z -= cy * dist * halfTan * 0.9; + dist *= span / 0.96; + } + place(); + this.home = { target: target.clone(), dist }; + this.controls.target.copy(target); + this.controls.minDistance = dist * 0.3; + this.controls.maxDistance = dist * 1.6; + this.controls.update(); + this.dirty = true; + } + + resize(): void { + const w = this.canvas.clientWidth; + const h = this.canvas.clientHeight; + if (!w || !h) return; + this.renderer.setSize(w, h, false); + this.labelScale = Math.max(0.62, Math.min(1, w / 980)); + this.camera.aspect = w / h; + this.camera.updateProjectionMatrix(); + if (!this.userMoved) this.fit(); + this.dirty = true; + } + + /** 回到預設視角 */ + resetView(): void { + this.userMoved = false; + this.fit(); + } + + // ── 互動 ── + + private listen(): void { + const el = this.canvas; + const pointer = (e: PointerEvent) => { + const r = el.getBoundingClientRect(); + return new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + }; + const pick = (e: PointerEvent): string | null => { + this.ray.setFromCamera(pointer(e), this.camera); + const hit = this.ray.intersectObjects(this.regions.map((r) => r.mesh), false)[0]; + return hit ? (this.regionByMesh.get(hit.object)?.code ?? null) : null; + }; + const onDown = (e: PointerEvent) => (this.down = { x: e.clientX, y: e.clientY }); + const onUp = (e: PointerEvent) => { + const d = this.down; + this.down = null; + if (!d || !this.clickable || Math.hypot(e.clientX - d.x, e.clientY - d.y) > 6) return; + const code = pick(e); + if (code) this.options.onSelect(code); + }; + const onMove = (e: PointerEvent) => { + if (!this.clickable || e.pointerType === "touch" || e.buttons) return; + this.setHover(pick(e)); + }; + const onLeave = () => this.setHover(null); + el.addEventListener("pointerdown", onDown); + el.addEventListener("pointerup", onUp); + el.addEventListener("pointermove", onMove); + el.addEventListener("pointerleave", onLeave); + this.cleanup.push(() => { + el.removeEventListener("pointerdown", onDown); + el.removeEventListener("pointerup", onUp); + el.removeEventListener("pointermove", onMove); + el.removeEventListener("pointerleave", onLeave); + }); + const io = new IntersectionObserver(([entry]) => { + this.visible = entry?.isIntersecting ?? true; + if (this.visible) this.dirty = true; + }); + io.observe(el); + this.cleanup.push(() => io.disconnect()); + } + + private setHover(code: string | null): void { + if (code === this.hovered) return; + this.hovered = code; + this.canvas.style.cursor = code ? "pointer" : ""; + this.dirty = true; + } + + // ── 每一幀 ── + + private loop = (): void => { + this.raf = requestAnimationFrame(this.loop); + if (!this.visible) return; + const now = performance.now(); + const dt = Math.min(0.05, (now - this.lastFrame) / 1000); + this.lastFrame = now; + let animating = this.controls.update(); + const playing = this.effects.update(now, dt); + if (playing) animating = true; + if (this.cinematic && this.home) { + if (!playing) this.cinematic.returning = true; + const goal = this.cinematic.returning ? this.home : this.cinematic; + const t = this.controls.target; + t.lerp(goal.target, 0.06); + const offset = this.camera.position.clone().sub(t); + const dist = offset.length(); + const next = dist + (goal.dist - dist) * 0.06; + this.camera.position.copy(t).add(offset.setLength(next)); + animating = true; + if (this.cinematic.returning && t.distanceTo(goal.target) < 1 && Math.abs(next - goal.dist) < 1) this.cinematic = null; + } + // 地形升降:選到的區升高,滑過的區浮一點 + for (const r of this.regions) { + const target = r.code === this.selected ? SELECT_LIFT : r.code === this.hovered ? HOVER_LIFT : 0; + if (Math.abs(r.lift - target) > 0.01) { + r.lift = this.options.reduceMotion ? target : r.lift + (target - r.lift) * 0.25; + animating = true; + } + r.mesh.position.y = r.lift; + const cap = r.mesh.material[0]!; + const pulse = this.highlight.has(r.code) ? (this.options.reduceMotion ? 0.18 : 0.12 + 0.1 * Math.sin(now / 260)) : 0; + const glow = r.code === this.selected ? 0.1 : r.code === this.hovered ? 0.06 : 0; + cap.emissive.setScalar(Math.max(pulse, glow)); + if (pulse > 0 && !this.options.reduceMotion) animating = true; + } + for (const p of this.pawns.values()) { + if (!p.start) { + p.group.position.copy(p.to); + continue; + } + const t = Math.min(1, (now - p.start) / 600); + const e = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; + p.group.position.lerpVectors(p.from, p.to, e); + p.group.position.y = LAND_H + Math.sin(t * Math.PI) * 14; + if (t >= 1) p.start = 0; + animating = true; + } + if (!animating && !this.dirty) return; + this.dirty = false; + this.renderer.render(this.scene, this.camera); + this.placeAnchors(); + }; + + private placeAnchors(): void { + const w = this.canvas.clientWidth; + const h = this.canvas.clientHeight; + const v = new THREE.Vector3(); + for (const el of this.anchors) { + const pawnKey = el.dataset.b3Pawn; + if (pawnKey) { + const pawn = this.pawns.get(pawnKey); + if (!pawn) continue; + v.copy(pawn.group.position); + v.y += this.figures.length ? FIGURE_H + 8 : PAWN_H + 1; + } else { + const [x, y, z] = (el.dataset.b3 ?? "0,0,0").split(",").map(Number) as [number, number, number]; + const region = el.dataset.b3Town ? this.regions.find((r) => r.code === el.dataset.b3Town) : undefined; + v.copy(stageToWorld(this.g, x, y, z + (region?.lift ?? 0))); + } + v.project(this.camera); + const hidden = v.z > 1 || v.x < -1.2 || v.x > 1.2 || v.y < -1.2 || v.y > 1.2; + el.style.visibility = hidden ? "hidden" : ""; + el.style.transform = `translate3d(${((v.x + 1) / 2) * w}px, ${((1 - v.y) / 2) * h}px, 0) scale(${this.labelScale})`; + } + } + + dispose(): void { + this.disposed = true; + this.effects.dispose(); + cancelAnimationFrame(this.raf); + for (const f of this.cleanup) f(); + this.controls.dispose(); + for (const p of this.pawns.values()) p.mesh.material.dispose(); + for (const m of [this.materials.sea.map, this.materials.frame.map]) m?.dispose(); + for (const d of this.disposables) d.dispose(); + this.colors.dispose(); + this.renderer.dispose(); + } +} + +/** 瀏覽器能不能跑 WebGL;不行就用平面地圖 */ +export function webglAvailable(): boolean { + try { + const c = document.createElement("canvas"); + return !!(c.getContext("webgl2") ?? c.getContext("webgl")); + } catch { + return false; + } +} + diff --git a/web/src/game/board3d/textures.ts b/web/src/game/board3d/textures.ts new file mode 100644 index 0000000..97da3d5 --- /dev/null +++ b/web/src/game/board3d/textures.ts @@ -0,0 +1,158 @@ +import * as THREE from "three"; +import type { StageGeometry } from "../stage/geometry.ts"; +import type { ColorResolver } from "./colors.ts"; + +/** 地圖貼圖的長邊像素:2048 足夠清楚,也不會讓手機吃不消 */ +const TEXTURE_LONG_SIDE = 2048; + +export interface MapColors { + neutral: string; + districtLine: string; + countyLine: string; +} + +/** + * 地形頂面的貼圖:各里的顏色畫在「底色層」,區界和縣界畫在「線條層」,兩層合成一張貼圖。 + * 開票夜每 0.1 秒多幾個里上色,只重畫顏色有變的里,不重建任何形狀。 + */ +export class MapPainter { + readonly texture: THREE.CanvasTexture; + private readonly scale: number; + private readonly fillLayer: HTMLCanvasElement; + private readonly lineLayer: HTMLCanvasElement; + private readonly output: HTMLCanvasElement; + private readonly paths: { code: string; town: string; path: Path2D }[]; + private readonly painted = new Map(); + + constructor(private readonly geometry: StageGeometry, private readonly colors: ColorResolver) { + this.scale = TEXTURE_LONG_SIDE / Math.max(geometry.width, geometry.height); + const w = Math.round(geometry.width * this.scale); + const h = Math.round(geometry.height * this.scale); + const make = () => Object.assign(document.createElement("canvas"), { width: w, height: h }); + this.fillLayer = make(); + this.lineLayer = make(); + this.output = make(); + this.paths = geometry.villages.map((v) => ({ code: v.code, town: v.town, path: new Path2D(v.d) })); + this.texture = new THREE.CanvasTexture(this.output); + this.texture.colorSpace = THREE.SRGBColorSpace; + this.texture.anisotropy = 4; + // 頂面的 UV 是擠出形狀的 x、y(見 BoardScene):換算回舞台座標 + this.texture.repeat.set(1 / geometry.width, 1 / geometry.height); + this.texture.offset.set(0.5, 0.5); + } + + /** 重畫線條層(主題換了才需要) */ + paintLines(c: MapColors): void { + const ctx = this.lineLayer.getContext("2d")!; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, this.lineLayer.width, this.lineLayer.height); + ctx.setTransform(this.scale, 0, 0, this.scale, 0, 0); + ctx.lineJoin = "round"; + ctx.lineCap = "round"; + ctx.strokeStyle = this.colors.css(c.districtLine); + ctx.lineWidth = 1.4; + ctx.stroke(new Path2D(this.geometry.borders)); + ctx.strokeStyle = this.colors.css(c.countyLine); + ctx.lineWidth = 2.2; + ctx.stroke(new Path2D(this.geometry.outline)); + } + + /** 依每個里的顏色上色;full 為 true 時整張重畫(換主題、換地圖) */ + paintFills(fillOf: (code: string, town: string) => string, full = false): void { + const ctx = this.fillLayer.getContext("2d")!; + if (full) { + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, this.fillLayer.width, this.fillLayer.height); + this.painted.clear(); + } + ctx.setTransform(this.scale, 0, 0, this.scale, 0, 0); + ctx.lineJoin = "round"; + ctx.lineWidth = 0.6; + let changed = full; + for (const v of this.paths) { + const color = fillOf(v.code, v.town); + if (this.painted.get(v.code) === color) continue; + const css = this.colors.css(color); + ctx.fillStyle = css; + ctx.strokeStyle = css; + ctx.fill(v.path); + ctx.stroke(v.path); + this.painted.set(v.code, color); + changed = true; + } + if (changed) this.compose(); + } + + private compose(): void { + const ctx = this.output.getContext("2d")!; + ctx.clearRect(0, 0, this.output.width, this.output.height); + ctx.drawImage(this.fillLayer, 0, 0); + ctx.drawImage(this.lineLayer, 0, 0); + this.texture.needsUpdate = true; + } + + /** 線條層重畫後要合成一次 */ + refresh(): void { + this.compose(); + } + + dispose(): void { + this.texture.dispose(); + } +} + +/** 木紋:桌遊盤的外框 */ +export function woodTexture(base: string, grain: string): THREE.CanvasTexture { + const c = Object.assign(document.createElement("canvas"), { width: 512, height: 128 }); + const ctx = c.getContext("2d")!; + ctx.fillStyle = base; + ctx.fillRect(0, 0, c.width, c.height); + // 用固定的種子,每次畫出來都一樣 + let seed = 11; + const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + ctx.strokeStyle = grain; + for (let i = 0; i < 46; i++) { + const y0 = rnd() * c.height; + const amp = 2 + rnd() * 5; + const freq = 0.006 + rnd() * 0.012; + ctx.globalAlpha = 0.08 + rnd() * 0.18; + ctx.lineWidth = 0.6 + rnd() * 1.6; + ctx.beginPath(); + for (let x = 0; x <= c.width; x += 8) { + const y = y0 + Math.sin(x * freq + i) * amp; + if (x === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + ctx.stroke(); + } + ctx.globalAlpha = 1; + const tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + tex.wrapS = tex.wrapT = THREE.RepeatWrapping; + return tex; +} + +/** 海面:和平面地圖一樣的波紋 */ +export function waveTexture(sea: string, line: string): THREE.CanvasTexture { + const c = Object.assign(document.createElement("canvas"), { width: 112, height: 48 }); + const ctx = c.getContext("2d")!; + ctx.fillStyle = sea; + ctx.fillRect(0, 0, c.width, c.height); + ctx.strokeStyle = line; + ctx.globalAlpha = 0.7; + ctx.lineWidth = 2; + for (const [ox, oy] of [ + [0, 12], + [56, 36], + ] as const) { + ctx.beginPath(); + ctx.moveTo(ox, oy); + ctx.quadraticCurveTo(ox + 14, oy - 10, ox + 28, oy); + ctx.quadraticCurveTo(ox + 42, oy + 10, ox + 56, oy); + ctx.stroke(); + } + const tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + tex.wrapS = tex.wrapT = THREE.RepeatWrapping; + return tex; +} diff --git a/web/src/game/board3d/town.ts b/web/src/game/board3d/town.ts new file mode 100644 index 0000000..3ca99e6 --- /dev/null +++ b/web/src/game/board3d/town.ts @@ -0,0 +1,205 @@ +import * as THREE from "three"; +import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js"; +import type { StageGeometry, StagePolygons } from "../stage/geometry.ts"; + +/** + * 桌遊盤上的小鎮:每一區依人口密度長出店面、住家或樹,像首頁的選戰小鎮。 + * 模型是 CC0(Kenney;web/public/assets/LICENSES.md),同一種模型合成一個 InstancedMesh,整張地圖只要幾十次繪製。 + * 擺放位置用區代碼當種子,同一張地圖每次都長得一樣;會避開區名和棋子站的位置。 + */ + +const A = "/assets/3d/"; +type Kind = "shop" | "house" | "tree"; +const MODELS: Record = { + shop: ["town-shops/building-a", "town-shops/building-c", "town-shops/building-e", "town-shops/building-h", "town-shops/building-k"], + house: ["town-houses/building-type-a", "town-houses/building-type-b", "town-houses/building-type-c", "town-houses/building-type-f"], + tree: ["nature/tree-default", "nature/tree-oak", "nature/tree-palm-short", "nature/plant-bush-large"], +}; +/** 模型的大小(舞台單位):店面以寬度、樹以高度 */ +const SIZE: Record = { shop: 16, house: 14, tree: 13 }; + +interface Model { + kind: Kind; + geometry: THREE.BufferGeometry; + material: THREE.Material | THREE.Material[]; +} + +let cache: Promise | null = null; + +/** 讀模型、合併成一個幾何、縮放到統一大小、底部貼齊 y=0 */ +function loadModels(): Promise { + cache ??= (async () => { + const loader = new GLTFLoader(); + // 住宅原本是綠屋頂,容易聯想成政黨色,換成磚紅色的貼圖版本 + const brick = await new THREE.TextureLoader().loadAsync(`${A}town-houses/Textures/variation-b.png`).catch(() => null); + if (brick) { + brick.flipY = false; + brick.colorSpace = THREE.SRGBColorSpace; + brick.magFilter = THREE.NearestFilter; + } + const entries = (Object.keys(MODELS) as Kind[]).flatMap((kind) => MODELS[kind].map((path) => ({ kind, path }))); + const models = await Promise.all( + entries.map(async ({ kind, path }): Promise => { + try { + const gltf = await loader.loadAsync(`${A}${path}.glb`); + gltf.scene.updateMatrixWorld(true); + const geos: THREE.BufferGeometry[] = []; + let material: THREE.Material | null = null; + gltf.scene.traverse((o) => { + const m = o as THREE.Mesh; + if (!m.isMesh) return; + const geo = m.geometry.clone().applyMatrix4(m.matrixWorld); + // 只保留合併需要的屬性,避免各部件屬性不一致合不起來 + for (const name of Object.keys(geo.attributes)) if (!["position", "normal", "uv"].includes(name)) geo.deleteAttribute(name); + geos.push(geo.index ? geo.toNonIndexed() : geo); + material ??= Array.isArray(m.material) ? m.material[0]! : m.material; + }); + if (geos.length === 0 || !material) return null; + const geometry = mergeGeometries(geos, false); + if (!geometry) return null; + geometry.computeBoundingBox(); + const box = geometry.boundingBox!; + const size = box.getSize(new THREE.Vector3()); + const k = SIZE[kind] / (kind === "tree" ? size.y : Math.max(size.x, size.z)); + const center = box.getCenter(new THREE.Vector3()); + geometry.translate(-center.x, -box.min.y, -center.z); + geometry.scale(k, k, k); + let mat = material as THREE.Material; + if (kind === "house" && brick && (mat as THREE.MeshStandardMaterial).map) { + mat = Object.assign((mat as THREE.MeshStandardMaterial).clone(), { map: brick }); + } + return { kind, geometry, material: mat }; + } catch { + return null; + } + }), + ); + return models.filter((m): m is Model => m !== null); + })(); + return cache; +} + +/** 由字串產生穩定的亂數 */ +function rng(seed: string): () => number { + let h = 2166136261; + for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619); + return () => { + h = Math.imul(h ^ (h >>> 15), 2246822507); + h = Math.imul(h ^ (h >>> 13), 3266489909); + h ^= h >>> 16; + return (h >>> 0) / 4294967296; + }; +} + +function ringArea(ring: readonly (readonly [number, number])[]): number { + let a = 0; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) a += (ring[j]![0] + ring[i]![0]) * (ring[j]![1] - ring[i]![1]); + return Math.abs(a / 2); +} + +function polygonsArea(polys: StagePolygons): number { + return polys.reduce((s, [outer, ...holes]) => s + ringArea(outer!) - holes.reduce((h, r) => h + ringArea(r), 0), 0); +} + +/** 點在不在多邊形裡(所有環一起算奇偶) */ +function inside(polys: StagePolygons, x: number, y: number): boolean { + let hit = false; + for (const poly of polys) + for (const ring of poly) + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, yi] = ring[i]!; + const [xj, yj] = ring[j]!; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) hit = !hit; + } + return hit; +} + +function bounds(polys: StagePolygons): [number, number, number, number] { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const poly of polys) for (const ring of poly) for (const [x, y] of ring) { + x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); + } + return [x0, y0, x1, y1]; +} + +export interface TownDecor { + /** 各區的裝飾群組;掛在區的地形下面,跟著區一起升降 */ + groups: Map; + dispose: () => void; +} + +/** + * 替每一區擺上建築與樹。adults:各區成年人口(沒有就只看面積,當作郊區)。 + * landH:地形的高度,裝飾站在地形頂面上。 + */ +export async function buildTownDecor(g: StageGeometry, adults: ReadonlyMap | null, landH: number, shadows: boolean): Promise { + const models = await loadModels(); + const groups = new Map(); + const meshes: THREE.InstancedMesh[] = []; + if (models.length === 0) return { groups, dispose: () => {} }; + const byKind = (k: Kind) => models.filter((m) => m.kind === k); + + // 人口密度排名決定這區是市區、郊區還是鄉下 + const info = g.towns.filter((t) => t.rings.length).map((t) => { + const area = Math.max(1, polygonsArea(t.rings)); + return { t, area, density: (adults?.get(t.code) ?? area * 50) / area }; + }); + const sorted = [...info].sort((a, b) => b.density - a.density); + const rank = new Map(sorted.map((x, i) => [x.t.code, i / Math.max(1, sorted.length - 1)])); + + for (const { t, area } of info) { + const r = rng(`decor:${t.code}`); + const pct = adults ? rank.get(t.code)! : 0.5; + const mix: Record = pct < 0.3 ? { shop: 0.7, house: 0.1, tree: 0.2 } : pct < 0.7 ? { shop: 0.15, house: 0.45, tree: 0.4 } : { shop: 0, house: 0.25, tree: 0.75 }; + const count = Math.max(1, Math.min(10, Math.round(Math.sqrt(area) / 9))); + const [x0, y0, x1, y1] = bounds(t.rings); + // 區名在中心、棋子在中心下方 46:這兩塊留空 + const keepOut = [ + { x: t.cx, y: t.cy, r: 16 }, + { x: t.cx, y: t.cy + 46, r: 18 }, + ]; + const placed: { x: number; y: number; kind: Kind }[] = []; + for (let tries = 0; placed.length < count && tries < count * 40; tries++) { + const x = x0 + r() * (x1 - x0); + const y = y0 + r() * (y1 - y0); + if (!inside(t.rings, x, y)) continue; + if (keepOut.some((k) => Math.hypot(k.x - x, k.y - y) < k.r)) continue; + if (placed.some((p) => Math.hypot(p.x - x, p.y - y) < 10)) continue; + const roll = r(); + const kind: Kind = roll < mix.shop ? "shop" : roll < mix.shop + mix.house ? "house" : "tree"; + placed.push({ x, y, kind }); + } + if (placed.length === 0) continue; + const group = new THREE.Group(); + // 同一種模型合成一個 InstancedMesh + const buckets = new Map(); + const m4 = new THREE.Matrix4(); + const q = new THREE.Quaternion(); + for (const p of placed) { + const list = byKind(p.kind); + if (list.length === 0) continue; + const model = list[Math.floor(r() * list.length)]!; + const turn = p.kind === "tree" ? r() * Math.PI * 2 : Math.floor(r() * 4) * (Math.PI / 2) + (r() - 0.5) * 0.3; + const s = 0.85 + r() * 0.3; + q.setFromAxisAngle(new THREE.Vector3(0, 1, 0), turn); + m4.compose(new THREE.Vector3(p.x - g.width / 2, landH, p.y - g.height / 2), q, new THREE.Vector3(s, s, s)); + buckets.set(model, [...(buckets.get(model) ?? []), m4.clone()]); + } + for (const [model, mats] of buckets) { + const mesh = new THREE.InstancedMesh(model.geometry, model.material, mats.length); + mats.forEach((m, i) => mesh.setMatrixAt(i, m)); + mesh.castShadow = shadows; + mesh.receiveShadow = shadows; + // 點區的時候射線不要打到房子,直接打到地形 + mesh.raycast = () => {}; + group.add(mesh); + meshes.push(mesh); + } + groups.set(t.code, group); + } + return { + groups, + dispose: () => meshes.forEach((m) => m.dispose()), + }; +} diff --git a/web/src/game/career/term/BillGame.tsx b/web/src/game/career/term/BillGame.tsx new file mode 100644 index 0000000..d02518b --- /dev/null +++ b/web/src/game/career/term/BillGame.tsx @@ -0,0 +1,225 @@ +import { Gavel } from "lucide-react"; +import { useMemo, useState } from "react"; +import { sfx } from "../../audio/sfx.ts"; +import { GameShell, Pops, TimerBar, useCountdown, usePops, useShake } from "./Shell.tsx"; +import { clamp, rng, shuffle } from "./rng.ts"; +import type { TermGameProps } from "./types.ts"; + +/** + * 講解法條:虛構法案拆成條文碎片,先放到正確的條次,再挑對的白話說明。 + * 答對讓座位圖上的委員亮起來(被說服),過半就三讀通過。法案與委員都是虛構的。 + */ + +const ARTICLES = [ + { n: "第一條", what: "立法目的" }, + { n: "第二條", what: "用詞定義" }, + { n: "第三條", what: "怎麼做" }, + { n: "第四條", what: "罰則" }, +] as const; + +interface Fragment { + /** 正確條次 0–3 */ + at: number; + text: string; + plain: string; + wrong: [string, string]; +} + +interface Bill { + name: string; + parts: Fragment[]; +} + +const BILLS: readonly Bill[] = [ + { + name: "社區托育補助條例", + parts: [ + { at: 0, text: "為減輕家庭育兒負擔,促進社區托育服務普及,特制定本條例。", plain: "這部法是要讓爸媽養小孩輕鬆一點。", wrong: ["這部法是要關掉私立托嬰中心。", "這部法是要提高托育人員的稅。"] }, + { at: 1, text: "本條例所稱社區托育,指由立案機構於住家附近提供未滿三歲幼兒之照顧服務。", plain: "「社區托育」就是家附近、有立案的托嬰。", wrong: ["「社區托育」就是請阿嬤顧小孩。", "「社區托育」指所有幼兒園。"] }, + { at: 2, text: "主管機關應按月補助送托家庭,每名幼兒每月新台幣五千元。", plain: "每個送托的小孩,每月補助五千元。", wrong: ["每個家庭一次領五千元就沒了。", "托嬰中心每月要繳五千元給政府。"] }, + { at: 3, text: "機構虛報托育人數詐領補助者,處新台幣十萬元以上五十萬元以下罰鍰。", plain: "托嬰中心灌人數騙補助,要罰十萬到五十萬。", wrong: ["爸媽忘了申請要罰十萬。", "補助不夠時托嬰中心可以加收費用。"] }, + ], + }, + { + name: "騎樓整平條例", + parts: [ + { at: 0, text: "為維護行人通行安全,改善騎樓高低不平之情形,特制定本條例。", plain: "這部法是要讓大家走騎樓不再上上下下。", wrong: ["這部法是要禁止店家使用騎樓。", "這部法是要拆掉所有騎樓。"] }, + { at: 1, text: "本條例所稱騎樓,指建築物臨接道路部分,供公眾通行之有頂走廊。", plain: "「騎樓」就是店門口有屋頂、讓人走的那段路。", wrong: ["「騎樓」指所有人行道。", "「騎樓」指大樓的地下停車場。"] }, + { at: 2, text: "直轄市、縣(市)政府應分期補助騎樓整平工程經費之百分之八十。", plain: "整平騎樓的工程費,政府分期出八成。", wrong: ["整平騎樓的錢全部由住戶自己出。", "政府一次出全額,住戶不用管。"] }, + { at: 3, text: "於整平後之騎樓違規堆放物品,經勸導不改善者,處新台幣一千二百元以上罰鍰。", plain: "整平後還在騎樓亂堆東西、勸了不改,要罰一千二起跳。", wrong: ["在騎樓走路太慢要罰一千二。", "所有騎樓擺攤都一律沒收。"] }, + ], + }, + { + name: "長輩共餐推動條例", + parts: [ + { at: 0, text: "為促進長者健康與社會參與,推動社區共餐服務,特制定本條例。", plain: "這部法是讓長輩有地方一起吃飯、出門走走。", wrong: ["這部法是要長輩自己煮飯。", "這部法是要取消敬老津貼。"] }, + { at: 1, text: "本條例所稱共餐據點,指經登記於社區提供長者用餐及活動之場所。", plain: "「共餐據點」就是登記過、長輩可以一起吃飯活動的地方。", wrong: ["「共餐據點」就是夜市。", "「共餐據點」指醫院的餐廳。"] }, + { at: 2, text: "主管機關應補助共餐據點食材費及志工交通費,並每年辦理衛生稽查。", plain: "政府出食材和志工車馬費,每年還會查衛生。", wrong: ["食材要長輩自己帶。", "志工每年要繳交通費給政府。"] }, + { at: 3, text: "據點違反衛生規定致生危害者,主管機關得停止補助並處罰鍰。", plain: "據點衛生出問題,政府可以停補助、開罰。", wrong: ["長輩吃太少要罰款。", "據點衛生不好也不會怎樣。"] }, + ], + }, +]; + +/** 半圓形的委員席:三排 7、10、13 席 */ +const SEATS = (() => { + const rows = [ + { r: 52, n: 7 }, + { r: 78, n: 10 }, + { r: 104, n: 13 }, + ]; + const out: { x: number; y: number; a: number }[] = []; + for (const { r, n } of rows) + for (let i = 0; i < n; i++) { + const a = Math.PI - (Math.PI * (i + 0.5)) / n; + out.push({ x: 120 + r * Math.cos(a), y: 116 - r * Math.sin(a), a }); + } + // 從左到右亮起來 + return out.sort((p, q) => q.a - p.a); +})(); +const BASE = 8; +const NEED = Math.floor(SEATS.length / 2) + 1; + +export function BillGame({ seed, level, characterName, onFinish }: TermGameProps) { + const total = Math.round(55 - level * 15); + const { bill, steps } = useMemo(() => { + const r = rng(seed); + const b = BILLS[Math.floor(r() * BILLS.length)]!; + return { bill: b, steps: shuffle(r, b.parts).map((p) => ({ ...p, options: shuffle(r, [p.plain, ...p.wrong]) })) }; + }, [seed]); + const max = steps.length * 3; + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [i, setI] = useState(0); + /** 這一條先放條次(place),再選白話(explain) */ + const [part, setPart] = useState<"place" | "explain">("place"); + const [placed, setPlaced] = useState<(number | null)[]>(() => ARTICLES.map(() => null)); + const [pts, setPts] = useState(0); + const [wrong, setWrong] = useState(0); + const [final, setFinal] = useState(0); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + const lit = clamp(BASE + pts - wrong, 0, SEATS.length); + + const finish = (p: number, w: number) => { + const s = clamp(((p - w) / max) * 100, 0, 100); + setFinal(s); + setPhase("done"); + if (BASE + p - w >= NEED) { + sfx.firecracker(); + sfx.applause(); + } else sfx.ooh(); + }; + const left = useCountdown(total, phase === "play", () => finish(pts, wrong)); + + const step = steps[i]; + const next = (p: number, w: number) => { + if (i + 1 >= steps.length) finish(p, w); + else { + setI(i + 1); + setPart("place"); + } + }; + + const place = (at: number) => { + if (!step) return; + if (at === step.at) { + setPts(pts + 1); + setPlaced((list) => list.map((x, k) => (k === at ? i : x))); + setPart("explain"); + sfx.place(); + pop("對!", "good", 50, 30); + } else { + setWrong(wrong + 1); + sfx.bad(); + doShake("small"); + pop(`不是${ARTICLES[at]!.n}`, "bad", 50, 30); + } + }; + + const explain = (text: string) => { + if (!step) return; + if (text === step.plain) { + const p = pts + 2; + setPts(p); + sfx.good(); + sfx.combo(p); + if (BASE + p - wrong >= NEED && BASE + pts - wrong < NEED) { + doShake("large"); + pop("過半!", "boom", 50, 20); + } else pop("委員點頭", "good", 50, 30); + next(p, wrong); + } else { + const w = wrong + 1; + setWrong(w); + sfx.bad(); + doShake("small"); + pop("講錯了", "bad", 50, 30); + next(pts, w); + } + }; + + const passed = BASE + pts - wrong >= NEED; + return ( + } + phase={phase} + onStart={() => setPhase("play")} + score={final} + verdict={passed ? `三讀通過!${characterName}的法案上路了。` : "票數不夠,法案退回委員會再議。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+ +
+ + {SEATS.map((s, k) => ( + + ))} + + + = NEED ? "is-pass" : ""}> + {lit} + /{NEED} 席過半 + +
+
    + {ARTICLES.map((a, k) => { + const filled = placed[k]; + return ( +
  1. + +
  2. + ); + })} +
+ {step && ( +
+ + {bill.name}・碎片 {i + 1}/{steps.length} + +

{step.text}

+
+ )} + {step && part === "place" &&

這段是第幾條?

} + {step && part === "explain" && ( + <> +

用白話跟委員說:

+
+ {step.options.map((o) => ( + + ))} +
+ + )} + +
+
+ ); +} diff --git a/web/src/game/career/term/BrawlGame.tsx b/web/src/game/career/term/BrawlGame.tsx new file mode 100644 index 0000000..25fa94f --- /dev/null +++ b/web/src/game/career/term/BrawlGame.tsx @@ -0,0 +1,202 @@ +import { Hand, Megaphone, Mic, Users } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { Avatar, avatarFromSeed } from "../../art/Avatar.tsx"; +import { sfx } from "../../audio/sfx.ts"; +import { GameShell, Pops, TimerBar, useCountdown, usePops, useShake } from "./Shell.tsx"; +import { clamp, rng } from "./rng.ts"; +import type { TermGameProps } from "./types.ts"; + +/** + * 搶主席台(鬧劇版):兩邊黨團推來擠去搶主席台。連點「推!」把控制條推高, + * 搶到飛出來的麥克風加一大段,舉標語讓對方愣住幾秒。控制條在 70 以上累積撐 10 秒就贏。 + * 只有推擠、搶麥克風、舉標語,沒有人受傷。兩邊黨團都是虛構的,不標真實政黨。 + */ + +const TOTAL = 30; +const HOLD = 10; +const LINE = 70; +const SIGN_CD = 6; +const SIGN_PAUSE = 2.5; +const PUSH_WORDS = ["推!", "擠!", "推!", "頂住!"]; + +export function BrawlGame({ seed, level, characterName, onFinish }: TermGameProps) { + const faces = useMemo( + () => ({ + us: [0, 1, 2].map((k) => avatarFromSeed(`brawl-us-${seed}-${k}`)), + them: [0, 1, 2].map((k) => avatarFromSeed(`brawl-them-${seed}-${k}`)), + }), + [seed], + ); + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [ctrl, setCtrl] = useState(50); + const [held, setHeld] = useState(0); + const [pauseLeft, setPauseLeft] = useState(0); + const [signCd, setSignCd] = useState(0); + const [mic, setMic] = useState<{ x: number; y: number; id: number } | null>(null); + const [final, setFinal] = useState(0); + const [won, setWon] = useState(false); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + const state = useRef({ ctrl: 50, held: 0, pause: 0, cd: 0, t: 0, nextMic: 4, micUntil: 0, surgeAt: 7, done: false }); + const r = useMemo(() => rng(seed ^ 0x5eed), [seed]); + // 對方每秒推回來多少:越後面的關卡越兇,時間越久也越兇 + const push = 9 + level * 6; + + const end = (win: boolean, timeLeft: number) => { + if (state.current.done) return; + state.current.done = true; + const s = win ? clamp(70 + timeLeft * 1.5, 70, 100) : clamp((state.current.held / HOLD) * 65, 0, 65); + setWon(win); + setFinal(s); + setPhase("done"); + if (win) { + sfx.firecracker(); + sfx.cheer(); + } else sfx.ooh(); + }; + + const left = useCountdown(TOTAL, phase === "play", () => end(false, 0)); + + useEffect(() => { + if (phase !== "play") return; + const st = state.current; + const dt = 0.1; + const t = setInterval(() => { + if (st.done) return; + st.t += dt; + if (st.pause > 0) st.pause = Math.max(0, st.pause - dt); + else st.ctrl -= (push + st.t * 0.25) * dt; + st.cd = Math.max(0, st.cd - dt); + // 對方偶爾一起衝一波 + if (st.t >= st.surgeAt) { + st.surgeAt = st.t + 5 + r() * 3; + if (st.pause <= 0) { + st.ctrl -= 8 + level * 4; + pop("人牆!", "bad", 74, 34); + sfx.ooh(); + } + } + // 麥克風從人群裡飛出來,1.6 秒內點到才算 + if (st.t >= st.nextMic) { + st.nextMic = st.t + 3.5 + r() * 2.5; + st.micUntil = st.t + 1.6; + setMic({ x: 18 + r() * 64, y: 18 + r() * 34, id: st.t }); + } else if (st.micUntil && st.t >= st.micUntil) { + st.micUntil = 0; + setMic(null); + } + st.ctrl = clamp(st.ctrl, 0, 100); + if (st.ctrl >= LINE) st.held += dt; + setCtrl(st.ctrl); + setHeld(st.held); + setPauseLeft(st.pause); + setSignCd(st.cd); + if (st.held >= HOLD) end(true, TOTAL - st.t); + }, 100); + return () => clearInterval(t); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [phase]); + + const nudge = (n: number) => { + const st = state.current; + st.ctrl = clamp(st.ctrl + n, 0, 100); + setCtrl(st.ctrl); + }; + + const taps = useRef(0); + const onPush = () => { + nudge(3.2); + sfx.hop(); + // 每兩下跳一個字,不然字會把主席台蓋住 + if (taps.current++ % 2) return; + pop(PUSH_WORDS[Math.floor(Math.random() * PUSH_WORDS.length)]!, "good", 24 + Math.random() * 30, 28 + Math.random() * 26); + }; + + const onMic = () => { + if (!mic) return; + state.current.micUntil = 0; + setMic(null); + nudge(12); + sfx.stamp(); + doShake("large"); + pop("搶麥!", "boom", mic.x, mic.y); + }; + + const onSign = () => { + const st = state.current; + if (st.cd > 0) return; + st.cd = SIGN_CD; + st.pause = SIGN_PAUSE; + setSignCd(SIGN_CD); + setPauseLeft(SIGN_PAUSE); + sfx.flag(); + doShake("small"); + pop("對方愣住了!", "boom", 70, 30); + }; + + // 主席台跟著控制條移動:控制越高越靠近我方 + const shift = (50 - ctrl) * 0.6; + return ( + } + phase={phase} + onStart={() => setPhase("play")} + score={final} + verdict={won ? `${characterName}的黨團坐上主席台,議事照我方的版本走。` : "主席台被對方守住,這回合只能場外喊話。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+ +
+
+ {faces.us.map((f, k) => ( + + ))} + 我方黨團 +
+
+ 主席台 +
+
0 ? " is-paused" : ""}`}> + {faces.them.map((f, k) => ( + + ))} + 對方黨團 +
+ {mic && ( + + )} + +
+
= LINE ? " is-hold" : ""}`} aria-label={`主席台控制 ${Math.round(ctrl)}`}> + + +
+
+ + 控制 {Math.round(ctrl)} + + + 撐住 {held.toFixed(1)}/{HOLD} 秒 + +
+
+ + +
+
+
+ ); +} diff --git a/web/src/game/career/term/BudgetGame.tsx b/web/src/game/career/term/BudgetGame.tsx new file mode 100644 index 0000000..c317e9c --- /dev/null +++ b/web/src/game/career/term/BudgetGame.tsx @@ -0,0 +1,315 @@ +import { Check, CloudLightning, Minus, Plus, Scissors, Wallet } from "lucide-react"; +import { useEffect, useMemo, useState } from "react"; +import { sfx } from "../../audio/sfx.ts"; +import { GameShell, Pops, TimerBar, useCountdown, usePops, useShake } from "./Shell.tsx"; +import { clamp, rng, shuffle } from "./rng.ts"; +import type { TermGameProps } from "./types.ts"; + +/** + * 預算: + * - mayor(縣市長):把 10 億分到五個項目,下方虛構的四個分區滿意度即時變化;中途颱風來,要挪 2 億救災。 + * - review(議員審預算):預算項目一個一個來,按「刪」或「過」。刪掉浮編得分,刪到必要的扣分。 + * 分區、項目都是虛構的。 + */ + +export function BudgetGame(props: TermGameProps & { mode?: "mayor" | "review" }) { + return props.mode === "review" ? : ; +} + +// ── 縣市長分預算 ── + +type Cat = "traffic" | "care" | "kids" | "safety" | "tour"; +const CATS: { id: Cat; label: string }[] = [ + { id: "traffic", label: "交通" }, + { id: "care", label: "長照" }, + { id: "kids", label: "托育" }, + { id: "safety", label: "治安" }, + { id: "tour", label: "觀光" }, +]; + +/** 一單位 = 1000 萬;總共 100 單位 = 10 億 */ +const BUDGET = 100; +const STEP = 5; +const RELIEF = 20; + +/** 四個虛構分區各自想要多少(單位) */ +const DISTRICTS: { name: string; need: Record }[] = [ + { name: "北區", need: { traffic: 10, kids: 8, safety: 3, care: 2, tour: 2 } }, + { name: "南區", need: { care: 9, safety: 6, traffic: 4, kids: 3, tour: 2 } }, + { name: "山區", need: { care: 7, traffic: 8, tour: 4, safety: 2, kids: 2 } }, + { name: "海線", need: { tour: 9, safety: 5, traffic: 4, care: 3, kids: 2 } }, +]; +const HIT_BY_TYPHOON = new Set(["山區", "海線"]); + +const yi = (u: number): string => `${(u / 10).toFixed(1)} 億`; + +function MayorGame({ seed, level, characterName, onFinish }: TermGameProps) { + const total = 40; + const typhoonAt = total - 15; + // 每一局各區想要的稍微不同 + const districts = useMemo(() => { + const r = rng(seed); + return DISTRICTS.map((d) => ({ + ...d, + need: Object.fromEntries(CATS.map((c) => [c.id, Math.max(1, d.need[c.id] + Math.round((r() - 0.5) * 4 * (0.5 + level)))])) as Record, + })); + }, [seed, level]); + const catNeed = useMemo(() => Object.fromEntries(CATS.map((c) => [c.id, districts.reduce((a, d) => a + d.need[c.id], 0)])) as Record, [districts]); + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [alloc, setAlloc] = useState>({ traffic: 15, care: 15, kids: 15, safety: 15, tour: 15 }); + const [relief, setRelief] = useState(0); + const [typhoon, setTyphoon] = useState(false); + const [final, setFinal] = useState(0); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + const used = CATS.reduce((a, c) => a + alloc[c.id], 0) + relief; + const pool = BUDGET - used; + + const sat = districts.map((d) => { + const want = CATS.reduce((a, c) => a + d.need[c.id], 0); + const got = CATS.reduce((a, c) => a + d.need[c.id] * Math.min(1, alloc[c.id] / catNeed[c.id]), 0); + const base = (got / want) * 100; + // 颱風來了還沒撥救災款,受災區滿意度打折 + const hit = typhoon && HIT_BY_TYPHOON.has(d.name) ? 0.55 + 0.45 * (relief / RELIEF) : 1; + return clamp(base * hit, 0, 100); + }); + const scoreOf = (s: number[]) => clamp(0.7 * (s.reduce((a, b) => a + b, 0) / s.length) + 0.3 * Math.min(...s), 0, 100); + + const finish = () => { + const s = scoreOf(sat); + setFinal(s); + setPhase("done"); + if (s >= 70) sfx.applause(); + else if (s < 40) sfx.ooh(); + }; + const left = useCountdown(total, phase === "play", finish); + const storm = phase === "play" && left <= typhoonAt; + useEffect(() => { + if (!storm || typhoon) return; + setTyphoon(true); + sfx.alert(); + doShake("large"); + pop("颱風來了!", "boom", 50, 30); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [storm, typhoon]); + + const add = (c: Cat, d: number) => { + const n = alloc[c] + d; + if (n < 0 || (d > 0 && pool < d)) { + sfx.bad(); + return; + } + setAlloc({ ...alloc, [c]: n }); + sfx.coin(); + }; + const addRelief = () => { + if (relief >= RELIEF) return; + if (pool < STEP) { + sfx.bad(); + pop("先從別的項目挪錢", "bad", 50, 40); + return; + } + const n = relief + STEP; + setRelief(n); + sfx.coin(); + if (n >= RELIEF) { + sfx.good(); + pop("救災款到位!", "good", 50, 40); + } + }; + + return ( + } + phase={phase} + onStart={() => setPhase("play")} + score={final} + verdict={final >= 75 ? `四區都說讚,${characterName}的預算被稱為「最會分錢的一年」。` : final >= 45 ? "大部分的區都還過得去。" : "有區域覺得被冷落,議會砲聲隆隆。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+ +
+ + 還沒分 {yi(pool)} + + + 已分 {yi(used)}/{yi(BUDGET)} + +
+ {typhoon && ( +
= RELIEF ? " is-done" : ""}`} role="alert"> + + + 颱風過境! + 救災款 {yi(relief)}/{yi(RELIEF)} + + +
+ )} +
    + {CATS.map((c) => ( +
  • + {c.label} + + + + {yi(alloc[c.id])} + + +
  • + ))} +
+
+ {districts.map((d, k) => { + const v = sat[k]!; + const top = CATS.filter((c) => d.need[c.id] >= 6).map((c) => c.label); + return ( +
= 75 ? " is-high" : ""}${typhoon && HIT_BY_TYPHOON.has(d.name) ? " is-storm" : ""}`}> + {d.name} + 想要:{top.join("、") || "都要一點"} + + + + {Math.round(v)} +
+ ); + })} +
+ +
+
+ ); +} + +// ── 議員審預算 ── + +interface Item { + name: string; + amount: string; + /** true=浮編,應該刪 */ + padded: boolean; +} + +const ITEMS: readonly Item[] = [ + { name: "國小營養午餐補助", amount: "1.2 億", padded: false }, + { name: "消防車汰換(車齡 25 年)", amount: "8000 萬", padded: false }, + { name: "長照交通車", amount: "3500 萬", padded: false }, + { name: "老舊校舍耐震補強", amount: "2.4 億", padded: false }, + { name: "路口號誌改善", amount: "1500 萬", padded: false }, + { name: "托育中心人力補助", amount: "6000 萬", padded: false }, + { name: "局長辦公室換真皮沙發", amount: "800 萬", padded: true }, + { name: "同一條路今年第三次重鋪", amount: "4200 萬", padded: true }, + { name: "形象影片(去年點閱 200 次)", amount: "3000 萬", padded: true }, + { name: "出國考察「城市美學」", amount: "1200 萬", padded: true }, + { name: "沒有人用的自行車道再延長", amount: "5000 萬", padded: true }, + { name: "跨年晚會請三組大牌歌手", amount: "9000 萬", padded: true }, +]; + +function ReviewGame({ seed, level, characterName, onFinish }: TermGameProps) { + const perItem = 4.5 - level * 1.5; + const items = useMemo(() => { + const r = rng(seed); + const pad = shuffle(r, ITEMS.filter((x) => x.padded)).slice(0, 4); + const ok = shuffle(r, ITEMS.filter((x) => !x.padded)).slice(0, 4); + return shuffle(r, [...pad, ...ok]); + }, [seed]); + const total = Math.round(perItem * items.length + 2); + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [i, setI] = useState(0); + const [right, setRight] = useState(0); + const [saved, setSaved] = useState(0); + const [final, setFinal] = useState(0); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + + const finish = (ok: number) => { + // 沒審到的項目算審錯 + const s = clamp((ok / items.length) * 100, 0, 100); + setFinal(s); + setPhase("done"); + if (s >= 70) sfx.applause(); + else if (s < 40) sfx.ooh(); + }; + const left = useCountdown(total, phase === "play", () => finish(right)); + + const decide = (cut: boolean) => { + const it = items[i]; + if (!it) return; + const ok = cut === it.padded; + const nextRight = right + (ok ? 1 : 0); + setRight(nextRight); + if (cut && it.padded) { + setSaved((v) => v + 1); + sfx.stamp(); + doShake("small"); + pop("刪得好!", "boom", 50, 34); + } else if (cut && !it.padded) { + sfx.bad(); + doShake("large"); + pop("這個不能刪!", "bad", 50, 34); + } else if (!cut && it.padded) { + sfx.bad(); + pop("浮編過關了…", "bad", 50, 34); + } else { + sfx.paper(); + pop("通過", "good", 50, 34); + } + if (i + 1 >= items.length) finish(nextRight); + else setI(i + 1); + }; + + const it = items[i]; + return ( + } + phase={phase} + onStart={() => setPhase("play")} + score={final} + verdict={final >= 75 ? `${characterName}把關預算,替市庫省下一筆。` : final >= 45 ? "大致有把關,還有幾筆看走眼。" : "審預算被說放水,公民團體點名批評。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+ +
+ + 第 {Math.min(i + 1, items.length)}/{items.length} 項 + + + 刪掉浮編 {saved} 筆 + +
+ {it && ( +
+ 預算書 + {it.name} + {it.amount} +
+ )} +
+ + +
+ +
+
+ ); +} diff --git a/web/src/game/career/term/InterpellationGame.tsx b/web/src/game/career/term/InterpellationGame.tsx new file mode 100644 index 0000000..15e07e1 --- /dev/null +++ b/web/src/game/career/term/InterpellationGame.tsx @@ -0,0 +1,197 @@ +import { BarChart3, Camera, FileText, Mic, ScrollText, type LucideIcon } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { Avatar, avatarFromSeed } from "../../art/Avatar.tsx"; +import { sfx } from "../../audio/sfx.ts"; +import { GameShell, Pops, usePops, useShake } from "./Shell.tsx"; +import { clamp, rng, shuffle } from "./rng.ts"; +import type { TermGameProps } from "./types.ts"; + +/** + * 質詢:虛構的部長、局長在台上一句一句回答,有些話是「破綻」(和事實不合的說法)。 + * 破綻出現時打出對的證據卡(預算書、公文、現場照片、數據)就得分;客套話時亂打會扣分。 + * 官員都是虛構職位,不對應真人。 + */ + +type Evidence = "budget" | "memo" | "photo" | "data"; + +const EVIDENCE: Record = { + budget: { label: "預算書", Icon: ScrollText }, + memo: { label: "公文", Icon: FileText }, + photo: { label: "現場照片", Icon: Camera }, + data: { label: "數據", Icon: BarChart3 }, +}; + +interface Line { + text: string; + /** 破綻要用哪一張證據;客套話是 null */ + flaw: Evidence | null; +} + +interface Official { + title: string; + topic: string; + flaws: Line[]; +} + +const FLUFF = ["謝謝委員關心,我們非常重視。", "這部分我們會持續跟地方溝通。", "委員的建議我們回去研究。", "這個問題很複雜,需要時間。", "我們一直都很努力。", "請委員給我們一點時間。"]; + +const OFFICIALS: readonly Official[] = [ + { + title: "交通部長", + topic: "捷運延伸線", + flaws: [ + { text: "這條線的經費早就編好了。", flaw: "budget" }, + { text: "工地現在已經全面復工。", flaw: "photo" }, + { text: "每天搭乘人數超過十萬人次。", flaw: "data" }, + { text: "我們從來沒收到地方的陳情。", flaw: "memo" }, + ], + }, + { + title: "衛福部長", + topic: "長照據點", + flaws: [ + { text: "長照據點已經普及到每一個里。", flaw: "data" }, + { text: "人力缺口的預算去年就補足了。", flaw: "budget" }, + { text: "據點的設備都是全新的。", flaw: "photo" }, + { text: "我們早就發文請各縣市改善。", flaw: "memo" }, + ], + }, + { + title: "教育部長", + topic: "老舊校舍補強", + flaws: [ + { text: "老舊校舍都完成補強了。", flaw: "photo" }, + { text: "補強經費一毛都沒有少。", flaw: "budget" }, + { text: "家長滿意度高達九成。", flaw: "data" }, + { text: "公文寫得很清楚,明年才要做。", flaw: "memo" }, + ], + }, + { + title: "環境部長", + topic: "工業區空污", + flaws: [ + { text: "空氣品質一年比一年好。", flaw: "data" }, + { text: "改善經費都已經撥下去了。", flaw: "budget" }, + { text: "那幾間工廠我們都稽查過了。", flaw: "photo" }, + { text: "地方從來沒有反映過這件事。", flaw: "memo" }, + ], + }, +]; + +export function InterpellationGame({ seed, level, characterName, onFinish }: TermGameProps) { + const script = useMemo(() => { + const r = rng(seed); + const pair = shuffle(r, OFFICIALS).slice(0, 2); + return pair.map((o, k) => { + const fluff = shuffle(r, FLUFF).slice(0, 4).map((text) => ({ text, flaw: null }) as Line); + return { ...o, face: avatarFromSeed(`official-${seed}-${k}`, { female: r() < 0.4 }), lines: shuffle(r, [...o.flaws, ...fluff]) }; + }); + }, [seed]); + const lineMs = Math.round(3400 - level * 1100); + const totalFlaws = script.reduce((a, o) => a + o.lines.filter((l) => l.flaw).length, 0); + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [o, setO] = useState(0); + const [k, setK] = useState(0); + const [hits, setHits] = useState(0); + const [wrong, setWrong] = useState(0); + const [sweat, setSweat] = useState(0); + const [final, setFinal] = useState(0); + const answered = useRef(new Set()); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + const score = (h: number, w: number) => clamp((h / Math.max(1, totalFlaws)) * 100 - w * 6, 0, 100); + + useEffect(() => { + if (phase !== "play") return; + const t = setTimeout(() => { + const official = script[o]!; + if (k + 1 < official.lines.length) setK(k + 1); + else if (o + 1 < script.length) { + setO(o + 1); + setK(0); + setSweat(0); + sfx.gong(); + } else { + const s = score(hits, wrong); + setFinal(s); + setPhase("done"); + if (s >= 70) sfx.applause(); + } + }, lineMs); + return () => clearTimeout(t); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [phase, o, k]); + + const official = script[o]!; + const line = official.lines[k]!; + const key = `${o}-${k}`; + + const use = (e: Evidence) => { + if (answered.current.has(key)) return; + answered.current.add(key); + if (line.flaw === e) { + setHits((h) => h + 1); + setSweat((x) => x + 1); + sfx.stamp(); + sfx.combo(hits); + doShake("large"); + pop("破綻!", "boom", 40 + Math.random() * 20, 26); + } else { + setWrong((w) => w + 1); + sfx.bad(); + doShake("small"); + pop(line.flaw ? "證據不對" : "委員別鬧了", "bad", 40 + Math.random() * 20, 26); + } + }; + + return ( + } + phase={phase} + onStart={() => { + answered.current.clear(); + setPhase("play"); + }} + score={final} + verdict={final >= 75 ? `${characterName}的質詢上了晚間新聞,官員冒汗的畫面被瘋傳。` : final >= 45 ? "有幾個問題問到重點。" : "這次質詢被說準備不夠。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+
+
= 2 ? " is-sweating" : ""}`}> + + + {official.title} + + {sweat > 0 && {"💧".repeat(Math.min(3, sweat))}} +
+
+ + 質詢主題:{official.topic}・第 {o + 1}/{script.length} 位 + +

「{line.text}」

+ +
+
+
+ 破綻 {hits}/{totalFlaws}・失誤 {wrong} +
+
+ {(Object.keys(EVIDENCE) as Evidence[]).map((e) => { + const { label, Icon } = EVIDENCE[e]; + return ( + + ); + })} +
+ +
+
+ ); +} diff --git a/web/src/game/career/term/PetitionGame.tsx b/web/src/game/career/term/PetitionGame.tsx new file mode 100644 index 0000000..8d05195 --- /dev/null +++ b/web/src/game/career/term/PetitionGame.tsx @@ -0,0 +1,187 @@ +import { MessageSquareHeart } from "lucide-react"; +import { useMemo, useState } from "react"; +import { Avatar, avatarFromSeed } from "../../art/Avatar.tsx"; +import { sfx } from "../../audio/sfx.ts"; +import { GameShell, Pops, TimerBar, useCountdown, usePops, useShake } from "./Shell.tsx"; +import { clamp, rng, shuffle } from "./rng.ts"; +import type { TermGameProps } from "./types.ts"; + +/** + * 里長陳情:里民一個一個來,挑處理方式。每種方式花時間或人情,處理得當里民滿意。 + * 颱風版(縣市長任期):積水、倒樹、停電,挑救災方式。 + */ + +interface Way { + id: string; + label: string; + hint: string; + hours: number; + favor: number; +} + +interface Petition { + who: string; + text: string; + /** 每種處理方式的效果:2 很好、1 還可以、0 沒用、−1 弄巧成拙 */ + quality: Record; +} + +const NORMAL_WAYS: readonly Way[] = [ + { id: "self", label: "親自處理", hint: "2 小時", hours: 2, favor: 0 }, + { id: "office", label: "轉給區公所", hint: "1 小時", hours: 1, favor: 0 }, + { id: "councilor", label: "找議員幫忙", hint: "1 小時・人情 1", hours: 1, favor: 1 }, + { id: "calm", label: "先安撫一下", hint: "半小時", hours: 0.5, favor: 0 }, +]; + +const TYPHOON_WAYS: readonly Way[] = [ + { id: "crew", label: "派志工清理", hint: "2 小時", hours: 2, favor: 0 }, + { id: "office", label: "通報公所", hint: "1 小時", hours: 1, favor: 0 }, + { id: "fund", label: "動用預備金", hint: "預算 1", hours: 0.5, favor: 1 }, + { id: "visit", label: "親自巡視", hint: "1 小時", hours: 1, favor: 0 }, +]; + +const NORMAL: readonly Petition[] = [ + { who: "巷口早餐店老闆", text: "路燈壞了快一個月,晚上收攤都摸黑。", quality: { office: 2, self: 1, councilor: 0, calm: -1 } }, + { who: "三樓的阿嬤", text: "隔壁的狗每天半夜一直叫,睡不著。", quality: { self: 2, calm: 1, office: 0, councilor: -1 } }, + { who: "上班族爸爸", text: "學校旁邊每天都有人違停,小孩過馬路好危險。", quality: { councilor: 2, office: 1, self: 1, calm: -1 } }, + { who: "公寓主委", text: "垃圾車改時間了,大家都追不到。", quality: { office: 2, councilor: 1, self: 0, calm: 0 } }, + { who: "社區媽媽", text: "公園的溜滑梯壞了,小朋友差點受傷。", quality: { office: 2, self: 1, councilor: 1, calm: -1 } }, + { who: "退休的老師", text: "想在活動中心開書法班,可以借場地嗎?", quality: { self: 2, calm: 1, office: 0, councilor: 0 } }, + { who: "兩位吵架的鄰居", text: "為了樓梯間的鞋櫃吵起來,要你評評理。", quality: { calm: 2, self: 1, office: -1, councilor: -1 } }, + { who: "菜市場攤商", text: "排水溝堵住,一下雨整條街都淹水。", quality: { councilor: 2, office: 1, self: 1, calm: -1 } }, + { who: "獨居的阿公", text: "冰箱壞了,不知道找誰修。", quality: { self: 2, calm: 1, office: 0, councilor: 0 } }, + { who: "國中生", text: "想在里辦公室旁邊辦一場街舞比賽。", quality: { self: 2, calm: 1, councilor: 0, office: 0 } }, +]; + +const TYPHOON: readonly Petition[] = [ + { who: "地下室的住戶", text: "地下室進水,車子快泡水了!", quality: { crew: 2, fund: 1, office: 1, visit: 0 } }, + { who: "騎機車的外送員", text: "路中間倒了一棵大樹,整條路過不去。", quality: { office: 2, crew: 1, fund: 0, visit: -1 } }, + { who: "老社區的住戶", text: "停電一整天了,長輩的氧氣機不能用。", quality: { fund: 2, office: 1, visit: 1, crew: 0 } }, + { who: "山邊的農家", text: "後山有土石滑下來,好擔心。", quality: { visit: 2, office: 1, crew: 0, fund: 0 } }, + { who: "學校警衛", text: "操場積水,明天能不能上課?", quality: { office: 2, visit: 1, crew: 1, fund: 0 } }, + { who: "超市店長", text: "店裡的東西泡水了,想知道有沒有補助。", quality: { fund: 2, visit: 1, office: 1, crew: 0 } }, + { who: "社區志工隊長", text: "大家都想幫忙,但不知道從哪裡開始。", quality: { crew: 2, visit: 1, office: 0, fund: 0 } }, +]; + +const GOOD = ["里民滿意!", "處理得漂亮!", "大家按讚!"]; +const BAD = ["里民搖頭…", "越弄越糟…", "被唸了一頓…"]; + +export function PetitionGame({ seed, level, characterName, onFinish, variant = "normal" }: TermGameProps & { variant?: "normal" | "typhoon" }) { + const typhoon = variant === "typhoon"; + const ways = typhoon ? TYPHOON_WAYS : NORMAL_WAYS; + const total = 45; + const queue = useMemo(() => { + const r = rng(seed); + const pool = shuffle(r, typhoon ? TYPHOON : NORMAL); + return pool.slice(0, 5 + Math.round(level * 2)).map((p, i) => ({ ...p, face: avatarFromSeed(`petition-${seed}-${i}`) })); + }, [seed, level, typhoon]); + const [phase, setPhase] = useState<"intro" | "play" | "done">("intro"); + const [i, setI] = useState(0); + const [hours, setHours] = useState(8); + const [favor, setFavor] = useState(2); + const [sum, setSum] = useState(0); + const [mood, setMood] = useState(50); + const [shake, doShake] = useShake(); + const [pops, pop] = usePops(); + const [final, setFinal] = useState(0); + + const finish = (s: number, handled: number) => { + // 沒處理到的陳情算弄巧成拙 + const unhandled = queue.length - handled; + const raw = s - unhandled; + const score = clamp(((raw + queue.length) / (3 * queue.length)) * 100, 0, 100); + setFinal(score); + setPhase("done"); + if (score >= 70) sfx.applause(); + else if (score < 40) sfx.ooh(); + }; + const left = useCountdown(total, phase === "play", () => finish(sum, i)); + + const choose = (w: Way) => { + const p = queue[i]!; + const q = p.quality[w.id] ?? 0; + setHours((h) => h - w.hours); + setFavor((f) => f - w.favor); + const nextSum = sum + q; + setSum(nextSum); + setMood((m) => clamp(m + q * 9, 0, 100)); + if (q >= 2) { + sfx.good(); + pop(GOOD[i % GOOD.length]!, "good", 50, 30); + } else if (q === 1) { + sfx.click(); + pop("還可以", "good", 50, 30); + } else if (q < 0) { + sfx.bad(); + doShake("small"); + pop(BAD[i % BAD.length]!, "bad", 50, 30); + } else { + sfx.click(); + pop("沒什麼用", "bad", 50, 30); + } + // 時間或人情用完、下一件已經沒有辦法處理:直接收工,剩下的算沒處理 + const h = hours - w.hours; + const f = favor - w.favor; + const canNext = ways.some((x) => x.hours <= h && x.favor <= f); + if (i + 1 >= queue.length || !canNext) finish(nextSum, i + 1); + else setI(i + 1); + }; + + const p = queue[i]; + return ( + } + phase={phase} + onStart={() => setPhase("play")} + score={final} + verdict={final >= 75 ? `${characterName}的服務口碑傳遍大街小巷。` : final >= 45 ? "大部分的事都有處理,還有進步空間。" : "很多陳情沒處理好,里民有點失望。"} + onContinue={() => onFinish(Math.round(final))} + shake={shake} + > +
+ +
+ + 時間 {hours.toFixed(1)} 小時 + + + {typhoon ? "預算" : "人情"} {favor} + + + 滿意度 + + + + + + {Math.min(i + 1, queue.length)} / {queue.length} + +
+ {p && ( +
+ +
+ {p.who} +

「{p.text}」

+
+
+ )} +
+ {ways.map((w) => ( + + ))} +
+ +
+
+ ); +} diff --git a/web/src/game/career/term/Shell.tsx b/web/src/game/career/term/Shell.tsx new file mode 100644 index 0000000..8b73880 --- /dev/null +++ b/web/src/game/career/term/Shell.tsx @@ -0,0 +1,176 @@ +import { Play, Timer } from "lucide-react"; +import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import { getSettings } from "../../audio/settings.ts"; +import { sfx } from "../../audio/sfx.ts"; +import { reducedMotion } from "./rng.ts"; +import "./term.css"; + +/** 任期畫面提供的「怎麼玩」步驟(TermScreen 包在每個小遊戲外面);沒有就只顯示一行規則 */ +export const TermHowTo = createContext<{ steps: string[]; reward: string } | null>(null); + +/** + * 小遊戲外框:開頭的怎麼玩(一二三步+做得好有什麼)+開始按鈕 → 遊戲 → 分數。 + * 震動(重擊)照 game-feel 分輕重兩級,設定關掉或減少動態時不震動。 + */ +export function GameShell({ + title, + rule, + icon, + phase, + onStart, + score, + verdict, + onContinue, + shake, + children, +}: { + title: string; + rule: string; + icon: ReactNode; + phase: "intro" | "play" | "done"; + onStart: () => void; + score: number; + verdict: string; + onContinue: () => void; + shake: "" | "small" | "large"; + children: ReactNode; +}) { + const howto = useContext(TermHowTo); + return ( +
+
+ + {icon} + +

{title}

+
+ {phase === "intro" && ( +
+ {howto ? ( + <> +
    + {howto.steps.map((step, i) => ( +
  1. {step}
  2. + ))} +
+

{howto.reward}

+ + ) : ( +

{rule}

+ )} + +
+ )} + {phase === "play" && children} + {phase === "done" && ( +
+ + {Math.round(score)} + 分 + +

{verdict}

+ +
+ )} +
+ ); +} + +/** 小遊戲的震動:輕(小失誤)、重(大成功或大失誤) */ +export function useShake(): ["" | "small" | "large", (level: "small" | "large") => void] { + const [cls, setCls] = useState<"" | "small" | "large">(""); + const timer = useRef | null>(null); + useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); + return [ + cls, + (level) => { + if (!getSettings().shake || reducedMotion()) return; + if (timer.current) clearTimeout(timer.current); + setCls(""); + requestAnimationFrame(() => setCls(level)); + timer.current = setTimeout(() => setCls(""), level === "large" ? 420 : 260); + }, + ]; +} + +/** 倒數計時:running 時每 100ms 減一次,到 0 呼叫 onEnd */ +export function useCountdown(seconds: number, running: boolean, onEnd: () => void): number { + const [left, setLeft] = useState(seconds); + const end = useRef(onEnd); + end.current = onEnd; + useEffect(() => { + if (!running) return; + const started = performance.now(); + const base = left; + const t = setInterval(() => { + const next = Math.max(0, base - (performance.now() - started) / 1000); + setLeft(next); + if (next <= 0) { + clearInterval(t); + end.current(); + } + }, 100); + return () => clearInterval(t); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [running]); + return left; +} + +export function TimerBar({ left, total }: { left: number; total: number }) { + const warn = left <= Math.min(8, total * 0.2); + return ( +
+ + + + + {Math.ceil(left)} +
+ ); +} + +/** 漫畫效果字(推!擠!破綻!),一段時間後自己消失 */ +export interface Pop { + key: number; + text: string; + tone: "good" | "bad" | "boom"; + x: number; + y: number; +} + +export function usePops(): [Pop[], (text: string, tone: Pop["tone"], x?: number, y?: number) => void] { + const [pops, setPops] = useState([]); + const id = useRef(0); + return [ + pops, + (text, tone, x = 50, y = 40) => { + const key = ++id.current; + setPops((list) => [...list.slice(-4), { key, text, tone, x, y }]); + setTimeout(() => setPops((list) => list.filter((p) => p.key !== key)), 900); + }, + ]; +} + +export function Pops({ pops }: { pops: readonly Pop[] }) { + return ( + <> + {pops.map((p) => ( + + {p.text} + + ))} + + ); +} diff --git a/web/src/game/career/term/TermPreview.tsx b/web/src/game/career/term/TermPreview.tsx new file mode 100644 index 0000000..4dbd4e9 --- /dev/null +++ b/web/src/game/career/term/TermPreview.tsx @@ -0,0 +1,51 @@ +import { useState } from "react"; +import { TermScreen } from "./TermScreen.tsx"; +import type { TermResult, TermScreenProps } from "./types.ts"; +import "./term.css"; + +/** 開發用預覽(#/term):挑任期、填名字,玩完看回傳的結果 */ + +const OFFICES: Record = { 1: "里長", 2: "議員", 3: "立委", 4: "縣市長" }; + +export function TermPreview() { + const [stage, setStage] = useState(1); + const [name, setName] = useState("林小安"); + const [run, setRun] = useState(null); + const [result, setResult] = useState(null); + + if (run !== null && !result) + return ( +
+ +
+ ); + + return ( +
+

任期小遊戲預覽

+
+ {([1, 2, 3, 4] as const).map((s) => ( + + ))} +
+ + + {result &&
{JSON.stringify(result, null, 2)}
} +
+ ); +} diff --git a/web/src/game/career/term/TermScreen.tsx b/web/src/game/career/term/TermScreen.tsx new file mode 100644 index 0000000..b9ec37e --- /dev/null +++ b/web/src/game/career/term/TermScreen.tsx @@ -0,0 +1,252 @@ +import { ArrowRight, Award, Check, ClipboardList, Coins, Megaphone, Newspaper, Sparkles } from "lucide-react"; +import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { sfx } from "../../audio/sfx.ts"; +import { BillGame } from "./BillGame.tsx"; +import { BrawlGame } from "./BrawlGame.tsx"; +import { BudgetGame } from "./BudgetGame.tsx"; +import { InterpellationGame } from "./InterpellationGame.tsx"; +import { PetitionGame } from "./PetitionGame.tsx"; +import { clamp } from "./rng.ts"; +import { TermHowTo } from "./Shell.tsx"; +import type { Ability, TermGameProps, TermResult, TermScreenProps } from "./types.ts"; +import "./term.css"; + +/** + * 一段任期:依職位串幾個小遊戲,最後顯示任期回顧(虛構的新聞標題、政績點、能力經驗、開局加成)。 + * 1 里長:陳情 ×2;2 議員:質詢+審預算;3 立委:講解法條+質詢+搶主席台;4 縣市長:分預算+颱風救災。 + */ + +type GameId = "petition" | "petition2" | "interpellation" | "review" | "bill" | "brawl" | "mayor" | "typhoon"; + +interface Step { + id: GameId; + label: string; + abilities: [Ability, Ability]; + render: (p: TermGameProps) => ReactNode; +} + +const STEPS: Record = { + petition: { id: "petition", label: "里民陳情", abilities: ["organization", "integrity"], render: (p) => }, + petition2: { id: "petition2", label: "里民陳情(下半年)", abilities: ["organization", "integrity"], render: (p) => }, + interpellation: { id: "interpellation", label: "質詢", abilities: ["eloquence", "media"], render: (p) => }, + review: { id: "review", label: "審預算", abilities: ["finance", "integrity"], render: (p) => }, + bill: { id: "bill", label: "講解法條", abilities: ["eloquence", "organization"], render: (p) => }, + brawl: { id: "brawl", label: "搶主席台", abilities: ["organization", "media"], render: (p) => }, + mayor: { id: "mayor", label: "分配預算", abilities: ["finance", "integrity"], render: (p) => }, + typhoon: { id: "typhoon", label: "颱風救災", abilities: ["organization", "integrity"], render: (p) => }, +}; + +/** 每個小遊戲開始前的「怎麼玩」:一二三步(使用者說看不懂任期要做什麼) */ +const HOWTO: Record = { + petition: ["里民一個一個來陳情,卡片上寫他要什麼。", "你一天只有 8 小時、2 個人情:點一個處理方式,每種方式花的時間和人情不一樣。", "45 秒內處理得越多、越妥當,分數越高;沒處理到的會扣分。"], + petition2: ["下半年的陳情更多更急,規則一樣。", "先看清楚時間和人情夠不夠,再決定怎麼處理。", "處理得越多、越妥當,分數越高。"], + interpellation: ["部長會一句一句回答,其中有幾句是破綻(數字對不上、推卸責任)。", "聽到破綻時,馬上點下面對的證據卡:預算書、公文、現場照片、數據。", "打中破綻加分、打錯會扣分;越後面的任期部長講越快。"], + review: ["預算項目一個一個出來,有的是必要的,有的是浮報的。", "看說明判斷:浮報的按「刪」,必要的按「過」。", "判斷對的比例就是分數。"], + bill: ["法案被拆成 4 段條文:先把每段拖到(或點選)正確的第一到第四條。", "再幫每一條選對的白話說明,讓委員聽得懂。", "放對、選對,議場的支持席次會亮起來,16 席過半就成功。"], + brawl: ["表決前的鬧劇(沒有人會受傷):連點「推!」把對方往後推。", "搶飛出來的麥克風;舉標語可以讓對方愣住一下。", "把控制條撐在 70 以上,累積 10 秒就贏。"], + mayor: ["10 億預算用 +/- 分給交通、長照、托育、治安、觀光。", "四個分區的滿意度會跟著變;15 秒後颱風來,要挪 2 億救災。", "四區平均滿意度和最不滿的那一區,決定分數。"], + typhoon: ["颱風夜,災情一件一件回報進來。", "用有限的人力和時間,點選怎麼處理每一件災情。", "處理得越快、越妥當,分數越高。"], +}; +const HOWTO_REWARD = "做得好:拿到生涯經驗(升級可以加能力)、政績點(蓋政策島)、下一場選舉的開局聲勢和資金。"; + +/** 任期的經驗(生涯升級用):各任期的基準 × 平均分數 */ +const TERM_EXP: Record = { 1: 30, 2: 50, 3: 75, 4: 110 }; + +const PLAN: Record = { + 1: ["petition", "petition2"], + 2: ["interpellation", "review"], + 3: ["bill", "interpellation", "brawl"], + 4: ["mayor", "typhoon"], +}; + +const LEVEL: Record = { 1: 0.1, 2: 0.35, 3: 0.6, 4: 0.85 }; + + +/** 每個遊戲的回顧標題:[高分, 低分](全部虛構) */ +const HEADLINES: Record string, (n: string, o: string) => string]> = { + petition: [(n, o) => `${o}${n}服務處燈火通明,里民:有事找${n}就對了`, (n) => `陳情案件堆積,${n}被里民在群組點名`], + petition2: [(n) => `巷口路燈、公園溜滑梯都修好了,${n}獲里民送匾額`, (n) => `里民抱怨反映多次沒下文,${n}:會再加強`], + interpellation: [(n) => `${n}質詢一針見血,官員當場改口`, (n) => `質詢被嫌準備不足,${n}:下次會更好`], + review: [(n) => `${n}揪出浮編預算,替市庫省下一筆`, (n) => `預算審查放水?${n}遭公民團體點名`], + bill: [(n) => `${n}主推法案三讀通過,條文白話好懂`, (n) => `${n}主推的法案卡在委員會`], + brawl: [(n) => `議場推擠鬧劇,${n}所屬黨團搶下主席台`, (n) => `搶主席台失利,${n}所屬黨團只能場外喊話`], + mayor: [(n) => `${n}端出年度預算,四區都說讚`, () => `預算分配不均,部分分區鄉親不滿`], + typhoon: [(n) => `颱風夜坐鎮應變中心,${n}救災速度獲肯定`, (n) => `災後清理慢半拍,${n}挨批`], +}; + +/** 分數 ≥40 得 1 點經驗、≥70 得 2、≥90 得 3 */ +const xpFor = (s: number): number => (s >= 90 ? 3 : s >= 70 ? 2 : s >= 40 ? 1 : 0); + +export function termResult(stage: TermScreenProps["stage"], characterName: string, office: string, scores: Partial>): TermResult { + const ids = PLAN[stage].filter((id) => scores[id] !== undefined); + const avg = ids.length ? ids.reduce((a, id) => a + scores[id]!, 0) / ids.length : 0; + const xp: Partial> = {}; + for (const id of ids) for (const a of STEPS[id].abilities) xp[a] = Math.min(3, (xp[a] ?? 0) + xpFor(scores[id]!)); + for (const a of Object.keys(xp) as Ability[]) if (!xp[a]) delete xp[a]; + const sorted = [...ids].sort((a, b) => scores[b]! - scores[a]!); + const best = sorted[0]; + const worst = sorted[sorted.length - 1]; + const points = Math.round(2 + (avg / 100) * 8); + const lines: string[] = []; + if (best && scores[best]! >= 55) lines.push(HEADLINES[best][0](characterName, office)); + for (const id of sorted.slice(1)) if (scores[id]! >= 70 && lines.length < 2) lines.push(HEADLINES[id][0](characterName, office)); + if (worst && worst !== best && scores[worst]! < 45) lines.push(HEADLINES[worst][1](characterName, office)); + if (best && lines.length === 0) lines.push(HEADLINES[best][scores[best]! >= 45 ? 0 : 1](characterName, office)); + lines.push(avg >= 70 ? `${office}任期滿意度創新高,${characterName}下一步動向受矚目` : avg >= 45 ? `${characterName}${office}任期平穩落幕,政績點 ${points} 點` : `${characterName}${office}任期評價兩極,選情恐受影響`); + return { + stage, + scores: Object.fromEntries(ids.map((id) => [id, Math.round(scores[id]!)])), + points, + xp, + exp: Math.round((TERM_EXP[stage] * avg) / 100), + headlines: lines.slice(0, 4), + bonus: { momentum: avg >= 80 ? 2 : avg >= 55 ? 1 : 0, money: Math.min(300, Math.round(avg * 3)) }, + }; +} + +export function TermScreen({ stage, characterName, office, seed, onDone }: TermScreenProps) { + const plan = PLAN[stage]; + const [k, setK] = useState(0); + const [briefed, setBriefed] = useState(false); + const [scores, setScores] = useState>>({}); + const result = useMemo(() => (k >= plan.length ? termResult(stage, characterName, office, scores) : null), [k, plan.length, stage, characterName, office, scores]); + + useEffect(() => { + if (!result) return; + sfx.drumroll(); + }, [result]); + + const step = plan[k] ? STEPS[plan[k]!] : null; + return ( +
+
+ {characterName}的任期 +

{office}任期

+
    + {plan.map((id, n) => ( +
  1. + {n < k ? : {n + 1}} + {STEPS[id].label} +
  2. + ))} +
  3. + {plan.length + 1}任期回顧 +
  4. +
+
+ {!briefed && setBriefed(true)} />} + {briefed && step && ( + + {step.render({ + seed: (seed + k * 7919) >>> 0, + level: LEVEL[stage], + characterName, + onFinish: (s) => { + setScores((m) => ({ ...m, [step.id]: clamp(s, 0, 100) })); + setK((n) => n + 1); + }, + })} + + )} + {result && onDone(result)} />} +
+ ); +} + +/** 任期開始前的任務簡報:這段任期要做哪幾件事、各怎麼玩、做好有什麼好處 */ +function TermBriefing({ office, plan, onStart }: { office: string; plan: readonly GameId[]; onStart: () => void }) { + return ( +
+

+ 恭喜當選{office}!接下來是一段任期 +

+

任期要處理 {plan.length} 件事,每件 30–50 秒,玩法如下。做得好,下一場選舉會更好打。

+
    + {plan.map((id, n) => ( +
  1. + + {n + 1}. {STEPS[id].label} + + {HOWTO[id][0]} + {HOWTO[id][1]} +
  2. + ))} +
+
+ + 生涯經驗:升級拿技能點,自己加能力 + + + 政績點:回政策島蓋建築 + + + 下一場開局:聲勢和資金 + +
+ +
+ ); +} + +function TermReview({ result, office, onDone }: { result: TermResult; office: string; onDone: () => void }) { + return ( +
+

+ {office}任期回顧 +

+
    + {result.headlines.map((h, n) => ( +
  • + {h} +
  • + ))} +
+
+
+ + 政績點 + {result.points} +
+
+ + 開局聲勢 + +{result.bonus.momentum} +
+
+ + 開局資金 + + +{result.bonus.money} + 萬 + +
+
+
+ + 生涯經驗 + +{result.exp} +
+ +
+ ); +} diff --git a/web/src/game/career/term/rng.ts b/web/src/game/career/term/rng.ts new file mode 100644 index 0000000..e24231a --- /dev/null +++ b/web/src/game/career/term/rng.ts @@ -0,0 +1,24 @@ +/** 任期小遊戲的亂數:mulberry32,同一個種子每次內容一樣 */ +export function rng(seed: number): () => number { + let a = seed >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export function shuffle(r: () => number, items: readonly T[]): T[] { + const out = [...items]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(r() * (i + 1)); + [out[i], out[j]] = [out[j]!, out[i]!]; + } + return out; +} + +export const clamp = (x: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, x)); + +export const reducedMotion = (): boolean => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; diff --git a/web/src/game/career/term/term.css b/web/src/game/career/term/term.css new file mode 100644 index 0000000..51bfc87 --- /dev/null +++ b/web/src/game/career/term/term.css @@ -0,0 +1,472 @@ +/* + * 任期小遊戲(tm-):台式競選文宣 × 立體桌遊。粗黑框、錯位硬陰影、螢光黃重點、圈選章紅。 + * 手機直式優先,按鈕至少 44px。減少動態效果時只留淡入淡出。 + */ + +.tm-screen, .tm-preview { box-sizing: border-box; width: 100%; display: grid; gap: 14px; max-width: 560px; margin: 0 auto; padding: 12px 16px 32px; color: var(--ink); } +.tm-preview > .tm-screen { padding: 0; } +.tm-preview h2 { margin: 8px 0 0; font-family: var(--font-serif); font-size: 26px; } + +/* ── 外框 ── */ +.tm-game { + position: relative; + background: var(--surface); + border: 3px solid var(--ink); + border-radius: 16px; + box-shadow: 4px 4px 0 var(--shadow-ink); + padding: 14px; + display: grid; + gap: 12px; + overflow: hidden; +} +.tm-game-head { display: flex; align-items: center; gap: 10px; } +.tm-game-head h3 { margin: 0; font-family: var(--font-serif); font-size: 22px; letter-spacing: 0.04em; } +.tm-game-icon { + display: inline-grid; + place-items: center; + width: 38px; + height: 38px; + border: 2px solid var(--ink); + border-radius: 10px; + background: var(--signal); + color: var(--signal-ink, var(--ink)); + box-shadow: 2px 2px 0 var(--shadow-ink); + transform: rotate(-4deg); +} +.tm-intro, .tm-done { display: grid; gap: 14px; justify-items: center; text-align: center; padding: 10px 4px 6px; animation: tm-in 260ms var(--ease-out) both; } +.tm-intro p, .tm-done p { margin: 0; font-size: 16px; line-height: 1.6; text-wrap: pretty; } +.tm-start, .tm-done .btn, .tm-next { min-height: 48px; min-width: 160px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; } +.tm-done-score { display: inline-flex; align-items: baseline; gap: 4px; font-family: var(--font-num); animation: tm-stamp-in 380ms var(--ease-out) both; } +.tm-done-score b { + font-size: 72px; + line-height: 1; + color: var(--stamp); + border: 4px solid var(--stamp); + border-radius: 14px; + padding: 2px 14px; + transform: rotate(-6deg); + display: inline-block; +} +.tm-done-score small { font-size: 20px; font-weight: 800; } + +.tm-play { position: relative; display: grid; gap: 12px; min-height: 340px; align-content: start; } + +/* ── 計時、資源、量表 ── */ +.tm-timer { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 8px; font-family: var(--font-num); font-weight: 800; } +.tm-timer b { font-size: 20px; min-width: 2ch; text-align: right; font-variant-numeric: tabular-nums; } +.tm-timer-track, .tm-meter, .tm-ctrl, .tm-alloc-bar { + position: relative; + display: block; + height: 12px; + border: 2px solid var(--ink); + border-radius: 999px; + background: var(--surface-2); + overflow: hidden; +} +.tm-timer-track > i, .tm-meter > i, .tm-ctrl > i, .tm-alloc-bar > i { + position: absolute; + inset: 0; + transform-origin: left center; + background: var(--signal); + transition: transform 120ms linear; +} +.tm-timer.is-warn { color: var(--stamp); } +.tm-timer.is-warn .tm-timer-track > i { background: var(--stamp); } +.tm-meter { display: inline-block; width: 64px; height: 10px; vertical-align: middle; margin-left: 6px; } +.tm-meter > i { background: var(--good); transition-duration: 300ms; } + +.tm-res { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 14px; color: var(--muted); } +.tm-res b { color: var(--ink); font-family: var(--font-num); font-size: 18px; margin: 0 2px; } + +/* ── 選項按鈕(陳情、白話說明、預覽) ── */ +.tm-choices { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.tm-choices-col { grid-template-columns: 1fr; } +.tm-choice, .tm-evi, .tm-article, .tm-step, .tm-sign, .tm-push, .tm-cut, .tm-pass { + min-height: 52px; + border: 2px solid var(--ink); + border-radius: 12px; + background: var(--surface); + color: var(--ink); + box-shadow: 3px 3px 0 var(--shadow-ink); + font: inherit; + cursor: pointer; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + user-select: none; + transition: transform 100ms var(--ease-out), box-shadow 100ms var(--ease-out), background-color 150ms ease, opacity 150ms ease; +} +.tm-choice { display: grid; gap: 2px; padding: 8px 10px; text-align: left; } +.tm-choice b { font-size: 16px; line-height: 1.35; } +.tm-choice small { color: var(--muted); font-family: var(--font-num); font-size: 13px; } +.tm-choice.is-on { background: var(--signal); color: var(--signal-ink, var(--ink)); } +:is(.tm-choice, .tm-evi, .tm-article, .tm-step, .tm-sign, .tm-push, .tm-cut, .tm-pass):active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +:is(.tm-choice, .tm-evi, .tm-article, .tm-step, .tm-sign, .tm-push, .tm-cut, .tm-pass):disabled { opacity: 0.4; box-shadow: none; cursor: default; } +@media (hover: hover) and (pointer: fine) { + :is(.tm-choice, .tm-evi, .tm-article, .tm-step, .tm-sign):hover:not(:disabled) { background: var(--signal); color: var(--signal-ink, var(--ink)); } +} + +/* ── 效果字(漫畫字) ── */ +.tm-pop { + position: absolute; + z-index: 5; + pointer-events: none; + translate: -50% -50%; + font-family: var(--font-serif); + font-weight: 900; + font-size: 26px; + white-space: nowrap; + padding: 2px 10px; + border: 2px solid var(--ink); + border-radius: 8px; + background: var(--surface); + box-shadow: 3px 3px 0 var(--shadow-ink); + animation: tm-pop 900ms var(--ease-out) both; +} +.tm-pop.is-good { background: var(--good); color: #fff; } +.tm-pop.is-bad { background: var(--surface-2); color: var(--stamp); font-size: 20px; } +.tm-pop.is-boom { background: var(--signal); color: var(--signal-ink, var(--ink)); font-size: 34px; transform: rotate(-6deg); } + +/* ── 陳情 ── */ +.tm-petition-card { + display: grid; + grid-template-columns: auto 1fr; + gap: 12px; + align-items: center; + padding: 12px; + border: 2px solid var(--ink); + border-radius: 14px; + background: var(--surface-2); + box-shadow: 3px 3px 0 var(--shadow-ink); + animation: tm-deal 280ms var(--ease-out) both; +} +.tm-petition-card b { font-size: 14px; color: var(--muted); } +.tm-petition-card p { margin: 4px 0 0; font-size: 17px; line-height: 1.5; font-weight: 700; } + +/* ── 質詢 ── */ +.tm-inter-stage { display: grid; grid-template-columns: auto 1fr; gap: 12px; align-items: start; } +.tm-official { position: relative; display: grid; justify-items: center; gap: 4px; } +.tm-official.is-sweating .avatar { animation: tm-wobble 600ms ease-in-out infinite; } +.tm-nameplate { + display: grid; + justify-items: center; + font-weight: 800; + font-size: 14px; + padding: 2px 8px; + background: var(--ink); + color: var(--surface); + border-radius: 6px; +} +.tm-nameplate small { font-size: 11px; font-weight: 500; opacity: 0.8; } +.tm-sweat { position: absolute; top: -4px; right: -8px; font-size: 18px; } +.tm-bubble { + position: relative; + display: grid; + gap: 6px; + padding: 12px 14px 16px; + border: 2px solid var(--ink); + border-radius: 14px; + background: var(--surface); + box-shadow: 3px 3px 0 var(--shadow-ink); + overflow: hidden; + animation: tm-in 220ms var(--ease-out) both; +} +.tm-bubble small { color: var(--muted); font-size: 12px; } +.tm-bubble p { margin: 0; font-size: 19px; line-height: 1.45; font-weight: 800; font-family: var(--font-serif); } +.tm-line-timer { position: absolute; left: 0; right: 0; bottom: 0; height: 5px; background: var(--signal); transform-origin: left; animation: tm-drain linear both; } +.tm-score-line { font-size: 14px; color: var(--muted); } +.tm-score-line b { color: var(--ink); font-family: var(--font-num); font-size: 18px; } +.tm-evidence { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.tm-evi { display: flex; align-items: center; justify-content: center; gap: 8px; min-height: 64px; font-size: 17px; background: var(--surface-2); } +.tm-evi:nth-child(odd) { transform: rotate(-1deg); } +.tm-evi:nth-child(even) { transform: rotate(1deg); } + +/* ── 講解法條 ── */ +.tm-seats { display: grid; justify-items: center; gap: 2px; } +.tm-seats svg { width: 100%; max-width: 300px; height: auto; } +.tm-seats circle { fill: var(--surface-2); stroke: var(--ink); stroke-width: 1.5; transition: fill 250ms ease; } +.tm-seats circle.is-lit { fill: var(--signal); } +.tm-seats-podium { fill: var(--ink); } +.tm-seats > b { font-family: var(--font-num); font-size: 28px; line-height: 1; } +.tm-seats > b small { font-size: 14px; color: var(--muted); margin-left: 4px; } +.tm-seats > b.is-pass { color: var(--good); } +.tm-articles { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; } +.tm-article { width: 100%; display: grid; gap: 2px; padding: 6px 2px; text-align: center; } +.tm-article b { font-size: 15px; } +.tm-article small { font-size: 11px; color: var(--muted); } +.tm-article.is-filled { background: var(--signal); color: var(--signal-ink, var(--ink)); opacity: 1; } +.tm-article.is-filled small { color: inherit; } +.tm-fragment { + padding: 12px 14px; + border: 2px dashed var(--ink); + border-radius: 12px; + background: var(--paper); + animation: tm-deal 240ms var(--ease-out) both; +} +.tm-fragment small { color: var(--muted); font-size: 12px; } +.tm-fragment p { margin: 4px 0 0; font-family: var(--font-news, var(--font-serif)); font-size: 17px; line-height: 1.6; } +.tm-ask { margin: 0; font-weight: 800; } + +/* ── 搶主席台 ── */ +.tm-brawl-floor { + position: relative; + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: end; + gap: 6px; + min-height: 170px; + padding: 12px 8px 10px; + border: 2px solid var(--ink); + border-radius: 14px; + background: linear-gradient(var(--surface-2) 62%, color-mix(in srgb, var(--board-wood, #b98a5a) 60%, var(--surface)) 62%); + overflow: hidden; +} +.tm-crowd { display: flex; flex-wrap: wrap; justify-content: center; gap: 2px; position: relative; } +.tm-crowd > span { flex-basis: 100%; text-align: center; font-size: 12px; font-weight: 800; } +.tm-crowd.is-us { animation: tm-shove 420ms ease-in-out infinite; } +.tm-crowd.is-them { animation: tm-shove 460ms ease-in-out infinite reverse; } +.tm-crowd.is-paused { animation: none; opacity: 0.55; } +.tm-crowd.is-paused::after { content: "愣住"; position: absolute; top: -6px; right: 0; font-size: 12px; font-weight: 800; background: var(--surface); border: 1.5px solid var(--ink); border-radius: 6px; padding: 0 4px; } +.tm-podium { + align-self: center; + display: grid; + place-items: center; + width: 82px; + height: 58px; + border: 3px solid var(--ink); + border-radius: 8px 8px 4px 4px; + background: var(--stamp); + color: #fff; + font-family: var(--font-serif); + font-weight: 900; + box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.tm-mic { + position: absolute; + z-index: 4; + translate: -50% -50%; + display: grid; + place-items: center; + width: 56px; + height: 56px; + border: 3px solid var(--ink); + border-radius: 50%; + background: var(--signal); + color: var(--ink); + box-shadow: 3px 3px 0 var(--shadow-ink); + cursor: pointer; + touch-action: manipulation; + animation: tm-mic 1600ms linear both; +} +.tm-ctrl { height: 20px; } +.tm-ctrl > i { background: var(--muted); transition-duration: 100ms; } +.tm-ctrl.is-hold > i { background: var(--signal); } +.tm-ctrl-line { position: absolute; top: -2px; bottom: -2px; width: 3px; background: var(--stamp); translate: -50% 0; } +.tm-brawl-actions { display: grid; grid-template-columns: 1fr 1.6fr; gap: 10px; } +.tm-sign { display: grid; justify-items: center; align-content: center; gap: 0; padding: 6px; } +.tm-sign b { font-size: 16px; } +.tm-sign small { font-size: 12px; color: var(--muted); font-family: var(--font-num); } +.tm-push { + min-height: 92px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + background: var(--stamp); + color: #fff; + font-family: var(--font-serif); + font-size: 34px; + font-weight: 900; + border-width: 3px; + box-shadow: 5px 5px 0 var(--shadow-ink); +} +.tm-push:active { transform: translate(3px, 3px) scale(0.98); box-shadow: 1px 1px 0 var(--shadow-ink); } + +/* ── 分預算 ── */ +.tm-typhoon { + display: grid; + grid-template-columns: auto 1fr auto; + align-items: center; + gap: 10px; + padding: 8px 10px; + border: 2px solid var(--ink); + border-radius: 12px; + background: var(--stamp); + color: #fff; + animation: tm-deal 280ms var(--ease-out) both; +} +.tm-typhoon > span { display: grid; gap: 0; font-size: 14px; } +.tm-typhoon b { font-size: 17px; } +.tm-typhoon.is-done { background: var(--good); } +.tm-typhoon .tm-step { color: var(--ink); } +.tm-alloc { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.tm-alloc li { display: grid; grid-template-columns: 3em 48px 1fr 48px; align-items: center; gap: 8px; } +.tm-alloc li > b { font-size: 16px; } +.tm-step { display: grid; place-items: center; width: 48px; min-height: 44px; padding: 0; } +.tm-alloc-bar { height: 26px; border-radius: 8px; } +.tm-alloc-bar > i { transition-duration: 180ms; transition-timing-function: var(--ease-out); } +.tm-alloc-bar > em { position: relative; display: block; text-align: center; line-height: 22px; font-style: normal; font-family: var(--font-num); font-weight: 800; font-size: 15px; } +.tm-districts { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } +.tm-district { + display: grid; + grid-template-columns: 1fr auto; + gap: 2px 6px; + align-items: center; + padding: 8px 10px; + border: 2px solid var(--ink); + border-radius: 10px; + background: var(--surface-2); + transition: background-color 250ms ease; +} +.tm-district small { grid-column: 1 / -1; font-size: 11px; color: var(--muted); } +.tm-district .tm-meter { width: 100%; margin: 0; } +.tm-district em { font-style: normal; font-family: var(--font-num); font-weight: 800; font-size: 18px; } +.tm-district.is-high { background: color-mix(in srgb, var(--good) 22%, var(--surface)); } +.tm-district.is-low { background: color-mix(in srgb, var(--stamp) 18%, var(--surface)); } +.tm-district.is-storm { border-style: dashed; } + +/* ── 審預算 ── */ +.tm-item { + position: relative; + display: grid; + gap: 6px; + justify-items: center; + text-align: center; + padding: 18px 14px; + border: 2px solid var(--ink); + border-radius: 14px; + background: var(--paper); + box-shadow: 4px 4px 0 var(--shadow-ink); + animation: tm-deal 240ms var(--ease-out) both; +} +.tm-item small { color: var(--muted); font-size: 12px; } +.tm-item b { font-family: var(--font-serif); font-size: 22px; line-height: 1.35; } +.tm-item em { font-style: normal; font-family: var(--font-num); font-size: 30px; font-weight: 800; color: var(--stamp); } +.tm-review-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.tm-cut, .tm-pass { min-height: 72px; display: flex; align-items: center; justify-content: center; gap: 8px; font-family: var(--font-serif); font-size: 26px; font-weight: 900; } +.tm-cut { background: var(--stamp); color: #fff; } +.tm-pass { background: var(--good); color: #fff; } + +/* ── 任期進度、回顧 ── */ +.tm-screen-head { display: grid; gap: 6px; } +.tm-screen-head small { color: var(--muted); font-weight: 700; } +.tm-screen-head h2 { margin: 0; font-family: var(--font-serif); font-size: 28px; letter-spacing: 0.04em; } +.tm-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; } +.tm-steps li { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 3px 10px 3px 4px; + border: 2px solid var(--line); + border-radius: 999px; + font-size: 13px; + font-weight: 700; + color: var(--muted); +} +.tm-steps li span { display: inline-grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; background: var(--surface-2); font-family: var(--font-num); } +.tm-steps li.is-now { border-color: var(--ink); background: var(--signal); color: var(--signal-ink, var(--ink)); } +.tm-steps li.is-done { border-color: var(--ink); color: var(--ink); padding-left: 8px; } +.tm-steps li.is-now span { background: var(--surface); color: var(--ink); } + +.tm-review-card { + display: grid; + gap: 14px; + padding: 16px; + border: 3px solid var(--ink); + border-radius: 16px; + background: var(--surface); + box-shadow: 4px 4px 0 var(--shadow-ink); + animation: tm-in 300ms var(--ease-out) both; +} +.tm-review-card h3 { display: flex; align-items: center; gap: 8px; margin: 0; font-family: var(--font-serif); font-size: 22px; } +.tm-headlines { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.tm-headlines li { + padding: 10px 12px; + border: 1.5px solid var(--ink); + border-left-width: 6px; + border-radius: 6px; + background: var(--paper); + font-family: var(--font-news, var(--font-serif)); + font-weight: 700; + font-size: 16px; + line-height: 1.5; + animation: tm-deal 320ms var(--ease-out) both; + animation-delay: calc(var(--i, 0) * 140ms); +} +.tm-gains { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.tm-gain { display: grid; justify-items: center; gap: 2px; padding: 10px 4px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface-2); text-align: center; } +.tm-gain span { font-size: 12px; color: var(--muted); } +.tm-gain b { font-family: var(--font-num); font-size: 26px; line-height: 1.1; white-space: nowrap; } +.tm-gain b small { font-size: 14px; margin-left: 2px; } +.tm-gain:first-child { background: var(--signal); color: var(--signal-ink, var(--ink)); } +.tm-gain:first-child span { color: inherit; } +.tm-next { justify-self: center; } + +/* ── 預覽頁 ── */ +.tm-preview-stages { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; } +.tm-preview-stages .tm-choice { text-align: center; justify-items: center; } +.tm-preview-name { display: grid; gap: 4px; font-weight: 700; } +.tm-preview-name input { min-height: 44px; padding: 0 12px; border: 2px solid var(--ink); border-radius: 10px; font: inherit; font-size: 16px; background: var(--surface); color: var(--ink); } +.tm-preview-json { margin: 0; padding: 12px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface-2); font-size: 12px; white-space: pre-wrap; word-break: break-all; } + +/* ── 震動(輕/重) ── */ +.tm-shake-small { animation: tm-shake-s 260ms ease-out; } +.tm-shake-large { animation: tm-shake-l 420ms ease-out; } + +@keyframes tm-in { from { opacity: 0; transform: translateY(8px); } } +@keyframes tm-deal { from { opacity: 0; transform: translateY(16px) rotate(-1.5deg); } } +@keyframes tm-stamp-in { from { opacity: 0; transform: scale(1.6); } 60% { opacity: 1; transform: scale(0.95); } } +@keyframes tm-pop { + 0% { opacity: 0; scale: 0.6; } + 18% { opacity: 1; scale: 1.12; } + 30% { scale: 1; } + 75% { opacity: 1; } + 100% { opacity: 0; translate: -50% -110%; } +} +@keyframes tm-drain { from { transform: scaleX(1); } to { transform: scaleX(0); } } +@keyframes tm-wobble { 50% { transform: rotate(-3deg) translateX(-2px); } } +@keyframes tm-shove { 50% { transform: translateX(4px); } } +@keyframes tm-mic { + 0% { opacity: 0; scale: 0.4; } + 15% { opacity: 1; scale: 1.1; } + 25% { scale: 1; } + 80% { opacity: 1; } + 100% { opacity: 0.2; scale: 0.85; } +} +@keyframes tm-shake-s { 20% { transform: translate(-4px, 1px); } 40% { transform: translate(3px, -2px); } 60% { transform: translate(-2px, 1px); } 80% { transform: translate(1px, 0); } } +@keyframes tm-shake-l { 15% { transform: translate(-8px, 3px) rotate(-0.6deg); } 30% { transform: translate(7px, -4px) rotate(0.5deg); } 45% { transform: translate(-5px, 2px); } 60% { transform: translate(4px, -1px); } 80% { transform: translate(-2px, 0); } } +@keyframes tm-fade { from { opacity: 0; } } + +@media (max-width: 380px) { + .tm-choices { grid-template-columns: 1fr; } + .tm-articles { grid-template-columns: repeat(2, 1fr); } + .tm-inter-stage { grid-template-columns: 1fr; justify-items: center; } +} + +/* 減少動態效果:不震、不彈、不晃,只淡入淡出 */ +@media (prefers-reduced-motion: reduce) { + .tm-intro, .tm-done, .tm-done-score, .tm-petition-card, .tm-bubble, .tm-fragment, .tm-typhoon, .tm-item, .tm-review-card, .tm-headlines li, .tm-pop, .tm-mic { animation: tm-fade 200ms ease both; } + .tm-crowd.is-us, .tm-crowd.is-them, .tm-official.is-sweating .avatar, .tm-shake-small, .tm-shake-large { animation: none; } + .tm-line-timer { animation-name: tm-drain; } + .tm-podium, .tm-timer-track > i, .tm-meter > i, .tm-ctrl > i, .tm-alloc-bar > i { transition: none; } +} + +/* 任期開始前的任務簡報 */ +.tm-brief { display: grid; gap: 12px; padding: 18px; border: 3px solid var(--ink); border-radius: 18px; background: var(--surface); color: var(--ink); box-shadow: 5px 5px 0 var(--shadow-ink); } +.tm-brief h3 { margin: 0; display: flex; align-items: center; gap: 8px; font-family: var(--font-serif); font-size: 22px; } +.tm-brief > p { margin: 0; color: var(--muted); } +.tm-brief-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.tm-brief-list li { display: grid; gap: 2px; padding: 10px 12px; border-radius: 12px; border: 2px solid var(--ink); background: var(--surface-2); animation: tm-brief-in 320ms var(--ease-out) calc(var(--i, 0) * 80ms) both; } +.tm-brief-list b { font-size: 17px; } +.tm-brief-list span { font-size: 14px; } +.tm-brief-list small { font-size: 13px; color: var(--muted); } +.tm-brief-reward { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 13px; font-weight: 800; } +.tm-brief-reward span { display: inline-flex; align-items: center; gap: 4px; } +.tm-brief-reward svg { color: var(--stamp); } +@keyframes tm-brief-in { from { opacity: 0; transform: translateY(8px); } } +/* 每個小遊戲開始前的一二三步 */ +.tm-howto { margin: 0; padding-left: 1.4em; display: grid; gap: 6px; text-align: left; font-size: 15px; line-height: 1.5; } +.tm-howto li::marker { font-weight: 900; color: var(--stamp); } +.tm-howto-reward { margin: 0; font-size: 13px; color: var(--muted); text-align: left; } +.tm-gain.is-exp { margin-top: 4px; } +@media (prefers-reduced-motion: reduce) { .tm-brief-list li { animation: none; } } diff --git a/web/src/game/career/term/types.ts b/web/src/game/career/term/types.ts new file mode 100644 index 0000000..7dc1fa9 --- /dev/null +++ b/web/src/game/career/term/types.ts @@ -0,0 +1,38 @@ +import type { CareerAbilities } from "@election2026/protocol"; + +/** 任期小遊戲的共同介面:玩完回報 0–100 分 */ +export interface TermGameProps { + seed: number; + /** 難度 0–1(越後面的關卡越難) */ + level: number; + characterName: string; + onFinish: (score: number) => void; +} + +export type Ability = keyof CareerAbilities; + +/** 一段任期的結果:分數、政績點、能力經驗、虛構的任期回顧標題、帶到下一場的開局加成 */ +export interface TermResult { + /** 1 里長任期、2 議員任期、3 立委任期、4 縣市長任期 */ + stage: 1 | 2 | 3 | 4; + scores: Record; + /** 政績點(給政策島),約 2–10 */ + points: number; + /** 每項 0–3 點經驗(舊版的能力經驗;政治生涯改成加 exp、自己分配技能點) */ + xp: Partial>; + /** 生涯經驗(升級拿技能點) */ + exp: number; + /** 2–4 行任期回顧(新聞標題) */ + headlines: string[]; + /** 帶到下一場選舉的開局加成:聲勢 0–2、資金 0–300 萬 */ + bonus: { momentum: number; money: number }; +} + +export interface TermScreenProps { + stage: 1 | 2 | 3 | 4; + characterName: string; + /** 這段任期的職位,例如「里長」「議員」 */ + office: string; + seed: number; + onDone: (r: TermResult) => void; +} diff --git a/web/src/game/creator/CreatorScreen.tsx b/web/src/game/creator/CreatorScreen.tsx new file mode 100644 index 0000000..88a95ad --- /dev/null +++ b/web/src/game/creator/CreatorScreen.tsx @@ -0,0 +1,294 @@ +import { Crown, Save, Sparkles } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; +import { peopleApi } from "../api.ts"; +import { PARTY_HEX, avatarFromSeed, type AvatarSpec } from "../art/Avatar.tsx"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { deleteCharacter, loadCharacters, saveCharacter } from "./characters.ts"; +import { NAME_MAX, NAME_MIN, NameTab, OriginTab, StatsTab } from "./IdentityTabs.tsx"; +import { loadProgress } from "../rogue/progress.ts"; +import { itemState } from "../shop/unlocks.ts"; +import { useWardrobe } from "../shop/wardrobe.ts"; +import { ExtraTab, FaceTab, GearTab, HairTab, OutfitTab, PropsTab, StyleTab, type LooksCtx } from "./LooksTabs.tsx"; +import { STAT_BUDGET, STAT_KEYS, TABS, bumpStat, originText, partyOf, randomStats, type Background, type Party, type StatKey, type TabId } from "./options.ts"; +import { SavedRail } from "./SavedRail.tsx"; +import { Stage } from "./Stage.tsx"; +import "./creator.css"; + +const SAY_MS = 2800; +const TALK_MS = 1200; +const NAME_CHECK_MS = 650; + +/** + * 捏人物(docs/15):競選總部的更衣間。中間是站在講台後面的角色,旁邊(手機在下面)是分頁: + * 臉部、髮型、服裝、配件、行頭(帽子、背心、彩帶、胸花)、道具(手持物、外框)、畫風、名字與政黨、出身、能力點數。 + * 最下面「存起來,去政治生涯」。新部位照部件目錄列(docs/24),沒拿到的灰色、寫怎麼拿到。 + * 角色存在這台瀏覽器(左邊的衣櫃);名字不能和真實候選人相同(這裡先查參選人資料,開局時伺服器也會再檢查)。 + */ +export function CreatorScreen({ charId }: { charId: string | null }) { + const [list, setList] = useState(loadCharacters); + const saved = useMemo(() => (charId ? loadCharacters().find((c) => c.id === charId) : undefined), [charId]); + const [id] = useState(saved?.id ?? `char-${Date.now().toString(36)}`); + const [avatar, setAvatar] = useState(saved?.avatar ?? avatarFromSeed(`creator-${Date.now()}`)); + const [name, setNameRaw] = useState(saved?.name ?? ""); + const [party, setPartyRaw] = useState(saved?.party ?? null); + const [background, setBackgroundRaw] = useState(saved?.background ?? "社運出身"); + const [stats, setStats] = useState(saved?.stats ?? { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }); + const [savedNow, setSavedNow] = useState(false); + const [tab, setTab] = useState("face"); + const [pulse, setPulse] = useState(0); + const [say, setSay] = useState<{ text: string; n: number } | null>(null); + const [talking, setTalking] = useState(false); + const [realHit, setRealHit] = useState(null); + const [nudge, setNudge] = useState(0); + const wardrobe = useWardrobe(); + const [progress] = useState(loadProgress); + const timers = useRef<{ say?: number; talk?: number }>({}); + const goRef = useRef(null); + + useEffect(() => setMusic("theme-march"), []); + useEffect(() => { + const t = timers.current; + return () => { + clearTimeout(t.say); + clearTimeout(t.talk); + }; + }, []); + + const speak = useCallback((text: string) => { + clearTimeout(timers.current.say); + clearTimeout(timers.current.talk); + setSay({ text, n: Date.now() }); + setTalking(true); + timers.current.talk = window.setTimeout(() => setTalking(false), TALK_MS); + timers.current.say = window.setTimeout(() => setSay(null), SAY_MS); + }, []); + + useEffect(() => { + if (!saved) speak("幫我打扮一下吧!"); + }, [saved, speak]); + + const trimmed = name.trim(); + const nameOk = trimmed.length >= NAME_MIN && trimmed.length <= NAME_MAX; + const isReal = realHit !== null && realHit === trimmed; + + // 打完名字停一下:查是不是真實參選人的名字,然後角色自我介紹 + useEffect(() => { + if (!nameOk) return; + let off = false; + const t = setTimeout(() => { + peopleApi + .list({ q: trimmed }) + .then((r) => { + if (off) return; + const hit = r.people.some((p) => p.name === trimmed); + setRealHit(hit ? trimmed : null); + speak(hit ? "這是真的參選人名字,換一個吧!" : `大家好,我是${trimmed}!`); + }) + .catch(() => !off && speak(`大家好,我是${trimmed}!`)); + }, NAME_CHECK_MS); + return () => { + off = true; + clearTimeout(t); + }; + }, [trimmed, nameOk, speak]); + + const used = STAT_KEYS.reduce((sum, k) => sum + stats[k], 0); + const left = STAT_BUDGET - used; + const valid = nameOk && !isReal && left >= 0; + const problem: { text: string; tab: TabId } | null = !nameOk + ? { text: "先到「名字」取個名字", tab: "name" } + : isReal + ? { text: "名字和真實參選人一樣,換一個", tab: "name" } + : left < 0 + ? { text: "能力點數超過了,減一些", tab: "stats" } + : null; + + /** 每次改東西:角色彈一下,「已存好」變回「先存起來」 */ + const touched = () => { + setSavedNow(false); + setPulse((n) => n + 1); + }; + const set = (patch: Partial) => { + setAvatar((a) => ({ ...a, ...patch })); + sfx.click(); + touched(); + }; + const setName = (v: string) => { + setNameRaw(v); + setSavedNow(false); + }; + const setParty = (p: Party) => { + setPartyRaw(p); + sfx.flag(); + touched(); + speak(partyOf(p).line); + }; + const setBackground = (b: Background) => { + setBackgroundRaw(b); + sfx.click(); + touched(); + speak(`我是${originText(b)}!`); + }; + const changeStats = (next: typeof stats) => { + if (next === stats) return; + setStats(next); + sfx.click(); + touched(); + }; + const dice = () => { + // 隨機換臉,身上的行頭、道具、畫風照穿 + setAvatar((a) => ({ ...avatarFromSeed(`creator-${Math.random()}`), ...(a.wear ? { wear: a.wear } : {}), ...(a.tint ? { tint: a.tint } : {}), ...(a.style ? { style: a.style } : {}), ...(a.v ? { v: a.v } : {}) })); + sfx.dice(); + touched(); + speak("換個造型!"); + }; + + const save = () => { + saveCharacter({ id, name: trimmed, party, background, stats, avatar }); + setList(loadCharacters()); + setSavedNow(true); + }; + const go = () => { + if (!valid) { + if (problem) setTab(problem.tab); + sfx.bad(); + setNudge((n) => n + 1); + return; + } + save(); + sfx.flag(); + location.hash = "#/rogue/career"; + }; + const remove = () => { + deleteCharacter(id); + location.hash = `#/create?new=${Date.now().toString(36)}`; + }; + + // 按了還不能走:按鈕抖一下 + useEffect(() => { + if (nudge === 0 || matchMedia("(prefers-reduced-motion: reduce)").matches) return; + goRef.current?.animate( + [{ transform: "translateX(0)" }, { transform: "translateX(-6px)" }, { transform: "translateX(5px)" }, { transform: "translateX(-3px)" }, { transform: "translateX(0)" }], + { duration: 360, easing: "ease-out" }, + ); + }, [nudge]); + + const onTabKey = (e: KeyboardEvent) => { + const i = TABS.findIndex((t) => t.id === tab); + const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0; + if (!step) return; + e.preventDefault(); + const next = TABS[(i + step + TABS.length) % TABS.length]!; + setTab(next.id); + document.getElementById(`cr-tab-${next.id}`)?.focus(); + }; + + const badge = (t: TabId): string | null => { + if (t === "name" && (!nameOk || isReal)) return "!"; + if (t === "stats" && left !== 0) return left > 0 ? String(left) : "!"; + return null; + }; + const current = TABS.find((t) => t.id === tab)!; + const partyColor = PARTY_HEX[partyOf(party).slot]; + const looks: LooksCtx = { partyColor, name: trimmed, stateOf: (item) => itemState(item, progress, wardrobe) }; + const isSaved = list.some((c) => c.id === id); + + return ( + } value={left} label="剩餘點數" />}> +
+ + + { + setTab("name"); + requestAnimationFrame(() => document.getElementById("cr-name")?.focus()); + }} + /> + +
+
+ {TABS.map((t) => { + const on = t.id === tab; + const b = badge(t.id); + return ( + + ); + })} +
+
+
+

{current.label}

+

{current.title}

+
+ {tab === "face" && } + {tab === "hair" && } + {tab === "outfit" && } + {tab === "extra" && } + {tab === "gear" && } + {tab === "props" && } + {tab === "style" && } + {tab === "name" && ( + + )} + {tab === "origin" && } + {tab === "stats" && ( + changeStats(bumpStat(stats, k, d))} + onSetAll={(v) => changeStats(Object.fromEntries(STAT_KEYS.map((k) => [k, v])) as typeof stats)} + onRandom={() => changeStats(randomStats())} + /> + )} +
+
+ +
+ + +
+
+
+ ); +} diff --git a/web/src/game/creator/IdentityTabs.tsx b/web/src/game/creator/IdentityTabs.tsx new file mode 100644 index 0000000..187d0d5 --- /dev/null +++ b/web/src/game/creator/IdentityTabs.tsx @@ -0,0 +1,256 @@ +import { PARTY_RECORDS, PARTY_RESOURCES, originBonusText, partyKind, type CustomCandidate } from "@election2026/protocol"; +import { Check, Minus, Plus, RotateCcw, Search, Shuffle, Trash2 } from "lucide-react"; +import { useEffect, useState, type CSSProperties } from "react"; +import type { AvatarSpec } from "../art/Avatar.tsx"; +import { Poster } from "../art/Poster.tsx"; +import { PartyFlag, hasPartyFlag } from "../PartyFlag.tsx"; +import { partyFacts, searchParties } from "../parties.ts"; +import { + BACKGROUND_INFO, + BACKGROUNDS, + PARTIES, + STAT_BUDGET, + STAT_KEYS, + STAT_LABELS, + STAT_MAX, + originText, + partyOf, + type Background, + type Party, + type StatKey, +} from "./options.ts"; +import { Section } from "./Pickers.tsx"; + +export const NAME_MIN = 2; +export const NAME_MAX = 12; + +export function NameTab({ + name, + setName, + realHit, + party, + setParty, + avatar, + canDelete, + onDelete, +}: { + name: string; + setName: (v: string) => void; + /** 名字和真實參選人一樣 */ + realHit: boolean; + party: Party; + setParty: (p: Party) => void; + avatar: AvatarSpec; + canDelete: boolean; + onDelete: () => void; +}) { + const [armed, setArmed] = useState(false); + useEffect(() => { + if (!armed) return; + const t = setTimeout(() => setArmed(false), 3000); + return () => clearTimeout(t); + }, [armed]); + const len = name.trim().length; + const p = partyOf(party); + return ( + <> +
+ setName(e.target.value)} + placeholder="例如:林小桃" + aria-describedby="cr-name-note" + aria-invalid={realHit || (len > 0 && len < NAME_MIN) ? true : undefined} + /> +

+ {realHit ? `「${name.trim()}」是真實參選人的名字,自創角色請換一個名字。` : `${NAME_MIN}–${NAME_MAX} 字,不能和真實候選人同名。`} +

+
+ +
+
+ {(PARTIES.some((it) => it.id === party) ? PARTIES : [partyOf(party), ...PARTIES]).map((it) => { + const on = it.id === party; + return ( + + ); + })} +
+ + +

劇本裡有同黨的候選人就取代他參選,沒有就以新候選人加入。民進黨、國民黨、民眾黨以外的政黨,選民基本盤和無黨籍一樣。

+
+ +
+
+ +
+
+ +

角色存在這台瀏覽器,清掉瀏覽器資料就會不見。

+ {canDelete && ( + + )} + + ); +} + +export function OriginTab({ background, setBackground }: { background: Background; setBackground: (b: Background) => void }) { + return ( +
+ {BACKGROUNDS.map((b) => { + const on = b === background; + const { note, Icon } = BACKGROUND_INFO[b]; + return ( + + ); + })} +
+ ); +} + +type Stats = CustomCandidate["stats"]; + +export function StatsTab({ + stats, + left, + onBump, + onSetAll, + onRandom, +}: { + stats: Stats; + left: number; + onBump: (k: StatKey, d: 1 | -1) => void; + onSetAll: (v: number) => void; + onRandom: () => void; +}) { + const even = Math.floor(STAT_BUDGET / STAT_KEYS.length); + return ( + <> +
+ {left} + + {left < 0 ? `超過 ${-left} 點,請減一些` : left === 0 ? "點數都分完了" : `還剩 ${left} 點可以加`} + + 總共 {STAT_BUDGET} 點,每項最多 {STAT_MAX} 點 + + +
+
+ + + +
+
    + {STAT_KEYS.map((k) => { + const v = stats[k]; + const { label, note } = STAT_LABELS[k]; + return ( +
  • +

    + {label} + {note} +

    +
    + + + {Array.from({ length: STAT_MAX }, (_, i) => ( + + ))} + + + {v} +
    +
  • + ); + })} +
+ + ); +} + +/** 更多政黨:台灣歷屆選舉推出過候選人的政黨都可以選(中選會資料,parties.ts),可以搜尋 */ +function MoreParties({ party, setParty }: { party: Party; setParty: (p: Party) => void }) { + const [open, setOpen] = useState(false); + const [q, setQ] = useState(""); + const list = searchParties(q); + return ( +
+ + {open && ( +
+ setQ(e.target.value)} placeholder="搜尋政黨名稱,例如:時代力量" autoComplete="off" aria-label="搜尋政黨" /> +
    + {list.map((r) => ( +
  • + +
  • + ))} + {list.length === 0 &&
  • 找不到「{q.trim()}」。清單是中選會選舉資料庫 1994–2024 年推出過候選人的政黨。
  • } +
+

資料來源:中央選舉委員會選舉資料庫(1994–2024),依推出的候選人數排序。

+
+ )} +
+ ); +} + +/** 黨的資源(不能自己點,18 第 53 項):好處和代價 */ +function PartyPerks({ party }: { party: Party }) { + const res = PARTY_RESOURCES[partyKind(party)]; + return ( +
+ 黨的資源・{res.label} + {res.perks.join("、")} + {res.costs.length > 0 && 代價:{res.costs.join("、")}} +
+ ); +} diff --git a/web/src/game/creator/LooksTabs.tsx b/web/src/game/creator/LooksTabs.tsx new file mode 100644 index 0000000..d3f45ed --- /dev/null +++ b/web/src/game/creator/LooksTabs.tsx @@ -0,0 +1,271 @@ +import { AVATAR_CATALOG, avatarSlot, slotItems, wearItem, type AvatarItem } from "@election2026/protocol"; +import { useState } from "react"; +import { Avatar, type AvatarSpec } from "../art/Avatar.tsx"; +import { tintOf } from "../art/avatar/parts.tsx"; +import { HAIR, SHIRT, SKIN, SUIT, TIE } from "../art/palette.ts"; +import { updateSettings, useSettings } from "../audio/settings.ts"; +import { RARITY_TEXT, setTint, wear, type ItemState } from "../shop/unlocks.ts"; +import { + AGES, + BEARDS, + BGS, + BROWS, + EYES, + FACES, + GLASSES, + HAIR_STYLES, + MOUTHS, + OUTFITS, + PARTED_HAIR, + hasCollar, + hasTie, + PARTS, + beardOf, + beardPatch, + type GlassesId, +} from "./options.ts"; +import { Section, Swatches, TileGrid } from "./Pickers.tsx"; + +/** 新部位要知道的事:政黨色、名字(印在部件上)、每件部件拿到了沒 */ +export interface LooksCtx { + partyColor: string; + name: string; + stateOf: (item: AvatarItem) => ItemState; +} +type Props = { avatar: AvatarSpec; set: (patch: Partial) => void; looks?: LooksCtx }; + +const labelOf = (items: { id: T; label: string }[], id: T | undefined): string | undefined => items.find((x) => x.id === id)?.label; + +/** 格子裡的小預覽:目前的角色套上這個選項 */ +const mini = (avatar: AvatarSpec, patch: Partial, extra: { partyColor?: string; name?: string; frame?: boolean; style?: string } = {}) => ( + +); +/** 整份換掉(wear、tint 拿掉時也要蓋掉舊的) */ +const whole = (next: AvatarSpec): Partial => ({ ...next, wear: next.wear, tint: next.tint, v: next.v }); + +export function FaceTab({ avatar, set }: Props) { + const age = String(Math.min(2, Math.max(0, avatar.lines ?? 0))) as "0" | "1" | "2"; + return ( + <> +
+ set({ skin })} /> +
+
+ set({ face })} preview={(face) => mini(avatar, { face })} zoom="face" /> +
+
+ set({ eyes })} preview={(eyes) => mini(avatar, { eyes })} zoom="face" /> +
+
+ set({ brows })} preview={(brows) => mini(avatar, { brows })} zoom="face" /> +
+
+ set({ mouth })} preview={(mouth) => mini(avatar, { mouth })} zoom="face" /> +
+
+ set({ lines: Number(v) })} preview={(v) => mini(avatar, { lines: Number(v) })} zoom="face" /> +
+ + ); +} + +export function HairTab({ avatar, set }: Props) { + return ( + <> +
+ set({ hair })} preview={(hair) => mini(avatar, { hair })} zoom="head" /> +
+
+ set({ hairColor })} /> +
+ {PARTED_HAIR.includes(avatar.hair) && ( +
+ set({ part })} preview={(part) => mini(avatar, { part })} zoom="head" wide /> +
+ )} + + ); +} + +export function OutfitTab({ avatar, set }: Props) { + return ( + <> +
+ set({ outfit })} preview={(outfit) => mini(avatar, { outfit })} /> +
+
+ set({ suit })} /> +
+
+ set({ shirt })} /> +
+ {hasTie(avatar.outfit) && ( +
+ set({ tie })} /> +
+ )} +
+ set({ bg })} /> +
+ + ); +} + +export function ExtraTab({ avatar, set, looks }: Props) { + const glasses: GlassesId = avatar.glasses ? (avatar.glassesStyle ?? "black") : "none"; + const pickGlasses = (id: GlassesId) => set(id === "none" ? { glasses: false } : { glasses: true, glassesStyle: id }); + const beard = beardOf(avatar); + return ( + <> +
+ mini(avatar, id === "none" ? { glasses: false } : { glasses: true, glassesStyle: id })} + zoom="face" + /> +
+ {looks && } +
+ set(beardPatch(id))} preview={(id) => mini(avatar, beardPatch(id))} zoom="face" /> +
+ + ); +} + +const ZOOM: Record = { hat: "head", mask: "face" }; + +/** 稀有度角標:普通不標 */ +export const rarityBadge = (item: AvatarItem | undefined) => (item && item.rarity !== "common" ? { text: RARITY_TEXT[item.rarity], kind: item.rarity } : null); + +/** + * 一個新部位(帽子、背心、彩帶…):第一格「不戴」,後面是目錄裡的部件。 + * 沒拿到的格子灰色、寫怎麼拿到;點了只說明怎麼拿到(商店的可以去服裝店試穿)。穿上的部件可以換色。 + */ +function WearSection({ slot, avatar, set, looks }: { slot: string; avatar: AvatarSpec; set: Props["set"]; looks: LooksCtx }) { + const [note, setNote] = useState(null); + const s = avatarSlot(slot); + const items = slotItems(slot); + if (!s || items.length === 0) return null; + const current = avatar.wear?.[slot]; + const worn = current ? wearItem(current) : undefined; + const tiles = [{ id: "none", label: "不戴" }, ...items.map((i) => ({ id: i.id, label: i.name }))]; + const byId = new Map(items.map((i) => [i.id, i])); + const pick = (id: string) => { + const item = byId.get(id); + if (item && !looks.stateOf(item).owned) { + setNote(item); + return; + } + setNote(null); + set(whole(wear(avatar, slot, id === "none" ? null : id))); + }; + const extra = { partyColor: looks.partyColor, name: looks.name, frame: slot === "frame" }; + return ( + <> +
+ mini(avatar, whole(wear(avatar, slot, id === "none" ? null : id)), extra)} + zoom={ZOOM[slot] ?? "none"} + locked={(id) => { + const item = byId.get(id); + if (!item) return null; + const st = looks.stateOf(item); + return st.owned ? null : st.how; + }} + badge={(id) => rarityBadge(byId.get(id))} + /> + {note && ( +

+ 「{note.name}」還沒拿到:{looks.stateOf(note).how}。 + {note.get.type === "shop" && 去服裝店試穿} +

+ )} +
+ {worn && + worn.tints.map((t) => { + const palette = AVATAR_CATALOG.palettes[t.palette]?.colors ?? []; + const colors = palette.map((c) => (c === "party" ? looks.partyColor : c)); + const value = tintOf(worn, t.key, { party: looks.partyColor, tint: avatar.tint, skin: avatar.skin, suit: avatar.suit, shirt: avatar.shirt, text: false }); + return ( +
+ set(whole(setTint(avatar, slot, t.key, t.default === "party" && c === looks.partyColor ? null : c)))} + /> +
+ ); + })} + + ); +} + +/** 行頭:帽子、背心外套、彩帶、胸前(照目錄 slots.tab = gear) */ +export function GearTab({ avatar, set, looks }: Props & { looks: LooksCtx }) { + return ( + <> + {AVATAR_CATALOG.slots + .filter((s) => s.tab === "gear" && !s.field && s.ui) + .map((s) => ( + + ))} +

還沒拿到的灰色格子寫著怎麼拿到;打完一局會發小鎮幣,可以去服裝店買。

+ + ); +} + +/** 道具:手持物、頭像外框(slots.tab = props) */ +export function PropsTab({ avatar, set, looks }: Props & { looks: LooksCtx }) { + return ( + <> + {AVATAR_CATALOG.slots + .filter((s) => s.tab === "props" && !s.field && s.ui) + .map((s) => ( + + ))} +

手持物和外框在很小的頭像(地圖棋子、幕僚小圓頭像)上會自動省略。

+ + ); +} + +/** 畫風:這個角色自己的,和全遊戲的(同一套部件換畫法,所有部件都能穿) */ +export function StyleTab({ avatar, set, looks }: Props & { looks: LooksCtx }) { + const settings = useSettings(); + const styles = AVATAR_CATALOG.styles; + const globalName = styles.find((s) => s.id === settings.avatarStyle)?.name ?? "漫畫"; + const mine = [{ id: "auto", label: `跟全遊戲(${globalName})` }, ...styles.map((s) => ({ id: s.id, label: s.name }))]; + const extra = { partyColor: looks.partyColor, name: looks.name }; + return ( + <> +
s.id === avatar.style)?.name : "跟全遊戲"}> + set({ style: id === "auto" ? undefined : id, v: 2 })} + preview={(id) => mini(avatar, {}, { ...extra, style: id === "auto" ? settings.avatarStyle : id })} + zoom="head" + /> +
+
+ ({ id: s.id, label: s.name }))} + value={settings.avatarStyle} + onPick={(id) => updateSettings({ avatarStyle: id })} + preview={(id) => mini(avatar, {}, { ...extra, style: id })} + zoom="head" + /> +

所有頭像(候選人、幕僚、政治人物)都用這個畫風;角色自己選了畫風的,用自己的。{styles.find((s) => s.id === settings.avatarStyle)?.note}

+
+ + ); +} diff --git a/web/src/game/creator/Pickers.tsx b/web/src/game/creator/Pickers.tsx new file mode 100644 index 0000000..4f23c08 --- /dev/null +++ b/web/src/game/creator/Pickers.tsx @@ -0,0 +1,115 @@ +import { Check, Lock } from "lucide-react"; +import type { CSSProperties, ReactNode } from "react"; + +/** 一個分類小節:標題+目前選的值 */ +export function Section({ title, value, htmlFor, children }: { title: string; value?: ReactNode; htmlFor?: string; children: ReactNode }) { + return ( +
+

+ {htmlFor ? : {title}} + {value !== undefined && {value}} +

+ {children} +
+ ); +} + +function Tick() { + return ( + + + + ); +} + +/** + * 一格一格的選項(像遊戲的造型格子):每格可以放一張小預覽圖。 + * zoom:face=放大到臉、head=放大到頭和頭髮、none=整個半身。 + * locked:還沒拿到的格子(灰色、鎖頭、下面寫怎麼拿到,跟圖鑑灰卡一樣;點了交給 onPick 決定要不要試穿)。 + * badge:右上角的稀有度角標(稀有、限定)。 + */ +export function TileGrid({ + label, + items, + value, + onPick, + preview, + zoom = "none", + wide = false, + locked, + badge, +}: { + label: string; + items: { id: T; label: string }[]; + value: T; + onPick: (id: T) => void; + preview?: (id: T) => ReactNode; + zoom?: "none" | "face" | "head"; + wide?: boolean; + locked?: (id: T) => string | null; + badge?: (id: T) => { text: string; kind: string } | null; +}) { + return ( +
+ {items.map((it) => { + const on = it.id === value; + const how = locked?.(it.id) ?? null; + const b = badge?.(it.id) ?? null; + return ( + + ); + })} +
+ ); +} + +/** 色票:圓形的顏色格子 */ +export function Swatches({ label, colors, value, onPick }: { label: string; colors: readonly string[]; value: string; onPick: (c: string) => void }) { + return ( +
+ {colors.map((c, i) => { + const on = c.toLowerCase() === value.toLowerCase(); + return ( + + ); + })} +
+ ); +} diff --git a/web/src/game/creator/SavedRail.tsx b/web/src/game/creator/SavedRail.tsx new file mode 100644 index 0000000..908983e --- /dev/null +++ b/web/src/game/creator/SavedRail.tsx @@ -0,0 +1,42 @@ +import { Plus } from "lucide-react"; +import { sfx } from "../audio/sfx.ts"; +import { Avatar } from "../art/Avatar.tsx"; +import type { SavedCharacter } from "./characters.ts"; + +/** + * 衣櫃:存在這台瀏覽器的角色,一排角色卡。點一張就換成那個角色來改;最上面一格捏新的。 + * 電腦版在舞台左邊,手機版疊在舞台左側。 + */ +export function SavedRail({ list, currentId }: { list: SavedCharacter[]; currentId: string }) { + const editingSaved = list.some((c) => c.id === currentId); + return ( + + ); +} diff --git a/web/src/game/creator/Stage.tsx b/web/src/game/creator/Stage.tsx new file mode 100644 index 0000000..e8a0bc3 --- /dev/null +++ b/web/src/game/creator/Stage.tsx @@ -0,0 +1,135 @@ +import { Dices, Pencil } from "lucide-react"; +import { useEffect, useRef, type CSSProperties } from "react"; +import { Avatar, type AvatarSpec } from "../art/Avatar.tsx"; +import { PartyFlag } from "../PartyFlag.tsx"; +import { originText, partyOf, type Background, type Party } from "./options.ts"; + +const TOP_BULBS = 9; +const SIDE_BULBS = 5; +const EASE_OUT = "cubic-bezier(0.23, 1, 0.32, 1)"; + +const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; + +/** + * 更衣間的舞台:化妝鏡(一圈燈泡)+聚光燈,人物站在講台後面。 + * 人物會呼吸、眨眼;每次換造型 pulse 加一,人物就彈一下。說話時嘴巴會動、頭旁邊冒對話框。 + */ +export function Stage({ + avatar, + name, + party, + partyColor, + background, + pulse, + say, + talking, + onDice, + onEditName, +}: { + avatar: AvatarSpec; + name: string; + party: Party; + /** 政黨色(#RRGGBB):競選背心、鴨舌帽…的預設色 */ + partyColor: string; + background: Background; + pulse: number; + say: { text: string; n: number } | null; + talking: boolean; + onDice: () => void; + /** 點講台名牌:跳到「名字」分頁、游標放進名字欄位(名牌看起來像填名字的地方) */ + onEditName: () => void; +}) { + const popRef = useRef(null); + const flashRef = useRef(null); + + useEffect(() => { + if (pulse === 0 || reducedMotion()) return; + popRef.current?.animate( + [{ transform: "scale(1, 1)" }, { transform: "scale(1.05, 0.95)" }, { transform: "scale(0.98, 1.03)" }, { transform: "scale(1, 1)" }], + { duration: 420, easing: EASE_OUT }, + ); + flashRef.current?.animate( + [ + { opacity: 0.7, transform: "scale(0.85)" }, + { opacity: 0, transform: "scale(1.25)" }, + ], + { duration: 520, easing: EASE_OUT }, + ); + }, [pulse]); + + const p = partyOf(party); + const shown = name.trim(); + // 名字越長字越小,講台上的名牌才放得下 + const nameScale = Math.min(1, 5 / Math.max(shown.length, 1)); + return ( +
+
+ {Array.from({ length: TOP_BULBS }, (_, i) => ( + + ))} + {Array.from({ length: SIDE_BULBS }, (_, i) => ( + + ))} + {Array.from({ length: SIDE_BULBS }, (_, i) => ( + + ))} +
+
+
+ +
+ + +
+
+ +
+
+ {say && ( +

+ {say.text} +

+ )} +
+ +
+ + + + + + + + + + +
+ + {avatar.wear?.frame && ( + // 頭像外框套在整張頭像卡上(舞台上的人物不畫外框,免得被講台擋住) + + + + )} + + +
+ ); +} diff --git a/web/src/game/creator/characters.ts b/web/src/game/creator/characters.ts new file mode 100644 index 0000000..ef5faf1 --- /dev/null +++ b/web/src/game/creator/characters.ts @@ -0,0 +1,44 @@ +import { DEFAULT_AVATAR_SPEC, parseAvatarLoose, type CustomCandidate } from "@election2026/protocol"; + +/** 玩家捏好的角色存在這台瀏覽器裡(只是方便下次再用;讀不到就是空的) */ +const KEY = "tongsuan.characters"; + +export type SavedCharacter = Omit & { id: string }; + +/** + * 讀存檔時清洗頭像(docs/24):照部件目錄檢查,看不懂的部件代號換成預設、壞掉的欄位丟掉,存檔壞掉也不會當機。 + * 舊存檔的頭像本來就合法,原封不動。 + */ +function cleanCharacter(raw: unknown): SavedCharacter | null { + if (!raw || typeof raw !== "object") return null; + const c = raw as SavedCharacter; + if (typeof c.id !== "string" || typeof c.name !== "string") return null; + return { ...c, avatar: parseAvatarLoose(c.avatar) ?? DEFAULT_AVATAR_SPEC }; +} + +export function loadCharacters(): SavedCharacter[] { + try { + const raw = localStorage.getItem(KEY); + const list: unknown = raw ? JSON.parse(raw) : []; + return Array.isArray(list) ? list.map(cleanCharacter).filter((c): c is SavedCharacter => c !== null) : []; + } catch { + return []; + } +} + +export function saveCharacter(c: SavedCharacter): void { + try { + const list = loadCharacters().filter((x) => x.id !== c.id); + localStorage.setItem(KEY, JSON.stringify([c, ...list].slice(0, 12))); + } catch { + // 存不了就算了,這次還是可以玩 + } +} + +export function deleteCharacter(id: string): void { + try { + localStorage.setItem(KEY, JSON.stringify(loadCharacters().filter((x) => x.id !== id))); + } catch { + // 同上 + } +} diff --git a/web/src/game/creator/creator.css b/web/src/game/creator/creator.css new file mode 100644 index 0000000..7631f9d --- /dev/null +++ b/web/src/game/creator/creator.css @@ -0,0 +1,415 @@ +/* 捏人物=競選總部的更衣間(CreatorScreen.tsx):整頁不捲,只有分頁裡的選項自己捲。 + 左邊衣櫃(存好的角色)、中間化妝鏡前的舞台、右邊分頁;手機版舞台在上、分頁在下,衣櫃疊在舞台左側。 + 顏色一律用 tokens.css 的變數;動畫只動 transform、opacity。 */ + +.cr-room { + height: 100%; min-height: 0; + display: grid; gap: 12px 16px; + grid-template-columns: 104px minmax(0, 1fr) minmax(380px, min(36vw, 540px)); + grid-template-rows: minmax(0, 1fr) auto; + grid-template-areas: "rail stage panel" "rail cta panel"; +} + +/* ── 衣櫃 ── */ +.cr-rail { grid-area: rail; min-height: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 10px; } +.cr-rail-h { + justify-self: center; margin: 0; padding: 2px 14px; + border: 3px solid var(--signal-ink); border-radius: 999px; background: var(--signal); color: var(--signal-ink); + font-family: var(--font-serif); font-size: 15px; box-shadow: 3px 3px 0 var(--signal-ink); +} +.cr-rail-list { display: grid; align-content: start; justify-items: center; gap: 12px; padding: 8px 4px 10px; } +.cr-slot { + display: grid; justify-items: center; gap: 4px; width: 88px; + color: var(--navy-ink); font-size: 13px; font-weight: 800; text-decoration: none; + transition: transform 140ms var(--ease-out); +} +.cr-slot-face { + width: 76px; height: 76px; display: grid; place-items: end center; overflow: hidden; + border-radius: 18px; border: 3px solid var(--signal-ink); background: var(--tv-ink); color: var(--signal-ink); + box-shadow: 3px 3px 0 var(--signal-ink); +} +.cr-slot-face .avatar { display: block; width: 112%; height: auto; transform: translateY(16%); } +.cr-slot.is-new .cr-slot-face { + place-items: center; border-style: dashed; border-color: color-mix(in srgb, var(--navy-ink) 60%, transparent); + background: color-mix(in srgb, var(--navy-ink) 10%, transparent); color: var(--navy-ink); box-shadow: none; +} +.cr-slot-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cr-slot.is-on .cr-slot-face { border-color: var(--signal); box-shadow: 0 0 0 3px var(--signal-ink), 0 0 0 6px color-mix(in srgb, var(--signal) 45%, transparent); } +.cr-slot.is-new.is-on .cr-slot-face { color: var(--signal); } +.cr-slot.is-on .cr-slot-name { color: var(--signal); } +.cr-slot:active { transform: scale(0.95); } +.cr-slot:focus-visible { outline: none; } +.cr-slot:focus-visible .cr-slot-face { outline: 4px solid var(--signal); outline-offset: 3px; } + +/* ── 舞台:化妝鏡、聚光燈、人物、講台 ── */ +.cr-stage { + grid-area: stage; position: relative; min-height: 0; overflow: hidden; container-type: size; + --fig: min(62cqh, 64cqw, 460px); + --b: 3cqh; +} +.cr-mirror { + --frame: 8px; + position: absolute; left: 0; right: 0; top: max(3cqh, calc(100cqh - var(--b) - var(--fig) * 1.5)); bottom: calc(var(--b) + var(--fig) * 0.2); + width: min(calc(var(--fig) * 1.55), 92cqw); margin-inline: auto; + border: var(--frame) solid var(--signal-ink); border-radius: 28px 28px 10px 10px; + background: + linear-gradient(115deg, transparent 0 34%, color-mix(in srgb, var(--navy-ink) 7%, transparent) 34% 42%, transparent 42% 47%, color-mix(in srgb, var(--navy-ink) 5%, transparent) 47% 50%, transparent 50%), + radial-gradient(ellipse at 50% 32%, color-mix(in srgb, var(--navy-2) 75%, transparent), color-mix(in srgb, var(--navy) 85%, transparent) 78%); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--signal) 30%, transparent), 0 18px 40px color-mix(in srgb, var(--navy) 70%, transparent); +} +.cr-bulb { + position: absolute; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; + background: var(--signal); box-shadow: 0 0 10px 2px color-mix(in srgb, var(--signal) 65%, transparent); + animation: cr-bulb 2.4s ease-in-out infinite; animation-delay: calc(var(--i) * -0.3s); +} +.cr-bulb.is-top { left: var(--at); top: calc(var(--frame) / -2); } +.cr-bulb.is-left { left: calc(var(--frame) / -2); top: var(--at); } +.cr-bulb.is-right { left: calc(100% + var(--frame) / 2); top: var(--at); } +@keyframes cr-bulb { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } } + +.cr-spot { + position: absolute; left: 0; right: 0; top: 0; bottom: var(--b); margin-inline: auto; width: calc(var(--fig) * 1.5); + clip-path: polygon(42% 0, 58% 0, 100% 100%, 0 100%); + background: linear-gradient(180deg, color-mix(in srgb, var(--signal) 40%, transparent), color-mix(in srgb, var(--signal) 5%, transparent) 92%); + transform-origin: 50% 0; animation: cr-sway 7s ease-in-out infinite alternate; pointer-events: none; +} +@keyframes cr-sway { from { transform: rotate(-3deg); } to { transform: rotate(3deg); } } +.cr-floor { + position: absolute; left: 0; right: 0; margin-inline: auto; bottom: calc(var(--b) - var(--fig) * 0.06); + width: calc(var(--fig) * 1.7); height: calc(var(--fig) * 0.28); border-radius: 50%; + background: radial-gradient(closest-side, color-mix(in srgb, var(--signal) 42%, transparent), transparent); +} + +.cr-actor { position: absolute; left: 0; right: 0; margin-inline: auto; bottom: calc(var(--b) + var(--fig) * 0.29); width: var(--fig); height: calc(var(--fig) * 1.1); } +.cr-backdrop { + position: absolute; left: 6%; top: 2%; width: 88%; aspect-ratio: 1; border-radius: 50%; + border: 4px solid var(--signal-ink); box-shadow: 0 0 0 6px color-mix(in srgb, var(--signal) 45%, transparent); +} +.cr-flash { position: absolute; left: 0; top: -3.5%; width: 100%; aspect-ratio: 1; border-radius: 50%; border: 6px solid var(--signal); opacity: 0; pointer-events: none; } +.cr-breathe { position: absolute; inset: 0; transform-origin: 50% 100%; animation: cr-breathe 3.6s ease-in-out infinite; } +@keyframes cr-breathe { 0%, 100% { transform: scale(1, 1); } 50% { transform: translateY(-0.5%) scale(1.012, 1.02); } } +.cr-pop { width: 100%; height: 100%; transform-origin: 50% 100%; } +.cr-pop .avatar { display: block; width: 100%; height: 100%; } + +.cr-bubble { + position: absolute; left: 62%; top: 0; z-index: 3; margin: 0; + width: max-content; max-width: min(280px, calc(50cqw - var(--fig) * 0.12 - 8px)); + padding: 6px 10px; border: 3px solid var(--signal-ink); border-radius: 16px; + background: var(--tv-ink); color: var(--signal-ink); box-shadow: 3px 3px 0 var(--signal-ink); + font-size: clamp(12px, calc(var(--fig) * 0.045), 18px); font-weight: 800; line-height: 1.3; + transform-origin: 0 100%; animation: cr-say 2800ms var(--ease-out) both; +} +.cr-bubble::after { + content: ""; position: absolute; left: 12px; bottom: -9px; width: 14px; height: 14px; + background: var(--tv-ink); border-right: 3px solid var(--signal-ink); border-bottom: 3px solid var(--signal-ink); + transform: rotate(45deg); +} +@keyframes cr-say { + 0% { opacity: 0; transform: translateY(8px) scale(0.6); } + 10% { opacity: 1; transform: scale(1.04); } + 16% { transform: none; } + 86% { opacity: 1; transform: none; } + 100% { opacity: 0; transform: translateY(-6px); } +} + +.cr-podium { position: absolute; left: 0; right: 0; margin-inline: auto; bottom: var(--b); width: calc(var(--fig) * 0.96); height: calc(var(--fig) * 0.35); } +.cr-podium-art { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } +.cr-podium-front { fill: var(--party); stroke: var(--signal-ink); stroke-width: 3px; stroke-linejoin: round; } +.cr-podium-stripe { fill: var(--signal); } +.cr-podium-top { fill: var(--signal-ink); } +.cr-mic { position: absolute; left: 6%; bottom: calc(100% - 6px); width: calc(var(--fig) * 0.08); height: calc(var(--fig) * 0.16); overflow: visible; } +.cr-mic path { fill: none; stroke: var(--signal-ink); stroke-width: 4; stroke-linecap: round; } +.cr-mic rect { fill: var(--signal-ink); } +.cr-sign { + position: absolute; left: 15%; right: 15%; top: 23%; bottom: 25%; + display: grid; place-content: center; justify-items: center; gap: 2px; padding: 2px 8px; overflow: hidden; + border: 3px solid var(--signal-ink); border-radius: 8px; background: var(--tv-ink); color: var(--signal-ink); text-align: center; +} +.cr-sign b { + max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-family: var(--font-serif); font-size: max(12px, calc(var(--fig) * 0.1 * var(--name-scale, 1))); line-height: 1.1; letter-spacing: 0.06em; +} +.cr-sign b.is-empty { opacity: 0.55; font-size: max(12px, calc(var(--fig) * 0.07)); } +.cr-sign { font: inherit; cursor: pointer; pointer-events: auto; transition: transform 140ms var(--ease-out); } +.cr-sign:active { transform: scale(0.98); } +.cr-sign:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.cr-sign-pen { margin-left: 0.3em; vertical-align: 0.1em; opacity: 0.5; } +@media (hover: hover) and (pointer: fine) { .cr-sign:hover .cr-sign-pen { opacity: 1; } } +.cr-sign > span { display: inline-flex; align-items: center; gap: 4px; max-width: 100%; overflow: hidden; white-space: nowrap; font-size: max(10px, calc(var(--fig) * 0.036)); font-weight: 800; } +.cr-sign-short { display: none; } + +/* 戴了頭像外框:舞台右上角放一張加框的頭像卡 */ +.cr-card-preview { + position: absolute; top: 10px; right: 10px; z-index: 4; width: clamp(64px, 18cqh, 104px); transform: rotate(3deg); + filter: drop-shadow(3px 3px 0 var(--signal-ink)); animation: cr-tick 260ms var(--ease-out) both; +} +.cr-card-preview .avatar { display: block; width: 100%; height: auto; } +.cr-dice { + position: absolute; right: 10px; bottom: calc(var(--b) + 4px); z-index: 4; + display: inline-flex; align-items: center; gap: 8px; min-height: 48px; padding: 6px 16px 6px 10px; + border: 3px solid var(--signal-ink); border-radius: 999px; background: var(--tv-ink); color: var(--signal-ink); + font-weight: 800; box-shadow: 3px 3px 0 var(--signal-ink); transition: transform 140ms var(--ease-out); +} +.cr-dice svg { transition: transform 200ms var(--ease-out); } +.cr-dice:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--signal-ink); } +.cr-dice:active svg { transform: rotate(-30deg); } +.cr-dice:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +@container (max-width: 640px) { + .cr-dice { width: 48px; padding: 0; justify-content: center; } + .cr-dice span { display: none; } + .cr-sign .cr-sign-full { display: none; } + .cr-sign .cr-sign-short { display: inline; } +} + +/* ── 分頁面板 ── */ +.cr-panel { grid-area: panel; min-height: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; } +/* 10 個分頁排成兩排(外觀一排、身分與畫風一排),手機上每格也夠大 */ +.cr-tabs { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; padding: 8px; background: var(--navy); border-bottom: 3px solid var(--ink); } +.cr-tab { + position: relative; display: grid; justify-items: center; align-content: center; gap: 2px; min-width: 0; min-height: 54px; padding: 6px 2px; + border: 2px solid transparent; border-radius: 12px; background: none; color: var(--navy-ink); + font-size: 13px; font-weight: 800; letter-spacing: 0.04em; opacity: 0.75; + transition: transform 140ms var(--ease-out), opacity 140ms ease; +} +.cr-tab.is-on { opacity: 1; background: var(--signal); color: var(--signal-ink); border-color: var(--signal-ink); box-shadow: 0 3px 0 var(--signal-ink); transform: translateY(-2px); } +.cr-tab:active { transform: scale(0.95); } +.cr-tab:focus-visible { outline: 3px solid var(--signal); outline-offset: 1px; } +.cr-badge { + position: absolute; top: 1px; right: 3px; min-width: 18px; height: 18px; padding: 0 4px; border-radius: 999px; + background: var(--stamp); color: var(--navy-ink); font: 800 12px/18px var(--font-num); font-style: normal; letter-spacing: 0; text-align: center; +} +.cr-tabpanel { min-height: 0; display: grid; align-content: start; gap: 18px; padding: 14px 16px 20px; animation: cr-panel-in 240ms var(--ease-out) both; } +@keyframes cr-panel-in { from { opacity: 0; transform: translateY(8px); } } +.cr-tabhead { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; } +.cr-tabhead h2 { margin: 0; font-family: var(--font-serif); font-size: 24px; } +.cr-tabhead p { margin: 0; color: var(--muted); font-size: 14px; font-weight: 700; } + +.cr-sec { display: grid; gap: 10px; } +.cr-sec-h { margin: 0; display: flex; align-items: baseline; justify-content: space-between; gap: 8px; font-family: var(--font-serif); font-size: 17px; } +.cr-sec-h small { color: var(--muted); font-family: var(--font-body); font-size: 13px; font-weight: 800; } +.cr-note { margin: 0; color: var(--muted); font-size: 13px; font-weight: 600; line-height: 1.5; } +.cr-note.is-warn { color: var(--stamp); font-weight: 800; } + +/* 造型格子 */ +.cr-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); gap: 12px 10px; } +.cr-tiles.is-wide { grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); } +.cr-tile { + position: relative; display: grid; justify-items: center; align-content: start; gap: 4px; min-height: 48px; padding: 6px 6px 8px; + border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); color: var(--ink); + box-shadow: 3px 3px 0 var(--shadow-ink); font-size: 13px; font-weight: 800; line-height: 1.2; text-align: center; + transition: transform 140ms var(--ease-out); +} +.cr-tiles.is-text .cr-tile { align-content: center; } +.cr-tile.is-on { background: var(--signal); color: var(--signal-ink); transform: translateY(-2px); box-shadow: 3px 5px 0 var(--shadow-ink); } +.cr-tile:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.cr-tile:focus-visible, .cr-swatch:focus-visible, .cr-origin:focus-visible, .cr-step:focus-visible, .cr-tool:focus-visible, .cr-delete:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.cr-tile-art { width: 100%; aspect-ratio: 1; display: grid; place-items: center; overflow: hidden; border-radius: 9px; background: color-mix(in srgb, var(--ink) 7%, transparent); } +.cr-tile.is-on .cr-tile-art { background: color-mix(in srgb, var(--tv-ink) 65%, transparent); } +.cr-tile-art .avatar { display: block; width: 100%; height: auto; } +.cr-tiles.is-face .cr-tile-art .avatar { transform: translateY(12%) scale(1.9); } +.cr-tiles.is-head .cr-tile-art .avatar { transform: translateY(15%) scale(1.35); } +.cr-tiles.is-none .cr-tile-art .avatar { transform: translateY(5%); } +/* 還沒拿到:灰色、鎖頭、下面寫怎麼拿到(跟圖鑑灰卡同一種做法) */ +.cr-tile.is-locked { border-style: dashed; border-color: var(--muted); background: var(--surface-2); box-shadow: none; } +.cr-tile.is-locked .cr-tile-art { filter: grayscale(1); opacity: 0.5; } +.cr-tile.is-locked .cr-tile-label { color: var(--muted); } +.cr-tile-how { display: flex; align-items: flex-start; justify-content: center; gap: 2px; color: var(--muted); font-size: 11px; font-weight: 700; line-height: 1.25; } +.cr-tile-how svg { flex: none; margin-top: 1px; } +/* 稀有度角標 */ +.cr-rarity { + position: absolute; top: -8px; left: -6px; padding: 1px 7px; border: 2px solid var(--ink); border-radius: 999px; + background: #7a5cc4; color: #fff; font-size: 11px; font-weight: 900; letter-spacing: 0.06em; transform: rotate(-6deg); +} +.cr-rarity.is-limited { background: var(--stamp); } +.cr-tile.is-locked .cr-rarity { opacity: 0.75; } +.cr-note.is-lock { padding: 8px 12px; border: 2px dashed var(--muted); border-radius: 12px; color: var(--ink); font-weight: 700; } +.cr-note.is-lock a { display: inline-block; margin: -12px 0 -12px 6px; padding: 12px 4px; color: var(--stamp); font-weight: 900; } +.cr-tick { + position: absolute; top: -9px; right: -9px; width: 24px; height: 24px; display: grid; place-items: center; border-radius: 50%; + border: 2px solid var(--signal-ink); background: var(--stamp); color: var(--navy-ink); + animation: cr-tick 260ms var(--ease-out) both; +} +@keyframes cr-tick { from { opacity: 0; transform: scale(0.4); } } + +/* 色票 */ +.cr-swatches { display: flex; flex-wrap: wrap; gap: 12px; } +.cr-swatch { + position: relative; width: 46px; height: 46px; padding: 0; border-radius: 50%; + border: 3px solid var(--ink); background: var(--sw); box-shadow: 2px 2px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.cr-swatch.is-on { transform: scale(1.08); box-shadow: 0 0 0 3px var(--surface), 0 0 0 6px var(--ink); } +.cr-swatch:active { transform: scale(0.94); } +.cr-swatch .cr-tick { top: -7px; right: -7px; width: 20px; height: 20px; } + +/* 名字、政黨 */ +.cr-name { + width: 100%; min-height: 54px; padding: 8px 14px; + border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); color: var(--ink); + box-shadow: inset 3px 3px 0 color-mix(in srgb, var(--ink) 10%, transparent); + font: inherit; font-family: var(--font-serif); font-size: 24px; letter-spacing: 0.08em; +} +.cr-name::placeholder { color: var(--muted); opacity: 0.7; } +.cr-name:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.cr-name.is-bad { border-color: var(--stamp); } +.cr-tiles.is-party { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.cr-party { display: flex; align-items: center; justify-content: flex-start; gap: 10px; min-height: 58px; padding: 8px 10px; border-bottom-width: 9px; border-bottom-color: var(--party); font-size: 15px; text-align: left; } +.cr-party-flag { display: inline-flex; flex: none; } +.cr-flag-none { display: inline-block; width: 39px; height: 26px; border-radius: 3px; background: var(--slot-other); } +.cr-poster .poster { width: 100%; } +.cr-delete { + justify-self: start; display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 8px 14px; + border: 2px dashed var(--stamp); border-radius: 12px; background: none; color: var(--stamp); font-weight: 800; +} +.cr-delete.is-armed { border-style: solid; background: var(--stamp); color: var(--navy-ink); } + +/* 出身 */ +.cr-origins { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 10px; } +.cr-origin { + position: relative; display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: center; column-gap: 10px; + min-height: 66px; padding: 8px 10px; text-align: left; + border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); color: var(--ink); box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.cr-origin-ic { grid-row: span 2; width: 40px; height: 40px; display: grid; place-items: center; border-radius: 10px; background: var(--navy); color: var(--navy-ink); } +.cr-origin b { font-family: var(--font-serif); font-size: 16px; line-height: 1.2; } +.cr-origin small { color: var(--muted); font-size: 12px; font-weight: 600; line-height: 1.35; } +.cr-origin.is-on { background: var(--signal); color: var(--signal-ink); transform: translateY(-2px); box-shadow: 3px 5px 0 var(--shadow-ink); } +.cr-origin.is-on small { color: color-mix(in srgb, var(--signal-ink) 75%, transparent); } +.cr-origin.is-on .cr-origin-ic { background: var(--stamp); } +.cr-origin:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } + +/* 能力點數 */ +.cr-pot { + display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px; padding: 10px 14px; + border: 3px solid var(--ink); border-radius: 16px; background: var(--navy); color: var(--navy-ink); box-shadow: 3px 3px 0 var(--shadow-ink); +} +.cr-pot-coin { + width: 58px; height: 58px; display: grid; place-items: center; border-radius: 50%; + border: 3px solid var(--signal-ink); background: var(--signal); color: var(--signal-ink); + box-shadow: inset 0 -5px 0 color-mix(in srgb, var(--signal-ink) 20%, transparent); + font: 900 30px/1 var(--font-num); font-variant-numeric: tabular-nums; +} +.cr-pot.is-over .cr-pot-coin { background: var(--stamp); color: var(--navy-ink); } +.cr-pot-txt { display: grid; gap: 2px; } +.cr-pot-txt b { font-family: var(--font-serif); font-size: 18px; } +.cr-pot-txt small { font-size: 12px; font-weight: 700; opacity: 0.8; } +.cr-pot-tools { display: flex; flex-wrap: wrap; gap: 8px; } +.cr-tool { + display: inline-flex; align-items: center; gap: 6px; min-height: 44px; padding: 6px 14px; + border: 2px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); + font-size: 14px; font-weight: 800; box-shadow: 2px 2px 0 var(--shadow-ink); transition: transform 120ms var(--ease-out); +} +.cr-tool:active { transform: translate(2px, 2px); box-shadow: none; } +.cr-stats { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; } +.cr-stat { display: grid; gap: 6px; padding: 10px 12px; border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); } +.cr-stat-txt { margin: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 10px; } +.cr-stat-txt b { font-family: var(--font-serif); font-size: 17px; } +.cr-stat-txt small { color: var(--muted); font-size: 12px; font-weight: 600; } +.cr-stat-ctl { display: grid; grid-template-columns: 44px minmax(0, 1fr) 44px 32px; align-items: center; gap: 8px; } +.cr-step { + width: 44px; height: 44px; display: grid; place-items: center; padding: 0; + border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); box-shadow: 2px 2px 0 var(--shadow-ink); + transition: transform 120ms var(--ease-out); +} +.cr-step.is-plus { background: var(--signal); color: var(--signal-ink); } +.cr-step:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: none; } +.cr-step:disabled { opacity: 0.35; box-shadow: none; } +.cr-pips { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); align-items: end; gap: 3px; height: 26px; } +.cr-pips i { height: 100%; border-radius: 4px; background: color-mix(in srgb, var(--ink) 14%, transparent); transform: scaleY(0.45); transform-origin: 50% 100%; transition: transform 220ms var(--ease-out); } +.cr-pips i.is-on { background: var(--stamp); transform: none; } +.cr-stat-val { font: 900 26px/1 var(--font-num); font-variant-numeric: tabular-nums; text-align: right; } + +/* ── 下面的大按鈕 ── */ +.cr-cta { grid-area: cta; display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: stretch; gap: 12px; } +.cr-save, .cr-go { border: 3px solid var(--signal-ink); border-radius: 16px; transition: transform 140ms var(--ease-out); } +.cr-save { + display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 56px; padding: 8px 18px; + background: var(--tv-ink); color: var(--signal-ink); box-shadow: 4px 4px 0 var(--signal-ink); font-size: 16px; font-weight: 800; +} +.cr-save:disabled { box-shadow: none; } +.cr-save:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 2px 2px 0 var(--signal-ink); } +.cr-go { + display: flex; align-items: center; justify-content: center; gap: 12px; min-height: 64px; padding: 8px 22px; + background: var(--stamp); color: var(--navy-ink); box-shadow: 5px 5px 0 var(--signal-ink); text-align: left; +} +.cr-go span { display: grid; min-width: 0; } +.cr-go b { font-family: var(--font-serif); font-size: clamp(18px, 1.9vw, 26px); line-height: 1.15; letter-spacing: 0.06em; } +.cr-go small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 700; opacity: 0.9; } +.cr-go.is-locked { background: color-mix(in srgb, var(--stamp) 40%, var(--navy-2)); cursor: not-allowed; } +.cr-go:active { transform: translate(3px, 3px); box-shadow: 2px 2px 0 var(--signal-ink); } +.cr-save:focus-visible, .cr-go:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } + +@media (hover: hover) and (pointer: fine) { + .cr-slot:hover { transform: translateY(-3px); } + .cr-tab:not(.is-on):hover { opacity: 1; transform: translateY(-2px); } + .cr-tile:not(.is-on):hover, .cr-origin:not(.is-on):hover { transform: translateY(-3px); } + .cr-swatch:not(.is-on):hover { transform: scale(1.1); } + .cr-dice:hover, .cr-tool:hover, .cr-step:not(:disabled):hover, .cr-save:not(:disabled):hover { background: var(--signal); color: var(--signal-ink); } + .cr-dice:hover svg { transform: rotate(20deg); } + .cr-go:not(.is-locked):hover { transform: translateY(-2px); } +} + +/* ── 平板、手機:舞台在上、分頁在中間、大按鈕在最下面;衣櫃疊在舞台左側 ── */ +@media (max-width: 820px) { + .cr-room { + gap: 10px; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(200px, 36fr) minmax(0, 64fr) auto; + grid-template-areas: "stage" "panel" "cta"; + } + .cr-rail { grid-area: stage; z-index: 5; justify-self: start; width: 64px; grid-template-rows: minmax(0, 1fr); } + .cr-rail-h, .cr-slot-name { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .cr-rail-list { gap: 10px; padding: 8px; } + .cr-slot { width: 48px; } + .cr-slot-face { width: 48px; height: 48px; border-radius: 50%; box-shadow: 2px 2px 0 var(--signal-ink); } + .cr-stage { --fig: min(64cqh, 56cqw, 460px); --b: 2cqh; } + .cr-mirror { --frame: 6px; width: min(calc(var(--fig) * 1.55), 100cqw - 136px); border-radius: 20px 20px 8px 8px; } + .cr-bulb { width: 9px; height: 9px; margin: -4.5px 0 0 -4.5px; } + .cr-sign { left: 10%; right: 10%; top: 20%; bottom: 18%; padding: 1px 4px; border-width: 2px; } + .cr-tabs { gap: 2px; padding: 6px; } + .cr-tab { min-height: 46px; padding: 3px 2px; font-size: 12px; letter-spacing: 0; } + .cr-tab svg { width: 18px; height: 18px; } + .cr-tabpanel { gap: 16px; padding: 12px 12px 18px; } + .cr-tabhead h2 { font-size: 20px; } + .cr-tiles { grid-template-columns: repeat(auto-fill, minmax(78px, 1fr)); } + .cr-cta { gap: 8px; } + .cr-save { min-height: 56px; padding: 6px 12px; font-size: 14px; } + .cr-go { min-height: 56px; gap: 8px; padding: 6px 12px; box-shadow: 4px 4px 0 var(--signal-ink); } + .cr-go b { font-size: 17px; letter-spacing: 0.02em; } + .cr-go small { font-size: 11px; } +} +@media (max-width: 820px) and (min-height: 960px) { + .cr-room { grid-template-rows: minmax(200px, 46fr) minmax(0, 54fr) auto; } +} +@media (max-width: 380px) { + .cr-origins { grid-template-columns: minmax(0, 1fr); } +} + +@media (prefers-reduced-motion: reduce) { + .cr-bulb, .cr-spot, .cr-breathe, .cr-tabpanel, .cr-tick, .cr-card-preview { animation: none; } + .cr-bubble { animation: cr-say-fade 2800ms linear both; } + .cr-pips i, .cr-slot, .cr-tab, .cr-tile, .cr-origin, .cr-swatch, .cr-step, .cr-tool, .cr-save, .cr-go, .cr-dice, .cr-dice svg { transition: none; } +} +@keyframes cr-say-fade { 0% { opacity: 0; } 6%, 88% { opacity: 1; } 100% { opacity: 0; } } + +/* 更多政黨(18 第 52 項):可搜尋的清單,歷屆推出過候選人的政黨都有 */ +.cr-more-parties { display: grid; gap: 8px; margin-top: 10px; } +.cr-more-toggle { justify-self: start; display: inline-flex; align-items: center; gap: 6px; min-height: 44px; padding: 6px 14px; border: 2px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); font: inherit; font-weight: 800; font-size: 14px; cursor: pointer; } +.cr-more-toggle[aria-expanded="true"] { background: var(--ink); color: var(--surface); } +.cr-more-toggle:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.cr-more-body { display: grid; gap: 8px; } +.cr-party-search { min-height: 46px; padding: 6px 14px; border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; font-size: 16px; } +.cr-party-search:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.cr-party-list { list-style: none; margin: 0; padding: 4px; display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 6px; max-height: 300px; overflow-y: auto; overscroll-behavior: contain; border: 2px solid var(--line); border-radius: 12px; } +.cr-party-list button { width: 100%; min-height: 48px; display: grid; gap: 1px; padding: 6px 10px; text-align: left; border: 2px solid var(--line); border-radius: 10px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; } +.cr-party-list button b { font-size: 15px; } +.cr-party-list button small { font-size: 11px; color: var(--muted); font-weight: 700; } +.cr-party-list button[aria-pressed="true"] { border: 3px solid var(--ink); background: var(--signal); color: var(--signal-ink); } +.cr-party-list button[aria-pressed="true"] small { color: #3a3a3a; } +.cr-party-list button:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } + +/* 黨的資源(18 第 53 項) */ +.cr-party-perks { display: grid; gap: 2px; margin-top: 10px; padding: 8px 12px; border: 2px dashed var(--line); border-radius: 12px; font-size: 13px; line-height: 1.5; } +.cr-party-perks span { color: var(--muted); font-weight: 600; } +.cr-party-perks .is-cost { color: var(--stamp); } diff --git a/web/src/game/creator/options.ts b/web/src/game/creator/options.ts new file mode 100644 index 0000000..34f367f --- /dev/null +++ b/web/src/game/creator/options.ts @@ -0,0 +1,153 @@ +import { BACKGROUNDS, STAT_BUDGET, STAT_MAX, avatarItem, slotItems, type CustomCandidate } from "@election2026/protocol"; +import { + Briefcase, + Building2, + Glasses, + GraduationCap, + HardHat, + Home, + IdCard, + Landmark, + Megaphone, + Mic, + Palette, + Scale, + Scissors, + Shirt, + Smartphone, + Smile, + Sparkles, + Stethoscope, + UserRound, + type LucideIcon, +} from "lucide-react"; +import type { AvatarSpec, HairStyle } from "../art/Avatar.tsx"; +import { FEATURED_PARTIES, partyShort, partySlot } from "../parties.ts"; + +/** 捏人物的選項清單(docs/15)。顏色色盤在 art/palette.ts,這裡只放「選哪一種」。 */ + +export type Option = { id: T; label: string }; +export type StatKey = keyof CustomCandidate["stats"]; +export type Party = CustomCandidate["party"]; +export type Background = CustomCandidate["background"]; + +/** 某個部位的選項:照部件目錄(docs/24)列,名字也是目錄裡的 */ +const fromCatalog = (slot: string): Option[] => slotItems(slot).map((i) => ({ id: i.id, label: i.name })); + +export const HAIR_STYLES: Option[] = fromCatalog("hair"); +/** 這些髮型有分線,可以選往左或往右分 */ +export const PARTED_HAIR: readonly HairStyle[] = slotItems("hair") + .filter((i) => i.flags.includes("parted")) + .map((i) => i.id); +export const PARTS: Option>[] = [ + { id: "left", label: "往左分" }, + { id: "right", label: "往右分" }, +]; + +export const OUTFITS: Option[] = fromCatalog("outfit"); +/** 有領帶的服裝、襯衫那一塊叫「領子」的服裝 */ +export const hasTie = (outfit: string): boolean => !!avatarItem("outfit", outfit)?.flags.includes("tie"); +export const hasCollar = (outfit: string): boolean => !!avatarItem("outfit", outfit)?.flags.includes("collar"); +/** 頭像背景色(頭像本身的色盤,和畫面主題色無關) */ +export const BGS = ["#dfe8f0", "#f1e4d3", "#e3eedf", "#efe0e6", "#e6e2f3", "#f6e7b8"] as const; + +export const FACES: Option[] = fromCatalog("face"); +export const EYES: Option[] = fromCatalog("eyes"); +export const BROWS: Option[] = fromCatalog("brows"); +export const MOUTHS: Option[] = fromCatalog("mouth"); +export const AGES: Option<"0" | "1" | "2">[] = [ + { id: "0", label: "政壇新人" }, + { id: "1", label: "有點歷練" }, + { id: "2", label: "資深老將" }, +]; + +export type GlassesId = string; +export const GLASSES: Option[] = [{ id: "none", label: "不戴" }, ...fromCatalog("glasses")]; +export type BeardId = "none" | "mustache" | "beard" | "both"; +export const BEARDS: Option[] = [ + { id: "none", label: "乾淨" }, + { id: "mustache", label: "小鬍子" }, + { id: "beard", label: "落腮鬍" }, + { id: "both", label: "全套" }, +]; +export const beardOf = (a: AvatarSpec): BeardId => (a.beard && a.mustache ? "both" : a.beard ? "beard" : a.mustache ? "mustache" : "none"); +export const beardPatch = (id: BeardId): Partial => ({ beard: id === "beard" || id === "both", mustache: id === "mustache" || id === "both" }); + +export interface PartyOption { + id: Party; + label: string; + short: string; + slot: "a" | "b" | "c" | "other"; + line: string; +} +export const partyOf = (id: Party): PartyOption => ({ + id, + label: id ?? "無黨籍", + short: partyShort(id), + slot: partySlot(id), + line: id ? `代表${partyShort(id)}參選!` : "無黨籍,靠自己!", +}); +/** 直接列出來的政黨:推出候選人最多的幾個+無黨籍;其他政黨到「更多政黨」搜尋(parties.ts) */ +export const PARTIES: PartyOption[] = [...FEATURED_PARTIES.map(partyOf), partyOf(null)]; + +export const BACKGROUND_INFO: Record = { + 醫師: { note: "口才加分,長輩較信任", Icon: Stethoscope }, + 律師: { note: "口才大幅加分", Icon: Scale }, + 教授: { note: "口才與謀略加分", Icon: GraduationCap }, + 前藝人: { note: "知名度大幅加分", Icon: Mic }, + 網紅: { note: "知名度加分,小額募款多三成", Icon: Smartphone }, + 政二代: { note: "地方組織現成,知名度加分", Icon: Landmark }, + 基層里長: { note: "地方組織強,但全市知名度較低", Icon: Home }, + 企業家: { note: "多 800 萬起始資金", Icon: Briefcase }, + 前官員: { note: "謀略加分,知名度加分", Icon: Building2 }, + 社運出身: { note: "知名度與口才小幅加分", Icon: Megaphone }, +}; +export { BACKGROUNDS, STAT_BUDGET, STAT_MAX }; +/** 「醫師」→「醫師出身」;「社運出身」本身就有出身兩個字 */ +export const originText = (b: Background): string => (b.endsWith("出身") ? b : `${b}出身`); + +export const STAT_KEYS: StatKey[] = ["fame", "eloquence", "strategy", "wealth", "network"]; +export const STAT_LABELS: Record = { + fame: { label: "知名度", note: "開局有多少人認識你" }, + eloquence: { label: "口才", note: "上節目、記者會的效果與失言機率" }, + strategy: { label: "謀略", note: "選戰判斷、祕密行動" }, + wealth: { label: "財力", note: "起始資金與自掏腰包上限" }, + network: { label: "人脈", note: "地方組織與幕僚人數" }, +}; + +export type TabId = "face" | "hair" | "outfit" | "extra" | "gear" | "props" | "style" | "name" | "origin" | "stats"; +/** 外觀分頁(新部位的分頁照目錄的 slots.tab 放:gear 行頭、props 道具、extra 配件的口罩) */ +export const TABS: { id: TabId; label: string; title: string; Icon: LucideIcon }[] = [ + { id: "face", label: "臉部", title: "膚色、臉型、表情", Icon: Smile }, + { id: "hair", label: "髮型", title: "髮型、髮色", Icon: Scissors }, + { id: "outfit", label: "服裝", title: "衣服、配色、背景", Icon: Shirt }, + { id: "extra", label: "配件", title: "眼鏡、口罩、鬍子", Icon: Glasses }, + { id: "gear", label: "行頭", title: "帽子、背心、彩帶、胸花", Icon: HardHat }, + { id: "props", label: "道具", title: "手上拿的、頭像外框", Icon: Megaphone }, + { id: "style", label: "畫風", title: "漫畫、Q 版、像素、貼紙", Icon: Palette }, + { id: "name", label: "名字", title: "名字、政黨", Icon: IdCard }, + { id: "origin", label: "出身", title: "出身會影響開局", Icon: UserRound }, + { id: "stats", label: "能力", title: `${STAT_BUDGET} 點自由分配`, Icon: Sparkles }, +]; + +/** 能力加減一點:每項 0–STAT_MAX,總和不超過 STAT_BUDGET(超過時只能減) */ +export function bumpStat(stats: CustomCandidate["stats"], key: StatKey, delta: 1 | -1): CustomCandidate["stats"] { + const used = STAT_KEYS.reduce((sum, k) => sum + stats[k], 0); + const next = stats[key] + delta; + if (next < 0 || next > STAT_MAX) return stats; + if (delta > 0 && used >= STAT_BUDGET) return stats; + return { ...stats, [key]: next }; +} + +/** 隨機把點數分完(每項不超過上限) */ +export function randomStats(rand: () => number = Math.random): CustomCandidate["stats"] { + const stats = { fame: 0, eloquence: 0, strategy: 0, wealth: 0, network: 0 }; + for (let left = STAT_BUDGET; left > 0; ) { + const open = STAT_KEYS.filter((k) => stats[k] < STAT_MAX); + if (open.length === 0) break; + const k = open[Math.floor(rand() * open.length)]!; + stats[k] += 1; + left -= 1; + } + return stats; +} diff --git a/web/src/game/format.ts b/web/src/game/format.ts new file mode 100644 index 0000000..c46ab38 --- /dev/null +++ b/web/src/game/format.ts @@ -0,0 +1,5 @@ +import type { PartySlotKey } from "@election2026/protocol"; + +export const slotColor = (slot: PartySlotKey): string => `var(--slot-${slot})`; + +export const pct = (x: number, digits = 1): string => `${(x * 100).toFixed(digits)}%`; diff --git a/web/src/game/game.css b/web/src/game/game.css new file mode 100644 index 0000000..42f497b --- /dev/null +++ b/web/src/game/game.css @@ -0,0 +1,178 @@ +/* 選舉小鎮遊戲畫面。視覺語彙:選舉公報、報紙、選票圈選章、電視開票(docs/17)。顏色一律用 tokens.css 的變數。 */ + +.game { min-height: 100dvh; display: grid; grid-template-rows: auto 1fr; background: var(--paper); } +.screen-center { min-height: 60dvh; display: grid; place-items: center; gap: 12px; padding: 24px; color: var(--muted); } +.muted { color: var(--muted); } +.small { font-size: 13px; } +.notice { background: color-mix(in srgb, var(--stamp) 10%, var(--surface)); border: 1px solid color-mix(in srgb, var(--stamp) 40%, var(--line)); border-radius: 8px; padding: 8px 12px; margin: 0; font-size: 14px; } +.tone-negative { color: color-mix(in srgb, var(--stamp) 75%, var(--ink)); } + +/* ── 按鈕 ── */ +button { font: inherit; color: inherit; cursor: pointer; } +button:disabled { cursor: not-allowed; opacity: 0.5; } +.btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border-radius: 10px; padding: 8px 14px; border: 1px solid transparent; font-weight: 600; text-decoration: none; transition: transform 120ms var(--ease-out), background-color 150ms ease; } +.btn:active:not(:disabled) { transform: scale(0.97); } +.btn-primary { background: var(--ink); color: var(--paper); } +.btn-soft { background: var(--surface-2); border-color: var(--line); color: var(--ink); } +.btn-ghost { background: none; border-color: var(--line); color: var(--ink); } +.btn-sm { padding: 4px 10px; font-size: 13px; } +.btn-lg { padding: 12px 22px; font-size: 17px; } +@media (hover: hover) and (pointer: fine) { + .btn-soft:hover:not(:disabled), .btn-ghost:hover:not(:disabled) { background: var(--surface); } +} +select, input[type="range"] { width: 100%; font: inherit; } +select { padding: 6px 8px; border-radius: 6px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); } + +/* ── 徽章、看板、黨旗 ── */ +.cand-badge { display: inline-grid; place-items: center; border-radius: 50%; color: #fff; font-weight: 900; font-family: var(--font-num); box-shadow: 0 0 0 2px var(--paper); flex: none; } +.cand-badge.has-avatar { overflow: hidden; padding: 2px; } +.cand-badge.has-avatar .avatar { width: 100%; height: auto; border-radius: 50%; transform: translateY(6%) scale(1.25); } +.poster.has-avatar { padding-right: 8px; } +.poster-avatar { position: absolute; right: 6px; bottom: 0; opacity: 0.95; } +.poster-avatar .avatar { display: block; } +.poster.has-avatar .poster-flag { right: auto; left: 8px; top: auto; bottom: 6px; } +.party-flag { flex: none; border-radius: 2px; } +.ballot-stamp { flex: none; } + +.poster { --poster-color: var(--slot-other); position: relative; display: grid; grid-template-columns: auto 1fr; grid-template-rows: 1fr auto; gap: 2px 8px; background: var(--poster-color); color: #fff; border-radius: 8px; padding: 10px; overflow: hidden; isolation: isolate; } +.poster::before { content: ""; position: absolute; inset: 0; background: repeating-linear-gradient(135deg, rgb(255 255 255 / 0.07) 0 6px, transparent 6px 14px); z-index: -1; } +.poster-number { grid-row: 1 / 3; font-family: var(--font-num); font-weight: 900; line-height: 1; background: #fff; color: var(--poster-color); border-radius: 50%; display: grid; place-items: center; align-self: start; } +.poster-name { font-family: var(--font-serif); font-weight: 900; letter-spacing: 0.08em; line-height: 1.1; } +.poster-flag { position: absolute; right: 8px; top: 8px; } +.poster-party { font-size: 12px; opacity: 0.9; } +.poster-sm { padding: 6px 8px; min-width: 112px; } +.poster-sm .poster-number { width: 28px; height: 28px; font-size: 16px; } +.poster-sm .poster-name { font-size: 16px; } +.poster-sm .poster-flag { display: none; } +.poster-md { min-width: 128px; } +.poster-md .poster-number { width: 34px; height: 34px; font-size: 19px; } +.poster-md .poster-name { font-size: 20px; padding-right: 24px; } +.poster-lg { min-height: 132px; padding: 14px; } +.poster-lg .poster-number { width: 48px; height: 48px; font-size: 28px; } +.poster-lg .poster-name { font-size: 30px; align-self: end; } + +/* ── 開始畫面 ── */ +.start { min-height: 100dvh; display: grid; gap: 20px; align-content: start; padding: 32px 16px 24px; max-width: 1120px; margin: 0 auto; } +.hero h1 { margin: 0; color: #1f1d1a; font-family: var(--font-serif); font-weight: 900; font-size: clamp(44px, 9vw, 104px); letter-spacing: 0.12em; line-height: 1; display: flex; align-items: baseline; gap: 12px; } +.hero h1 span { font-family: var(--font-num); font-size: 0.32em; letter-spacing: 0.05em; color: var(--stamp); } +.pick { display: grid; gap: 12px; background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 20px; } +.sources { font-size: 14px; } +.sources summary { cursor: pointer; font-weight: 700; } +.sources ul { margin: 8px 0; padding-left: 20px; display: grid; gap: 4px; } +.sources a { color: inherit; } + +/* ── 頂部狀態列 ── */ +.me { display: flex; align-items: center; gap: 8px; } +.bar { display: inline-block; width: 52px; height: 7px; border-radius: 4px; background: var(--surface-2); border: 1px solid var(--line); overflow: hidden; } +.bar span { display: block; height: 100%; background: var(--good); transform-origin: left; transition: transform 400ms var(--ease-out); } +.bar.is-cap span { background: var(--muted); } + +/* ── 版面:左邊地圖、右邊面板 ── */ +.board { display: grid; grid-template-columns: minmax(0, 1fr) minmax(420px, 520px); gap: 14px; padding: 14px; align-items: start; } +@media (max-width: 1000px) { .board { grid-template-columns: minmax(0, 1fr); } } +/* 桌機:地圖、手牌、跑馬燈剛好一個畫面高,地圖自己縮放,不用捲動 */ +.map-loading { aspect-ratio: 760 / 640; display: grid; place-items: center; color: var(--muted); } +.side { display: grid; gap: 10px; align-content: start; min-width: 0; } +.side-body { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; padding: 14px; min-height: 200px; } + +/* ── 地圖舞台 ── */ +.stage { display: block; width: 100%; height: auto; } +.stage .is-clickable { cursor: pointer; } +.sea-label { font-family: var(--font-serif); font-size: 18px; letter-spacing: 0.6em; fill: var(--sea-line); font-weight: 700; } +.neighbor-label { font-size: 13px; fill: var(--muted); letter-spacing: 0.3em; } +.town-label { font-size: 13px; font-weight: 700; fill: var(--ink); paint-order: stroke; stroke: var(--paper); stroke-width: 3px; stroke-linejoin: round; } +.town-label.is-selected { font-size: 15px; } +.marker-more { font-size: 11px; font-weight: 700; fill: var(--ink); paint-order: stroke; stroke: var(--paper); stroke-width: 3px; } +.town-highlight { fill: rgb(255 255 255 / 0.18); stroke: var(--ink); stroke-width: 2.4px; stroke-dasharray: 5 3; } +.marker.is-fresh { animation: marker-in 260ms var(--ease-out) both; transform-box: fill-box; transform-origin: center; } +@keyframes marker-in { from { opacity: 0; transform: scale(0.6); } } +.token { transition: transform 600ms var(--ease-in-out); } +.token-inner { display: grid; place-items: center; width: 30px; height: 30px; filter: drop-shadow(0 2px 3px rgb(0 0 0 / 0.35)); } +.float-text { font-size: 15px; font-weight: 900; paint-order: stroke; stroke: var(--paper); stroke-width: 4px; animation: float-up 1000ms var(--ease-out) both; } +.float-text.tone-good { fill: var(--good); } +.float-text.tone-bad { fill: var(--stamp); } +@keyframes float-up { from { opacity: 0; transform: translateY(8px); } 30% { opacity: 1; } to { opacity: 1; transform: translateY(-6px); } } +@keyframes card-in { from { opacity: 0; transform: translateY(-4px); } } + +/* ── 跑馬燈 ── */ +.ticker { display: flex; align-items: center; gap: 10px; background: var(--ink); color: var(--paper); border-radius: 10px; padding: 6px 10px; font-size: 14px; overflow: hidden; } +.ticker.is-empty { justify-content: center; letter-spacing: 0.2em; } +.ticker .tone-negative { color: #ffb3ae; } +@keyframes ticker { to { transform: translateX(-50%); } } + +/* ── 行程表 ── */ +.plan { display: grid; gap: 10px; } + +/* ── 選擇行動 ── */ +@keyframes fade-in { from { opacity: 0; } } +@keyframes modal-in { from { opacity: 0; transform: scale(0.97) translateY(6px); } } +.ghost { background: none; border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; } +.primary { background: var(--ink); color: var(--paper); border: 0; border-radius: 8px; padding: 10px 16px; font-weight: 700; } + +/* ── 民調、新聞、戰報(側邊面板) ── */ +.report { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; font-size: 14px; } +.news { display: grid; gap: 4px; } +.news summary { font-size: 14px; color: var(--muted); margin-top: 6px; cursor: pointer; font-weight: 700; } +.news ul { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 4px; font-size: 14px; } +.news li { display: flex; gap: 8px; align-items: baseline; } +.news .tier { font-size: 11px; border: 1px solid var(--line); border-radius: 4px; padding: 0 4px; color: var(--muted); flex: none; } +.bars { display: grid; gap: 6px; } + +/* ── 晨報 ── */ +.paper { position: relative; min-width: 0; width: min(980px, 100%); max-height: calc(100dvh - 32px); overflow: auto; background: var(--newsprint); color: var(--ink); border-radius: 4px; padding: 22px 26px; box-shadow: 0 20px 60px rgb(0 0 0 / 0.35); animation: paper-in 380ms var(--ease-out); isolation: isolate; } +.paper::before { content: ""; position: absolute; inset: 0; z-index: -1; background-image: radial-gradient(rgb(0 0 0 / 0.035) 1px, transparent 1px); background-size: 4px 4px; } +@keyframes paper-in { from { opacity: 0; transform: translateY(18px) rotate(-0.6deg) scale(0.98); } } +@media (max-width: 720px) { + .paper { padding: 14px; max-height: calc(100dvh - 16px); } +} +.col-title { margin: 6px 0 0; font-size: 13px; letter-spacing: 0.3em; border-bottom: 2px solid var(--ink); padding-bottom: 2px; } + +/* ── 開票夜(電視直播) ── */ +.tv { position: relative; display: grid; gap: 0; background: var(--tv-bg); color: var(--tv-ink); min-height: calc(100dvh - 58px); grid-template-rows: auto 1fr auto; } +@keyframes blink { 50% { opacity: 0.2; } } +@keyframes stamp-in { from { opacity: 0; transform: scale(1.6); } } +.tv .btn-ghost { color: var(--tv-ink); border-color: rgb(255 255 255 / 0.3); } +.verdict { position: relative; margin: 0 16px 16px; background: var(--surface); color: var(--ink); border-radius: 16px; padding: 18px; display: grid; gap: 10px; justify-items: start; overflow: hidden; animation: card-in 300ms var(--ease-out); } +.confetti { position: absolute; inset: 0; pointer-events: none; } +.confetti span { position: absolute; top: -12px; width: 8px; height: 14px; border-radius: 2px; animation: confetti-fall 1800ms var(--ease-out) both; } +@keyframes confetti-fall { from { opacity: 1; transform: translate(0, 0) rotate(0deg); } to { opacity: 0; transform: translate(var(--drift), 260px) rotate(540deg); } } + +/* ── 減少動態:保留淡入淡出,拿掉位移、縮放、跑馬燈與彩紙 ── */ +@media (prefers-reduced-motion: reduce) { + .marker.is-fresh, .verdict { animation: fade-in 160ms ease-out both; } + .paper { animation: fade-in 200ms ease-out both; } + .float-text { animation: fade-in 200ms ease-out both; } + .token, .bar span { transition: none; } + .confetti { display: none; } +} + +/* 候選人頭像(Q 版卡通):看板右邊的大頭像、徽章右下的號次 */ +.cand-badge.has-avatar { position: relative; overflow: visible; } +.cand-badge.has-avatar .avatar { border-radius: 50%; overflow: hidden; } +.cand-badge-num { + position: absolute; + right: -3px; + bottom: -3px; + display: grid; + place-items: center; + min-width: 15px; + height: 15px; + padding: 0 3px; + border-radius: 8px; + background: #fff; + color: #111419; + font-family: var(--font-num); + font-style: normal; + font-size: 11px; + font-weight: 900; + line-height: 1; + box-shadow: 0 0 0 1.5px currentColor; +} +.poster.has-avatar { padding-right: 10px; } +.poster-avatar { position: absolute; right: 2px; bottom: -4px; z-index: 0; pointer-events: none; filter: drop-shadow(0 4px 6px rgb(0 0 0 / 0.25)); } +.poster-number, .poster-name, .poster-party { position: relative; z-index: 1; } +.poster-name { text-shadow: 0 2px 0 rgb(0 0 0 / 0.25); } +.poster-lg .poster-name { padding-right: 112px; } +.poster-md .poster-name { padding-right: 66px; } +.poster-sm .poster-name { padding-right: 40px; } +.poster-lg .poster-party { padding-right: 112px; } diff --git a/web/src/game/home/HeroHand.tsx b/web/src/game/home/HeroHand.tsx new file mode 100644 index 0000000..fa3ba5a --- /dev/null +++ b/web/src/game/home/HeroHand.tsx @@ -0,0 +1,74 @@ +import { useEffect, useRef, useState } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { CardFace, type FaceData } from "../rogue/cards.tsx"; +import { flyCard } from "../rogue/juice.tsx"; +import type { HeroCheer } from "../start/HeroDiorama.tsx"; + +/** 首頁示範用的五張牌(數字是牌的基準值,真正開局會依縣市大小調整) */ +const DEMO: (FaceData & { id: string; cheer: Parameters[0]; votes: number })[] = [ + { id: "canvass", name: "掃街拜票", art: "street_canvass", cost: 1, money: null, rarity: "basic", value: "+1,720", text: "該區 +1,720;人口密集 ×1.3", tags: ["ground"], cheer: "crowd", votes: 1720 }, + { id: "rally", name: "造勢晚會", art: "rally", cost: 2, money: 200, rarity: "basic", value: "+3,450", text: "該區 +3,450、隔壁區兩成半,聲勢 +2", tags: ["rally"], cheer: "rally", votes: 3450 }, + { id: "truck", name: "宣傳車遊街", art: "sound_truck", cost: 1, money: 30, rarity: "common", value: "+1,150", text: "該區 +1,150,隔壁每一區也有一半", tags: ["ground"], cheer: "truck", votes: 1150 }, + { id: "temple", name: "宮廟參拜", art: "temple_visit", cost: 1, money: null, rarity: "basic", value: "+1,260", text: "該區 +1,260;宮廟多 ×2", tags: ["ground", "temple"], cheer: "crowd", votes: 2520 }, + { id: "tv", name: "電視廣告", art: "tv_ad", cost: 1, money: 300, rarity: "common", value: "+5,180", text: "全市 +5,180,長輩多的區分到較多", tags: ["media"], cheer: "crowd", votes: 5180 }, +]; + +/** + * 首頁小鎮右下角的一手牌:點一張就「打」進小鎮(牌飛過去、小鎮跟著動、跳出票數), + * 一進首頁就摸得到這個遊戲的核心動作。只是示範,不會影響任何一局。 + */ +export function HeroHand({ cheer }: { cheer: HeroCheer }) { + const [played, setPlayed] = useState(null); + const [pop, setPop] = useState<{ key: number; name: string; votes: number } | null>(null); + const [total, setTotal] = useState(0); + const [count, setCount] = useState(0); + const ref = useRef(null); + const timers = useRef[]>([]); + useEffect(() => () => timers.current.forEach(clearTimeout), []); + + const play = (card: (typeof DEMO)[number], el: HTMLElement) => { + if (played) return; + const stage = ref.current?.closest(".hero3d")?.querySelector(".hero3d-stage") ?? null; + flyCard(el, stage); + if (card.cheer === "rally") sfx.cheer(); + else if (card.cheer === "truck") sfx.alert(); + else sfx.place(); + cheer(card.cheer); + setPlayed(card.id); + setPop({ key: Date.now(), name: card.name, votes: card.votes }); + setTotal((t) => t + card.votes); + setCount((n) => n + 1); + timers.current.push( + setTimeout(() => sfx.combo(2), 260), + setTimeout(() => setPlayed(null), 900), + setTimeout(() => setPop(null), 1500), + ); + }; + + return ( +
+ {pop && ( + + {pop.name}+{pop.votes.toLocaleString("en-US")} 票 + + )} +

+ {count === 0 ? "點一張牌,打進小鎮試試" : count < 3 ? `已經拉了 ${total.toLocaleString("en-US")} 票` : `拉了 ${total.toLocaleString("en-US")} 票!真正的選戰:按「開始選戰」`} +

+
+ {DEMO.map((c, i) => ( + + ))} +
+
+ ); +} diff --git a/web/src/game/home/HomeScreen.tsx b/web/src/game/home/HomeScreen.tsx new file mode 100644 index 0000000..f9ff17b --- /dev/null +++ b/web/src/game/home/HomeScreen.tsx @@ -0,0 +1,61 @@ +import { BookOpen, Gamepad2, Landmark, Store, UserRoundPlus, Users, type LucideIcon } from "lucide-react"; +import { useEffect } from "react"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { TitleMenu } from "../rogue/RogueStart.tsx"; +import { HeroDiorama } from "../start/HeroDiorama.tsx"; +import { HeroHand } from "./HeroHand.tsx"; +import "./home.css"; + +const DOCK: { href: string; label: string; Icon: LucideIcon }[] = [ + { href: "#/rogue/collection", label: "圖鑑", Icon: BookOpen }, + { href: "#/island", label: "政策島", Icon: Landmark }, + { href: "#/people", label: "參選人", Icon: Users }, + { href: "#/create", label: "捏人物", Icon: UserRoundPlus }, + { href: "#/shop", label: "商店", Icon: Store }, + { href: "#/minigames", label: "小遊戲", Icon: Gamepad2 }, +]; + +/** + * 首頁=遊戲的標題畫面(docs/22、18 第 28、40、43 項):全螢幕的 3D 選戰小鎮,不捲動。 + * 左邊是標題和選單(繼續或開始選戰、自由選戰、每日一戰、政治生涯、新手教學),下面一排圓形圖示(圖鑑、政策島、參選人、捏人物、商店、小遊戲); + * 右下一手牌點了會打進小鎮。#/rogue(選戰大廳)也是這個畫面。 + */ +export function HomeScreen() { + useEffect(() => setMusic("theme-march"), []); + + const copy = ( +
+
+ ELECTION TOWN・台灣選戰卡牌 +

+ 選舉 + 小鎮 +

+

+ 出牌拉票 一區一區翻過來 +

+
+ + +

+ 地圖和開局底盤來自內政部、中選會公開資料・向 1994 年《臺灣模擬選戰》致敬・資料・美術 +

+
+ ); + + return ( +
+ } /> +
+ ); +} diff --git a/web/src/game/home/home.css b/web/src/game/home/home.css new file mode 100644 index 0000000..7aae5ee --- /dev/null +++ b/web/src/game/home/home.css @@ -0,0 +1,135 @@ +/* 首頁=遊戲的標題畫面:全螢幕 3D 小鎮、不捲動;左邊標題+選單,下面一排圓形圖示 */ +.home { height: 100dvh; overflow: hidden; background: #111419; color: var(--ink); } +.home .hero3d { width: 100%; height: 100dvh; min-height: 0; border: 0; border-radius: 0; box-shadow: none; } +.home .hero3d-stamp { display: none; } +.home .hero3d-game { left: auto; right: max(16px, env(safe-area-inset-right, 0px)); top: max(16px, env(safe-area-inset-top, 0px)); bottom: auto; translate: none; max-width: 340px; justify-content: flex-end; } +.home .hero3d::before { background: linear-gradient(90deg, rgb(17 20 25 / 0.78) 0%, rgb(17 20 25 / 0.45) 30%, transparent 52%); } + +.home .home-copy { + position: absolute; inset: 0 auto 0 0; width: min(460px, 44vw); min-height: 0; + display: flex; flex-direction: column; justify-content: center; gap: 18px; + padding: max(28px, env(safe-area-inset-top, 0px)) 28px max(20px, env(safe-area-inset-bottom, 0px)) max(36px, env(safe-area-inset-left, 0px)); +} +.home-logo { display: grid; gap: 8px; } +.home-logo .hero3d-title { font-size: clamp(52px, 6vw, 88px); } +.home-logo .hero3d-slogan { white-space: nowrap; font-size: clamp(18px, 2.2vw, 28px); } + +/* 標題選單 */ +.tmenu { display: grid; gap: 10px; } +.tmenu-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; } +.tmenu-item { + --c: var(--stamp); + display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; column-gap: 12px; align-items: center; + width: 100%; padding: 8px 16px 8px 8px; text-align: left; text-decoration: none; font: inherit; cursor: pointer; + background: rgb(255 250 240 / 0.95); color: #111419; border: 3px solid #111419; border-radius: 16px; box-shadow: 4px 4px 0 #111419; + transition: transform 160ms var(--ease-out), background-color 160ms ease; + animation: tmenu-in 380ms var(--ease-out) calc(280ms + var(--i, 0) * 70ms) both; +} +.tmenu-item > svg { grid-row: span 2; width: 44px; height: 44px; padding: 9px; border-radius: 12px; border: 2px solid #111419; background: var(--c); color: #fff; } +.tmenu-list li:nth-child(2) .tmenu-item { --c: #2f6fd1; } +.tmenu-list li:nth-child(3) .tmenu-item { --c: #1f8a4c; } +.tmenu-list li:nth-child(4) .tmenu-item { --c: #c99400; } +.tmenu-list li:nth-child(5) .tmenu-item { --c: #7a5cc4; } +.tmenu-item b { font-family: var(--font-serif); font-size: 22px; line-height: 1.15; } +.tmenu-item small { font-size: 12px; font-weight: 700; color: #5d6068; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.tmenu-item.is-primary { background: var(--signal); padding-block: 12px; } +.tmenu-item.is-primary b { font-size: 28px; } +.tmenu-item.is-primary small { color: #3a3a3a; } +.tmenu-item.is-primary > svg { --c: #d61f2c; width: 52px; height: 52px; } +.tmenu-item:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 2px 2px 0 #111419; } +.tmenu-item:disabled { opacity: 0.6; cursor: default; } +.tmenu-item:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +@media (hover: hover) and (pointer: fine) { .tmenu-item:hover:not(:disabled) { transform: translateX(8px); } } +@keyframes tmenu-in { from { opacity: 0; transform: translateX(-28px); } } +.tmenu-challenge { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; padding: 10px 12px; border: 3px solid #111419; border-radius: 16px; background: var(--stamp); color: #fff; box-shadow: 4px 4px 0 #111419; } +.tmenu-challenge span { display: grid; } +.tmenu-challenge small { font-size: 12px; opacity: 0.9; } +.tmenu-error { margin: 0; } +/* 自由選戰:在畫面上跳出設定,不換頁 */ +.tmenu-sheet-wrap { pointer-events: auto; z-index: 60; } +.tmenu-sheet { position: relative; width: min(980px, 100%); max-height: calc(100dvh - 32px); overflow-y: auto; color: var(--ink); } +.tmenu-sheet > h2 { margin: 0 40px 8px 0; font-family: var(--font-serif); font-size: 26px; } + +/* 下面一排圓形圖示 */ +.home-dock { display: flex; flex-wrap: wrap; gap: 10px 8px; margin-top: 6px; } +.home-dock a { display: grid; justify-items: center; gap: 4px; width: 56px; color: #fff; font-size: 12px; font-weight: 800; text-decoration: none; text-shadow: 0 1px 3px rgb(0 0 0 / 0.7); transition: transform 140ms var(--ease-out); } +.home-dock-ic { width: 50px; height: 50px; display: grid; place-items: center; border-radius: 50%; background: #fffaf0; color: #111419; border: 3px solid #111419; box-shadow: 3px 3px 0 #111419; } +.home-dock a:active { transform: scale(0.95); } +@media (hover: hover) and (pointer: fine) { .home-dock a:hover { transform: translateY(-4px); } .home-dock a:hover .home-dock-ic { background: var(--signal); } } +.home-legal { margin: 0; font-size: 11px; color: rgb(255 255 255 / 0.6); } +.home-legal a { color: inherit; } + +/* 示範手牌 */ +.home-hand { + position: absolute; z-index: 3; right: 44px; bottom: 62px; + display: grid; justify-items: center; gap: 4px; + --rg-card-w: 96px; + pointer-events: none; +} +.home-hand-tip { + margin: 0; padding: 4px 12px; border: 2px solid #111419; border-radius: 999px; + background: #fff; color: #111419; font-size: 13px; font-weight: 800; box-shadow: 3px 3px 0 #111419; +} +.home-hand-cards { display: flex; align-items: flex-end; padding: 18px 10px 0; } +.home-hand-card { + pointer-events: auto; flex: none; margin: 0 -12px; padding: 0; border: 0; background: none; cursor: pointer; + transform: translateY(var(--lift)) rotate(var(--fan)); transform-origin: 50% 120%; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), opacity 160ms ease-out; + animation: home-deal 420ms cubic-bezier(0.23, 1, 0.32, 1) calc(600ms + var(--i) * 70ms) both; +} +.home-hand-card.is-played { opacity: 0; transform: translateY(30px) rotate(0deg); } +.home-hand-card:focus-visible { outline: 3px solid var(--signal); outline-offset: 4px; border-radius: 12px; } +.home-hand-card:active { transform: translateY(calc(var(--lift) - 4px)) rotate(var(--fan)) scale(0.97); } +@media (hover: hover) and (pointer: fine) { + .home-hand-card:hover { transform: translateY(-18px) rotate(0deg); z-index: 2; } +} +@keyframes home-deal { from { opacity: 0; transform: translateY(60px) rotate(0deg); } } +.home-hand-pop { + position: absolute; z-index: 4; right: 40px; bottom: calc(100% + 30px); + display: grid; justify-items: center; padding: 8px 18px 10px; border: 3px solid #111419; border-radius: 16px; + background: var(--signal); color: #111419; font-family: var(--font-num); font-size: 34px; line-height: 1.05; white-space: nowrap; + box-shadow: 4px 4px 0 #111419; animation: home-pop 1500ms cubic-bezier(0.23, 1, 0.32, 1) both; +} +.home-hand-pop small { font-family: var(--font-serif); font-size: 15px; } +@keyframes home-pop { + 0% { opacity: 0; transform: translateY(10px) scale(0.8); } + 14% { opacity: 1; transform: translateY(0) scale(1.06); } + 24% { transform: scale(1); } + 80% { opacity: 1; transform: translateY(-10px); } + 100% { opacity: 0; transform: translateY(-20px); } +} + +@media (max-width: 720px) { + /* 手機:標題在上、小鎮在中間、選單和圖示在下面 */ + .home .hero3d::before { background: linear-gradient(180deg, rgb(17 20 25 / 0.7) 0%, transparent 26%, transparent 38%, rgb(17 20 25 / 0.82) 62%); } + .home .home-copy { width: 100%; justify-content: flex-end; gap: 12px; padding: max(18px, env(safe-area-inset-top, 0px)) 16px max(14px, env(safe-area-inset-bottom, 0px)); } + .home-logo { position: absolute; top: max(18px, env(safe-area-inset-top, 0px)); left: 16px; right: 16px; } + .home-logo .hero3d-title { font-size: 50px; } + .home-logo .hero3d-slogan { font-size: 20px; } + .home-logo .hero3d-kicker { display: none; } + /* 小鎮畫在上半部(標題和選單中間),下半部是選單 */ + .home .hero3d-stage { bottom: 40%; } + .home .hero3d-music { top: max(14px, env(safe-area-inset-top, 0px)); right: 12px; bottom: auto; } + .tmenu-list { gap: 8px; } + .tmenu-item { padding: 6px 12px 6px 6px; } + .tmenu-item > svg { width: 36px; height: 36px; padding: 7px; } + .tmenu-item b { font-size: 18px; } + .tmenu-item.is-primary b { font-size: 22px; } + .tmenu-item.is-primary > svg { width: 42px; height: 42px; } + .home-dock { justify-content: space-between; gap: 4px; } + .home-dock a { width: 52px; } + .home-dock-ic { width: 44px; height: 44px; } + .home-legal { display: none; } + .home .hero3d-game { display: none; } + .home-hand { display: none; } +} +@media (max-height: 760px) and (min-width: 721px) { + .tmenu-item small { display: none; } + .tmenu-item > svg { width: 36px; height: 36px; padding: 7px; } + .home-logo .hero3d-title { font-size: 56px; } +} +@media (prefers-reduced-motion: reduce) { + .tmenu-item { animation: hero-fade 300ms ease both; } + .home-hand-card { animation: none; transition: opacity 160ms ease-out; } + .home-hand-pop { animation: hero-fade 300ms ease both; } +} diff --git a/web/src/game/hud/SettingsMenu.tsx b/web/src/game/hud/SettingsMenu.tsx new file mode 100644 index 0000000..356ad9d --- /dev/null +++ b/web/src/game/hud/SettingsMenu.tsx @@ -0,0 +1,60 @@ +import { Settings as Gear } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { updateSettings, useSettings } from "../audio/settings.ts"; + +/** 設定:音效、主播語音、每週新聞播報、全遊戲的頭像畫風(原作也有音樂、音效、動畫開關) */ +const STYLES: { id: string; label: string }[] = [ + { id: "comic", label: "漫畫" }, + { id: "chibi", label: "Q 版大頭" }, + { id: "pixel", label: "復刻像素" }, + { id: "sticker", label: "平面貼紙" }, +]; + +export function SettingsMenu() { + const settings = useSettings(); + const [open, setOpen] = useState(false); + const ref = useRef(null); + useEffect(() => { + if (!open) return; + const close = (e: MouseEvent) => !ref.current?.contains(e.target as Node) && setOpen(false); + addEventListener("mousedown", close); + return () => removeEventListener("mousedown", close); + }, [open]); + return ( +
+ + {open && ( +
+ + + + + +
+ )} +
+ ); +} diff --git a/web/src/game/island/IslandScreen.tsx b/web/src/game/island/IslandScreen.tsx new file mode 100644 index 0000000..546a658 --- /dev/null +++ b/web/src/game/island/IslandScreen.tsx @@ -0,0 +1,417 @@ +import type { IslandBuilding } from "@election2026/protocol"; +import { Box, Coins, Hammer, Hand, LayoutGrid, Lightbulb, ScrollText, X } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { rogueApi } from "../api.ts"; +import { CardArt } from "../art/CardArt.tsx"; +import { sfx } from "../audio/sfx.ts"; +import { EARN_RULES, FALLBACK_BUILDINGS, MAX_LEVEL, nextCost, POLICY_HOME, targetsOf } from "./data.ts"; +import { createIsland, type IslandHandle } from "./island3d.ts"; +import { PolicyWorkshop } from "./PolicyWorkshop.tsx"; +import { build, useIsland, type IslandState } from "./store.ts"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import "./island.css"; + +/** + * 政策島(docs/23 跨局成長):打完選戰拿政績點,回來蓋建築(下一局開局有加成), + * 也可以到政策工坊組自己的政策,帶進下一局變成政策卡。 + * 3D 小島用 three.js;WebGL 不能用、模型讀不到時退回平面格子版。 + */ + +type Tab = "island" | "workshop"; + +/** 建築清單:伺服器的圖鑑有就用伺服器的,讀不到(或伺服器還沒給)就用備用清單 */ +function useBuildings(): { list: readonly IslandBuilding[]; settled: boolean } { + const [state, setState] = useState<{ list: readonly IslandBuilding[]; settled: boolean }>({ list: FALLBACK_BUILDINGS, settled: false }); + useEffect(() => { + let alive = true; + const done = (list: readonly IslandBuilding[]) => alive && setState((s) => (s.settled ? s : { list, settled: true })); + // 伺服器太慢就先用備用清單蓋島,不要讓玩家一直等 + const timer = setTimeout(() => done(FALLBACK_BUILDINGS), 1500); + rogueApi + .catalog() + .then((c) => done(c.buildings?.length ? c.buildings : FALLBACK_BUILDINGS)) + .catch(() => done(FALLBACK_BUILDINGS)); + return () => { + alive = false; + clearTimeout(timer); + }; + }, []); + return state; +} + +const stars = (level: number) => "★".repeat(level) + "☆".repeat(Math.max(0, MAX_LEVEL - level)); + +export function IslandScreen({ initialTab = "island" }: { initialTab?: Tab }) { + const island = useIsland(); + const [tab, setTab] = useState(initialTab); + const [earnOpen, setEarnOpen] = useState(false); + const choose = (t: Tab) => { + if (t === tab) return; + sfx.click(); + setTab(t); + }; + return ( + + + } value={island.points} label="政績點" /> + + } + > +
+ +
+ + +
+ {tab === "workshop" && ( + + )} + {earnOpen && setEarnOpen(false)} />} +
+
+ ); +} + +/** 政績點怎麼賺,加上最近的紀錄(右上角點開的小卡) */ +function Earn({ island, onClose }: { island: IslandState; onClose: () => void }) { + const recent = island.log.slice(-5).reverse(); + return ( +
+ + + 怎麼賺政績點 + +
    + {EARN_RULES.map((r) => ( +
  • + {r.label} {r.points} +
  • + ))} +
+ {recent.length > 0 && ( +
+ 最近拿到的政績點 +
    + {recent.map((e, i) => ( +
  1. + {e.date} {e.reason} +{e.points} +
  2. + ))} +
+
+ )} +
+ ); +} + +function IslandView({ island }: { island: IslandState }) { + const { list, settled } = useBuildings(); + const [selected, setSelected] = useState(null); + const [mode, setMode] = useState<"3d" | "2d">(() => (hasWebGL() ? "3d" : "2d")); + const [loading, setLoading] = useState(true); + const [stamp, setStamp] = useState<{ id: string; level: number; key: number } | null>(null); + const canvasRef = useRef(null); + const wrapRef = useRef(null); + const handleRef = useRef(null); + // 3D 場景建立時要拿到當下的等級和選取,但不要因為它們變了就重建場景 + const latest = useRef({ levels: island.buildings, selected, island }); + latest.current = { levels: island.buildings, selected, island }; + const plotKey = list.map((b) => `${b.id}:${b.name}`).join("|"); + const pick = (id: string) => { + sfx.click(); + setSelected(id); + }; + + useEffect(() => { + if (mode !== "3d" || !settled) return; + const canvas = canvasRef.current; + const wrap = wrapRef.current; + if (!canvas || !wrap) return; + setLoading(true); + const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; + const lowPower = matchMedia("(max-width: 720px)").matches || (navigator.hardwareConcurrency ?? 8) <= 4; + const handle = createIsland(canvas, { + plots: list.map((b) => ({ id: b.id, name: b.name })), + levels: latest.current.levels, + policies: landedMap(latest.current.island), + selected: latest.current.selected, + reduceMotion, + lowPower, + onReady: () => setLoading(false), + onError: () => setMode("2d"), + onPick: pick, + }); + handleRef.current = handle; + const size = () => { + const r = wrap.getBoundingClientRect(); + handle.resize(Math.round(r.width), Math.round(r.height)); + }; + size(); + const ro = new ResizeObserver(size); + ro.observe(wrap); + // 捲到看不見或切到別的分頁時暫停,省電 + const io = new IntersectionObserver(([e]) => handle.setActive(Boolean(e?.isIntersecting) && !document.hidden)); + io.observe(wrap); + const onVis = () => handle.setActive(!document.hidden); + document.addEventListener("visibilitychange", onVis); + return () => { + ro.disconnect(); + io.disconnect(); + document.removeEventListener("visibilitychange", onVis); + handle.dispose(); + handleRef.current = null; + }; + // list 只在 plotKey 變的時候換,不用放進依賴 + }, [mode, settled, plotKey]); + + useEffect(() => handleRef.current?.setLevels(island.buildings), [island.buildings]); + useEffect(() => handleRef.current?.setPolicies(landedMap(island)), [island.policies]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => handleRef.current?.select(selected), [selected]); + // 手機上面板在島的下面:選了一塊地就把面板捲進畫面(只捲到剛好看得到) + const panelRef = useRef(null); + useEffect(() => { + const panel = panelRef.current; + if (!selected || !panel || panel.getBoundingClientRect().top < innerHeight - 120) return; + panel.scrollIntoView({ block: "nearest", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); + }, [selected]); + + const building = list.find((b) => b.id === selected) ?? null; + const onBuild = (b: IslandBuilding) => { + const before = island.buildings[b.id] ?? 0; + if (!build(b.id, list)) { + sfx.bad(); + return; + } + if (before === 0) { + sfx.stamp(); + sfx.coin(); + } else sfx.combo(before + 1); + setStamp({ id: b.id, level: before + 1, key: Date.now() }); + }; + + return ( +
+
+ {mode === "3d" ? ( +
+ + {loading && 小島載入中…} + + 左右拖曳轉島・點空地蓋建設 + +
+ ) : ( + + )} + {hasWebGL() && ( + + )} +
+ + + + {mode === "3d" && ( + + )} +
+ ); +} + +/** WebGL 不能用時的平面格子版 */ +function Lots({ list, levels, landed, selected, onSelect }: { list: readonly IslandBuilding[]; levels: Record; landed: Record; selected: string | null; onSelect: (id: string) => void }) { + return ( +
+ {list.map((b) => { + const lv = levels[b.id] ?? 0; + return ( + + ); + })} +
+ ); +} + +/** 落在這棟建築的政策(政策工坊存的),帶進下一局的排前面 */ +function landedAt(island: IslandState, id: string): { name: string; active: boolean }[] { + return island.policies + .map((p, i) => ({ name: p.name, active: island.active.includes(i), home: POLICY_HOME[p.target] })) + .filter((p) => p.home === id) + .sort((a, b) => Number(b.active) - Number(a.active)) + .map(({ name, active }) => ({ name, active })); +} + +/** 每塊地上落了哪些政策(3D 名牌、平面格子用) */ +const landedMap = (island: IslandState): Record => { + const out: Record = {}; + island.policies.forEach((p) => { + const home = POLICY_HOME[p.target]; + (out[home] ??= []).push(p.name); + }); + return out; +}; + +function BuildingPanel({ + b, + level, + points, + stamp, + landed, + onBuild, +}: { + b: IslandBuilding; + level: number; + points: number; + stamp: { level: number; key: number } | null; + landed: { name: string; active: boolean }[]; + onBuild: () => void; +}) { + const cost = nextCost(b, level); + const short = cost !== null ? cost - points : 0; + const targets = targetsOf(b.id); + return ( +
+
+ + + +
+

{b.name}

+ {level ? `${stars(level)} ${level} 級` : "還是空地"} +
+ {stamp && ( + + {stamp.level === 1 ? "蓋好了" : "升級"} + + )} +
+
    + {b.levels.map((text, i) => ( +
  1. + {i + 1} 級 + {text} + {b.cost[i]} 點 +
  2. + ))} +
+ {cost !== null ? ( + <> +

+ {level === 0 ? "蓋好之後" : "升級之後"}:{b.levels[level]} + (下一局開始生效) +

+ + {short > 0 && 還差 {short} 點,再打一局選戰吧} + + ) : ( +

已經蓋到最高級了!

+ )} + {targets.length > 0 && ( +
+

+ 政策落地 + 「{targets.join("」「")}」政策落在這裡,每級 +10%{level ? `(現在 +${level * 10}%)` : ""} +

+ {landed.length ? ( +
    + {landed.map((p, i) => ( +
  • + {p.name} + {p.active ? "帶進下一局" : "沒有帶"} +
  • + ))} +
+ ) : ( +

+ 還沒有。到政策工坊寫一份「{targets[0]}」政策,就會落在這裡。 +

+ )} +
+ )} +
+ ); +} + +let webgl: boolean | null = null; +function hasWebGL(): boolean { + if (webgl === null) { + try { + const c = document.createElement("canvas"); + const gl = c.getContext("webgl2") ?? c.getContext("webgl"); + webgl = !!gl; + // 只是檢查,用完馬上釋放,不佔瀏覽器的 WebGL 名額 + gl?.getExtension("WEBGL_lose_context")?.loseContext(); + } catch { + webgl = false; + } + } + return webgl; +} diff --git a/web/src/game/island/PolicyWorkshop.tsx b/web/src/game/island/PolicyWorkshop.tsx new file mode 100644 index 0000000..631f9cc --- /dev/null +++ b/web/src/game/island/PolicyWorkshop.tsx @@ -0,0 +1,257 @@ +import type { PolicySpec } from "@election2026/protocol"; +import { Armchair, Baby, Briefcase, Check, ChevronLeft, ChevronRight, Factory, Hammer, HandCoins, Landmark, Mountain, Percent, PiggyBank, Receipt, Scale, Scissors, Sparkles, Wheat, X, type LucideIcon } from "lucide-react"; +import { useState } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { CardFace } from "../rogue/cards.tsx"; +import { defaultPolicyName, FALLBACK_BUILDINGS, FUNDINGS, METHODS, POLICY_HOME, policyBonuses, policyBoost, policyFace, TARGETS } from "./data.ts"; +import { deletePolicy, MAX_POLICIES, policySlots, savePolicy, setPolicyActive, type IslandState } from "./store.ts"; + +/** + * 政策工坊(docs/23):選對象 → 做法 → 財源,組出一張自己的政策卡。 + * 最多存 6 份,每局可以帶 1 份(政策研究院升級後 2、3 份),開局時變成牌組裡的稀有牌。 + * 每份政策會「落地」在島上的一棟建築(長輩→長照中心…),那棟蓋越高政策越強;卡片下面列出小島給它的加成。 + */ + +const stars = (n: number) => "★".repeat(n) + "☆".repeat(Math.max(0, 3 - n)); + +/** 小島給這份政策的加成:蓋了的亮、還沒蓋的寫「蓋了每級 +N%」 */ +function IslandBonuses({ spec, levels }: { spec: Pick; levels: Record }) { + const rows = policyBonuses(spec, levels); + const boost = policyBoost(spec, levels); + return ( +
+

+ 小島加成 {boost > 0 ? 現在 +{boost}% : 還沒有} +

+
    + {rows.map((r) => ( +
  • + + {r.home && 落地} + {r.name} {stars(r.level)} + + {r.text} +
  • + ))} +
+
+ ); +} + +type Step = 0 | 1 | 2; +type Draft = Pick; + +const ICONS: Record = { + old: Armchair, + young: Sparkles, + workers: Briefcase, + farmers: Wheat, + hakka: Mountain, + believers: Landmark, + families: Baby, + subsidy: HandCoins, + build: Hammer, + law: Scale, + tax_cut: Receipt, + tax: Percent, + debt: PiggyBank, + cut: Scissors, + invest: Factory, +}; + +const STEPS = [ + { title: "照顧誰", hint: "政策的對象:這種人多的區,政策卡的效果比較好" }, + { title: "怎麼做", hint: "做法決定花多少體力和錢、加票加在哪裡" }, + { title: "錢從哪來", hint: "每種財源都有代價,挑一個你最能接受的" }, +] as const; + +const MAX_NAME = 20; +const FALLBACK_NAMES = new Map(FALLBACK_BUILDINGS.map((b) => [b.id, b.name])); + +export function PolicyWorkshop({ island }: { island: IslandState }) { + const [step, setStep] = useState(0); + const [draft, setDraft] = useState({ target: "old", method: "subsidy", funding: "debt" }); + const [name, setName] = useState(null); + const [notice, setNotice] = useState<{ text: string; tone: "good" | "bad" } | null>(null); + const [confirmDelete, setConfirmDelete] = useState(null); + + const fallbackName = defaultPolicyName(draft.target, draft.method); + const finalName = (name ?? "").trim() || fallbackName; + const spec: PolicySpec = { ...draft, name: finalName }; + const full = island.policies.length >= MAX_POLICIES; + const slots = policySlots(island); + + const pickOption = (key: K, value: Draft[K]) => { + sfx.place(); + setDraft((d) => ({ ...d, [key]: value })); + setNotice(null); + }; + const go = (to: number) => { + if (to < 0 || to > 2) return; + sfx.flip(); + setStep(to as Step); + }; + const onSave = () => { + if ([...finalName].length > MAX_NAME) { + setNotice({ text: `名字最多 ${MAX_NAME} 個字`, tone: "bad" }); + sfx.bad(); + return; + } + const before = island.active.length; + if (!savePolicy(spec)) { + setNotice({ text: full ? `最多存 ${MAX_POLICIES} 份,先刪掉一份舊的` : "存不起來,請再試一次", tone: "bad" }); + sfx.bad(); + return; + } + sfx.stamp(); + const auto = before < slots; + setNotice({ text: auto ? `「${finalName}」存好了,已經勾選帶進下一局` : `「${finalName}」存好了。要帶進下一局,請在下面勾選`, tone: "good" }); + setName(null); + setStep(0); + }; + const onToggle = (i: number, on: boolean) => { + if (!setPolicyActive(i, on)) { + sfx.bad(); + setNotice({ text: `每局最多帶 ${slots} 份政策。先取消另一份,或到小島升級「政策研究院」`, tone: "bad" }); + return; + } + sfx.click(); + setNotice(null); + }; + const onDelete = (i: number) => { + if (confirmDelete !== i) { + setConfirmDelete(i); + return; + } + deletePolicy(i); + sfx.paper(); + setConfirmDelete(null); + }; + + const options = step === 0 ? TARGETS.map((t) => ({ id: t.id, label: t.label, text: `${t.area}效果比較好` })) : step === 1 ? METHODS : FUNDINGS; + const current = step === 0 ? draft.target : step === 1 ? draft.method : draft.funding; + const choose = (id: string) => { + if (step === 0) pickOption("target", id as Draft["target"]); + else if (step === 1) pickOption("method", id as Draft["method"]); + else pickOption("funding", id as Draft["funding"]); + }; + + return ( +
+
+
    + {STEPS.map((s, i) => ( +
  1. + +
  2. + ))} +
+
+

+ 第 {step + 1} 步:{STEPS[step].title} +

+

{STEPS[step].hint}

+
+ {options.map((o) => { + const Icon = ICONS[o.id] ?? Sparkles; + const on = current === o.id; + return ( + + ); + })} +
+
+ + {step < 2 && ( + + )} +
+
+
+ + + + {notice && ( +

+ {notice.text} +

+ )} + +
+
+

+ 我的政策({island.policies.length}/{MAX_POLICIES}) +

+

+ 勾選要帶進下一局的政策:目前每局可以帶 {slots} 份 + {slots < 3 && "(到小島升級「政策研究院」可以多帶)"},已勾 {island.active.length} 份。 +

+
+ {island.policies.length === 0 ? ( +

還沒有政策。上面選好對象、做法、財源,存一份試試看。

+ ) : ( +
    + {island.policies.map((p, i) => { + const on = island.active.includes(i); + return ( +
  • + + + 落地:{FALLBACK_NAMES.get(POLICY_HOME[p.target]) ?? POLICY_HOME[p.target]} {stars(island.buildings[POLICY_HOME[p.target]] ?? 0)} + {policyBoost(p, island.buildings) > 0 && +{policyBoost(p, island.buildings)}%} + + + +
  • + ); + })} +
+ )} +
+
+ ); +} diff --git a/web/src/game/island/data.ts b/web/src/game/island/data.ts new file mode 100644 index 0000000..3c4dc0b --- /dev/null +++ b/web/src/game/island/data.ts @@ -0,0 +1,175 @@ +import type { IslandBuilding, PolicySpec } from "@election2026/protocol"; +import type { FaceData } from "../rogue/cards.tsx"; + +/** + * 政策島和政策工坊的畫面資料。規則在伺服器(backend/packages/rogue/src/meta.ts), + * 這裡只是畫面用的備用清單:伺服器的圖鑑有 buildings 就用伺服器的,讀不到才用這份。 + * 改 meta.ts 的 BUILDINGS、政策卡數字時,這裡也要一起改。 + */ + +export const FALLBACK_BUILDINGS: readonly IslandBuilding[] = [ + { id: "hub", name: "交通樞紐", art: "sound_truck", levels: ["第 1 週體力 +1", "前 2 週體力 +1", "前 3 週體力 +1"], cost: [3, 6, 10] }, + { id: "care", name: "長照中心", art: "market_visit", levels: ["長輩多的區 +8%", "長輩多的區 +16%", "長輩多的區 +24%"], cost: [3, 6, 10] }, + { id: "nursery", name: "托育園", art: "forum", levels: ["年輕人多的區 +8%", "年輕人多的區 +16%", "年輕人多的區 +24%"], cost: [3, 6, 10] }, + { id: "techpark", name: "科技園區", art: "online_ad", levels: ["網路牌 +10%", "網路牌 +20%", "網路牌 +30%"], cost: [3, 6, 10] }, + { id: "nightmarket", name: "觀光夜市", art: "night_market", levels: ["市場夜市牌 +10%、資金 +50 萬", "+20%、+100 萬", "+30%、+150 萬"], cost: [3, 6, 10] }, + { id: "plaza", name: "宮廟廣場", art: "temple_visit", levels: ["宮廟牌 +10%", "宮廟牌 +20%", "宮廟牌 +30%"], cost: [3, 6, 10] }, + { id: "media", name: "媒體中心", art: "tv_ad", levels: ["媒體牌 +6%", "媒體牌 +12%", "媒體牌 +18%"], cost: [3, 6, 10] }, + { id: "volunteer", name: "志工之家", art: "recruit_volunteers", levels: ["第 1 週多抽 1 張", "多抽 2 張", "多抽 3 張"], cost: [3, 6, 10] }, + { id: "academy", name: "競選學院", art: "study", levels: ["開局 1 張牌升級", "開局 2 張牌升級", "開局 3 張牌升級"], cost: [4, 8, 12] }, + { id: "vault", name: "競選金庫", art: "party_fund", levels: ["開局資金 +150 萬", "+300 萬", "+450 萬"], cost: [3, 6, 10] }, + { id: "hq", name: "競選總部", art: "open_office", levels: ["開局聲勢 +1", "開局聲勢 +2", "開局聲勢 +3"], cost: [4, 8, 12] }, + { id: "library", name: "政策研究院", art: "white_paper", levels: ["可以帶 2 份政策", "可以帶 3 份政策", "所有政策牌 +15%"], cost: [3, 6, 10] }, +]; + +export const MAX_LEVEL = 3; + +/** 升到下一級要幾點;已經滿級回 null */ +export function nextCost(b: IslandBuilding, level: number): number | null { + if (level >= MAX_LEVEL) return null; + return b.cost[level] ?? null; +} + +/** 政績點怎麼賺(畫面說明用;實際發點在結果畫面) */ +export const EARN_RULES: readonly { label: string; points: string }[] = [ + { label: "打完一局當選", points: "+3" }, + { label: "打完一局落選", points: "+1" }, + { label: "拿到 S 評價", points: "+2" }, + { label: "第一次拿到的成就", points: "每個 +1" }, + { label: "政治生涯每做完一任", points: "另外給" }, +]; + +/** 一局打完可以拿幾點政績點:當選 +3、落選 +1、S 評價 +2、第一次拿到的成就每個 +1 */ +export function pointsForRun(r: { won: boolean; grade?: string | null; newFeats?: number }): { points: number; reason: string } { + const parts = [r.won ? "當選 +3" : "落選 +1"]; + let points = r.won ? 3 : 1; + if (r.grade === "S") { + points += 2; + parts.push("S 評價 +2"); + } + const feats = Math.max(0, Math.floor(r.newFeats ?? 0)); + if (feats > 0) { + points += feats; + parts.push(`新成就 +${feats}`); + } + return { points, reason: parts.join("、") }; +} + +// ── 政策工坊 ── + +type Target = PolicySpec["target"]; +type Method = PolicySpec["method"]; +type Funding = PolicySpec["funding"]; + +export const TARGETS: readonly { id: Target; label: string; area: string }[] = [ + { id: "old", label: "長輩", area: "長輩多的區" }, + { id: "young", label: "年輕人", area: "年輕人多的區" }, + { id: "workers", label: "上班族", area: "人口密集的區" }, + { id: "farmers", label: "農漁民", area: "鄉下的區" }, + { id: "hakka", label: "客家鄉親", area: "客家庄" }, + { id: "believers", label: "信眾", area: "宮廟多的區" }, + { id: "families", label: "育兒家庭", area: "年輕人多的區" }, +]; + +export const METHODS: readonly { id: Method; label: string; text: string }[] = [ + { id: "subsidy", label: "補助", text: "1 體力、150 萬:在一區拉票,對象多的區拉更多" }, + { id: "build", label: "蓋建設", text: "2 體力、250 萬:一區之後每週都會加票" }, + { id: "law", label: "修法", text: "1 體力、不花錢:全市加票,聲勢 +1" }, + { id: "tax_cut", label: "減稅", text: "1 體力、不花錢:全市加最多票" }, +]; + +export const FUNDINGS: readonly { id: Funding; label: string; text: string }[] = [ + { id: "tax", label: "加稅", text: "花費少一半,但每次打出會多一張「記者追問」" }, + { id: "debt", label: "舉債", text: "不花錢,但效果 −10%,電視辯論會被追問錢從哪裡來" }, + { id: "cut", label: "刪別的預算", text: "效果 +15%,但全市會流失一點票" }, + { id: "invest", label: "招商", text: "每次打出資金 +100 萬,但效果 −10%" }, +]; + +const label = (list: readonly { id: T; label: string }[], id: T): string => list.find((x) => x.id === id)?.label ?? id; + +/** 預設的政策名稱,例如「長輩補助政策」 */ +export const defaultPolicyName = (target: Target, method: Method): string => `${label(TARGETS, target)}${label(METHODS, method)}政策`; + +const FUNDING_MULT: Record = { tax: 1, debt: 0.9, cut: 1.15, invest: 0.9 }; +const MONEY_MULT: Record = { tax: 0.5, debt: 0, cut: 1, invest: 1 }; +const FUNDING_KEY: Record = { tax: "多記者追問", debt: "效果 −10%", cut: "全市流失一點票", invest: "資金 +100 萬" }; + +const fmt = (n: number): string => (Math.round(n / 10) * 10).toLocaleString("en-US"); + +/** 政策卡的牌面(數字照伺服器的 policyCardDef;實際會再照縣市大小調整) */ +export function policyFace(p: PolicySpec): FaceData { + const fm = FUNDING_MULT[p.funding]; + const n = (x: number) => fmt(x * fm); + const money = (x: number) => Math.round(x * MONEY_MULT[p.funding]); + const who = label(TARGETS, p.target); + const base = { name: p.name.trim() || defaultPolicyName(p.target, p.method), rarity: "rare", keywords: [`${label(FUNDINGS, p.funding)}:${FUNDING_KEY[p.funding]}`] }; + switch (p.method) { + case "subsidy": + return { ...base, art: "small_donations", cost: 1, money: money(150), value: `+${n(2070)}`, tags: ["ground", "policy"], text: `該區 +${n(2070)};${who}多的區 ×1.8` }; + case "build": + return { ...base, art: "open_office", cost: 2, money: money(250), value: `+${n(690)}/週`, tags: ["org", "policy"], text: `該區現在和之後每週 +${n(690)};${who}多的區 ×1.5` }; + case "law": + return { ...base, art: "white_paper", cost: 1, money: 0, value: `+${n(2070)}`, tags: ["press", "media", "policy"], text: `全市 +${n(2070)},${who}多的區分到較多,聲勢 +1` }; + case "tax_cut": + return { ...base, art: "announce_policy", cost: 1, money: 0, value: `+${n(2990)}`, tags: ["media", "policy"], text: `全市 +${n(2990)},${who}多的區分到較多` }; + } +} + +// ── 政策落地:政策和小島的關係 ── + +/** 每種政策對象的「家」(和 backend/packages/rogue/src/meta.ts 的 POLICY_HOME 一樣;伺服器圖鑑的 policyHome 為準) */ +export const POLICY_HOME: Record = { + old: "care", + young: "techpark", + workers: "hub", + farmers: "nightmarket", + hakka: "plaza", + believers: "plaza", + families: "nursery", +}; + +/** 落在這棟建築的政策對象(「長輩」「育兒家庭」…) */ +export const targetsOf = (buildingId: string): string[] => TARGETS.filter((t) => POLICY_HOME[t.id] === buildingId).map((t) => t.label); + +export interface PolicyBonus { + building: string; + name: string; + level: number; + /** 這份政策的家 */ + home: boolean; + /** 現在已經吃得到(政策研究院要 3 級才算) */ + active: boolean; + text: string; +} + +/** + * 這份政策從小島拿到的加成(數字照伺服器 cards.ts): + * 落地(家每級 +10%);打在一區的政策,長照中心、托育園對長輩、年輕人多的區每級 +8%; + * 修法、減稅算媒體牌,媒體中心每級 +6%;政策研究院 3 級所有政策牌 +15%。 + */ +export function policyBonuses(p: Pick, levels: Record, buildings: readonly IslandBuilding[] = FALLBACK_BUILDINGS): PolicyBonus[] { + const name = (id: string) => buildings.find((b) => b.id === id)?.name ?? id; + const lv = (id: string) => levels[id] ?? 0; + const per = (id: string, step: number, what: string) => (lv(id) ? `${what} +${step * lv(id)}%` : `${what}:蓋了每級 +${step}%`); + const rows = new Map(); + const add = (id: string, text: string, home = false, active = lv(id) > 0) => { + const had = rows.get(id); + rows.set(id, had ? { ...had, home: had.home || home, text: `${had.text};${text}` } : { building: id, name: name(id), level: lv(id), home, active, text }); + }; + add(POLICY_HOME[p.target], per(POLICY_HOME[p.target], 10, "政策落地"), true); + const inTown = p.method === "subsidy" || p.method === "build"; + if (inTown && p.target === "old") add("care", per("care", 8, "打在長輩多的區")); + if (inTown && (p.target === "young" || p.target === "families")) add("nursery", per("nursery", 8, "打在年輕人多的區")); + if (p.method === "law" || p.method === "tax_cut") add("media", per("media", 6, "算媒體牌")); + add("library", lv("library") >= 3 ? "所有政策牌 +15%" : "3 級時所有政策牌 +15%", false, lv("library") >= 3); + return [...rows.values()]; +} + +/** 現在這份政策總共多幾 %(只算一定吃得到的:落地、媒體中心、政策研究院 3 級) */ +export function policyBoost(p: Pick, levels: Record): number { + const lv = (id: string) => levels[id] ?? 0; + let m = 1 + 0.1 * lv(POLICY_HOME[p.target]); + if (p.method === "law" || p.method === "tax_cut") m *= 1 + 0.06 * lv("media"); + if (lv("library") >= 3) m *= 1.15; + return Math.round((m - 1) * 100); +} diff --git a/web/src/game/island/island.css b/web/src/game/island/island.css new file mode 100644 index 0000000..f9453cf --- /dev/null +++ b/web/src/game/island/island.css @@ -0,0 +1,239 @@ +/* 政策島與政策工坊:台式競選文宣 × 立體桌遊(粗黑框、硬陰影、黃紅)。顏色只用 tokens.css,不用政黨色 */ + +/* ── 怎麼賺 ── */ +.isl-earn { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 10px 14px; background: var(--surface); border: 2px dashed var(--ink); border-radius: 14px; } +.isl-earn-title { display: inline-flex; align-items: center; gap: 4px; font-family: var(--font-serif); } +.isl-earn ul { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; } +.isl-earn li { padding: 3px 10px; border: 2px solid var(--line); border-radius: 999px; background: var(--surface-2); font-size: 14px; font-weight: 700; } +.isl-earn li b { color: var(--stamp); font-family: var(--font-num); font-size: 16px; } +.isl-log { flex-basis: 100%; font-size: 14px; } +.isl-log summary { cursor: pointer; font-weight: 800; min-height: 32px; display: flex; align-items: center; } +.isl-log ol { margin: 4px 0 0; padding-left: 1.2em; display: grid; gap: 2px; } +.isl-log span { color: var(--muted); font-family: var(--font-num); } +.isl-log b { color: var(--stamp); } + +/* ── 小島 ── */ +.isl-main { display: grid; grid-template-columns: minmax(0, 1fr) 340px; grid-template-areas: "stage panel" "chips chips"; gap: 14px; align-items: start; } +.isl-stage { grid-area: stage; position: relative; } +.isl-canvas { position: relative; aspect-ratio: 16 / 10; min-height: 340px; border: 3px solid var(--ink); border-radius: 20px; overflow: hidden; background: linear-gradient(180deg, #bfe6f0 0%, #d9f0f4 55%, #bfe6f0 100%); box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-canvas canvas { display: block; width: 100%; height: 100%; touch-action: pan-y; cursor: grab; } +.isl-loading { position: absolute; inset: 0; display: grid; place-items: center; font-family: var(--font-serif); font-size: 20px; color: #111419; } +.isl-hint { position: absolute; left: 10px; bottom: 10px; display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; background: rgba(255, 250, 240, 0.92); color: #111419; border: 2px solid #111419; border-radius: 999px; font-size: 13px; font-weight: 800; pointer-events: none; } +.isl-mode { position: absolute; top: 10px; right: 10px; min-height: 40px; border: 2px solid var(--ink); } + +.isl-panel { grid-area: panel; position: sticky; top: 12px; display: grid; gap: 12px; padding: 16px 18px 18px; background: var(--surface); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-intro h2 { margin: 0 0 6px; font-family: var(--font-serif); font-size: 22px; } +.isl-intro p { margin: 0 0 6px; } +.isl-intro b { font-family: var(--font-num); font-size: 20px; color: var(--stamp); } + +.isl-building { display: grid; gap: 12px; } +.isl-bhead { position: relative; display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 12px; align-items: center; } +.isl-bart .card-art { display: block; width: 76px; height: 76px; border: 3px solid var(--ink); border-radius: 14px; overflow: hidden; background: var(--surface-2); } +.isl-bart .card-art img { width: 100%; height: 100%; object-fit: cover; display: block; } +.isl-bart .card-art svg { width: 60%; height: 60%; margin: 20%; display: block; } +.isl-bhead h2 { margin: 0; font-family: var(--font-serif); font-size: 26px; line-height: 1.1; } +.isl-stars { color: #b8860b; font-weight: 800; letter-spacing: 0.04em; } +.isl-stamp { position: absolute; right: -4px; top: -10px; padding: 4px 10px; border: 3px solid var(--stamp); border-radius: 8px; color: var(--stamp); font-family: var(--font-serif); font-size: 22px; background: color-mix(in srgb, var(--surface) 85%, transparent); transform: rotate(-12deg); animation: isl-stamp 300ms var(--ease-out) both; pointer-events: none; } +@keyframes isl-stamp { + from { opacity: 0; transform: rotate(-12deg) scale(1.6); } + to { opacity: 1; transform: rotate(-12deg) scale(1); } +} +.isl-levels { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.isl-levels li { display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; gap: 8px; align-items: center; padding: 8px 10px; border: 2px solid var(--line); border-radius: 12px; background: var(--surface-2); color: var(--muted); font-size: 14px; } +.isl-levels li b { font-family: var(--font-num); font-size: 16px; } +.isl-levels li small { font-family: var(--font-num); font-weight: 700; } +.isl-levels li.is-done { border-color: var(--ink); background: color-mix(in srgb, var(--signal) 45%, var(--surface)); color: var(--ink); } +.isl-levels li.is-next { border: 2px dashed var(--ink); background: var(--surface); color: var(--ink); } +.isl-next { margin: 0; display: grid; gap: 2px; } +.isl-next b { font-size: 18px; } +.isl-next small { color: var(--muted); } +.isl-next.is-max { font-family: var(--font-serif); font-size: 20px; color: var(--stamp); } +.isl-build { min-height: 56px; width: 100%; font-family: var(--font-serif); font-size: 20px; background: var(--stamp); color: #fff; border: 3px solid var(--ink); box-shadow: 4px 4px 0 var(--shadow-ink); } +.isl-build:disabled { background: var(--surface-2); color: var(--muted); border-color: var(--line); box-shadow: none; cursor: not-allowed; } +.isl-build:active:not(:disabled) { transform: translate(3px, 3px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.isl-short { color: var(--muted); font-weight: 700; } + +/* 全部建築的捷徑(鍵盤、報讀器也能選) */ +.isl-chips { grid-area: chips; display: flex; flex-wrap: wrap; gap: 8px; } +.isl-chips button { display: inline-grid; justify-items: center; min-height: 52px; min-width: 88px; padding: 6px 12px; border: 2px solid var(--line); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; font-weight: 800; cursor: pointer; transition: transform 160ms var(--ease-out); } +.isl-chips button small { font-size: 12px; color: var(--muted); font-weight: 700; } +.isl-chips button.is-built { border-color: var(--ink); background: color-mix(in srgb, var(--signal) 35%, var(--surface)); } +.isl-chips button.is-built small { color: var(--ink); } +.isl-chips button[aria-pressed="true"] { border: 3px solid var(--ink); background: var(--ink); color: var(--surface); } +.isl-chips button[aria-pressed="true"] small { color: var(--signal); } +.isl-chips button:active { transform: scale(0.97); } + +/* 平面版:格子 */ +.isl-lots { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; padding: 14px; border: 3px solid var(--ink); border-radius: 20px; background: linear-gradient(180deg, #bfe6f0, #d9f0f4); box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-stage.has-toggle .isl-lots { padding-top: 58px; } +.isl-lot { display: grid; justify-items: center; gap: 4px; min-height: 120px; padding: 8px 6px 10px; border: 2px dashed #5a6470; border-radius: 14px; background: #f3e8cc; color: #111419; font: inherit; cursor: pointer; transition: transform 160ms var(--ease-out); } +.isl-lot .card-art { display: block; width: 100%; aspect-ratio: 16 / 10; border-radius: 8px; overflow: hidden; opacity: 0.55; filter: grayscale(0.6); } +.isl-lot .card-art img { width: 100%; height: 100%; object-fit: cover; display: block; } +.isl-lot .card-art svg { width: 40%; height: 60%; margin: 6% auto; display: block; } +.isl-lot b { font-family: var(--font-serif); font-size: 16px; } +.isl-lot small { font-weight: 800; color: #5a6470; } +.isl-lot.is-built { border: 3px solid #111419; background: #ffd23f; box-shadow: 3px 3px 0 #111419; } +.isl-lot.is-built .card-art { opacity: 1; filter: none; } +.isl-lot.is-built small { color: #8a4b00; } +.isl-lot[aria-pressed="true"] { outline: 4px solid var(--stamp); outline-offset: 2px; } +.isl-lot:active { transform: scale(0.97); } + +/* ── 政策工坊 ── */ +.isl-ws { display: grid; grid-template-columns: minmax(0, 1fr) 300px; grid-template-areas: "make preview" "notice notice" "saved saved"; gap: 14px; align-items: start; } +.isl-ws-make { grid-area: make; display: grid; gap: 12px; } +.isl-steps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 0; padding: 0; list-style: none; } +.isl-steps button { width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-areas: "n t" "n v"; column-gap: 8px; align-items: center; min-height: 56px; padding: 6px 12px; border: 2px solid var(--line); border-radius: 14px; background: var(--surface); color: var(--ink); font: inherit; text-align: left; cursor: pointer; } +.isl-steps b { grid-area: n; display: grid; place-items: center; width: 32px; height: 32px; border: 2px solid var(--ink); border-radius: 50%; font-family: var(--font-num); font-size: 18px; } +.isl-steps span { grid-area: t; font-weight: 800; } +.isl-steps small { grid-area: v; color: var(--muted); font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.isl-steps button[aria-current="step"] { border: 3px solid var(--ink); background: var(--signal); color: var(--signal-ink); box-shadow: 3px 3px 0 var(--shadow-ink); } +.isl-steps button[aria-current="step"] b { background: var(--ink); color: var(--signal); } +.isl-steps button[aria-current="step"] small { color: var(--signal-ink); } + +.isl-step { display: grid; gap: 10px; padding: 16px 18px 18px; background: var(--surface); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-step h2 { margin: 0; font-family: var(--font-serif); font-size: 26px; } +.isl-step-hint { margin: -4px 0 0; color: var(--muted); font-weight: 700; } +.isl-options { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } +.isl-options.is-many { grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); } +.isl-options.is-many .isl-option { grid-template-columns: minmax(0, 1fr); grid-template-areas: "i" "l" "t"; justify-items: start; row-gap: 4px; min-height: 0; } +.isl-option { position: relative; display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-areas: "i l" "i t"; column-gap: 10px; align-items: center; min-height: 84px; padding: 12px 14px; border: 2px solid var(--line); border-radius: 16px; background: var(--surface-2); color: var(--ink); font: inherit; text-align: left; cursor: pointer; transition: transform 160ms var(--ease-out), box-shadow 160ms var(--ease-out); } +.isl-option-icon { grid-area: i; display: grid; place-items: center; width: 48px; height: 48px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface); } +.isl-option b { grid-area: l; font-family: var(--font-serif); font-size: 20px; } +.isl-option small { grid-area: t; color: var(--muted); font-size: 13px; font-weight: 700; line-height: 1.35; } +.isl-option[aria-checked="true"] { border: 3px solid var(--ink); background: var(--signal); color: var(--signal-ink); box-shadow: 4px 4px 0 var(--shadow-ink); transform: translate(-1px, -1px); } +.isl-option[aria-checked="true"] small { color: var(--signal-ink); } +.isl-option[aria-checked="true"] .isl-option-icon { background: var(--stamp); color: #fff; border-color: #111419; } +.isl-option-check { position: absolute; top: 8px; right: 8px; color: var(--stamp); } +.isl-option:active { transform: scale(0.97); } +.isl-step-nav { display: flex; justify-content: space-between; gap: 8px; } +.isl-step-nav .btn { min-height: 48px; border: 2px solid var(--ink); } + +.isl-ws-preview { grid-area: preview; position: sticky; top: 12px; display: grid; justify-items: center; gap: 12px; padding: 18px 16px; background: color-mix(in srgb, var(--signal) 22%, var(--surface)); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-preview-card { --rg-card-w: 190px; padding: 6px 0 4px; } +.isl-preview-card .rgc.is-big { --rgc-w: var(--rg-card-w); transform: rotate(-2deg); } +.isl-name { width: 100%; display: grid; gap: 4px; font-weight: 800; } +.isl-name input { min-height: 48px; padding: 6px 12px; border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; font-size: 18px; font-weight: 700; } +.isl-name input:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +.isl-name small { color: var(--muted); font-weight: 700; } +.isl-save { width: 100%; min-height: 56px; font-family: var(--font-serif); font-size: 22px; background: var(--stamp); color: #fff; border: 3px solid var(--ink); box-shadow: 4px 4px 0 var(--shadow-ink); } +.isl-save:disabled { background: var(--surface-2); color: var(--muted); border-color: var(--line); box-shadow: none; } +.isl-save:active:not(:disabled) { transform: translate(3px, 3px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.isl-fine { margin: 0; font-size: 12px; color: var(--muted); } + +.isl-notice { grid-area: notice; margin: 0; padding: 10px 14px; border: 3px solid var(--ink); border-radius: 12px; font-weight: 800; animation: isl-in 220ms var(--ease-out) both; } +.isl-notice.is-good { background: color-mix(in srgb, var(--signal) 60%, var(--surface)); color: var(--ink); } +.isl-notice.is-bad { background: color-mix(in srgb, var(--stamp) 14%, var(--surface)); color: var(--ink); border-color: var(--stamp); } +@keyframes isl-in { + from { opacity: 0; transform: translateY(-6px); } + to { opacity: 1; transform: none; } +} + +.isl-saved { grid-area: saved; display: grid; gap: 10px; padding: 16px 18px 18px; background: var(--surface); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); } +.isl-saved h2 { margin: 0; font-family: var(--font-serif); font-size: 24px; } +.isl-saved header p { margin: 4px 0 0; } +.isl-saved header b { font-family: var(--font-num); font-size: 18px; color: var(--stamp); } +.isl-saved ul { --rg-card-w: 132px; display: flex; flex-wrap: wrap; gap: 18px 14px; margin: 0; padding: 6px 0 0; list-style: none; } +.isl-saved li { display: grid; justify-items: center; gap: 6px; padding: 10px; border: 2px dashed var(--line); border-radius: 16px; } +.isl-saved li.is-on { border: 3px solid var(--ink); background: color-mix(in srgb, var(--signal) 30%, var(--surface)); } +.isl-carry { display: inline-flex; align-items: center; gap: 6px; min-height: 44px; font-weight: 800; cursor: pointer; } +.isl-carry input { width: 22px; height: 22px; accent-color: var(--stamp); } +.isl-del { min-height: 40px; } +.isl-del.is-confirm { background: var(--stamp); color: #fff; border-color: var(--ink); } +.isl-empty { margin: 0; color: var(--muted); font-weight: 700; } + +/* 滑鼠才有 hover,避免手機點完卡在 hover 樣式 */ +@media (hover: hover) and (pointer: fine) { + .isl-chips button:hover, .isl-lot:hover, .isl-option:hover, .isl-steps button:hover { transform: translateY(-2px); } + .isl-option[aria-checked="true"]:hover { transform: translate(-1px, -3px); } +} + +/* ── 手機直式:島在上、面板在下 ── */ +@media (max-width: 860px) { + .isl-main { grid-template-columns: minmax(0, 1fr); grid-template-areas: "stage" "chips" "panel"; } + .isl-panel, .isl-ws-preview { position: static; } + .isl-canvas { aspect-ratio: 1 / 1; min-height: 0; max-height: 64vh; width: 100%; } + .isl-chips { flex-wrap: nowrap; overflow-x: auto; padding-bottom: 6px; scroll-snap-type: x proximity; overscroll-behavior-x: contain; } + .isl-chips button { flex: 0 0 auto; scroll-snap-align: start; } + .isl-lots { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .isl-ws { grid-template-columns: minmax(0, 1fr); grid-template-areas: "make" "preview" "notice" "saved"; } +} +@media (max-width: 520px) { + .isl-lots { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .isl-options { grid-template-columns: minmax(0, 1fr); } + .isl-options.is-many { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .isl-steps button { grid-template-columns: minmax(0, 1fr); grid-template-areas: "n" "t" "v"; justify-items: center; text-align: center; padding: 6px; } + .isl-saved ul { --rg-card-w: 120px; justify-content: center; } +} + +@media (prefers-reduced-motion: reduce) { + .isl-chips button, .isl-lot, .isl-option { transition: none; } + .isl-stamp { animation: none; } + .isl-notice { animation: isl-fade 200ms ease both; } + @keyframes isl-fade { + from { opacity: 0; } + to { opacity: 1; } + } +} + +/* 小島加成:政策卡下面列出島上哪幾棟會讓它變強 */ +.isl-bonus { display: grid; gap: 6px; width: 100%; padding: 10px 12px; border: 2px dashed var(--ink); border-radius: 12px; background: var(--surface); } +.isl-bonus h3 { margin: 0; display: flex; align-items: baseline; gap: 8px; font-size: 15px; } +.isl-bonus h3 b { color: #1f8a4c; font-size: 15px; } +.isl-bonus h3 small { color: var(--muted); font-weight: 700; } +.isl-bonus ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; } +.isl-bonus li { display: grid; gap: 0; font-size: 13px; color: var(--muted); } +.isl-bonus li > span:first-child { font-weight: 800; color: var(--ink); white-space: nowrap; } +.isl-bonus li small { color: #c99400; letter-spacing: 1px; } +.isl-bonus li.is-on > span:last-child { color: #1f8a4c; font-weight: 800; } +.isl-bonus li em { font-style: normal; margin-right: 4px; padding: 0 6px; border-radius: 999px; background: var(--stamp); color: #fff; font-size: 11px; } +.isl-home { display: flex; flex-wrap: wrap; gap: 4px; align-items: baseline; font-size: 12px; color: var(--muted); } +.isl-home b { color: #1f8a4c; } + +/* 建築說明:落在這裡的政策 */ +.isl-landed { display: grid; gap: 6px; padding: 10px 12px; border-radius: 12px; background: color-mix(in srgb, var(--stamp) 8%, var(--surface)); border: 2px solid color-mix(in srgb, var(--stamp) 50%, var(--line)); } +.isl-landed h3 { margin: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; font-size: 15px; } +.isl-landed h3 svg { color: var(--stamp); } +.isl-landed h3 small { width: 100%; font-weight: 700; color: var(--muted); font-size: 12px; } +.isl-landed ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; } +.isl-landed li { display: flex; justify-content: space-between; gap: 8px; font-weight: 800; font-size: 14px; } +.isl-landed li small { font-weight: 700; color: var(--muted); } +.isl-landed li.is-on small { color: #1f8a4c; } +.isl-landed p { margin: 0; font-size: 13px; color: var(--muted); } +.isl-lot-policy { font-style: normal; font-size: 11px; font-weight: 800; padding: 0 8px; border-radius: 999px; background: var(--stamp); color: #fff; } + +/* ── 政策島場景(GameScene):小島佔滿畫面,建築卡在右邊,政策工坊從右邊滑出來 ── */ +.isl-scene-body { position: relative; height: 100%; min-height: 0; } +.isl-scene .isl-main { height: 100%; grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: minmax(0, 1fr) auto; grid-template-areas: "stage panel" "chips chips"; gap: 12px; align-items: stretch; } +.isl-scene .isl-stage { min-height: 0; } +.isl-scene .isl-canvas { aspect-ratio: auto; height: 100%; min-height: 0; } +.isl-scene .isl-lots { height: 100%; overflow-y: auto; } +.isl-scene .isl-panel { position: relative; top: 0; max-height: 100%; overflow-y: auto; align-content: start; } +.isl-scene .isl-chips { flex-wrap: nowrap; overflow-x: auto; padding-bottom: 2px; scrollbar-width: thin; } +.isl-scene .isl-chips button { flex: none; } +/* 小島建設/政策工坊:浮在小島左上角 */ +.isl-switch { position: absolute; top: 12px; left: 12px; z-index: 4; display: flex; gap: 6px; } +.isl-switch button { display: inline-flex; align-items: center; gap: 6px; min-height: 44px; padding: 6px 14px; border: 3px solid var(--ink); border-radius: 999px; background: #fffaf0; color: #111419; font: inherit; font-weight: 900; cursor: pointer; box-shadow: 3px 3px 0 var(--shadow-ink); } +.isl-switch button[aria-selected="true"] { background: var(--ink); color: #fffaf0; } +.isl-scene .isl-mode { z-index: 4; } +/* 政策工坊抽屜 */ +.isl-drawer { position: absolute; z-index: 6; top: 0; right: 0; bottom: 0; width: min(1020px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); animation: isl-drawer 300ms var(--ease-out) both; } +.isl-drawer-head { position: relative; display: flex; align-items: center; padding: 10px 56px 6px 16px; } +.isl-drawer-head h2 { margin: 0; display: inline-flex; align-items: center; gap: 8px; font-family: var(--font-serif); font-size: 24px; } +.isl-drawer-head .rg-close { top: 8px; right: 10px; } +.isl-drawer-body { padding: 4px 16px 16px; } +@keyframes isl-drawer { from { opacity: 0; transform: translateX(40px); } } +/* 怎麼賺政績點:右上角點開的小卡 */ +.isl-earn-btn { display: inline-flex; align-items: center; gap: 4px; min-height: 44px; padding: 4px 12px; border: 3px solid #111419; border-radius: 999px; background: #fffaf0; color: #111419; font: inherit; font-weight: 800; font-size: 13px; cursor: pointer; box-shadow: 3px 3px 0 #111419; } +.isl-earn-btn[aria-expanded="true"] { background: var(--signal); } +.isl-earn.is-pop { position: absolute; z-index: 7; top: 0; right: 0; width: min(420px, 100%); padding: 14px 44px 14px 16px; border-style: solid; animation: isl-drawer 220ms var(--ease-out) both; } +.isl-earn.is-pop .rg-close { top: 8px; right: 8px; width: 30px; height: 30px; } +@media (max-width: 860px) { + .isl-scene-body { overflow-y: auto; } + .isl-scene .isl-main { height: auto; grid-template-columns: minmax(0, 1fr); grid-template-rows: auto; grid-template-areas: "stage" "chips" "panel"; } + .isl-scene .isl-canvas { height: 52dvh; } + .isl-switch button { padding: 4px 10px; font-size: 14px; } + .isl-earn-btn span { display: none; } +} +@media (prefers-reduced-motion: reduce) { + .isl-drawer, .isl-earn.is-pop { animation: gs-fade 200ms ease both; } +} diff --git a/web/src/game/island/island3d.ts b/web/src/game/island/island3d.ts new file mode 100644 index 0000000..a04430e --- /dev/null +++ b/web/src/game/island/island3d.ts @@ -0,0 +1,747 @@ +import * as THREE from "three"; +import { GLTFLoader, type GLTF } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { clone as cloneSkinned } from "three/examples/jsm/utils/SkeletonUtils.js"; + +/** + * 政策島(docs/23):海上的低多邊形小島,一圈空地圍著中間的廣場。 + * 蓋了的建築依等級長大(1 級小房子,2 級旁邊多一樣東西,3 級變大、再多一樣東西、插旗)。 + * 拖曳可以轉島,點空地或建築選取。模型、貼圖都是 CC0(web/public/assets/LICENSES.md); + * 廣場上的人物是不具名的 Q 版小人,不代表任何真人。 + */ + +const A = "/assets/3d/"; +const PALETTE = ["#d61f2c", "#ffd23f", "#1d4fa3", "#ffffff", "#0f8a4a", "#ff8a3d"]; +const ISLAND_R = 8.4; +const RING_R = 5.6; +const TILE = 2.1; +const TILE_H = 0.16; + +/** 每種建築用哪個模型,升到 2 級、3 級旁邊多長出什麼 */ +const LOOKS: Record = { + hub: { model: "town-shops/building-h", extras: ["vehicles/taxi", "vehicles/van"] }, + care: { model: "town-houses/building-type-c", extras: ["town-houses/planter", "nature/flower-red-a"] }, + nursery: { model: "town-houses/building-type-a", extras: ["festive/present-b-round", "props/heart"] }, + techpark: { model: "town-shops/building-skyscraper-a", extras: ["vehicles/sedan", "props/star"] }, + nightmarket: { model: "town-shops/building-k", extras: ["food/steamer", "town-shops/detail-parasol-a"] }, + plaza: { model: "town-houses/building-type-k", extras: ["props/flowers", "nature/tree-oak"] }, + media: { model: "town-shops/building-c", extras: ["props/sign", "props/star"] }, + volunteer: { model: "town-houses/building-type-b", extras: ["props/crate", "props/heart"] }, + academy: { model: "town-shops/building-a", extras: ["props/sign", "nature/tree-default"] }, + vault: { model: "town-shops/building-e", extras: ["props/chest", "props/coin-gold"] }, + hq: { model: "town-houses/building-type-f", extras: ["vehicles/truck", "props/flag"] }, + library: { model: "town-houses/building-type-h", extras: ["town-houses/tree-small", "town-houses/fence-1x2"] }, +}; +const DEFAULT_LOOK = LOOKS.volunteer!; +/** 各等級建築的最大寬、高 */ +const SIZES = [ + { w: 1.1, h: 1.3 }, + { w: 1.45, h: 1.9 }, + { w: 1.75, h: 2.6 }, +]; +const PEOPLE = ["character-female-b", "character-male-c", "character-female-e", "character-male-f"]; +const DECOR = ["nature/tree-palm-tall", "nature/tree-oak", "nature/tree-palm-short", "nature/rock-small-a", "nature/plant-bush-large", "nature/flower-yellow-a"]; + +export interface IslandPlot { + id: string; + name: string; +} + +export interface IslandHandle { + resize: (w: number, h: number) => void; + /** 更新建築等級;等級變高的那塊地會放彩帶、小人跳起來 */ + setLevels: (levels: Record) => void; + /** 每塊地上落了哪些政策(名牌下面多一條紅色政策條) */ + setPolicies: (policies: Record) => void; + select: (id: string | null) => void; + setActive: (active: boolean) => void; + dispose: () => void; +} + +interface Options { + plots: readonly IslandPlot[]; + levels: Record; + /** 每塊地上落了哪些政策 */ + policies: Record; + selected: string | null; + reduceMotion: boolean; + /** 手機:關陰影、降解析度 */ + lowPower: boolean; + onReady: () => void; + onError: () => void; + onPick: (id: string) => void; +} + +/** 縮放到不超過指定的寬、高,底部貼齊 y=0 */ +function fitBox(obj: THREE.Object3D, maxW: number, maxH: number): THREE.Group { + const box = new THREE.Box3().setFromObject(obj); + const dim = box.getSize(new THREE.Vector3()); + obj.scale.multiplyScalar(Math.min(maxW / Math.max(dim.x, dim.z, 0.001), maxH / Math.max(dim.y, 0.001))); + const after = new THREE.Box3().setFromObject(obj); + const center = after.getCenter(new THREE.Vector3()); + obj.position.x -= center.x; + obj.position.z -= center.z; + obj.position.y -= after.min.y; + const wrap = new THREE.Group(); + wrap.add(obj); + return wrap; +} + +function shadows(obj: THREE.Object3D, on: boolean) { + obj.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = on; + o.receiveShadow = on; + } + }); +} + +/** 固定的亂數(島的形狀每次都一樣) */ +function seeded(seed: number): () => number { + let s = seed; + return () => { + s = (s * 16807) % 2147483647; + return (s - 1) / 2147483646; + }; +} + +/** 文宣看板:紙白底、紅框、粗黑字 */ +function signTexture(text: string, sub: string): THREE.CanvasTexture { + const c = document.createElement("canvas"); + c.width = 512; + c.height = 224; + const g = c.getContext("2d")!; + g.fillStyle = "#d61f2c"; + g.fillRect(0, 0, c.width, c.height); + g.fillStyle = "#fffaf0"; + g.fillRect(14, 14, c.width - 28, c.height - 28); + g.fillStyle = "#111419"; + g.textAlign = "center"; + g.textBaseline = "middle"; + g.font = `900 104px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(text, c.width / 2, 92); + g.fillStyle = "#d61f2c"; + g.font = `900 32px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(sub, c.width / 2, 178); + const t = new THREE.CanvasTexture(c); + t.colorSpace = THREE.SRGBColorSpace; + return t; +} + +/** 名牌的高:上面 140 是名字和星星,下面 50 是政策條(沒有政策就留空) */ +const LABEL_W = 300; +const LABEL_H = 190; +const LABEL_BOX = 140; + +/** 空地/建築上方的名牌:蓋了的是黃底加星星,空地是紙白底;有政策落地就在下面加一條紅色政策條 */ +function drawLabel(canvas: HTMLCanvasElement, name: string, level: number, selected: boolean, policies: readonly string[]) { + const g = canvas.getContext("2d")!; + const w = canvas.width; + const h = LABEL_BOX; + g.clearRect(0, 0, w, canvas.height); + if (policies.length) { + const text = policies.length > 1 ? `${policies[0]} 等 ${policies.length} 份` : policies[0]!; + g.beginPath(); + g.roundRect(26, h - 6, w - 52, 46, 14); + g.fillStyle = "#d61f2c"; + g.fill(); + g.lineWidth = 5; + g.strokeStyle = "#111419"; + g.stroke(); + g.fillStyle = "#ffffff"; + g.textAlign = "center"; + g.textBaseline = "middle"; + g.font = `900 26px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(text.length > 11 ? `${text.slice(0, 10)}…` : text, w / 2, h + 17, w - 70); + } + g.beginPath(); + g.roundRect(8, 8, w - 16, h - 16, 22); + g.fillStyle = selected ? "#d61f2c" : level > 0 ? "#ffd23f" : "rgba(255,250,240,0.92)"; + g.fill(); + g.lineWidth = 6; + g.strokeStyle = "#111419"; + g.stroke(); + g.fillStyle = selected ? "#ffffff" : "#111419"; + g.textAlign = "center"; + g.textBaseline = "middle"; + g.font = `900 46px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(name, w / 2, h * 0.38); + g.font = `900 34px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(level > 0 ? "★".repeat(level) + "☆".repeat(Math.max(0, 3 - level)) : "+ 空地", w / 2, h * 0.74); +} + +const easeOutBack = (x: number) => 1 + 2.2 * Math.pow(x - 1, 3) + 1.2 * Math.pow(x - 1, 2); + +export function createIsland(canvas: HTMLCanvasElement, opts: Options): IslandHandle { + const noop: IslandHandle = { resize: () => {}, setLevels: () => {}, setPolicies: () => {}, select: () => {}, setActive: () => {}, dispose: () => {} }; + let renderer: THREE.WebGLRenderer; + try { + renderer = new THREE.WebGLRenderer({ canvas, antialias: !opts.lowPower, alpha: true, powerPreference: "low-power" }); + } catch { + opts.onError(); + return noop; + } + renderer.setPixelRatio(Math.min(devicePixelRatio, opts.lowPower ? 1.25 : 1.75)); + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = !opts.lowPower; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + + const scene = new THREE.Scene(); + scene.fog = new THREE.Fog("#bfe6f0", 34, 70); + const camera = new THREE.PerspectiveCamera(34, 2, 0.1, 200); + + scene.add(new THREE.HemisphereLight("#fff6e4", "#5a7a8a", 1.15)); + const sun = new THREE.DirectionalLight("#ffe6c0", 2.1); + sun.position.set(-9, 16, 10); + sun.castShadow = !opts.lowPower; + sun.shadow.mapSize.set(1024, 1024); + Object.assign(sun.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 45 }); + sun.shadow.bias = -0.0008; + scene.add(sun); + const rim = new THREE.DirectionalLight("#a8c4ff", 0.5); + rim.position.set(10, 6, -10); + scene.add(rim); + + const textures: THREE.Texture[] = []; + const rand = seeded(2026); + + // 海:低多邊形的水面,慢慢起伏 + const waterGeo = new THREE.PlaneGeometry(90, 90, 36, 36); + waterGeo.rotateX(-Math.PI / 2); + const waterBase = Float32Array.from(waterGeo.attributes.position!.array); + const water = new THREE.Mesh(waterGeo, new THREE.MeshStandardMaterial({ color: "#4fb3c9", roughness: 0.35, metalness: 0.05, flatShading: true })); + water.position.y = -0.62; + water.receiveShadow = true; + scene.add(water); + + // 島:會跟著拖曳一起轉 + const isle = new THREE.Group(); + scene.add(isle); + const radial = 20; + const bumps = Array.from({ length: radial }, () => 1 + (rand() - 0.5) * 0.12); + const lumpy = (geo: THREE.CylinderGeometry) => { + const pos = geo.attributes.position!; + for (let i = 0; i < pos.count; i++) { + const x = pos.getX(i); + const z = pos.getZ(i); + if (Math.hypot(x, z) < 0.01) continue; + const a = Math.atan2(x, z); + const k = bumps[((Math.round(((a + Math.PI) / (Math.PI * 2)) * radial) % radial) + radial) % radial]!; + pos.setX(i, x * k); + pos.setZ(i, z * k); + } + geo.computeVertexNormals(); + return geo; + }; + const cliff = new THREE.MeshStandardMaterial({ color: "#b98b58", roughness: 0.95, flatShading: true }); + const grass = new THREE.MeshStandardMaterial({ color: "#a9cf7f", roughness: 0.95, flatShading: true }); + const land = new THREE.Mesh(lumpy(new THREE.CylinderGeometry(ISLAND_R, ISLAND_R - 1.2, 1.3, radial, 1)), [cliff, grass, cliff]); + land.position.y = -0.65; + land.receiveShadow = true; + isle.add(land); + const beach = new THREE.Mesh(lumpy(new THREE.CylinderGeometry(ISLAND_R + 0.9, ISLAND_R + 1.4, 0.4, radial, 1)), new THREE.MeshStandardMaterial({ color: "#efd9a4", roughness: 1, flatShading: true })); + beach.position.y = -0.62; + beach.receiveShadow = true; + isle.add(beach); + + // 中間的廣場與「政策島」看板 + const plaza = new THREE.Mesh(new THREE.CylinderGeometry(2.4, 2.5, 0.12, 24), new THREE.MeshStandardMaterial({ color: "#e8d6ae", roughness: 0.9 })); + plaza.position.y = 0.06; + plaza.receiveShadow = true; + isle.add(plaza); + const signTex = signTexture("政策島", "蓋建設・寫政策・選戰更有力"); + textures.push(signTex); + const ink = new THREE.MeshStandardMaterial({ color: "#111419" }); + const board = new THREE.Mesh(new THREE.BoxGeometry(2.3, 1.0, 0.08), [ink, ink, ink, ink, new THREE.MeshStandardMaterial({ map: signTex, roughness: 0.7 }), ink]); + board.position.set(0, 1.45, -0.6); + const posts = [-1.05, 1.05].map((x) => { + const p = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.05, 1.95), new THREE.MeshStandardMaterial({ color: "#2b2f36" })); + p.position.set(x, 0.98, -0.64); + return p; + }); + const sign = new THREE.Group(); + sign.add(board, ...posts); + shadows(sign, !opts.lowPower); + isle.add(sign); + + // 空地 + const n = opts.plots.length; + const plotAngle = (i: number) => Math.PI / n + (i / n) * Math.PI * 2; + const tileMat = { empty: new THREE.MeshStandardMaterial({ color: "#f3e8cc", roughness: 0.9 }), built: new THREE.MeshStandardMaterial({ color: "#d9c7a0", roughness: 0.9 }), selected: new THREE.MeshStandardMaterial({ color: "#ffd23f", roughness: 0.7 }) }; + const edgeMat = new THREE.LineBasicMaterial({ color: "#111419" }); + interface Plot { + id: string; + name: string; + group: THREE.Group; + tile: THREE.Mesh; + building: THREE.Object3D | null; + level: number; + height: number; + label: THREE.Sprite; + labelCanvas: HTMLCanvasElement; + labelTex: THREE.CanvasTexture; + grow: number | null; + } + const plots: Plot[] = opts.plots.map((p, i) => { + const a = plotAngle(i); + const group = new THREE.Group(); + group.position.set(Math.sin(a) * RING_R, 0, Math.cos(a) * RING_R); + const tile = new THREE.Mesh(new THREE.BoxGeometry(TILE, TILE_H, TILE), tileMat.empty); + tile.position.y = TILE_H / 2; + tile.receiveShadow = true; + const edges = new THREE.LineSegments(new THREE.EdgesGeometry(tile.geometry), edgeMat); + tile.add(edges); + group.add(tile); + group.userData.plot = i; + const labelCanvas = document.createElement("canvas"); + labelCanvas.width = LABEL_W; + labelCanvas.height = LABEL_H; + const labelTex = new THREE.CanvasTexture(labelCanvas); + labelTex.colorSpace = THREE.SRGBColorSpace; + textures.push(labelTex); + const label = new THREE.Sprite(new THREE.SpriteMaterial({ map: labelTex, depthTest: false, transparent: true, toneMapped: false })); + label.renderOrder = 10; + group.add(label); + isle.add(group); + return { id: p.id, name: p.name, group, tile, building: null, level: 0, height: 0, label, labelCanvas, labelTex, grow: null }; + }); + let selected = opts.selected; + let policies = opts.policies; + let labelScale = 1; + const refreshLabel = (p: Plot) => { + drawLabel(p.labelCanvas, p.name, p.level, p.id === selected, policies[p.id] ?? []); + p.labelTex.needsUpdate = true; + // 名牌含政策條比例 300:190;名字那一塊的下緣維持原本的高度 + p.label.scale.set(2 * labelScale, 2 * (LABEL_H / LABEL_W) * labelScale, 1); + p.label.position.set(0, TILE_H + Math.max(0.9, p.height + 0.45) + 0.25 * labelScale - ((LABEL_H - LABEL_BOX) / LABEL_W) * labelScale, 0); + p.tile.material = p.id === selected ? tileMat.selected : p.level > 0 ? tileMat.built : tileMat.empty; + }; + plots.forEach(refreshLabel); + + // 選取的那塊地上方跳動的箭頭 + const arrow = new THREE.Mesh(new THREE.ConeGeometry(0.2, 0.42, 4), new THREE.MeshBasicMaterial({ color: "#d61f2c", toneMapped: false })); + arrow.rotation.x = Math.PI; + arrow.visible = false; + isle.add(arrow); + + // 彩帶 + const CONFETTI = opts.reduceMotion ? 0 : opts.lowPower ? 100 : 200; + const confetti = new THREE.InstancedMesh(new THREE.PlaneGeometry(0.12, 0.07), new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, toneMapped: false }), Math.max(1, CONFETTI)); + const bits = Array.from({ length: CONFETTI }, () => ({ p: new THREE.Vector3(0, -10, 0), v: new THREE.Vector3(), r: new THREE.Euler(), w: new THREE.Vector3(Math.random() * 6, Math.random() * 6, Math.random() * 6) })); + const color = new THREE.Color(); + for (let i = 0; i < CONFETTI; i++) confetti.setColorAt(i, color.set(PALETTE[i % PALETTE.length]!)); + confetti.count = CONFETTI; + confetti.frustumCulled = false; + scene.add(confetti); + const burst = (at: THREE.Vector3) => { + let k = 0; + for (const b of bits) { + if (b.p.y > -1 || k > 80) continue; + b.p.set(at.x + (Math.random() - 0.5) * 1.4, at.y + 1.8 + Math.random(), at.z + (Math.random() - 0.5) * 1.4); + b.v.set((Math.random() - 0.5) * 3, 2.5 + Math.random() * 3, (Math.random() - 0.5) * 3); + k++; + } + }; + + // ── 模型 ── + const loader = new GLTFLoader(); + const cache = new Map>(); + const load = (path: string) => { + let p = cache.get(path); + if (!p) { + p = new Promise((resolve, reject) => loader.load(`${A}${path}.glb`, resolve, undefined, reject)); + cache.set(path, p); + } + return p; + }; + const models = new Map(); + // 住宅原本是綠屋頂,容易聯想成政黨色,換成磚紅色的貼圖版本 + const brick = new THREE.TextureLoader().load(`${A}town-houses/Textures/variation-b.png`); + brick.flipY = false; + brick.colorSpace = THREE.SRGBColorSpace; + brick.magFilter = THREE.NearestFilter; + textures.push(brick); + const prepare = (path: string, gltf: GLTF) => { + if (path.startsWith("town-houses/building")) { + gltf.scene.traverse((o) => { + const m = o as THREE.Mesh; + if (m.isMesh) m.material = Object.assign((m.material as THREE.MeshStandardMaterial).clone(), { map: brick }); + }); + } + models.set(path, gltf.scene); + }; + const mixers: THREE.AnimationMixer[] = []; + interface Person { + root: THREE.Object3D; + base: THREE.AnimationAction | null; + jump: THREE.AnimationAction | null; + } + const people: Person[] = []; + let ready = false; + /** 模型還沒讀完時收到的等級,讀完再套用 */ + let pendingLevels = opts.levels; + + const lookOf = (id: string) => LOOKS[id] ?? DEFAULT_LOOK; + const piece = (path: string, w: number, h: number): THREE.Object3D | null => { + const src = models.get(path); + if (!src) return null; + const obj = fitBox(src.clone(), w, h); + shadows(obj, !opts.lowPower); + return obj; + }; + /** 依等級組出一塊地上的東西:主建築,2 級起旁邊多一樣,3 級再多一樣加一支旗子 */ + const makeBuilding = (id: string, level: number): { obj: THREE.Group; height: number } => { + const look = lookOf(id); + const size = SIZES[Math.min(SIZES.length, level) - 1]!; + const obj = new THREE.Group(); + const main = piece(look.model, size.w, size.h); + let height = 0; + if (main) { + main.position.z = -0.15; + obj.add(main); + height = new THREE.Box3().setFromObject(main).max.y; + } + if (level >= 2) { + const e = piece(look.extras[0], 0.5, 0.55); + if (e) { + e.position.set(0.68, 0, 0.72); + obj.add(e); + } + } + if (level >= 3) { + const e = piece(look.extras[1], 0.5, 0.6); + if (e) { + e.position.set(-0.68, 0, 0.72); + obj.add(e); + } + const f = piece("props/flag", 1.2, 1.2); + if (f) { + f.position.set(0.8, 0, -0.7); + obj.add(f); + } + } + obj.position.y = TILE_H; + return { obj, height }; + }; + const emptyMarker = (): THREE.Object3D | null => { + const s = piece("props/sign", 0.5, 0.5); + if (s) s.position.set(0, TILE_H, 0.2); + return s; + }; + + const applyLevel = (p: Plot, level: number, celebrate: boolean) => { + if (p.building) { + p.group.remove(p.building); + p.building = null; + } + p.level = level; + if (level > 0) { + const { obj, height } = makeBuilding(p.id, level); + p.building = obj; + p.height = height; + } else { + p.building = emptyMarker(); + p.height = 0; + } + if (p.building) { + p.building.userData.plot = plots.indexOf(p); + p.group.add(p.building); + } + if (celebrate && !opts.reduceMotion) { + p.grow = clock.elapsedTime; + p.building?.scale.setScalar(0.4); + burst(p.group.getWorldPosition(new THREE.Vector3())); + people.forEach((_, i) => setTimeout(() => jump(i), 80 + i * 70)); + } + refreshLabel(p); + invalidate(); + }; + + const decorate = () => { + // 島邊的樹、石頭、花:放在兩塊空地之間的外圈 + for (let i = 0; i < n; i++) { + const a = plotAngle(i) + Math.PI / n; + const r = ISLAND_R - 0.9 - rand() * 0.5; + const d = piece(DECOR[i % DECOR.length]!, 1.4, i % DECOR.length < 3 ? 1.8 + rand() * 0.6 : 0.6); + if (!d) continue; + d.position.set(Math.sin(a) * r, 0, Math.cos(a) * r); + d.rotation.y = rand() * Math.PI * 2; + isle.add(d); + // 外側再放一棵小一點的,讓海岸線不要太空 + const small = piece(DECOR[(i + 2) % 3]!, 1, 1.2 + rand() * 0.4); + if (small) { + const a2 = plotAngle(i) + (rand() - 0.5) * 0.3; + small.position.set(Math.sin(a2) * (ISLAND_R - 0.4), 0, Math.cos(a2) * (ISLAND_R - 0.4)); + isle.add(small); + } + } + }; + + const addPeople = (chars: GLTF[]) => { + const spots: [number, number, number][] = [ + [-1.3, 0.6, 0.5], + [1.35, 0.5, -0.5], + [-0.45, 1.45, 0.2], + [0.6, 1.3, -0.15], + ]; + chars.forEach((gltf, i) => { + const [x, z, ry] = spots[i % spots.length]!; + const root = fitBox(cloneSkinned(gltf.scene), 1, 0.85); + root.position.set(x, 0.12, z); + root.rotation.y = ry; + shadows(root, !opts.lowPower); + isle.add(root); + const mixer = new THREE.AnimationMixer(root.children[0]!); + const clip = THREE.AnimationClip.findByName(gltf.animations, i % 2 ? "emote-yes" : "idle") ?? gltf.animations[0]; + const base = clip ? mixer.clipAction(clip) : null; + if (base && clip) { + base.time = (i * 0.37 * clip.duration) % clip.duration; + base.play(); + } + const jumpClip = THREE.AnimationClip.findByName(gltf.animations, "jump"); + const jumpAction = jumpClip ? mixer.clipAction(jumpClip) : null; + if (jumpAction) { + jumpAction.setLoop(THREE.LoopOnce, 1); + jumpAction.clampWhenFinished = false; + } + mixer.addEventListener("finished", () => base?.reset().fadeIn(0.2).play()); + mixers.push(mixer); + people.push({ root, base, jump: jumpAction }); + }); + }; + const jump = (i: number) => { + const p = people[i]; + if (!p?.jump || opts.reduceMotion) return; + p.base?.fadeOut(0.1); + p.jump.reset().fadeIn(0.1).play(); + }; + + const setup = async () => { + const paths = new Set(["props/flag", "props/sign", ...DECOR]); + for (const p of opts.plots) { + const look = lookOf(p.id); + paths.add(look.model); + look.extras.forEach((e) => paths.add(e)); + } + const [loaded, chars] = await Promise.all([ + Promise.all([...paths].map(async (path) => [path, await load(path)] as const)), + Promise.all(PEOPLE.map((c) => load(`characters/${c}`))), + ]); + for (const [path, gltf] of loaded) prepare(path, gltf); + decorate(); + addPeople(chars); + ready = true; + plots.forEach((p) => applyLevel(p, Math.max(0, Math.min(3, pendingLevels[p.id] ?? 0)), false)); + }; + + // ── 鏡頭、拖曳、點選 ── + let view = { radius: 21, height: 14, lift: 0, fov: 34 }; + let pointerX = 0; + const place = (t: number) => { + const sway = opts.reduceMotion ? 0 : Math.sin(t * 0.1) * 0.06 + pointerX * 0.04; + camera.position.set(Math.sin(sway) * view.radius, view.height, Math.cos(sway) * view.radius); + camera.lookAt(0, view.lift, 0.6); + }; + const ray = new THREE.Raycaster(); + // 空地的黑框是線段,預設的判定範圍太寬,會點到隔壁那塊 + ray.params.Line = { threshold: 0.02 }; + const ndc = new THREE.Vector2(); + const pick = (e: PointerEvent): number | null => { + const r = canvas.getBoundingClientRect(); + ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + ray.setFromCamera(ndc, camera); + // 名牌、建築、空地都算點到那塊地 + for (const h of ray.intersectObjects( + plots.map((p) => p.group), + true, + )) { + for (let o: THREE.Object3D | null = h.object; o; o = o.parent) { + if (typeof o.userData.plot === "number") return o.userData.plot as number; + } + } + return null; + }; + let drag: { x: number; rot: number; moved: boolean; id: number } | null = null; + let spin = 0; + const onDown = (e: PointerEvent) => { + drag = { x: e.clientX, rot: isle.rotation.y, moved: false, id: e.pointerId }; + spin = 0; + }; + const onMove = (e: PointerEvent) => { + const r = canvas.getBoundingClientRect(); + pointerX = ((e.clientX - r.left) / r.width - 0.5) * 2; + if (drag && e.pointerId === drag.id) { + const dx = e.clientX - drag.x; + if (!drag.moved && Math.abs(dx) > 6) { + drag.moved = true; + try { + canvas.setPointerCapture(e.pointerId); + } catch { + // 有些瀏覽器拿不到 capture,拖曳一樣能用 + } + } + if (drag.moved) { + const next = drag.rot + dx * 0.008; + spin = next - isle.rotation.y; + isle.rotation.y = next; + invalidate(); + } + return; + } + if (e.pointerType === "mouse") canvas.style.cursor = pick(e) !== null ? "pointer" : "grab"; + }; + const onUp = (e: PointerEvent) => { + if (!drag || e.pointerId !== drag.id) return; + const wasDrag = drag.moved; + drag = null; + if (wasDrag) return; + const i = pick(e); + if (i !== null) opts.onPick(plots[i]!.id); + }; + const onCancel = () => { + drag = null; + }; + canvas.addEventListener("pointerdown", onDown); + canvas.addEventListener("pointermove", onMove); + canvas.addEventListener("pointerup", onUp); + canvas.addEventListener("pointercancel", onCancel); + + // ── 繪圖迴圈:減少動態時只在有變化時畫一次 ── + const clock = new THREE.Clock(); + let active = true; + let disposed = false; + let dirty = true; + let raf = 0; + function invalidate() { + dirty = true; + } + const dummy = new THREE.Object3D(); + const frame = () => { + if (disposed) return; + raf = requestAnimationFrame(frame); + if (!active) return; + const dt = Math.min(clock.getDelta(), 0.05); + const t = clock.elapsedTime; + const animate = ready && !opts.reduceMotion; + if (!animate && !dirty) return; + dirty = false; + place(t); + if (animate) { + for (const m of mixers) m.update(dt); + // 放開之後島還會慢慢滑一下 + if (!drag && Math.abs(spin) > 0.0005) { + isle.rotation.y += spin; + spin *= 0.9; + } + const pos = waterGeo.attributes.position!; + for (let i = 0; i < pos.count; i++) { + const x = waterBase[i * 3]!; + const z = waterBase[i * 3 + 2]!; + pos.setY(i, Math.sin(x * 0.45 + t * 0.9) * 0.08 + Math.cos(z * 0.5 + t * 0.7) * 0.08); + } + pos.needsUpdate = true; + waterGeo.computeVertexNormals(); + for (const p of plots) { + if (p.grow === null || !p.building) continue; + const k = Math.min(1, (t - p.grow) / 0.5); + p.building.scale.setScalar(0.4 + 0.6 * easeOutBack(k)); + if (k >= 1) p.grow = null; + } + for (let i = 0; i < CONFETTI; i++) { + const b = bits[i]!; + if (b.p.y > -1) { + b.v.y -= 4.5 * dt; + b.v.multiplyScalar(0.985); + b.p.addScaledVector(b.v, dt); + b.r.x += b.w.x * dt; + b.r.y += b.w.y * dt; + if (b.p.y < 0.05) b.p.y = -10; + } + dummy.position.copy(b.p); + dummy.rotation.copy(b.r); + dummy.updateMatrix(); + confetti.setMatrixAt(i, dummy.matrix); + } + if (CONFETTI) confetti.instanceMatrix.needsUpdate = true; + } + const sel = plots.find((p) => p.id === selected); + arrow.visible = !!sel; + if (sel) { + const top = TILE_H + Math.max(0.9, sel.height + 0.45) + 1.05 * labelScale + 0.25; + arrow.position.set(sel.group.position.x, top + (animate ? Math.abs(Math.sin(t * 4)) * 0.18 : 0), sel.group.position.z); + arrow.rotation.y = animate ? t * 2 : 0.6; + } + renderer.render(scene, camera); + }; + + setup() + .then(() => { + if (disposed) return; + invalidate(); + opts.onReady(); + }) + .catch(() => !disposed && opts.onError()); + raf = requestAnimationFrame(frame); + + return { + resize(w, h) { + renderer.setSize(w, h, false); + camera.aspect = w / Math.max(1, h); + // 直式(手機)拉遠一點,整圈空地都看得到(島邊的樹切掉一點沒關係) + view = camera.aspect < 0.9 ? { radius: 26, height: 20, lift: -0.5, fov: 40 } : camera.aspect < 1.4 ? { radius: 20, height: 15, lift: -0.4, fov: 36 } : { radius: 19, height: 12.5, lift: -0.4, fov: 34 }; + camera.fov = view.fov; + camera.updateProjectionMatrix(); + // 畫面越窄名牌越大,手機上才看得清楚 + const nextScale = Math.round(Math.min(1.5, Math.max(1, 640 / Math.max(1, w))) * 20) / 20; + if (nextScale !== labelScale) { + labelScale = nextScale; + plots.forEach(refreshLabel); + } + invalidate(); + }, + setLevels(levels) { + if (!ready) { + pendingLevels = levels; + return; + } + for (const p of plots) { + const next = Math.max(0, Math.min(3, levels[p.id] ?? 0)); + if (next !== p.level) applyLevel(p, next, next > p.level); + } + }, + setPolicies(next) { + policies = next; + plots.forEach(refreshLabel); + invalidate(); + }, + select(id) { + selected = id; + plots.forEach(refreshLabel); + invalidate(); + }, + setActive(on) { + active = on; + if (on) { + clock.getDelta(); + invalidate(); + } + }, + dispose() { + disposed = true; + cancelAnimationFrame(raf); + canvas.removeEventListener("pointerdown", onDown); + canvas.removeEventListener("pointermove", onMove); + canvas.removeEventListener("pointerup", onUp); + canvas.removeEventListener("pointercancel", onCancel); + textures.forEach((t) => t.dispose()); + scene.traverse((o) => { + const m = o as THREE.Mesh; + m.geometry?.dispose(); + const mat = m.material as THREE.Material | THREE.Material[] | undefined; + (Array.isArray(mat) ? mat : mat ? [mat] : []).forEach((x) => x.dispose()); + }); + renderer.dispose(); + }, + }; +} diff --git a/web/src/game/island/store.ts b/web/src/game/island/store.ts new file mode 100644 index 0000000..2f936c4 --- /dev/null +++ b/web/src/game/island/store.ts @@ -0,0 +1,193 @@ +import { PolicySpec, type IslandBuilding, type IslandPerk } from "@election2026/protocol"; +import { useEffect, useState } from "react"; +import { FALLBACK_BUILDINGS, MAX_LEVEL, nextCost } from "./data.ts"; + +/** + * 政策島的進度(docs/23 跨局成長):政績點、建築等級、政策工坊存的政策、要帶進下一局的政策、拿點紀錄。 + * 只存在玩家自己的瀏覽器(localStorage);讀不到(私密模式、資料壞掉)就當作空的島。 + * 每個寫入的函式都是「讀 → 算出新的一份 → 存 → 通知畫面」,不改舊的物件。 + */ + +export interface IslandLogEntry { + /** 拿到點數的日期(YYYY-MM-DD,玩家當地時間) */ + date: string; + points: number; + reason: string; + /** 哪一局給的;同一局只算一次 */ + runId?: string; +} + +export interface IslandState { + points: number; + /** 建築 id → 等級 1–3(沒蓋的不列) */ + buildings: Record; + /** 政策工坊存的政策,最多 6 份 */ + policies: PolicySpec[]; + /** 要帶進下一局的政策(policies 的 index) */ + active: number[]; + log: IslandLogEntry[]; +} + +export const ISLAND_KEY = "tongsuan.island.v1"; +export const MAX_POLICIES = 6; +/** 紀錄只留最近這麼多筆(同一局只算一次靠這份紀錄,200 局內不會重複) */ +const MAX_LOG = 200; +const EVENT = "tongsuan:island"; + +const empty = (): IslandState => ({ points: 0, buildings: {}, policies: [], active: [], log: [] }); + +const today = (now = new Date()): string => + `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`; + +/** 每局可以帶幾份政策:基本 1 份,政策研究院 1、2 級各多 1 份(跟伺服器 meta.ts 一樣) */ +export const policySlots = (state: Pick): number => 1 + Math.min(2, state.buildings.library ?? 0); + +/** 存檔是玩家瀏覽器裡的資料,可能被改過或是舊版:逐欄檢查,不對的丟掉 */ +function sanitize(raw: unknown): IslandState { + if (!raw || typeof raw !== "object") return empty(); + const r = raw as Partial>; + const points = typeof r.points === "number" && Number.isFinite(r.points) ? Math.max(0, Math.floor(r.points)) : 0; + const buildings: Record = {}; + if (r.buildings && typeof r.buildings === "object") { + for (const [id, lv] of Object.entries(r.buildings as Record)) { + if (typeof lv === "number" && lv >= 1 && id.length <= 30) buildings[id] = Math.min(MAX_LEVEL, Math.floor(lv)); + } + } + const policies = (Array.isArray(r.policies) ? r.policies : []) + .map((p) => PolicySpec.safeParse(p)) + .flatMap((p) => (p.success ? [p.data] : [])) + .slice(0, MAX_POLICIES); + const slots = policySlots({ buildings }); + const active = [...new Set(Array.isArray(r.active) ? r.active : [])] + .filter((i): i is number => Number.isInteger(i) && i >= 0 && i < policies.length) + .slice(0, slots); + const log = (Array.isArray(r.log) ? r.log : []) + .filter((e): e is IslandLogEntry => !!e && typeof e === "object" && typeof e.points === "number" && typeof e.reason === "string" && typeof e.date === "string") + .map((e) => ({ date: e.date, points: e.points, reason: e.reason, ...(typeof e.runId === "string" ? { runId: e.runId } : {}) })) + .slice(-MAX_LOG); + return { points, buildings, policies, active, log }; +} + +export function loadIsland(): IslandState { + try { + const raw = localStorage.getItem(ISLAND_KEY); + return raw ? sanitize(JSON.parse(raw)) : empty(); + } catch { + return empty(); + } +} + +export function saveIsland(state: IslandState): void { + try { + localStorage.setItem(ISLAND_KEY, JSON.stringify(state)); + } catch { + // 私密模式存不了:這次的進度只留在畫面上 + } + try { + dispatchEvent(new CustomEvent(EVENT)); + } catch { + // 沒有 window(測試環境) + } +} + +const commit = (next: IslandState): IslandState => { + saveIsland(next); + return next; +}; + +/** 加政績點;同一個 runId 只算一次。回傳這次有沒有真的加到 */ +export function addPoints(points: number, reason: string, runId?: string): boolean { + const s = loadIsland(); + const n = Math.floor(points); + if (!Number.isFinite(n) || n <= 0) return false; + if (runId && s.log.some((e) => e.runId === runId)) return false; + const entry: IslandLogEntry = { date: today(), points: n, reason, ...(runId ? { runId } : {}) }; + commit({ ...s, points: s.points + n, log: [...s.log, entry].slice(-MAX_LOG) }); + return true; +} + +/** 蓋或升級一棟建築,扣政績點。點數不夠、已經滿級、不認得的建築回 false */ +export function build(id: string, list: readonly IslandBuilding[] = FALLBACK_BUILDINGS): boolean { + const b = list.find((x) => x.id === id); + if (!b) return false; + const s = loadIsland(); + const level = s.buildings[id] ?? 0; + const cost = nextCost(b, level); + if (cost === null || s.points < cost) return false; + commit({ ...s, points: s.points - cost, buildings: { ...s.buildings, [id]: level + 1 } }); + return true; +} + +/** 開局時帶給伺服器的建築加成(rogueApi.create 的 perks) */ +export function perksForRun(): IslandPerk[] { + return Object.entries(loadIsland().buildings) + .filter(([, level]) => level >= 1) + .map(([id, level]) => ({ id, level })) + .slice(0, 20); +} + +/** 開局時帶給伺服器的政策(rogueApi.create 的 policies,最多 3 份) */ +export function policiesForRun(): PolicySpec[] { + const s = loadIsland(); + return s.active + .slice(0, policySlots(s)) + .map((i) => s.policies[i]) + .filter((p): p is PolicySpec => !!p) + .map((p) => ({ ...p, name: p.name.trim() })) + .slice(0, 3); +} + +/** 存一份新政策;已經存滿或格式不對回 false。剛存的政策如果還有空位就自動勾選帶進下一局 */ +export function savePolicy(spec: PolicySpec): boolean { + const parsed = PolicySpec.safeParse(spec); + if (!parsed.success) return false; + const s = loadIsland(); + if (s.policies.length >= MAX_POLICIES) return false; + const index = s.policies.length; + const active = s.active.length < policySlots(s) ? [...s.active, index] : s.active; + commit({ ...s, policies: [...s.policies, parsed.data], active }); + return true; +} + +/** 刪一份政策;後面的政策往前補,勾選的 index 跟著調 */ +export function deletePolicy(index: number): void { + const s = loadIsland(); + if (index < 0 || index >= s.policies.length) return; + commit({ + ...s, + policies: s.policies.filter((_, i) => i !== index), + active: s.active.filter((i) => i !== index).map((i) => (i > index ? i - 1 : i)), + }); +} + +/** 勾選/取消帶進下一局;超過可帶的份數回 false */ +export function setPolicyActive(index: number, on: boolean): boolean { + const s = loadIsland(); + if (index < 0 || index >= s.policies.length) return false; + if (!on) { + commit({ ...s, active: s.active.filter((i) => i !== index) }); + return true; + } + if (s.active.includes(index)) return true; + if (s.active.length >= policySlots(s)) return false; + commit({ ...s, active: [...s.active, index] }); + return true; +} + +/** 畫面用:目前的島,別的分頁或元件改了也會跟著更新 */ +export function useIsland(): IslandState { + const [state, setState] = useState(loadIsland); + useEffect(() => { + const update = () => setState(loadIsland()); + const onStorage = (e: StorageEvent) => { + if (e.key === ISLAND_KEY) update(); + }; + addEventListener(EVENT, update); + addEventListener("storage", onStorage); + return () => { + removeEventListener(EVENT, update); + removeEventListener("storage", onStorage); + }; + }, []); + return state; +} diff --git a/web/src/game/minigames/BillboardGame.tsx b/web/src/game/minigames/BillboardGame.tsx new file mode 100644 index 0000000..7c29330 --- /dev/null +++ b/web/src/game/minigames/BillboardGame.tsx @@ -0,0 +1,367 @@ +import { Check, Construction, Footprints, RotateCw, Undo2 } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { BillboardArt } from "./art.tsx"; +import { BB_N, BILLBOARD_MS, PIECE_NAMES, SHAPES, TURNS, billboardScore, footprint, makeBillboard, rotate, walkway, type PieceKind } from "./billboard-logic.ts"; +import { Pops, Shell, usePops, useShake } from "./Shell.tsx"; +import { mgSound } from "./sound.ts"; +import type { MiniGameMeta, MiniGameProps } from "./types.ts"; +import { useRound } from "./useRound.ts"; +import "./billboard.css"; + +export const BILLBOARD_META: MiniGameMeta = { + id: "billboard", + title: "看板卡位", + rules: "把手上的看板掛到人多的格子(數字=經過的人流)。不能壓到施工、對手的看板,也不能把路堵死,行人要能從左邊走到右邊。", + reward: "那一區每週自動加票(看板)", + pitch: "把看板掛在人流最多的格子,路不能堵死", + steps: ["格子上的數字是人流,看板蓋在數字大的地方", "不能壓到施工、對手的看板", "要留一條路,讓行人從左邊走到右邊(腳印)"], + controls: "手機點一下預覽、再點一次掛上;電腦用滑鼠點,或方向鍵+Enter,R 轉向、Z 復原", +}; + +const N = BB_N; +const HINT = "點格子掛看板・腳印是行人要走的路"; + +interface Placed { + piece: number; + cells: readonly number[]; +} + +interface Status { + text: string; + tone: "info" | "good" | "bad" | "big"; + key: number; +} + +/** 托盤裡的小圖:看板目前的方向 */ +function Mini({ kind, turn }: { kind: PieceKind; turn: number }) { + const shape = rotate(SHAPES[kind], turn % TURNS[kind]); + const minR = Math.min(...shape.map(([r]) => r)); + const minC = Math.min(...shape.map(([, c]) => c)); + return ( + + {shape.map(([r, c]) => ( + + ))} + + ); +} + +/** + * 看板卡位:6×6 的街區,把 3–4 塊看板掛在人流多的格子上,但要留一條路讓行人從左走到右。 + * 分數=蓋到的人流和最佳擺法比(billboard-logic.ts);最佳擺法開局時用搜尋算好,一定做得到。 + * 觸控:點一下預覽(虛線框)、再點一次掛上;滑鼠:滑過去預覽、點下去掛上;鍵盤:方向鍵移動、Enter 掛上。 + */ +export function BillboardGame(props: MiniGameProps) { + const { seed, level } = props; + const lv = useMemo(() => makeBillboard(seed, level), [seed, level]); + const round = useRound({ durationMs: BILLBOARD_MS, stepMs: 100 }); + const { phase, elapsed, live } = round; + const [placed, setPlaced] = useState([]); + const [selected, setSelected] = useState(0); + const [turn, setTurn] = useState(0); + const [aim, setAim] = useState(null); + const [cursor, setCursor] = useState(0); + const [status, setStatus] = useState({ text: HINT, tone: "info", key: 0 }); + const [golden, setGolden] = useState(0); + const [doneAt, setDoneAt] = useState(null); + const [pops, addPop] = usePops(1); + const [shakeClass, shake] = useShake(); + const lastPointer = useRef(""); + const confirmAt = useRef(-Infinity); + const cellRefs = useRef<(HTMLButtonElement | null)[]>([]); + + useEffect(() => { + setPlaced([]); + setSelected(0); + setAim(null); + }, [lv]); + + const say = (text: string, tone: Status["tone"]) => setStatus({ text, tone, key: performance.now() }); + + const owner = new Map(); + placed.forEach((p, k) => p.cells.forEach((i) => owner.set(i, k))); + const covered = placed.reduce((a, p) => a + p.cells.reduce((s, i) => s + lv.traffic[i]!, 0), 0); + const score = billboardScore(covered, lv.best); + const used = new Set(placed.map((p) => p.piece)); + const allPlaced = used.size === lv.pieces.length; + const kind = lv.pieces[selected]!; + const path = walkway((i) => lv.tiles[i] !== "free" || owner.has(i)); + const pathSet = new Set(path ?? []); + + useEffect(() => { + if (phase === "done") setDoneAt((d) => d ?? elapsed); + }, [phase]); // eslint-disable-line react-hooks/exhaustive-deps + + const problem = (fp: { cells: number[]; inside: boolean }): string | null => { + if (!fp.inside) return "超出街區了,換個位置或轉向"; + if (fp.cells.some((i) => lv.tiles[i] === "build")) return "那裡在施工,不能掛"; + if (fp.cells.some((i) => lv.tiles[i] === "rival")) return "對手先卡位了"; + if (fp.cells.some((i) => owner.has(i))) return "跟自己的看板重疊了"; + if (!walkway((i) => lv.tiles[i] !== "free" || owner.has(i) || fp.cells.includes(i))) return "這樣會把路堵死,行人過不去"; + return null; + }; + + const place = (cell: number) => { + if (!live) return; + if (used.has(selected)) { + say("都掛好了:按「完成」或「復原」", "info"); + return; + } + const fp = footprint(kind, turn, cell); + const why = problem(fp); + if (why) { + setAim(cell); + mgSound.wrong(); + shake(); + say(why, "bad"); + return; + } + const gain = fp.cells.reduce((s, i) => s + lv.traffic[i]!, 0); + const center = fp.cells.reduce((a, i) => ({ x: a.x + ((i % N) + 0.5) / fp.cells.length, y: a.y + (Math.floor(i / N) + 0.5) / fp.cells.length }), { x: 0, y: 0 }); + const next = [...placed, { piece: selected, cells: fp.cells }]; + setPlaced(next); + setAim(null); + const isGold = gain > 0 && gain >= lv.topByKind[kind] * 0.85; + if (isGold) { + setGolden((g) => g + 1); + sfx.coin(); + } else sfx.place(); + addPop({ x: (center.x / N) * 100, y: (center.y / N) * 100, text: `+${gain}`, tone: isGold ? "big" : "good" }); + const nextPiece = lv.pieces.findIndex((_, k) => k !== selected && !used.has(k)); + if (nextPiece >= 0) { + setSelected(nextPiece); + say(isGold ? `黃金位置!人流 +${gain}` : `人流 +${gain},下一塊:${PIECE_NAMES[lv.pieces[nextPiece]!]}`, isGold ? "big" : "good"); + } else { + sfx.good(); + say("全部掛好了!按「完成」結算", "big"); + } + }; + + const undo = () => { + const last = placed[placed.length - 1]; + if (!live || !last) return; + setPlaced(placed.slice(0, -1)); + setSelected(last.piece); + sfx.click(); + say(`拿回${PIECE_NAMES[lv.pieces[last.piece]!]}`, "info"); + }; + const spin = () => { + if (!live) return; + setTurn((t) => (t + 1) % 4); + sfx.flip(); + }; + const pick = (k: number) => { + if (!live || used.has(k) || k >= lv.pieces.length) return; + setSelected(k); + sfx.click(); + }; + // 還有看板沒掛就按「完成」:先提醒,3 秒內再按一次才結算 + const finishNow = () => { + if (!live || placed.length === 0) return; + const left = lv.pieces.length - used.size; + if (left > 0 && performance.now() - confirmAt.current > 3000) { + confirmAt.current = performance.now(); + mgSound.wrong(); + say(`還有 ${left} 塊沒掛,再按一次「完成」就結算`, "bad"); + return; + } + round.finish(true); + }; + + // 鍵盤:R 轉向、Z/Backspace 復原、1–4 選看板(用 ref 拿最新的處理函式,不用每次重綁) + const keys = useRef({ spin, undo, pick }); + keys.current = { spin, undo, pick }; + useEffect(() => { + if (phase !== "play") return; + const onKey = (e: KeyboardEvent) => { + if (e.metaKey || e.ctrlKey || e.altKey) return; + if (e.code === "KeyR") keys.current.spin(); + else if (e.code === "KeyZ" || e.key === "Backspace") keys.current.undo(); + else if (/^Digit[1-4]$/.test(e.code)) keys.current.pick(Number(e.code.slice(5)) - 1); + else return; + e.preventDefault(); + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }, [phase]); + + // 方向鍵在格子間移動(只有目前那一格在 Tab 順序裡) + const onGridKey = (e: React.KeyboardEvent) => { + const d = { ArrowUp: -N, ArrowDown: N, ArrowLeft: -1, ArrowRight: 1 }[e.key]; + if (d === undefined) return; + e.preventDefault(); + const c = cursor % N; + if ((e.key === "ArrowLeft" && c === 0) || (e.key === "ArrowRight" && c === N - 1)) return; + const next = cursor + d; + if (next < 0 || next >= N * N) return; + setCursor(next); + cellRefs.current[next]?.focus(); + }; + + const ghost = aim !== null && live && !used.has(selected) ? footprint(kind, turn, aim) : null; + const ghostSet = new Set(ghost?.cells ?? []); + const ghostBad = ghost !== null && problem(ghost) !== null; + const edgeRow = (i: number | undefined) => (i === undefined ? null : `${((Math.floor(i / N) + 0.5) / N) * 100}%`); + const enter = edgeRow(path?.[0]); + const exit = edgeRow(path?.[path.length - 1]); + + return ( + } + timer={{ leftMs: BILLBOARD_MS - elapsed, totalMs: BILLBOARD_MS }} + shakeClass={shakeClass} + hud={ + + 人流 + + {covered} + /{lv.best} + + + } + summary={[ + { label: "蓋到人流", value: `${covered}/${lv.best}` }, + { label: "掛上看板", value: `${used.size}/${lv.pieces.length} 塊` }, + { label: "黃金位置", value: `${golden} 次` }, + { label: "用時", value: `${Math.round((doneAt ?? elapsed) / 1000)} 秒` }, + ]} + > +
+
+

+ {status.text} +

+
+ + {enter && } + +
lastPointer.current === "mouse" && setAim(null)} onKeyDown={onGridKey}> + {Array.from({ length: N }, (_, r) => ( +
+ {Array.from({ length: N }, (_, c) => { + const i = r * N + c; + const v = lv.traffic[i]!; + const tile = lv.tiles[i]!; + const mine = owner.get(i); + const cls = ["mg-cell", `is-${tile}`]; + if (mine !== undefined) { + cls.push("is-mine"); + if (mine === placed.length - 1) cls.push("is-new"); + if (r > 0 && owner.get(i - N) === mine) cls.push("no-t"); + if (r < N - 1 && owner.get(i + N) === mine) cls.push("no-b"); + if (c > 0 && owner.get(i - 1) === mine) cls.push("no-l"); + if (c < N - 1 && owner.get(i + 1) === mine) cls.push("no-r"); + } else if (pathSet.has(i)) cls.push("is-path"); + if (ghostSet.has(i)) cls.push(ghostBad ? "is-ghost-bad" : "is-ghost"); + if (v === 0) cls.push("is-zero"); + if (v >= 5) cls.push("is-hot"); + const label = tile === "build" ? "施工中" : tile === "rival" ? "對手的看板" : mine !== undefined ? `你的看板,人流 ${v}` : `人流 ${v}`; + return ( + + ); + })} +
+ ))} + +
+ + {exit && } + +
+
+
+ {lv.pieces.map((k, idx) => ( + + ))} +
+
+ + + +
+
    +
  • + + 7 + + 人流 +
  • +
  • + + 施工 +
  • +
  • + + 對手 +
  • +
  • + + 行人的路 +
  • +
+
+
+
+
+ ); +} diff --git a/web/src/game/minigames/HandshakeGame.tsx b/web/src/game/minigames/HandshakeGame.tsx new file mode 100644 index 0000000..bb99d8e --- /dev/null +++ b/web/src/game/minigames/HandshakeGame.tsx @@ -0,0 +1,248 @@ +import { Camera } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { HandshakeArt } from "./art.tsx"; +import { HAND_POINTS, HANDSHAKE_MS, HS_KEY_LABELS, HS_KEYS, MISS_PENALTY, REPORTER_PENALTY, handshakeScore, makeHandshake, portraitSpots, type Spot } from "./handshake-logic.ts"; +import { ComboBadge, Pops, Shell, usePops, useShake } from "./Shell.tsx"; +import { mgSound } from "./sound.ts"; +import type { MiniGameMeta, MiniGameProps } from "./types.ts"; +import { useRound } from "./useRound.ts"; +import "./handshake.css"; + +export const HANDSHAKE_META: MiniGameMeta = { + id: "handshake", + title: "掃街握手", + rules: "20 秒內,點人群裡舉手(黃色光圈)的鄉親跟他握手;戴紅彩帶的里長伯一次算三位。拿相機的是記者,點到會被拍到扣分。", + reward: "那一區加票,90 分以上聲勢 +1", + pitch: "點舉手的鄉親握手,別讓記者拍到", + steps: ["鄉親舉手(黃色光圈)時點他,握到手 +1", "戴紅彩帶的里長伯 +3,但手放得比較快", `拿相機的是記者,點到被拍 −${REPORTER_PENALTY} 分;亂點也會扣分`], + controls: "手機直接點人;電腦用滑鼠,或鍵盤 Q–Y/A–H/Z–N 對應三排人", +}; + +/** 騎樓的店招(虛構的店名) */ +const SHOPS = ["阿嬤麵線", "好運彩券", "大眾理容", "日日鮮果", "老街豆花", "福利五金"]; + +type Outcome = "hit" | "caught"; + +/** 畫面是不是直的(手機直拿):人群改排成四排 */ +function usePortrait(): boolean { + const query = "(orientation: portrait)"; + const [portrait, setPortrait] = useState(() => typeof matchMedia === "function" && matchMedia(query).matches); + useEffect(() => { + if (typeof matchMedia !== "function") return; + const mq = matchMedia(query); + const on = () => setPortrait(mq.matches); + mq.addEventListener("change", on); + return () => mq.removeEventListener("change", on); + }, []); + return portrait; +} + +/** + * 掃街握手:騎樓下的人群裡有人舉手,點下去就是握到手。20 秒,越後面越快。 + * 分數=拿到的分 ÷(全部 × 0.95)× 100,被記者拍到 −8、揮空 −1.5(handshake-logic.ts)。 + */ +export function HandshakeGame(props: MiniGameProps) { + const { seed, level } = props; + const lv = useMemo(() => makeHandshake(seed, level), [seed, level]); + const portrait = usePortrait(); + const spots: readonly Spot[] = useMemo(() => (portrait ? portraitSpots(lv.people.length) : lv.people), [portrait, lv]); + const round = useRound({ durationMs: HANDSHAKE_MS }); + const { elapsed, phase } = round; + const [outcomes, setOutcomes] = useState>(new Map()); + const [points, setPoints] = useState(0); + const [hits, setHits] = useState(0); + const [vips, setVips] = useState(0); + const [reporters, setReporters] = useState(0); + const [misses, setMisses] = useState(0); + const [streak, setStreak] = useState(0); + const [maxStreak, setMaxStreak] = useState(0); + const [bump, setBump] = useState<{ person: number; key: number } | null>(null); + const [flash, setFlash] = useState(0); + const [kbd, setKbd] = useState(false); + const [pops, addPop] = usePops(); + const [shakeClass, shake] = useShake(); + const streakRef = useRef(0); + const expiredSeen = useRef(0); + + // 換關卡(大廳換難度)時重來 + useEffect(() => { + setOutcomes(new Map()); + expiredSeen.current = 0; + }, [lv]); + + const active = new Map(); + lv.spawns.forEach((s, i) => { + if (!outcomes.has(i) && s.t <= elapsed && elapsed < s.t + s.dur) active.set(s.person, i); + }); + + // 鄉親手放下了還沒握到:連續握手中斷 + const expired = lv.spawns.reduce((n, s, i) => n + (s.kind !== "reporter" && !outcomes.has(i) && elapsed >= s.t + s.dur ? 1 : 0), 0); + useEffect(() => { + if (phase !== "play" || expired <= expiredSeen.current) return; + expiredSeen.current = expired; + if (streakRef.current > 0) { + streakRef.current = 0; + setStreak(0); + } + const last = lv.spawns.findLast((s, i) => s.kind !== "reporter" && !outcomes.has(i) && elapsed >= s.t + s.dur); + const p = last ? spots[last.person] : undefined; + if (p) addPop({ x: p.x, y: p.y, lift: 1.1 * p.scale, text: "錯過", tone: "dim" }); + }, [expired]); // eslint-disable-line react-hooks/exhaustive-deps + + const score = handshakeScore({ points, totalPoints: lv.totalPoints, reporters, misses }); + + const tap = (person: number) => { + if (!round.live) return; + const p = spots[person]!; + const at = { x: p.x, y: p.y, lift: 1.15 * p.scale }; + const i = active.get(person); + if (i === undefined) { + setMisses((m) => m + 1); + streakRef.current = 0; + setStreak(0); + sfx.click(); + addPop({ ...at, text: `揮空 −${MISS_PENALTY}`, tone: "bad" }); + return; + } + const kind = lv.spawns[i]!.kind; + setOutcomes((m) => new Map(m).set(i, kind === "reporter" ? "caught" : "hit")); + setBump({ person, key: performance.now() }); + if (kind === "reporter") { + setReporters((n) => n + 1); + streakRef.current = 0; + setStreak(0); + setFlash((f) => f + 1); + mgSound.shutter(); + sfx.bad(); + shake(); + addPop({ ...at, text: `被拍到了!−${REPORTER_PENALTY}`, tone: "bad" }); + return; + } + const next = streakRef.current + 1; + streakRef.current = next; + setStreak(next); + setMaxStreak((m) => Math.max(m, next)); + setPoints((x) => x + HAND_POINTS[kind]); + setHits((h) => h + 1); + sfx.combo(Math.min(8, next)); + if (kind === "vip") { + setVips((v) => v + 1); + sfx.coin(); + addPop({ ...at, text: "里長伯 +3", tone: "big" }); + } else if (next % 5 === 0) { + sfx.cheer(); + addPop({ ...at, text: `連續 ${next} 位!`, tone: "big" }); + } else addPop({ ...at, text: "+1", tone: "good" }); + }; + + // 鍵盤:三排人=鍵盤三排 + const tapRef = useRef(tap); + tapRef.current = tap; + useEffect(() => { + if (phase !== "play") return; + const onKey = (e: KeyboardEvent) => { + if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return; + const idx = HS_KEYS.indexOf(e.code as (typeof HS_KEYS)[number]); + if (idx < 0) return; + e.preventDefault(); + setKbd(true); + tapRef.current(idx); + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }, [phase]); + + const fans = lv.spawns.filter((s) => s.kind !== "reporter").length; + + return ( + } + timer={{ leftMs: HANDSHAKE_MS - elapsed, totalMs: HANDSHAKE_MS }} + shakeClass={shakeClass} + summary={[ + { label: "握到手", value: `${hits}/${fans}` }, + { label: "里長伯", value: `${vips} 位` }, + { label: "被拍/揮空", value: `${reporters}/${misses}` }, + { label: "最長連續", value: `${maxStreak} 位` }, + ]} + > +
+
+ {SHOPS.map((s) => ( + + {s} + + ))} +
+
+ {lv.people.map((person, i) => { + const p = spots[i]!; + const spawnIndex = active.get(i); + const kind = spawnIndex === undefined ? null : lv.spawns[spawnIndex]!.kind; + const cls = ["mg-person", `is-row${p.row}`]; + if (kind) cls.push("is-up", `is-${kind}`); + const label = kind === "reporter" ? "記者(不要點)" : kind === "vip" ? "舉手的里長伯(3 分)" : kind ? "舉手的鄉親" : "路人"; + return ( + + ); + })} + +
+ + {flash > 0 && } +
+
+ ); +} diff --git a/web/src/game/minigames/MiniGameLobby.tsx b/web/src/game/minigames/MiniGameLobby.tsx new file mode 100644 index 0000000..cccdad5 --- /dev/null +++ b/web/src/game/minigames/MiniGameLobby.tsx @@ -0,0 +1,219 @@ +import { ChevronRight, LockKeyhole, Star } from "lucide-react"; +import { useEffect, useMemo, useState } from "react"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { GAME_ART } from "./art.tsx"; +import { MAX_STARS, TIERS, TIER_INDEXES, isUnlocked, loadRecords, lockReason, parseTier, recordResult, saveRecords, tierStars, totalStars, type Records, type TierIndex } from "./records.ts"; +import { MINI_GAMES } from "./registry.ts"; +import { Stars } from "./Shell.tsx"; +import { GAME_IDS, type GameId } from "./types.ts"; +import "./lobby.css"; + +const LOBBY = "#/minigames"; +const newSeed = () => Math.floor(Math.random() * 999_983) + 1; + +function useHash(): string { + const [hash, setHash] = useState(location.hash); + useEffect(() => { + const update = () => setHash(location.hash); + addEventListener("hashchange", update); + return () => removeEventListener("hashchange", update); + }, []); + return hash; +} + +interface Route { + game: GameId | null; + query: URLSearchParams; + dev: boolean; +} + +function parseRoute(hash: string): Route { + const [path = "", q = ""] = hash.split("?"); + const id = path.replace(/^#\/minigames\/?/, ""); + const query = new URLSearchParams(q); + return { game: (GAME_IDS as readonly string[]).includes(id) ? (id as GameId) : null, query, dev: query.has("dev") }; +} + +/** + * 小遊戲大廳(#/minigames):三張遊戲卡(插圖、一句玩法、各難度的星等與最佳分數),點了進遊戲。 + * 難度三級:新手、老手、選戰老將;前一級拿到 2 星才解鎖下一級。紀錄存在瀏覽器(records.ts)。 + * #/minigames/<遊戲>?t=<難度> 是遊戲本身(全螢幕),瀏覽器的上一頁會回到大廳。 + * 開發用:#/minigames?dev 多一列難度(0–1)和種子,進去玩不存紀錄。 + */ +export function MiniGameLobby() { + const hash = useHash(); + const route = parseRoute(hash); + const [records, setRecords] = useState(loadRecords); + useEffect(() => setMusic("theme-march"), []); + + if (route.game && route.dev && route.query.has("campaign")) return ; + if (route.game) return ; + return ; +} + +function LobbyView({ records, dev, last }: { records: Records; dev: boolean; last: string | null }) { + const [devLevel, setDevLevel] = useState(0.3); + const [devSeed, setDevSeed] = useState(20261128); + const stars = totalStars(records); + const href = (id: GameId) => (dev ? `${LOBBY}/${id}?dev&level=${devLevel}&seed=${devSeed}` : `${LOBBY}/${id}`); + return ( + } value={`${stars}/${MAX_STARS}`} label="星星" />}> +
+

選戰途中「小遊戲」站會遇到的三個遊戲,在這裡先練。每場 20–40 秒,拿到 2 星解鎖下一級難度。

+ + {dev && ( +
+ 開發 + + + + + 選戰模式: + {GAME_IDS.map((id) => ( + + {MINI_GAMES[id].meta.title} + + ))} + + {last && 上一局(選戰模式):{last}} +
+ )} +
+
+ ); +} + +/** + * 開發用:照選戰「小遊戲」站的方式掛遊戲(沒有 practice,只能玩一次)。 + * 網址可以帶 title、reward、exitLabel 試「大絕招」的樣子,例如 + * #/minigames/rally?dev&campaign&title=大絕招・選前之夜大造勢&reward=聲勢 +3&exitLabel=回到選戰 + */ +function CampaignPreview({ game, query }: { game: GameId; query: URLSearchParams }) { + const { Game } = MINI_GAMES[game]; + const done = (score: number | null) => { + location.hash = `${LOBBY}?dev&last=${score === null ? "不玩" : score}`; + }; + return ( + done(null)} + /> + ); +} + +function PlayView({ game, route, records, setRecords }: { game: GameId; route: Route; records: Records; setRecords: (r: Records) => void }) { + const { Game } = MINI_GAMES[game]; + const [tier, setTier] = useState(() => parseTier(route.query.get("t"), records, game)); + const [seed, setSeed] = useState(() => (route.dev ? Math.max(1, Number(route.query.get("seed")) || 1) : newSeed())); + const [round, setRound] = useState(0); + const devLevel = route.dev ? Math.max(0, Math.min(1, Number(route.query.get("level")) || 0)) : null; + const level = devLevel ?? TIERS[tier].level; + const back = () => { + location.hash = route.dev ? `${LOBBY}?dev` : LOBBY; + }; + const next = tier < 2 ? ((tier + 1) as TierIndex) : null; + + const tiers = useMemo( + () => + devLevel === null + ? TIER_INDEXES.map((t) => ({ + label: TIERS[t].label, + stars: tierStars(records, game, t), + locked: lockReason(records, game, t), + selected: t === tier, + onPick: () => setTier(t), + })) + : undefined, + [records, game, tier, devLevel], + ); + + return ( + 0, + onResult: (score) => { + if (devLevel !== null) return; + const res = recordResult(records, game, tier, score); + saveRecords(res.records); + setRecords(res.records); + }, + onReplay: () => { + if (devLevel === null) setSeed(newSeed()); + setRound((r) => r + 1); + }, + }} + /> + ); +} diff --git a/web/src/game/minigames/RallyGame.tsx b/web/src/game/minigames/RallyGame.tsx new file mode 100644 index 0000000..0dc8105 --- /dev/null +++ b/web/src/game/minigames/RallyGame.tsx @@ -0,0 +1,348 @@ +import { Megaphone } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { currentMusic, setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { RallyArt } from "./art.tsx"; +import { EARLY_PENALTY, GOOD_MS, PERFECT_MS, RALLY_COUNT_IN, judgeOffset, makeChart, rallyScore, type Chart, type Judge } from "./rally-logic.ts"; +import { ComboBadge, Pops, Shell, usePops, useShake } from "./Shell.tsx"; +import { mgAudio } from "./sound.ts"; +import { reducedMotion, type MiniGameMeta, type MiniGameProps } from "./types.ts"; +import { useRound } from "./useRound.ts"; +import "./rally.css"; + +export const RALLY_META: MiniGameMeta = { + id: "rally", + title: "造勢喊凍蒜", + rules: "主持人喊「凍——」,白色外圈縮到黃色判定圈的那一刻按下「凍蒜!」(或空白鍵)。抓得越準、連擊越多,台下越嗨;亂按會扣分。", + reward: "聲勢 +1~+2、全市小加票", + pitch: "跟著鼓點,外圈縮進黃圈時喊凍蒜", + steps: ["先數「預備、3、2、1」,接著主持人喊「凍——」", "白色外圈縮到黃色圈的那一刻,按「凍蒜!」", `抓得越準分數越高;亂按斷連擊、每次 −${EARLY_PENALTY} 分`], + controls: "手機點畫面或大按鈕;電腦按空白鍵或 Enter", +}; + +/** 開始前的緩衝:讓鼓聲排程趕得上 */ +const LEAD_MS = 150; +const COUNT_LABELS = ["預備", "3", "2", "1"]; + +interface Drum { + stop: (when?: number) => void; +} + +/** + * 用 Web Audio 合成鼓點(大鼓+小鼓,先數的四拍是木魚聲),不用外部音檔;音效關掉時不出聲。 + * fromMs=從曲子的第幾毫秒開始(暫停回來接著打),回傳排好的聲音,暫停時全部停掉。 + */ +function scheduleDrums(chart: Chart, fromMs: number, leadSec: number): Drum[] { + const a = mgAudio(); + if (!a) return []; + // 喇叭有延遲:提早一點點排,聽到的鼓聲才會跟畫面對齊 + const latency = Math.min(leadSec, a.outputLatency || a.baseLatency || 0); + const t0 = a.currentTime + leadSec - latency; + const out: Drum[] = []; + const kick = (at: number, gain: number) => { + const o = a.createOscillator(); + const g = a.createGain(); + o.type = "sine"; + o.frequency.setValueAtTime(150, at); + o.frequency.exponentialRampToValueAtTime(45, at + 0.18); + g.gain.setValueAtTime(0.0001, at); + g.gain.exponentialRampToValueAtTime(gain, at + 0.01); + g.gain.exponentialRampToValueAtTime(0.0001, at + 0.22); + o.connect(g).connect(a.destination); + o.start(at); + o.stop(at + 0.25); + out.push(o); + }; + const block = (at: number, accent: boolean) => { + const o = a.createOscillator(); + const g = a.createGain(); + o.type = "triangle"; + o.frequency.setValueAtTime(accent ? 1250 : 950, at); + g.gain.setValueAtTime(0.0001, at); + g.gain.exponentialRampToValueAtTime(0.16, at + 0.005); + g.gain.exponentialRampToValueAtTime(0.0001, at + 0.08); + o.connect(g).connect(a.destination); + o.start(at); + o.stop(at + 0.1); + out.push(o); + }; + const snare = (at: number) => { + const len = Math.ceil(a.sampleRate * 0.12); + const buf = a.createBuffer(1, len, a.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len); + const src = a.createBufferSource(); + src.buffer = buf; + const f = a.createBiquadFilter(); + f.type = "highpass"; + f.frequency.value = 1400; + const g = a.createGain(); + g.gain.value = 0.12; + src.connect(f).connect(g).connect(a.destination); + src.start(at); + out.push(src); + }; + for (let i = 0; i <= chart.beats; i++) { + const ms = i * chart.beatMs; + if (ms < fromMs - 1) continue; + const at = t0 + (ms - fromMs) / 1000; + if (i < RALLY_COUNT_IN) block(at, i === 0); + else { + kick(at, (i - RALLY_COUNT_IN) % 4 === 0 ? 0.5 : 0.32); + if (i % 2 === 1) snare(at); + } + } + return out; +} + +/** 按下去時台下一起喊:短短的合成「凍蒜」(音效關掉時不出聲) */ +function shout(perfect: boolean) { + const a = mgAudio(); + if (!a) return; + const at = a.currentTime; + [perfect ? 392 : 330, perfect ? 523 : 440].forEach((f, i) => { + const o = a.createOscillator(); + const g = a.createGain(); + o.type = "square"; + o.frequency.setValueAtTime(f, at + i * 0.09); + g.gain.setValueAtTime(0.0001, at + i * 0.09); + g.gain.exponentialRampToValueAtTime(0.05, at + i * 0.09 + 0.01); + g.gain.exponentialRampToValueAtTime(0.0001, at + i * 0.09 + 0.12); + o.connect(g).connect(a.destination); + o.start(at + i * 0.09); + o.stop(at + i * 0.09 + 0.14); + }); +} + +type Last = { judge: Judge | "early" | "late"; key: number }; + +function stopAll(list: readonly Drum[]) { + list.forEach((d) => { + try { + d.stop(); + } catch { + // 已經停掉的聲音再停一次也沒關係 + } + }); +} + +/** + * 造勢喊凍蒜:節奏遊戲。先數四拍,再 8 小節(約 18–23 秒)。 + * 分數=(Perfect 1、Good 0.5) 平均 × 90 + 最長連擊比例 × 10,亂按每次 −2(rally-logic.ts)。 + * 系統減少動態時,外圈不縮放,改成三顆燈依序亮起(第三顆亮完就是該按的時候)。 + */ +export function RallyGame(props: MiniGameProps) { + const { seed, level } = props; + const chart = useMemo(() => makeChart(seed, level), [seed, level]); + const drums = useRef([]); + const round = useRound({ + durationMs: chart.endMs, + countdown: false, + leadMs: LEAD_MS, + rewindMs: chart.beatMs * 2, + onRun: (from, lead) => { + stopAll(drums.current); + drums.current = scheduleDrums(chart, from, lead / 1000); + }, + onHalt: () => { + stopAll(drums.current); + drums.current = []; + }, + }); + const { phase, elapsed: now } = round; + const [judges, setJudges] = useState(() => chart.notes.map(() => null)); + const judgesRef = useRef(judges); + const [combo, setCombo] = useState(0); + const comboRef = useRef(0); + const [maxCombo, setMaxCombo] = useState(0); + const [early, setEarly] = useState(0); + const [last, setLast] = useState(null); + const [pops, addPop] = usePops(); + const [shakeClass, shake] = useShake(); + const reduce = useMemo(reducedMotion, []); + + useEffect(() => { + const fresh = chart.notes.map(() => null); + judgesRef.current = fresh; + setJudges(fresh); + }, [chart]); + + // 節奏關卡要聽鼓點:遊戲中先停背景音樂,結束再放回來 + const playing = phase === "play"; + useEffect(() => { + if (!playing) return; + const prev = currentMusic(); + setMusic(null); + return () => setMusic(prev); + }, [playing]); + + const breakCombo = () => { + comboRef.current = 0; + setCombo(0); + }; + + // 錯過的拍子算 Miss + useEffect(() => { + if (phase !== "play") return; + const j = judgesRef.current; + if (!chart.notes.some((n, i) => j[i] === null && now > n + GOOD_MS)) return; + const next = j.map((x, i) => (x === null && now > chart.notes[i]! + GOOD_MS ? "miss" : x)); + judgesRef.current = next; + setJudges(next); + breakCombo(); + setLast({ judge: "miss", key: performance.now() }); + }, [now]); // eslint-disable-line react-hooks/exhaustive-deps + + const hit = useCallback(() => { + if (!round.live) return; + const t = round.now(); + const j = judgesRef.current; + let best = -1; + let bestD = Infinity; + chart.notes.forEach((n, i) => { + if (j[i] !== null) return; + const d = Math.abs(t - n); + if (d < bestD) { + bestD = d; + best = i; + } + }); + const judge = best >= 0 ? judgeOffset(t - chart.notes[best]!) : null; + if (!judge) { + // 亂按:斷連擊、扣分,不吃掉拍子 + const nearest = chart.notes.reduce((a, n) => (Math.abs(t - n) < Math.abs(t - a) ? n : a), chart.notes[0] ?? 0); + breakCombo(); + setEarly((e) => e + 1); + setLast({ judge: t < nearest ? "early" : "late", key: performance.now() }); + sfx.click(); + return; + } + const next = j.map((x, i) => (i === best ? judge : x)); + judgesRef.current = next; + setJudges(next); + const c = comboRef.current + 1; + comboRef.current = c; + setCombo(c); + setMaxCombo((m) => Math.max(m, c)); + setLast({ judge, key: performance.now() }); + shout(judge === "perfect"); + if (c > 0 && c % 8 === 0) { + sfx.cheer(); + shake(); + addPop({ x: 50, y: 22, text: `${c} 連擊!`, tone: "big" }); + } else addPop({ x: 50 + ((c % 3) - 1) * 16, y: 40, text: judge === "perfect" ? "凍蒜!" : "蒜!", tone: judge === "perfect" ? "big" : "good" }); + }, [round, chart, addPop, shake]); + + const hitRef = useRef(hit); + hitRef.current = hit; + useEffect(() => { + if (phase !== "play") return; + const onKey = (e: KeyboardEvent) => { + if (e.code === "Space" || e.key === " " || e.key === "Enter") { + e.preventDefault(); + if (!e.repeat) hitRef.current(); + } + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }, [phase]); + + const n = chart.notes.length; + const perfect = judges.filter((x) => x === "perfect").length; + const good = judges.filter((x) => x === "good").length; + const miss = judges.filter((x) => x === "miss").length; + const score = rallyScore({ perfect, good, early, maxCombo, total: n }); + + // 接下來要打的那一拍:外圈從大縮到判定圈(減少動態:三顆燈依序亮) + const nextIndex = judges.findIndex((x, i) => x === null && chart.notes[i]! + GOOD_MS >= now); + const rings = chart.notes + .map((t, i) => ({ t, i })) + .filter(({ t, i }) => judges[i] === null && now >= t - chart.approachMs && now <= t + GOOD_MS) + .map(({ t, i }) => ({ i, scale: 1 + Math.max(0, (t - now) / chart.approachMs) * 1.8 })); + const nextAt = nextIndex >= 0 ? chart.notes[nextIndex]! : null; + const lamp = nextAt === null ? 0 : Math.max(0, Math.min(3, Math.floor((1 - (nextAt - now) / chart.approachMs) * 3 + 0.0001))); + const onBeat = nextAt !== null && Math.abs(nextAt - now) <= PERFECT_MS; + const hype = Math.min(1, combo / 10); + const beat = Math.floor(now / chart.beatMs); + const counting = phase === "play" && now >= 0 && beat < RALLY_COUNT_IN; + const calling = nextAt !== null && nextAt - now < chart.beatMs * 0.9 && nextAt - now > -GOOD_MS; + const judgedCount = judges.filter((x) => x !== null).length; + + return ( + } + progress={{ done: judgedCount, total: n, unit: "拍" }} + shakeClass={shakeClass} + summary={[ + { label: "Perfect", value: perfect }, + { label: "Good", value: good }, + { label: "Miss/亂按", value: `${miss}/${early}` }, + { label: "最長連擊", value: maxCombo }, + ]} + > +
{ + if (e.button !== 0 && e.pointerType === "mouse") return; + e.preventDefault(); + hit(); + }} + > +
+ 凍蒜!凍蒜! + +
+
+ + + + {phase === "play" && (counting ? 預備—— : calling ? 凍—— : null)} +
+ {combo >= 8 && !reduce && } +
+ + {reduce ? ( + + {[0, 1, 2].map((k) => ( + = nextAt - chart.approachMs && k < lamp ? "is-on" : ""} /> + ))} + + ) : ( + rings.map((r) => ) + )} + + {last && ( + + {last.judge === "perfect" ? "Perfect" : last.judge === "good" ? "Good" : last.judge === "miss" ? "Miss" : last.judge === "early" ? "太早" : "太晚"} + + )} +
+
+ {Array.from({ length: 15 }, (_, i) => ( + + + + + ))} +
+ + {counting && ( +
+ + {COUNT_LABELS[beat]} + +
+ )} + +
+
+ ); +} diff --git a/web/src/game/minigames/Shell.tsx b/web/src/game/minigames/Shell.tsx new file mode 100644 index 0000000..3ca0bc1 --- /dev/null +++ b/web/src/game/minigames/Shell.tsx @@ -0,0 +1,460 @@ +import { Keyboard, LockKeyhole, Pause, Play, RotateCcw, Star, Trophy, X } from "lucide-react"; +import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; +import { createPortal } from "react-dom"; +import { getSettings } from "../audio/settings.ts"; +import { sfx } from "../audio/sfx.ts"; +import "../ui/scene.css"; +import { mgSound } from "./sound.ts"; +import { STAR_CUTS, reducedMotion, starsFor, type MiniGameMeta, type MiniGameProps, type TierChoice } from "./types.ts"; +import type { Round } from "./useRound.ts"; +import "./minigames.css"; + +export type { Phase } from "./useRound.ts"; + +const VERDICTS = ["今天狀況不太好", "還可以,再加把勁", "很拚喔!", "鄉親都記住你了!"] as const; + +/** 分數的評語(結束畫面),跟星等一致 */ +export function verdict(score: number): string { + return VERDICTS[starsFor(score)]; +} + +export interface SummaryItem { + label: string; + value: string | number; +} + +/** 結束後先蓋一個「時間到!」,再出結算卡(避免最後一下連點按到結算按鈕) */ +const SPLASH_MS = 900; + +/** + * 小遊戲的全螢幕外框(用 portal 掛在 body 上,選戰的面板裡也一樣滿版): + * - 上面:左邊暫停/離開鍵+名牌,右邊分數、時間。 + * - 開始畫面:示範圖、三步規則、操作方式、獎勵(大廳是難度選擇)、開始。 + * - 3-2-1 倒數、暫停選單、「時間到!」、結算(分數、星等、新紀錄、再玩一次/回到選戰)。 + * 結算按了按鈕才呼叫 onFinish,讓玩家看清楚分數。 + */ +export function Shell({ + meta, + game, + round, + score, + scene, + demo, + timer, + progress, + hud, + summary, + shakeClass, + children, +}: { + meta: MiniGameMeta; + game: MiniGameProps; + round: Round; + score: number; + /** 背景:街道(白天)、晚會舞台(夜)、街區地圖(紙) */ + scene: "street" | "stage" | "board"; + /** 開始畫面的示範圖 */ + demo: ReactNode; + /** 倒數計時(毫秒) */ + timer?: { leftMs: number; totalMs: number }; + /** 沒有計時的遊戲(節奏)顯示進度 */ + progress?: { done: number; total: number; unit: string }; + /** 右上多放的東西 */ + hud?: ReactNode; + /** 結算時列出的數字 */ + summary: readonly SummaryItem[]; + shakeClass?: string; + children: ReactNode; +}) { + const { practice } = game; + const title = game.title ?? meta.title; + const kicker = practice ? practice.tierLabel : (game.townName ?? null); + const titleId = useId(); + const stars = starsFor(score); + const [showResult, setShowResult] = useState(false); + const bestAtStart = useRef(null); + const reported = useRef(false); + const exited = useRef(false); + const startRef = useRef(null); + const resumeRef = useRef(null); + const resultRef = useRef(null); + const { phase, hold } = round; + const newBest = practice !== undefined && score > 0 && (bestAtStart.current === null || score > bestAtStart.current); + + const start = useCallback(() => { + bestAtStart.current = practice?.best ?? null; + sfx.stamp(); + round.start(); + }, [practice?.best, round]); + + // 「再玩一次」直接倒數 + useEffect(() => { + if (practice?.autoStart) start(); + // 只在第一次掛上時看 + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (phase === "intro") startRef.current?.focus(); + }, [phase]); + useEffect(() => { + if (hold === "pause") resumeRef.current?.focus(); + }, [hold]); + + // 結束:馬上回報分數(存紀錄),「時間到!」之後出結算,星星一顆一顆亮 + useEffect(() => { + if (phase !== "done") return; + if (!reported.current) { + reported.current = true; + practice?.onResult(score); + } + mgSound.timesUp(); + const ids: ReturnType[] = [setTimeout(() => setShowResult(true), SPLASH_MS)]; + for (let i = 0; i < stars; i++) ids.push(setTimeout(() => mgSound.star(i), SPLASH_MS + 420 + i * 260)); + const after = SPLASH_MS + 520 + stars * 260; + if (newBest || (practice?.unlocks && stars >= 2)) ids.push(setTimeout(() => mgSound.record(), after)); + else if (stars === 0) ids.push(setTimeout(() => mgSound.flop(), after)); + else if (stars >= 2) ids.push(setTimeout(() => sfx.applause(), after)); + return () => ids.forEach(clearTimeout); + }, [phase]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (showResult) resultRef.current?.focus(); + }, [showResult]); + + // Esc:遊戲中暫停,暫停時繼續 + useEffect(() => { + if (phase !== "play") return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + e.preventDefault(); + if (round.hold === "pause") round.resume(); + else round.pause(); + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }, [phase, round]); + + // 最後 5 秒滴答 + const secLeft = timer ? Math.ceil(timer.leftMs / 1000) : null; + useEffect(() => { + if (round.live && secLeft !== null && secLeft > 0 && secLeft <= 5) mgSound.tick(); + }, [secLeft]); // eslint-disable-line react-hooks/exhaustive-deps + + const exit = () => { + if (exited.current) return; + exited.current = true; + sfx.click(); + game.onFinish(score); + }; + const quit = game.onQuit + ? () => { + sfx.click(); + game.onQuit?.(); + } + : null; + const quitLabel = practice ? (game.exitLabel ?? "回到大廳") : "不玩了"; + + const view = ( +
+
+ {phase === "play" ? ( + + ) : phase === "intro" && quit ? ( + + ) : ( + + )} +
7 ? " is-long" : ""}`}> + {kicker && {kicker}} +

{title}

+
+
+ {hud} + + 分數 + {score} + + {timer && } + {progress && } +
+
+ +
{children}
+ + {phase === "intro" && ( +
+
+
{demo}
+
+ {title} +
    + {meta.steps.map((s, i) => ( +
  1. + {i + 1} + {s} +
  2. + ))} +
+

+ + {meta.controls} +

+ {practice?.tiers ? :

{game.reward ?? meta.reward}

} +
+ {quit && ( + + )} + +
+
+
+
+ )} + + {round.count !== null && ( +
+ + {round.count === 0 ? "開始!" : round.count} + +
+ )} + + {phase === "play" && hold === "pause" && ( +
+
+ 暫停 +

按「繼續」會再倒數 3 秒。

+
+ + {practice && ( + + )} + {quit && ( + + )} +
+
+
+ )} + + {phase === "done" && !showResult && ( +
+ {round.endedEarly ? "完成!" : "時間到!"} +
+ )} + + {phase === "done" && showResult && ( +
+
+ + {title} + {practice ? `・${practice.tierLabel}` : ""} + +
+ + {score} + 分 + + +
+

{VERDICTS[stars]}

+ {practice && ( +

+ {newBest ? ( + <> + 新紀錄! + + ) : ( + `最佳紀錄 ${Math.max(bestAtStart.current ?? 0, score)} 分` + )} +

+ )} + {practice?.unlocks && ( +

= 2 ? " is-open" : ""}`}>{stars >= 2 ? `解鎖新難度「${practice.unlocks}」!` : `拿到 2 星(${STAR_CUTS[1]} 分)就能解鎖「${practice.unlocks}」`}

+ )} +
+ {summary.map((s) => ( +
+
{s.label}
+
{s.value}
+
+ ))} +
+
+ {practice ? ( + <> + + + + ) : ( + + )} +
+
+
+ )} +
+ ); + return typeof document === "undefined" ? view : createPortal(view, document.body); +} + +/** 三顆星:拿到的實心;reveal=結算時一顆一顆蓋上去 */ +export function Stars({ n, reveal = false, size = 30 }: { n: number; reveal?: boolean; size?: number }) { + return ( + + {[0, 1, 2].map((i) => ( + + ))} + + ); +} + +function TierPicker({ tiers }: { tiers: readonly TierChoice[] }) { + const locked = tiers.find((t) => t.locked && !t.selected); + return ( +
+ + 難度 + +
+ {tiers.map((t) => ( + + ))} +
+ {locked && {`「${locked.label}」:${locked.locked}`}} +
+ ); +} + +function TimerPill({ leftMs, totalMs }: { leftMs: number; totalMs: number }) { + const sec = Math.max(0, Math.ceil(leftMs / 1000)); + return ( + + + 秒 + {sec} + + ); +} + +function ProgressPill({ done, total, unit }: { done: number; total: number; unit: string }) { + return ( + + + {unit} + + {done} + /{total} + + + ); +} + +/** 連擊徽章:遊戲區上方正中間,2 以上才出現 */ +export function ComboBadge({ n, label }: { n: number; label: string }) { + if (n < 2) return null; + return ( + = 10 ? " is-fire" : n >= 5 ? " is-hot" : ""}`} aria-live="polite"> + {n} + {label} + + ); +} + +/** 畫面震動(重擊時):設定關掉或系統減少動態時不震動 */ +export function useShake(): [string, () => void] { + const [cls, setCls] = useState(""); + const timer = useRef | null>(null); + const shake = useCallback(() => { + if (!getSettings().shake || reducedMotion()) return; + if (timer.current) clearTimeout(timer.current); + setCls(""); + requestAnimationFrame(() => setCls("mg-shake")); + timer.current = setTimeout(() => setCls(""), 320); + }, []); + useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); + return [cls, shake]; +} + +export interface Pop { + id: number; + x: number; + y: number; + text: string; + tone: "good" | "bad" | "big" | "dim"; + /** 再往上抬幾個「人高」(--mg-ph,掃街握手用:字跳在頭上) */ + lift?: number; +} + +/** 點中時跳出的字:一秒後自己消失;max=同時最多幾個(看板只留 1 個,避免字疊在一起) */ +export function usePops(max = 6): [Pop[], (p: Omit) => void] { + const [pops, setPops] = useState([]); + const id = useRef(0); + const timers = useRef(new Set>()); + const add = useCallback( + (p: Omit) => { + const n = ++id.current; + setPops((list) => [...list, { ...p, id: n }].slice(-max)); + const t = setTimeout(() => { + timers.current.delete(t); + setPops((list) => list.filter((x) => x.id !== n)); + }, 900); + timers.current.add(t); + }, + [max], + ); + useEffect(() => () => timers.current.forEach(clearTimeout), []); + return [pops, add]; +} + +export function Pops({ pops }: { pops: readonly Pop[] }) { + return ( + <> + {pops.map((p) => ( + + {p.text} + + ))} + + ); +} diff --git a/web/src/game/minigames/art.tsx b/web/src/game/minigames/art.tsx new file mode 100644 index 0000000..77afd24 --- /dev/null +++ b/web/src/game/minigames/art.tsx @@ -0,0 +1,242 @@ +import { useId } from "react"; + +/** + * 三個小遊戲的插圖(原創,純 SVG 向量,不用照片、不畫真人):大廳卡片和開始畫面的示範圖共用。 + * demo=開始畫面的示範動畫(只動 transform/opacity;系統減少動態時停在說明用的靜態畫面)。 + */ +const K = "#111419"; + +interface FigureProps { + x: number; + y: number; + s?: number; + shirt: string; + hair?: string; + skin?: string; +} + +/** 圓頭+身體的人形;(x, y) 是腳底 */ +function Figure({ x, y, s = 1, shirt, hair = "#2a2220", skin = "#f1c9a2", children }: FigureProps & { children?: React.ReactNode }) { + return ( + + + + + {children} + + ); +} + +/** 舉起來的手(相對於人形的腳底) */ +function RaisedArm({ shirt, skin = "#f1c9a2" }: { shirt: string; skin?: string }) { + return ( + + + + + ); +} + +export function HandshakeArt({ demo = false }: { demo?: boolean }) { + return ( + + + + + {[0, 1, 2].map((i) => ( + + + + + + ))} + +
+
+ {/* 記者:深色衣服、拿相機,旁邊打叉 */} +
+ + +
+ + + + +
+ {/* 舉手的鄉親+黃色光圈 */} + + + + + +
+ + + +
+ {/* 手指點下去、跳出 +1 */} + + + + + + + + + + + +1 + + + +
+ ); +} + +export function RallyArt({ demo = false }: { demo?: boolean }) { + return ( + + + {Array.from({ length: 17 }, (_, i) => ( + + ))} + + + + + 凍蒜!凍蒜! + + +
+ +
+ + + + 凍—— + + + {/* 判定圈+縮小中的外圈 */} + + + + + + + Perfect + + + + {/* 台下群眾 */} + {[8, 26, 44, 62, 80, 98].map((x, i) => ( + +
+ {i % 2 === 0 && } +
+ ))} +
+ ); +} + +/** 4×6 的小街區:數字是人流,紅色 L 型是你的看板 */ +const BB_VALUES = [ + [1, 2, 3, 2, 1, 0], + [2, 5, 8, 6, 2, 1], + [3, 7, 9, 7, 3, 1], + [1, 3, 4, 3, 1, 0], +]; +const BB_PIECE = new Set(["1,2", "2,2", "2,3"]); +const BB_RIVAL = "2,1"; +const BB_BUILD = "3,4"; +const BB_PATH = new Set(["0,0", "0,1", "0,2", "0,3", "0,4", "0,5"]); + +export function BillboardArt({ demo = false }: { demo?: boolean }) { + const stripe = `mga-stripe-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; + const x0 = 34; + const y0 = 14; + const s = 22; + const heat = (v: number) => `color-mix(in srgb, #ffd23f ${Math.round((v / 9) * 100)}%, #ffffff)`; + return ( + + + + + + + + + + {BB_VALUES.map((row, r) => + row.map((v, c) => { + const key = `${r},${c}`; + const x = x0 + c * s; + const y = y0 + r * s; + if (key === BB_BUILD) return ; + if (key === BB_RIVAL) + return ( + + + + 對手 + + + ); + return ( + + + + {v} + + {BB_PATH.has(key) && } + + ); + }), + )} + + {/* 你的看板(L 型)落下來 */} + + {[...BB_PIECE].map((key) => { + const [r, c] = key.split(",").map(Number) as [number, number]; + return ( + + + + {BB_VALUES[r]![c]} + + + ); + })} + + + + + + + 人流 +24 + + + + {/* 腳印:行人從左走到右 */} + {[18, 182].map((x) => ( + + + + + ))} + + ); +} + +export const GAME_ART = { handshake: HandshakeArt, rally: RallyArt, billboard: BillboardArt } as const; diff --git a/web/src/game/minigames/billboard-logic.ts b/web/src/game/minigames/billboard-logic.ts new file mode 100644 index 0000000..3c9bd5b --- /dev/null +++ b/web/src/game/minigames/billboard-logic.ts @@ -0,0 +1,188 @@ +import { clampScore, mulberry32 } from "./types.ts"; + +/** 看板卡位:6×6 的街區,40 秒 */ +export const BB_N = 6; +export const BILLBOARD_MS = 40_000; +const N = BB_N; +/** 算最佳解時,每塊看板只試人流最多的前幾個位置 */ +const TOP_K = 24; + +export type Tile = "free" | "build" | "rival"; +export type PieceKind = "one" | "two" | "ell"; +type Shape = readonly (readonly [number, number])[]; + +/** 看板的形狀;第一格是點下去的那一格(L 型是轉角那格) */ +export const SHAPES: Record = { + one: [[0, 0]], + two: [ + [0, 0], + [0, 1], + ], + ell: [ + [0, 0], + [-1, 0], + [0, 1], + ], +}; +export const TURNS: Record = { one: 1, two: 2, ell: 4 }; +export const PIECE_NAMES: Record = { one: "小看板", two: "長看板", ell: "轉角看板" }; + +export function rotate(shape: Shape, turns: number): Shape { + let out = shape; + for (let i = 0; i < turns; i++) out = out.map(([r, c]) => [c, -r] as const); + return out; +} + +/** 點在 cell 時看板蓋到的格子;inside=整塊都在範圍內 */ +export function footprint(kind: PieceKind, turn: number, cell: number): { cells: number[]; inside: boolean } { + const r0 = Math.floor(cell / N); + const c0 = cell % N; + const cells: number[] = []; + let inside = true; + for (const [dr, dc] of rotate(SHAPES[kind], turn % TURNS[kind])) { + const r = r0 + dr; + const c = c0 + dc; + if (r < 0 || r >= N || c < 0 || c >= N) inside = false; + else cells.push(r * N + c); + } + return { cells, inside }; +} + +/** 行人從最左欄走到最右欄的最短路;走不通回 null */ +export function walkway(blocked: (i: number) => boolean): number[] | null { + const prev = new Array(N * N).fill(-2); + const queue: number[] = []; + for (let r = 0; r < N; r++) { + if (!blocked(r * N)) { + prev[r * N] = -1; + queue.push(r * N); + } + } + for (let q = 0; q < queue.length; q++) { + const i = queue[q]!; + if (i % N === N - 1) { + const path: number[] = []; + for (let j = i; j >= 0; j = prev[j]!) path.push(j); + return path.reverse(); + } + const r = Math.floor(i / N); + const c = i % N; + const next = [r > 0 ? i - N : -1, r < N - 1 ? i + N : -1, c > 0 ? i - 1 : -1, c < N - 1 ? i + 1 : -1]; + for (const j of next) { + if (j < 0 || prev[j] !== -2 || blocked(j)) continue; + prev[j] = i; + queue.push(j); + } + } + return null; +} + +export interface BillboardLevel { + traffic: readonly number[]; + tiles: readonly Tile[]; + pieces: readonly PieceKind[]; + /** 最佳擺法蓋到的人流(分數的分母) */ + best: number; + /** 每種看板單獨擺最好的位置有多少人流(判斷「黃金位置」) */ + topByKind: Record; +} + +interface Placement { + cells: number[]; + sum: number; +} + +function placementsFor(kind: PieceKind, traffic: readonly number[], tiles: readonly Tile[]): Placement[] { + const out: Placement[] = []; + for (let cell = 0; cell < N * N; cell++) { + for (let t = 0; t < TURNS[kind]; t++) { + const { cells, inside } = footprint(kind, t, cell); + if (inside && cells.every((i) => tiles[i] === "free")) out.push({ cells, sum: cells.reduce((s, i) => s + traffic[i]!, 0) }); + } + } + return out.sort((a, b) => b.sum - a.sum); +} + +/** 有界的深度優先搜尋:每塊看板試前 TOP_K 個位置(也可以不放),路要走得通 */ +export function solve(traffic: readonly number[], tiles: readonly Tile[], pieces: readonly PieceKind[]): number { + const opts = pieces.map((k) => placementsFor(k, traffic, tiles).slice(0, TOP_K)); + const rest = pieces.map((_, p) => opts.slice(p).reduce((s, o) => s + (o[0]?.sum ?? 0), 0)); + const used = new Uint8Array(N * N); + const blocked = (i: number) => tiles[i] !== "free" || used[i] === 1; + let best = 0; + const go = (p: number, sum: number) => { + best = Math.max(best, sum); + if (p === pieces.length || sum + rest[p]! <= best) return; + const after = rest[p + 1] ?? 0; + for (const o of opts[p]!) { + if (sum + o.sum + after <= best) break; + if (o.cells.some((i) => used[i] === 1)) continue; + o.cells.forEach((i) => (used[i] = 1)); + if (walkway(blocked)) go(p + 1, sum + o.sum); + o.cells.forEach((i) => (used[i] = 0)); + } + go(p + 1, sum); + }; + go(0, 0); + return best; +} + +/** 人流由 2–3 個熱點擴散;對手先卡走了幾個熱門位置,再隨機撒施工 */ +function tryLevel(seed: number, level: number, obstacles: boolean): BillboardLevel | null { + const r = mulberry32(seed); + const spots = Array.from({ length: r() < 0.5 ? 3 : 2 }, () => ({ y: r() * (N - 1), x: 0.5 + r() * (N - 2), amp: 5 + r() * 4, s: 1.1 + r() * 0.6 })); + const traffic = Array.from({ length: N * N }, (_, i) => { + const y = Math.floor(i / N); + const x = i % N; + const v = spots.reduce((a, s) => a + s.amp * Math.exp(-((y - s.y) ** 2 + (x - s.x) ** 2) / (2 * s.s ** 2)), 0); + return Math.min(9, Math.round(v)); + }); + const tiles: Tile[] = new Array(N * N).fill("free"); + const scatter = (count: number, from: readonly number[], tile: Tile) => { + for (let k = 0, guard = 0; k < count && guard < 80; guard++) { + const i = from[Math.floor(r() * from.length)]!; + if (tiles[i] === "free") { + tiles[i] = tile; + k++; + } + } + }; + if (obstacles) { + const hot = traffic + .map((v, i) => ({ v, i })) + .sort((a, b) => b.v - a.v) + .slice(0, 10) + .map((h) => h.i); + scatter(level > 0.6 ? 3 : 2, hot, "rival"); + scatter( + 2 + Math.round(level * 2), + traffic.map((_, i) => i), + "build", + ); + } + if (!walkway((i) => tiles[i] !== "free")) return null; + const pieces: PieceKind[] = level > 0.5 ? ["ell", "two", "two", "one"] : ["ell", "two", "one"]; + const best = solve(traffic, tiles, pieces); + if (obstacles && best < 18) return null; + const top = (k: PieceKind) => placementsFor(k, traffic, tiles)[0]?.sum ?? 0; + return { traffic, tiles, pieces, best: Math.max(1, best), topByKind: { one: top("one"), two: top("two"), ell: top("ell") } }; +} + +export function makeBillboard(seed: number, level: number): BillboardLevel { + for (let attempt = 0; attempt < 40; attempt++) { + const lv = tryLevel((seed + attempt * 7919) >>> 0, level, true); + if (lv) return lv; + } + // 理論上用不到:沒有障礙物的空地一定走得通 + return tryLevel(seed, level, false)!; +} + +/** + * 分數:蓋到的人流 ÷ 最佳擺法,再拉開差距——達到最佳的 45% 以下 0 分、100% 滿分。 + * 隨手擺(約 70–80%)≈ 45–64 分,擺得好(90–97%)≈ 82–95 分。 + */ +export function billboardScore(covered: number, best: number): number { + if (best <= 0) return 0; + const r = Math.min(1, covered / best); + return clampScore(((r - 0.45) / 0.55) * 100); +} diff --git a/web/src/game/minigames/billboard.css b/web/src/game/minigames/billboard.css new file mode 100644 index 0000000..4b43d35 --- /dev/null +++ b/web/src/game/minigames/billboard.css @@ -0,0 +1,393 @@ +/* 看板卡位(BillboardGame.tsx):手機上下排(提示、格子、看板、工具);電腦橫排(格子在左、看板與工具在右) */ +.mg-billboard { + --mg-cell: light-dark(#ffffff, #1b2a40); + display: grid; + container-type: size; +} +.mg-bb { + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto auto auto; + justify-items: center; + align-content: center; + gap: 10px; + min-height: 0; + padding: 6px 12px max(12px, env(safe-area-inset-bottom, 0px)); +} +.mg-status { + max-width: 100%; + min-height: 32px; + margin: 0; + padding: 4px 14px; + font-size: 15px; + font-weight: 800; + line-height: 1.5; + text-align: center; + color: var(--muted); + border: 3px solid transparent; + border-radius: 999px; + animation: mg-fade 160ms ease-out; +} +.mg-status.is-good { + color: var(--good); +} +.mg-status.is-bad { + color: #fff; + background: #c3121e; + border-color: var(--mg-k); +} +.mg-status.is-big { + color: var(--mg-k); + background: var(--signal); + border-color: var(--mg-k); +} +.mg-gridwrap { + --gw: min(600px, calc(100cqw - 24px), calc(100cqh - 250px)); + display: grid; + grid-template-columns: 24px minmax(0, 1fr) 24px; + width: max(260px, var(--gw)); +} +.mg-walk { + position: relative; + color: var(--muted); +} +.mg-walk svg { + position: absolute; + left: 50%; + transform: translate(-50%, -50%) rotate(90deg); +} +.mg-grid { + position: relative; + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + aspect-ratio: 1; + background: var(--mg-cell); + border: 3px solid var(--mg-k); + box-shadow: 5px 5px 0 var(--shadow-ink); +} +.mg-grid-row { + display: contents; +} +.mg-cell { + position: relative; + display: grid; + place-items: center; + min-width: 0; + min-height: 44px; + padding: 0; + font-family: var(--font-num); + font-size: clamp(17px, calc(var(--gw) / 15), 34px); + font-weight: 800; + color: var(--ink); + background: color-mix(in srgb, var(--signal) calc(var(--heat) * 100%), var(--mg-cell)); + border: 1px solid light-dark(#d6d4cd, #2c3f5b); + cursor: pointer; + touch-action: manipulation; +} +.mg-cell:disabled { + cursor: default; +} +.mg-cell.is-zero b { + opacity: 0.35; +} +/* 人流 5 以上的格子很黃:深色模式也用黑字 */ +.mg-cell.is-hot:not(.is-mine):not(.is-ghost):not(.is-ghost-bad) { + color: var(--mg-k); +} +.mg-cell.is-path::after { + content: ""; + position: absolute; + right: 6px; + bottom: 6px; + width: 8px; + height: 8px; + background: var(--ink); + border-radius: 50%; + opacity: 0.35; +} +.mg-cell.is-build { + color: var(--mg-k); + background: repeating-linear-gradient(45deg, var(--signal) 0 7px, var(--mg-k) 7px 14px); +} +.mg-cell.is-build svg { + box-sizing: content-box; + padding: 3px; + background: #fff; + border: 2px solid var(--mg-k); + border-radius: 50%; +} +.mg-cell.is-rival { + color: #fff; + background: #6f757d; + border: 3px solid var(--mg-k); +} +.mg-cell.is-rival small { + font-family: var(--font-serif); + font-size: clamp(12px, calc(var(--gw) / 30), 18px); +} +.mg-cell.is-mine { + z-index: 1; + color: #fff; + background: #d61f2c; + border: 3px solid var(--mg-k); +} +.mg-cell.no-t { + border-top-width: 0; +} +.mg-cell.no-b { + border-bottom-width: 0; +} +.mg-cell.no-l { + border-left-width: 0; +} +.mg-cell.no-r { + border-right-width: 0; +} +.mg-cell.is-new { + animation: mg-drop 260ms var(--ease-out); +} +.mg-cell.is-ghost { + z-index: 2; + color: #fff; + background: color-mix(in srgb, #d61f2c 70%, var(--mg-cell)); + outline: 3px dashed var(--mg-k); + outline-offset: -5px; +} +.mg-cell.is-ghost-bad { + z-index: 2; + color: var(--ink); + background: repeating-linear-gradient(-45deg, rgb(195 18 30 / 0.55) 0 6px, transparent 6px 12px), var(--mg-cell); + outline: 3px solid #c3121e; + outline-offset: -4px; +} + +/* 右邊(手機在下面):看板托盤、工具、圖例 */ +.mg-side { + display: grid; + justify-items: center; + gap: 10px; +} +.mg-tray { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 10px; +} +.mg-piece { + position: relative; + display: grid; + grid-template-rows: 1fr auto; + place-items: center; + width: 76px; + height: 80px; + padding: 6px 2px 4px; + font: inherit; + color: var(--ink); + background: var(--surface); + border: 3px solid var(--ink); + border-radius: 12px; + box-shadow: 3px 3px 0 var(--shadow-ink); + cursor: pointer; + transition: transform 120ms var(--ease-out); +} +.mg-piece small { + font-size: 11px; + font-weight: 800; + white-space: nowrap; +} +.mg-piece kbd { + position: absolute; + top: 3px; + left: 5px; + font-family: var(--font-num); + font-size: 12px; + font-weight: 800; + color: var(--muted); +} +.mg-piece.is-selected { + color: var(--mg-k); + background: var(--signal); + border-color: var(--mg-k); + transform: translate(-2px, -2px); + box-shadow: 5px 5px 0 var(--shadow-ink); +} +.mg-piece.is-selected kbd { + color: var(--mg-k); +} +.mg-piece:disabled { + cursor: default; +} +.mg-piece.is-used { + opacity: 0.45; + box-shadow: none; +} +.mg-piece-done { + position: absolute; + top: -9px; + right: -9px; + padding: 2px; + color: #fff; + background: var(--good); + border: 2px solid var(--mg-k); + border-radius: 50%; + box-sizing: content-box; +} +.mg-mini { + display: grid; + grid-template-columns: repeat(3, 14px); + grid-auto-rows: 14px; + gap: 2px; +} +.mg-mini i { + background: #d61f2c; + border: 2px solid var(--mg-k); +} +.mg-tools { + display: flex; + justify-content: center; + gap: 8px; +} +.mg-tools .gs-btn { + min-height: 48px; + padding: 6px 14px; + white-space: nowrap; +} +.mg-tools kbd { + padding: 0 5px; + font-family: var(--font-num); + font-size: 12px; + line-height: 1.4; + border: 2px solid currentColor; + border-radius: 5px; + opacity: 0.6; +} +.mg-tools .is-ready { + animation: mg-ready 700ms var(--ease-in-out) infinite alternate; +} +.mg-legend { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 4px 14px; + margin: 0; + padding: 0; + font-size: 12px; + font-weight: 800; + color: var(--muted); + list-style: none; +} +.mg-legend li { + display: inline-flex; + align-items: center; + gap: 5px; +} +.mg-legend i { + display: inline-grid; + place-items: center; + width: 18px; + height: 18px; + font-family: var(--font-num); + font-size: 12px; + font-style: normal; + color: var(--mg-k); + border: 2px solid var(--mg-k); +} +.mg-legend .is-heat { + background: color-mix(in srgb, var(--signal) 78%, #fff); +} +.mg-legend .is-build { + background: repeating-linear-gradient(45deg, var(--signal) 0 4px, var(--mg-k) 4px 8px); +} +.mg-legend .is-rival { + background: #6f757d; +} +.mg-legend .is-path { + background: radial-gradient(circle, var(--ink) 0 3px, transparent 4px), var(--mg-cell); + opacity: 0.8; +} +/* 觸控裝置沒有鍵盤:不顯示快捷鍵 */ +@media (hover: none) { + .mg-tools kbd, + .mg-piece kbd { + display: none; + } +} +@media (hover: hover) and (pointer: fine) { + .mg-piece:hover:not(:disabled):not(.is-selected) { + background: color-mix(in srgb, var(--signal) 35%, var(--surface)); + } +} + +/* 電腦、平板橫放:格子在左,右邊放托盤和工具 */ +@container (min-width: 760px) and (orientation: landscape) { + .mg-bb { + grid-template-columns: auto 300px; + grid-template-rows: auto auto; + column-gap: 40px; + justify-content: center; + align-items: center; + } + .mg-status { + grid-column: 1; + grid-row: 1; + } + .mg-gridwrap { + grid-column: 1; + grid-row: 2; + } + .mg-side { + grid-column: 2; + grid-row: 1 / span 2; + } + .mg-gridwrap { + --gw: min(640px, calc(100cqh - 90px), calc(100cqw - 400px)); + } + .mg-side { + gap: 18px; + } + .mg-tray { + gap: 12px; + } + .mg-piece { + width: 88px; + height: 92px; + } + .mg-mini { + grid-template-columns: repeat(3, 17px); + grid-auto-rows: 17px; + } + .mg-tools { + display: grid; + grid-template-columns: 1fr 1fr; + width: 100%; + } + .mg-tools .gs-btn:last-child { + grid-column: 1 / -1; + min-height: 56px; + font-size: 18px; + } +} + +@keyframes mg-drop { + 0% { + transform: scale(1.25); + } + 60% { + transform: scale(0.95); + } +} +@keyframes mg-ready { + to { + transform: translate(-1px, -1px) scale(1.04); + } +} +@media (prefers-reduced-motion: reduce) { + .mg-cell.is-new, + .mg-tools .is-ready, + .mg-status { + animation: none; + } + .mg-piece { + transition: none; + } +} diff --git a/web/src/game/minigames/handshake-logic.ts b/web/src/game/minigames/handshake-logic.ts new file mode 100644 index 0000000..1763201 --- /dev/null +++ b/web/src/game/minigames/handshake-logic.ts @@ -0,0 +1,137 @@ +import { clampScore, mulberry32 } from "./types.ts"; + +/** 掃街握手:一局 20 秒,越後面舉手越快、放得越快 */ +export const HANDSHAKE_MS = 20_000; +export const HS_COLS = 6; + +export type HandKind = "fan" | "vip" | "reporter"; +/** 握到一位鄉親 1 分、里長伯 3 分;記者不算分(點到扣分) */ +export const HAND_POINTS: Record = { fan: 1, vip: 3, reporter: 0 }; +/** 點到記者、揮空各扣幾分(0–100 的分數) */ +export const REPORTER_PENALTY = 8; +export const MISS_PENALTY = 1.5; + +/** 鍵盤對應:三排人=鍵盤三排(Q–Y、A–H、Z–N),用 code 判斷,注音輸入法開著也能玩 */ +export const HS_KEYS = ["KeyQ", "KeyW", "KeyE", "KeyR", "KeyT", "KeyY", "KeyA", "KeyS", "KeyD", "KeyF", "KeyG", "KeyH", "KeyZ", "KeyX", "KeyC", "KeyV", "KeyB", "KeyN"] as const; +export const HS_KEY_LABELS = "QWERTYASDFGHZXCVBN"; + +const SHIRTS = ["#e8833a", "#2f7f8f", "#7a5cc4", "#c99400", "#d6457a", "#5b6270", "#a3670f", "#3a8a5c"]; +const HAIRS = ["#2a2220", "#3b2f2a", "#6b6b6b", "#1c1c1c", "#8a5a3c", "#d9d4cc"]; +const SKINS = ["#f1c9a2", "#e5b48c", "#c98f62", "#f6d7b8"]; + +export interface Person { + /** 位置(人群區塊的百分比;y 是腳底) */ + x: number; + y: number; + row: number; + scale: number; + shirt: string; + hair: string; + skin: string; +} + +export interface Spawn { + /** 第幾毫秒舉手 */ + t: number; + person: number; + kind: HandKind; + /** 舉手多久 */ + dur: number; +} + +export interface HandshakeLevel { + people: Person[]; + spawns: Spawn[]; + /** 全部握到的話有幾分(分數的分母) */ + totalPoints: number; +} + +const clamp01 = (x: number) => Math.max(0, Math.min(1, Number.isFinite(x) ? x : 0)); + +/** + * 人群三排、每排 6 人,後排小前排大;誰舉手、什麼時候舉全部由種子決定。 + * 同一個人手還沒放下不會再被選到(不會兩次舉手疊在一起);開頭兩位一定是一般鄉親。 + */ +export function makeHandshake(seed: number, level: number): HandshakeLevel { + const r = mulberry32(seed); + const lv = clamp01(level); + const rows = [ + { y: 36, scale: 0.84 }, + { y: 66, scale: 0.94 }, + { y: 97, scale: 1.04 }, + ]; + const people: Person[] = []; + rows.forEach((row, ri) => { + for (let c = 0; c < HS_COLS; c++) { + const x = 9 + c * 16.4 + (ri === 1 ? 3.5 : -1) + (r() - 0.5) * 3; + people.push({ + x: Math.max(7, Math.min(93, x)), + y: row.y + (r() - 0.5) * 2, + row: ri, + scale: row.scale, + shirt: SHIRTS[Math.floor(r() * SHIRTS.length)]!, + hair: HAIRS[Math.floor(r() * HAIRS.length)]!, + skin: SKINS[Math.floor(r() * SKINS.length)]!, + }); + } + }); + + const gap0 = 720 - lv * 260; + const dur0 = 1350 - lv * 450; + const reporterP = 0.12 + lv * 0.14; + const vipP = 0.06; + const busyUntil = new Array(people.length).fill(-1); + const spawns: Spawn[] = []; + let recent: number[] = []; + let t = 450; + while (t < HANDSHAKE_MS - 500) { + const p = t / HANDSHAKE_MS; + const roll = r(); + const kind: HandKind = spawns.length < 2 ? "fan" : roll < reporterP ? "reporter" : roll < reporterP + vipP ? "vip" : "fan"; + const dur = (kind === "vip" ? 0.75 : 1) * dur0 * (1 - 0.22 * p) * (0.88 + r() * 0.24); + const free = people.map((_, i) => i).filter((i) => busyUntil[i]! < t && !recent.includes(i)); + if (free.length > 0) { + const person = free[Math.floor(r() * free.length)]!; + busyUntil[person] = t + dur + 200; + recent = [person, ...recent].slice(0, 2); + spawns.push({ t: Math.round(t), person, kind, dur: Math.round(dur) }); + } + t += gap0 * (1 - 0.4 * p) * (0.7 + r() * 0.6); + } + const totalPoints = spawns.reduce((s, x) => s + HAND_POINTS[x.kind], 0); + return { people, spawns, totalPoints }; +} + +export interface Spot { + x: number; + y: number; + row: number; + scale: number; +} + +/** + * 直式手機的排法:四排 5、4、5、4 人(人比較大、比較好點)。 + * 第 i 個人固定站第 i 個位置,關卡(誰舉手)不變,只是站的地方不一樣。 + */ +export function portraitSpots(count: number): Spot[] { + const rows = [ + { n: 5, y: 27, scale: 0.86 }, + { n: 4, y: 51, scale: 0.92 }, + { n: 5, y: 75, scale: 0.98 }, + { n: 4, y: 97, scale: 1.04 }, + ]; + const out: Spot[] = []; + rows.forEach((r, ri) => { + for (let c = 0; c < r.n && out.length < count; c++) { + const i = out.length; + const jitter = (((i * 7919) % 5) - 2) * 0.7; + out.push({ x: (r.n === 5 ? 11 + c * 19.5 : 20.5 + c * 19.5) + jitter, y: r.y + ((i * 31) % 3) - 1, row: ri, scale: r.scale }); + } + }); + return out; +} + +/** 分數:拿到的分 ÷(全部 × 0.95)× 100,被記者拍到每次 −8、揮空每次 −1.5 */ +export function handshakeScore(s: { points: number; totalPoints: number; reporters: number; misses: number }): number { + return clampScore((s.points / Math.max(1, s.totalPoints * 0.95)) * 100 - s.reporters * REPORTER_PENALTY - s.misses * MISS_PENALTY); +} diff --git a/web/src/game/minigames/handshake.css b/web/src/game/minigames/handshake.css new file mode 100644 index 0000000..26775af --- /dev/null +++ b/web/src/game/minigames/handshake.css @@ -0,0 +1,217 @@ +/* 掃街握手(HandshakeGame.tsx):騎樓店面+地磚上的人群。人的大小跟著遊戲區放大(container query) */ +.mg-street { + --mg-floor: light-dark(#f3ead6, #1d2b40); + --mg-floor-line: light-dark(#e2d3b2, #2a3c56); + position: relative; + display: grid; + grid-template-rows: clamp(64px, 15%, 130px) minmax(0, 1fr); + overflow: hidden; + background: + repeating-linear-gradient(90deg, transparent 0 62px, var(--mg-floor-line) 62px 64px), + repeating-linear-gradient(0deg, transparent 0 62px, var(--mg-floor-line) 62px 64px), + var(--mg-floor); + border-top: 3px solid var(--mg-k); + touch-action: none; +} +.mg-shops { + display: flex; + gap: 6px; + padding: 6px 8px 0; + background: #b98a5a; + border-bottom: 4px solid var(--mg-k); +} +.mg-shop { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + background: repeating-linear-gradient(0deg, #b9bcc0 0 6px, #9fa3a8 6px 8px); + border: 2px solid var(--mg-k); + border-bottom: 0; +} +.mg-shop b { + padding: 3px 2px; + overflow: hidden; + font-family: var(--font-serif); + font-size: clamp(11px, 1.4vw, 18px); + line-height: 1.2; + text-align: center; + white-space: nowrap; + color: #fff; + background: #d61f2c; + border-bottom: 2px solid var(--mg-k); +} +.mg-shop:nth-child(even) b { + color: var(--mg-k); + background: var(--signal); +} + +/* 人群區:最寬 1100px,置中;人的寬度 --pw 依區塊大小決定 */ +.mg-crowd { + position: relative; + justify-self: center; + width: min(100%, 1100px); + height: calc(100% - 18px); + container-type: size; + --pw: clamp(46px, min(14cqw, 21cqh), 124px); + --mg-ph: calc(var(--pw) * 1.5); +} +.mg-crowd.is-portrait { + --pw: clamp(46px, min(17cqw, 15cqh), 124px); +} +.mg-person { + position: absolute; + width: max(46px, calc(var(--pw) * var(--s))); + height: max(66px, calc(var(--pw) * var(--s) * 1.5)); + padding: 0; + background: none; + border: 0; + border-radius: 12px; + cursor: pointer; + touch-action: none; + transform: translate(-50%, -100%); +} +.mg-fig { + position: absolute; + inset: 0; + display: block; +} +.mg-fig.is-bump { + animation: mg-bump 280ms var(--ease-out); +} +/* 手:肩膀當支點,舉手時往上轉 */ +.mg-arm { + position: absolute; + top: 52%; + left: 74%; + width: 15%; + height: 30%; + background: var(--shirt); + border: 2.5px solid var(--mg-k); + border-radius: 6px; + transform-origin: 50% 8%; + transform: rotate(-14deg); + transition: transform 160ms var(--ease-out); +} +.mg-arm::after { + content: ""; + position: absolute; + bottom: -32%; + left: 50%; + width: 150%; + aspect-ratio: 1; + background: var(--skin, var(--mg-skin)); + border: 2.5px solid var(--mg-k); + border-radius: 50%; + transform: translateX(-50%); +} +.mg-person.is-up .mg-arm { + transform: rotate(-168deg); +} +.mg-ring { + position: absolute; + top: 30%; + left: 50%; + z-index: -1; + width: 128%; + aspect-ratio: 1; + background: rgb(255 210 63 / 0.22); + border: 5px solid var(--signal); + border-radius: 50%; + box-shadow: + 0 0 0 2px var(--mg-k), + inset 0 0 0 2px var(--mg-k); + transform: translate(-50%, -50%); + animation: mg-ring 700ms var(--ease-in-out) infinite alternate; +} +/* 里長伯:紅彩帶、橘色粗光圈、頭上掛牌 */ +.mg-person.is-vip .mg-ring { + border-width: 7px; + border-color: #ff9d00; + background: rgb(255 157 0 / 0.25); +} +.mg-person.is-vip .mg-body::after { + content: ""; + position: absolute; + inset: 0; + background: linear-gradient(130deg, transparent 36%, #d61f2c 36% 56%, transparent 56%); + border-radius: inherit; +} +.mg-vip-tag { + position: absolute; + bottom: 100%; + left: 50%; + z-index: 2; + padding: 1px 7px; + font-family: var(--font-serif); + font-size: clamp(11px, calc(var(--pw) * 0.17), 16px); + white-space: nowrap; + color: #fff; + background: #d61f2c; + border: 2px solid var(--mg-k); + border-radius: 6px; + transform: translate(-50%, -4px); +} +/* 記者:深色衣服、舉相機(沒有黃色光圈) */ +.mg-person.is-reporter .mg-body, +.mg-person.is-reporter .mg-arm { + background: #3a3f47; +} +.mg-person.is-reporter .mg-arm { + transform: rotate(-120deg); +} +.mg-cam { + position: absolute; + top: 8%; + left: -16%; + z-index: 2; + width: 52%; + height: auto; + padding: 3px; + color: #fff; + background: var(--mg-k); + border: 2px solid #fff; + border-radius: 7px; +} +.mg-key { + position: absolute; + bottom: 0; + left: 50%; + z-index: 3; + min-width: 22px; + padding: 1px 5px; + font-family: var(--font-num); + font-size: 13px; + font-weight: 800; + line-height: 1.2; + color: var(--mg-k); + background: var(--mg-cream); + border: 2px solid var(--mg-k); + border-radius: 6px; + box-shadow: 0 2px 0 var(--mg-k); + transform: translate(-50%, 55%); +} + +@keyframes mg-bump { + 40% { + transform: scale(1.12, 0.9); + } + 70% { + transform: scale(0.96, 1.05); + } +} +@keyframes mg-ring { + to { + transform: translate(-50%, -50%) scale(1.1); + } +} + +@media (prefers-reduced-motion: reduce) { + .mg-fig.is-bump, + .mg-ring { + animation: none; + } + .mg-arm { + transition: none; + } +} diff --git a/web/src/game/minigames/lobby.css b/web/src/game/minigames/lobby.css new file mode 100644 index 0000000..a46d5db --- /dev/null +++ b/web/src/game/minigames/lobby.css @@ -0,0 +1,280 @@ +/* 小遊戲大廳(MiniGameLobby.tsx):夜色場景裡三張大遊戲卡。電腦三欄、手機三列(插圖在上、說明在下),整頁不捲 */ +.mgl-body { + display: grid; + grid-template-rows: auto minmax(0, 1fr) auto; + gap: 14px; + height: 100%; + max-width: 1320px; + margin: 0 auto; +} +.mgl-lead { + margin: 0; + font-size: 15px; + line-height: 1.5; + color: rgb(255 255 255 / 0.86); +} +.mgl-cards { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + align-items: center; + gap: 22px; + min-height: 0; + margin: 0; + padding: 0 6px 6px 0; + list-style: none; + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; +} +.mgl-cards > li { + min-height: 0; + animation: mgl-in 420ms var(--ease-out) both; + animation-delay: calc(var(--n) * 70ms); +} +.mgl-card { + display: grid; + grid-template-rows: auto auto auto; + height: 100%; + overflow: hidden; + color: var(--ink); + text-decoration: none; + background: var(--surface); + border: 3px solid var(--ink); + border-radius: 20px; + box-shadow: 6px 6px 0 var(--shadow-ink); + transition: transform 160ms var(--ease-out); +} +.mgl-card:active { + transform: translate(3px, 3px); + box-shadow: 2px 2px 0 var(--shadow-ink); +} +.mgl-card:focus-visible { + outline: 4px solid var(--signal); + outline-offset: 4px; +} +.mgl-art { + display: block; + aspect-ratio: 16 / 10; + overflow: hidden; + background: #fbf1da; + border-bottom: 3px solid var(--ink); +} +.mgl-card.is-rally .mgl-art { + background: #1a2e4a; +} +.mgl-card.is-billboard .mgl-art { + background: #f3ead6; +} +.mgl-info { + display: grid; + align-content: start; + gap: 6px; + min-width: 0; + padding: 14px 18px 8px; +} +.mgl-title { + font-family: var(--font-serif); + font-size: clamp(24px, 2.2vw, 30px); + line-height: 1.15; +} +.mgl-pitch { + font-size: 15px; + line-height: 1.5; + color: var(--muted); +} +.mgl-tiers { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 6px; + margin-top: 6px; +} +.mgl-tier { + display: grid; + justify-items: center; + align-content: center; + gap: 3px; + min-height: 48px; + padding: 5px 2px; + background: var(--surface-2); + border: 2px solid var(--line); + border-radius: 10px; +} +.mgl-tier small { + font-size: 12px; + font-weight: 800; + color: var(--muted); + white-space: nowrap; +} +.mgl-tier-stars { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--muted); +} +.mgl-tier-stars b { + font-family: var(--font-num); + font-size: 17px; + color: var(--ink); +} +.mgl-tier.is-locked { + border-style: dashed; +} +.mgl-tier-lock { + display: inline-flex; + color: var(--muted); +} +.mgl-sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +.mgl-go { + display: flex; + align-items: center; + justify-content: center; + gap: 2px; + min-height: 52px; + margin: 6px 18px 18px; + font-size: 18px; + font-weight: 900; + color: #111419; + background: var(--signal); + border: 3px solid #111419; + border-radius: 14px; + box-shadow: 3px 3px 0 #111419; +} + +/* 開發用的難度、種子(#/minigames?dev) */ +.mgl-dev { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + padding: 8px 14px; + font-size: 14px; + color: var(--ink); + background: var(--surface); + border: 2px dashed var(--ink); + border-radius: 12px; +} +.mgl-dev label { + display: inline-flex; + align-items: center; + gap: 6px; +} +.mgl-dev input[type="number"] { + width: 8em; + min-height: 40px; + padding: 0 8px; + font: inherit; + color: var(--ink); + background: var(--surface-2); + border: 2px solid var(--ink); + border-radius: 8px; +} +.mgl-dev a { + margin-left: 8px; + color: var(--ink); +} +.mgl-dev output { + font-family: var(--font-num); + font-weight: 800; +} + +@media (hover: hover) and (pointer: fine) { + .mgl-card:hover { + transform: translate(-2px, -2px); + box-shadow: 9px 9px 0 var(--shadow-ink); + } + .mgl-card:hover .mgl-go { + background: #ffe174; + } +} + +/* 手機:三張卡上下排,插圖在上面裁成橫幅,說明一行、難度一列 */ +@media (max-width: 720px) { + .mgl-body { + gap: 10px; + } + .mgl-lead { + font-size: 13px; + } + .mgl-cards { + grid-template-columns: minmax(0, 1fr); + grid-auto-rows: minmax(0, 1fr); + align-items: stretch; + gap: 12px; + } + .mgl-card { + position: relative; + grid-template-rows: minmax(0, 1fr) auto; + border-radius: 16px; + box-shadow: 4px 4px 0 var(--shadow-ink); + } + .mgl-art { + aspect-ratio: auto; + min-height: 56px; + } + .mgl-info { + gap: 2px; + padding: 8px 12px 10px; + } + .mgl-title { + font-size: 21px; + } + .mgl-pitch { + overflow: hidden; + font-size: 13px; + text-overflow: ellipsis; + white-space: nowrap; + } + .mgl-tiers { + margin-top: 4px; + } + .mgl-tier { + grid-template-columns: auto auto; + gap: 6px; + min-height: 34px; + padding: 3px 4px; + } + .mgl-tier-stars b { + font-size: 15px; + } + .mgl-go { + position: absolute; + top: 10px; + right: 10px; + min-height: 40px; + margin: 0; + padding: 0 8px 0 14px; + font-size: 15px; + } +} +@media (max-width: 720px) and (max-height: 700px) { + .mgl-lead { + display: none; + } +} + +@keyframes mgl-in { + from { + opacity: 0; + transform: translateY(16px); + } +} +@media (prefers-reduced-motion: reduce) { + .mgl-cards > li { + animation: mgl-fade 200ms ease both; + } + .mgl-card { + transition: none; + } +} +@keyframes mgl-fade { + from { + opacity: 0; + } +} diff --git a/web/src/game/minigames/minigames.css b/web/src/game/minigames/minigames.css new file mode 100644 index 0000000..96fad7e --- /dev/null +++ b/web/src/game/minigames/minigames.css @@ -0,0 +1,1077 @@ +/* 選戰小遊戲的共用外框(Shell.tsx):全螢幕場景、上方名牌與計分、開始/倒數/暫停/結算。 + 台式競選文宣 × 立體桌遊:粗黑框、硬陰影、螢光黃+圈選章紅。所有 class 都用 mg- 開頭。 + 各遊戲本體的樣式在 handshake.css、rally.css、billboard.css;大廳在 lobby.css。 */ + +.mg { + /* 插圖、計分牌的黑線與奶油白:不隨深色模式變(跟 GameScene 的返回鍵、名牌一樣) */ + --mg-k: #111419; + --mg-cream: #fffaf0; + --mg-skin: #f1c9a2; + position: fixed; + inset: 0; + z-index: 70; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + height: 100dvh; + overflow: hidden; + overflow: clip; + padding-left: env(safe-area-inset-left, 0px); + padding-right: env(safe-area-inset-right, 0px); + color: var(--ink); + font-family: var(--font-body); + background: var(--paper); + user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; + overscroll-behavior: none; +} +.mg-scene-street { + background: linear-gradient(180deg, light-dark(#8fd3ff, #1a2a4a) 0%, light-dark(#c9ecff, #2b3d63) 100%); +} +.mg-scene-stage { + color: var(--navy-ink); + background: radial-gradient(ellipse at 50% 0%, #24365e, #0f1e33 70%); +} +.mg-scene-board { + background: + repeating-linear-gradient(135deg, rgb(0 0 0 / 0.025) 0 2px, transparent 2px 14px), + radial-gradient(ellipse at 50% 0%, rgb(255 210 63 / 0.22), transparent 60%), + var(--newsprint); +} + +/* ── 上方:暫停鍵、名牌、分數與時間 ── */ +.mg-top { + position: relative; + z-index: 6; + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 12px; + padding: max(10px, env(safe-area-inset-top, 0px)) 16px 10px; +} +.mg-round { + display: grid; + place-items: center; + width: 52px; + height: 52px; + padding: 0; + color: var(--mg-k); + background: var(--mg-cream); + border: 3px solid var(--mg-k); + border-radius: 50%; + box-shadow: 3px 3px 0 var(--mg-k); + cursor: pointer; + transition: transform 140ms var(--ease-out); +} +.mg-round.is-blank { + visibility: hidden; +} +.mg-round:active { + transform: translate(2px, 2px); + box-shadow: 1px 1px 0 var(--mg-k); +} +.mg-plate { + min-width: 0; +} +.mg-plate small { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mg-plate h2 { + margin: 0; + overflow: hidden; + font-family: var(--font-serif); + font-size: clamp(20px, 3vw, 30px); + line-height: 1.1; + text-overflow: ellipsis; + white-space: nowrap; +} +.mg-plate.is-long h2 { + font-size: clamp(18px, 2.4vw, 26px); +} +.mg-hud { + display: flex; + align-items: center; + gap: 8px; +} +.mg-pill { + position: relative; + display: inline-grid; + justify-items: center; + min-width: 62px; + padding: 4px 12px 5px; + overflow: hidden; + line-height: 1; + color: var(--mg-k); + background: var(--mg-cream); + border: 3px solid var(--mg-k); + border-radius: 14px; + box-shadow: 3px 3px 0 var(--mg-k); +} +.mg-pill small { + position: relative; + font-size: 11px; + font-weight: 800; + letter-spacing: 0.08em; + color: #5d646e; +} +.mg-pill b { + position: relative; + font-family: var(--font-num); + font-size: 28px; + font-variant-numeric: tabular-nums; +} +.mg-pill b span { + font-size: 15px; + color: #5d646e; +} +.mg-pill-score b { + color: #b3141f; +} +.mg-timer { + min-width: 70px; +} +.mg-timer i { + position: absolute; + inset: 0; + background: var(--signal); + transform-origin: left center; +} +.mg-timer.is-progress i { + background: #ffe9a3; +} +.mg-timer.is-low i { + background: #ffb3b3; +} +.mg-timer.is-low b { + color: #b3141f; + animation: mg-blink 500ms steps(1, end) infinite alternate; +} + +/* ── 遊戲區 ── */ +.mg-stage { + position: relative; + z-index: 0; + display: grid; + min-height: 0; + overflow: hidden; + overflow: clip; +} +.mg-stage > * { + min-width: 0; + min-height: 0; +} + +/* ── 蓋在遊戲上的卡片:開始、暫停、結算 ── */ +.mg-cover { + position: absolute; + inset: 0; + z-index: 20; + display: grid; + place-items: center; + padding: max(16px, env(safe-area-inset-top, 0px)) 16px max(16px, env(safe-area-inset-bottom, 0px)); + overflow-y: auto; + overscroll-behavior: contain; + background: rgb(17 20 25 / 0.55); + animation: mg-fade 200ms ease-out both; +} +.mg-card { + display: grid; + gap: 14px; + width: min(100%, 460px); + padding: 20px; + color: var(--ink); + background: var(--surface); + border: 3px solid var(--ink); + border-radius: 18px; + box-shadow: 6px 6px 0 var(--shadow-ink); + animation: mg-card-in 280ms var(--ease-out) both; +} +.mg-card p { + margin: 0; + line-height: 1.6; +} +.mg-cover-title { + justify-self: start; + padding: 2px 14px 4px; + font-family: var(--font-serif); + font-size: clamp(24px, 3.4vw, 32px); + line-height: 1.2; + color: var(--mg-k); + background: var(--signal); + border: 3px solid var(--mg-k); + box-shadow: 3px 3px 0 var(--mg-k); + transform: rotate(-1.5deg); +} +.mg-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 10px; +} +.mg-actions .gs-btn { + min-height: 52px; + font-size: 17px; +} +.mg-actions.is-stack { + flex-direction: column; + align-items: stretch; +} +.mg-go { + flex: 1 1 160px; + font-size: 20px !important; +} + +/* 開始畫面:電腦版示範圖在左、說明在右;手機上下排 */ +.mg-intro { + width: min(100%, 860px); + grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); + align-items: center; + gap: 20px 24px; +} +.mg-demo { + overflow: hidden; + aspect-ratio: 16 / 10; + background: #fbf1da; + border: 3px solid var(--mg-k); + border-radius: 14px; + box-shadow: 4px 4px 0 var(--shadow-ink); +} +.mg-intro-body { + display: grid; + gap: 12px; +} +.mg-steps { + display: grid; + gap: 8px; + margin: 0; + padding: 0; + list-style: none; +} +.mg-steps li { + display: grid; + grid-template-columns: 28px 1fr; + align-items: start; + gap: 10px; + font-size: 16px; + line-height: 1.5; +} +.mg-steps li > span { + display: grid; + place-items: center; + width: 28px; + height: 28px; + font-family: var(--font-num); + font-size: 17px; + font-weight: 800; + color: var(--mg-k); + background: var(--signal); + border: 2px solid var(--mg-k); + border-radius: 50%; +} +.mg-controls { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: 13px; + color: var(--muted); +} +.mg-controls svg { + flex: none; + margin-top: 3px; +} +.mg-reward { + padding-top: 10px; + font-size: 14px; + color: var(--muted); + border-top: 2px dashed var(--line); +} +.mg-reward::before { + content: "獎勵 "; + font-weight: 800; + color: var(--stamp); +} + +/* 難度選擇(大廳) */ +.mg-tiers { + display: grid; + gap: 6px; + padding-top: 10px; + border-top: 2px dashed var(--line); +} +.mg-tiers-label { + font-size: 13px; + font-weight: 800; + color: var(--muted); +} +.mg-tier-row { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} +.mg-tier { + display: grid; + justify-items: center; + gap: 2px; + min-height: 56px; + padding: 6px 4px; + font: inherit; + color: var(--ink); + background: var(--surface-2); + border: 3px solid var(--ink); + border-radius: 12px; + cursor: pointer; + transition: transform 140ms var(--ease-out); +} +.mg-tier b { + font-size: 15px; + white-space: nowrap; +} +.mg-tier.is-on { + color: var(--mg-k); + background: var(--signal); + border-color: var(--mg-k); + box-shadow: 3px 3px 0 var(--shadow-ink); + transform: translate(-1px, -1px); +} +.mg-tier.is-locked { + cursor: not-allowed; + opacity: 0.55; +} +.mg-tier-hint { + font-size: 12px; + color: var(--muted); +} + +/* 星星 */ +.mg-stars { + display: inline-flex; + gap: 2px; +} +.mg-stars svg { + fill: transparent; + stroke: currentColor; + opacity: 0.4; +} +.mg-stars svg.is-on { + fill: var(--signal); + stroke: var(--mg-k); + opacity: 1; +} +.mg-stars.is-reveal svg.is-on { + animation: mg-star 420ms var(--ease-out) both; + animation-delay: calc(420ms + var(--i) * 260ms); +} + +/* ── 3-2-1、時間到 ── */ +.mg-count, +.mg-splash { + position: absolute; + inset: 0; + z-index: 15; + display: grid; + place-items: center; + pointer-events: none; +} +.mg-count-n { + font-family: var(--font-num); + font-size: clamp(110px, 26vmin, 220px); + font-weight: 800; + line-height: 1; + color: var(--signal); + text-shadow: + -4px 0 var(--mg-k), + 4px 0 var(--mg-k), + 0 -4px var(--mg-k), + 0 4px var(--mg-k), + 8px 8px 0 var(--mg-k); + animation: mg-count 650ms var(--ease-out) both; +} +.mg-count-n.is-go { + padding: 0 0.3em 0.05em; + font-family: var(--font-serif); + font-size: clamp(56px, 13vmin, 110px); + color: #fff; + text-shadow: none; + background: var(--stamp); + border: 4px solid var(--mg-k); + box-shadow: 6px 6px 0 var(--mg-k); + rotate: -3deg; +} +.mg-splash { + z-index: 25; + background: rgb(17 20 25 / 0.35); + animation: mg-fade 200ms ease-out both; +} +.mg-splash span { + padding: 4px 0.5em 6px; + font-family: var(--font-serif); + font-size: clamp(48px, 11vmin, 96px); + color: #fff; + background: var(--stamp); + border: 4px solid var(--mg-k); + box-shadow: 6px 6px 0 var(--mg-k); + rotate: -4deg; + animation: mg-stamp-in 380ms var(--ease-out) both; +} + +/* ── 暫停 ── */ +.mg-pause { + width: min(100%, 360px); + justify-items: stretch; +} +.mg-pause p { + color: var(--muted); +} + +/* ── 結算 ── */ +.mg-result { + justify-items: center; + width: min(100%, 460px); + text-align: center; +} +.mg-result-kicker { + font-size: 13px; + font-weight: 800; + letter-spacing: 0.08em; + color: var(--muted); +} +.mg-result-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 8px 22px; +} +.mg-score { + display: inline-grid; + place-items: center; + align-content: center; + width: 124px; + height: 124px; + font-family: var(--font-num); + font-size: 56px; + line-height: 0.9; + color: var(--stamp); + border: 5px solid var(--stamp); + border-radius: 50%; + rotate: -8deg; + animation: mg-stamp-in 420ms var(--ease-out) both; +} +.mg-score small { + font-family: var(--font-serif); + font-size: 15px; +} +.mg-result .mg-stars { + color: var(--muted); +} +.mg-card .mg-verdict { + font-family: var(--font-serif); + font-size: 22px; + line-height: 1.3; +} +.mg-record { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 15px; + font-weight: 800; + color: var(--muted); +} +.mg-record.is-new { + padding: 3px 14px; + color: var(--mg-k); + background: var(--signal); + border: 3px solid var(--mg-k); + border-radius: 999px; + box-shadow: 3px 3px 0 var(--shadow-ink); + rotate: -2deg; + animation: mg-star 420ms var(--ease-out) 1.1s both; +} +.mg-unlock { + font-size: 14px; + color: var(--muted); +} +.mg-unlock.is-open { + font-weight: 900; + color: var(--good); +} +.mg-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(64px, 1fr)); + gap: 6px; + width: 100%; + margin: 0; +} +.mg-summary > div { + display: grid; + gap: 2px; + padding: 6px 4px; + background: var(--surface-2); + border: 2px solid var(--line); + border-radius: 10px; +} +.mg-summary dt { + font-size: 12px; + font-weight: 800; + color: var(--muted); +} +.mg-summary dd { + margin: 0; + font-family: var(--font-num); + font-size: 19px; + white-space: nowrap; + font-weight: 800; +} +.mg-result .mg-actions { + justify-content: center; + width: 100%; +} +.mg-result .mg-actions .gs-btn { + flex: 1 1 140px; +} + +/* ── 連擊徽章、跳字、震動、閃光 ── */ +.mg-combo { + position: absolute; + top: 10px; + left: 50%; + z-index: 12; + display: inline-flex; + align-items: baseline; + gap: 6px; + padding: 2px 16px 4px; + font-family: var(--font-serif); + font-size: 15px; + white-space: nowrap; + color: #fff; + pointer-events: none; + background: var(--stamp); + border: 3px solid var(--mg-k); + border-radius: 999px; + box-shadow: 3px 3px 0 var(--mg-k); + translate: -50% 0; +} +.mg-combo b { + display: inline-block; + font-family: var(--font-num); + font-size: 28px; + line-height: 1; + animation: mg-bump-num 260ms var(--ease-out); +} +.mg-combo.is-hot { + color: var(--mg-k); + background: var(--signal); +} +.mg-combo.is-fire { + color: var(--mg-k); + background: var(--signal); + scale: 1.12; +} +.mg-pop { + position: absolute; + z-index: 100; + padding: 0 4px; + font-family: var(--font-serif); + font-size: clamp(16px, 2.2vw, 22px); + white-space: nowrap; + color: var(--mg-k); + pointer-events: none; + text-shadow: + -2px 0 #fff, + 2px 0 #fff, + 0 -2px #fff, + 0 2px #fff; + transform: translate(-50%, -50%); + animation: mg-pop 900ms var(--ease-out) forwards; +} +.mg-pop.is-good { + color: #1f6b3e; +} +.mg-pop.is-bad { + color: #c3121e; +} +.mg-pop.is-dim { + font-size: 15px; + color: #5d646e; +} +.mg-pop.is-big { + padding: 2px 10px; + font-size: clamp(18px, 2.6vw, 26px); + color: var(--mg-k); + text-shadow: none; + background: var(--signal); + border: 3px solid var(--mg-k); + border-radius: 8px; + box-shadow: 3px 3px 0 var(--mg-k); + animation-name: mg-pop-big; +} +.mg-shake { + animation: mg-shake 320ms linear; +} +.mg-flash { + position: absolute; + inset: 0; + z-index: 30; + background: #fff; + pointer-events: none; + animation: mg-flash 320ms ease-out forwards; +} + +/* ── 人形(圓頭+身體,不畫真人):掃街握手、造勢台下共用 ── */ +.mg-head { + position: absolute; + top: 2%; + left: 50%; + width: 44%; + aspect-ratio: 1; + background: linear-gradient(var(--hair, #2a2220) 0 36%, var(--skin, var(--mg-skin)) 36%); + border: 2.5px solid var(--mg-k); + border-radius: 50%; + transform: translateX(-50%); +} +.mg-body { + position: absolute; + bottom: 0; + left: 50%; + width: 70%; + height: 54%; + background: var(--shirt, #5b6270); + border: 2.5px solid var(--mg-k); + border-radius: 46% 46% 8px 8px; + transform: translateX(-50%); +} + +/* ── 插圖(art.tsx) ── */ +.mga { + display: block; + width: 100%; + height: 100%; +} +.mga text { + font-family: var(--font-num); + font-weight: 800; +} +.mga .mga-cjk { + font-family: var(--font-serif); +} +.mga .mga-ring, +.mga .mga-approach, +.mga .mga-piece, +.mga .mga-plus, +.mga .mga-finger, +.mga .mga-perfect, +.mga .mga-fan { + transform-box: fill-box; + transform-origin: center; +} + +/* 開始畫面的示範動畫(系統減少動態時停在靜態說明圖) */ +@media (prefers-reduced-motion: no-preference) { + .mga.is-demo .mga-raise { + animation: mga-raise 2.8s var(--ease-out) infinite; + } + .mga.is-demo .mga-ring { + animation: mga-ring 700ms var(--ease-in-out) infinite alternate; + } + .mga.is-demo .mga-finger { + animation: mga-finger 2.8s var(--ease-out) infinite; + } + .mga.is-demo .mga-plus { + animation: mga-plus 2.8s var(--ease-out) infinite; + } + .mga.is-demo .mga-approach { + animation: mga-approach 1.6s linear infinite; + } + .mga.is-demo .mga-perfect { + animation: mga-perfect 1.6s linear infinite; + } + .mga.is-demo .mga-fan { + animation: mga-jump 400ms var(--ease-in-out) infinite alternate; + animation-delay: calc(var(--i) * -70ms); + } + .mga.is-demo .mga-piece { + animation: mga-drop 3s var(--ease-out) infinite; + } + .mga-billboard.is-demo .mga-plus { + animation: mga-plus 3s var(--ease-out) infinite; + } +} + +/* ── 滑鼠 hover(觸控不會卡住) ── */ +@media (hover: hover) and (pointer: fine) { + .mg-round:hover { + background: var(--signal); + } + .mg-tier:hover:not(:disabled):not(.is-on) { + background: color-mix(in srgb, var(--signal) 35%, var(--surface-2)); + } +} +.mg :focus-visible { + outline: 4px solid var(--signal); + outline-offset: 3px; +} + +/* ── 手機 ── */ +@media (max-width: 720px) { + .mg-top { + gap: 8px; + padding-inline: 10px; + } + .mg-round { + width: 44px; + height: 44px; + } + .mg-plate { + padding: 3px 14px 4px 10px; + } + .mg-plate h2 { + font-size: 19px; + } + .mg-plate.is-long h2 { + display: -webkit-box; + font-size: 16px; + line-height: 1.15; + white-space: normal; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + } + .mg-hud { + gap: 6px; + } + .mg-pill { + min-width: 52px; + padding: 3px 8px 4px; + border-radius: 12px; + } + .mg-pill small { + font-size: 10px; + } + .mg-pill b { + font-size: 23px; + } + .mg-pill b span { + font-size: 13px; + } + .mg-timer { + min-width: 54px; + } + .mg-card { + padding: 16px; + } + .mg-intro { + grid-template-columns: minmax(0, 1fr); + gap: 12px; + } + .mg-demo { + justify-self: center; + width: min(100%, 280px); + } + .mg-steps li { + font-size: 15px; + } + .mg-score { + width: 108px; + height: 108px; + font-size: 48px; + } + .mg-summary dd { + font-size: 17px; + } + .mg-summary dt { + font-size: 11px; + } +} +@media (max-width: 380px) { + .mg-pill-score small { + display: none; + } +} + +/* ── 動畫(只動 transform/opacity) ── */ +@keyframes mg-fade { + from { + opacity: 0; + } +} +@keyframes mg-card-in { + from { + opacity: 0; + transform: translateY(14px) scale(0.96); + } +} +@keyframes mg-count { + 0% { + opacity: 0; + transform: scale(1.7); + } + 30% { + opacity: 1; + transform: scale(1); + } + 80% { + opacity: 1; + } + 100% { + opacity: 0; + transform: scale(0.92); + } +} +@keyframes mg-stamp-in { + 0% { + opacity: 0; + transform: scale(1.8); + } + 70% { + opacity: 1; + transform: scale(0.94); + } + 100% { + transform: scale(1); + } +} +@keyframes mg-star { + 0% { + opacity: 0; + transform: scale(0.2) rotate(-40deg); + } + 70% { + opacity: 1; + transform: scale(1.25) rotate(6deg); + } + 100% { + opacity: 1; + transform: none; + } +} +@keyframes mg-blink { + to { + opacity: 0.35; + } +} +@keyframes mg-bump-num { + 40% { + transform: scale(1.4); + } +} +@keyframes mg-pop { + 0% { + opacity: 0; + transform: translate(-50%, -30%) scale(0.8); + } + 15% { + opacity: 1; + transform: translate(-50%, -60%) scale(1.08); + } + 70% { + opacity: 1; + } + 100% { + opacity: 0; + transform: translate(-50%, -140%) scale(1); + } +} +@keyframes mg-pop-big { + 0% { + opacity: 0; + transform: translate(-50%, -50%) scale(0.5) rotate(-4deg); + } + 20% { + opacity: 1; + transform: translate(-50%, -70%) scale(1.15) rotate(-2deg); + } + 75% { + opacity: 1; + transform: translate(-50%, -80%) scale(1) rotate(-2deg); + } + 100% { + opacity: 0; + transform: translate(-50%, -110%) scale(1) rotate(-2deg); + } +} +@keyframes mg-shake { + 0%, + 100% { + transform: none; + } + 20% { + transform: translate(-6px, 2px); + } + 40% { + transform: translate(5px, -3px); + } + 60% { + transform: translate(-4px, 1px); + } + 80% { + transform: translate(2px, -1px); + } +} +@keyframes mg-flash { + from { + opacity: 0.8; + } + to { + opacity: 0; + } +} +@keyframes mga-raise { + 0%, + 8% { + opacity: 0; + } + 16%, + 78% { + opacity: 1; + } + 90%, + 100% { + opacity: 0; + } +} +@keyframes mga-ring { + to { + transform: scale(1.1); + } +} +@keyframes mga-finger { + 0%, + 22% { + opacity: 0; + transform: translate(26px, 18px); + } + 40% { + opacity: 1; + transform: none; + } + 46% { + transform: scale(0.8); + } + 52%, + 78% { + opacity: 1; + transform: none; + } + 90%, + 100% { + opacity: 0; + } +} +@keyframes mga-plus { + 0%, + 45% { + opacity: 0; + transform: translateY(8px); + } + 55%, + 80% { + opacity: 1; + transform: none; + } + 92%, + 100% { + opacity: 0; + transform: translateY(-6px); + } +} +@keyframes mga-approach { + 0% { + opacity: 0; + transform: scale(2.4); + } + 12% { + opacity: 1; + } + 62% { + opacity: 1; + transform: scale(1); + } + 70%, + 100% { + opacity: 0; + transform: scale(1); + } +} +@keyframes mga-perfect { + 0%, + 60% { + opacity: 0; + transform: scale(0.7); + } + 66%, + 88% { + opacity: 1; + transform: scale(1.1); + } + 100% { + opacity: 0; + } +} +@keyframes mga-jump { + to { + transform: translateY(-4px); + } +} +@keyframes mga-drop { + 0%, + 10% { + opacity: 0; + transform: translateY(-16px) scale(1.15); + } + 28%, + 85% { + opacity: 1; + transform: none; + } + 100% { + opacity: 0; + } +} + +/* 系統要求減少動態:不震動、不彈跳、不縮放,只留淡入淡出 */ +@media (prefers-reduced-motion: reduce) { + .mg-shake, + .mg-combo b, + .mg-timer.is-low b { + animation: none; + } + .mg-card, + .mg-score, + .mg-splash span, + .mg-count-n, + .mg-record.is-new, + .mg-stars.is-reveal svg.is-on { + animation-name: mg-fade; + } + .mg-pop, + .mg-pop.is-big { + animation: mg-fade-out 900ms ease-out forwards; + } + .mg-flash { + animation: mg-flash-soft 320ms ease-out forwards; + } + .mg-round, + .mg-tier { + transition: none; + } +} +@keyframes mg-fade-out { + 0%, + 60% { + opacity: 1; + } + 100% { + opacity: 0; + } +} +@keyframes mg-flash-soft { + from { + opacity: 0.35; + } + to { + opacity: 0; + } +} diff --git a/web/src/game/minigames/rally-logic.ts b/web/src/game/minigames/rally-logic.ts new file mode 100644 index 0000000..7e543a0 --- /dev/null +++ b/web/src/game/minigames/rally-logic.ts @@ -0,0 +1,72 @@ +import { clampScore, mulberry32 } from "./types.ts"; + +/** 造勢喊凍蒜:先數 4 拍(預備、3、2、1),接著 8 小節,每小節 4 拍 */ +export const RALLY_COUNT_IN = 4; +export const RALLY_BARS = 8; +/** 判定:誤差 60 毫秒內 Perfect、130 毫秒內 Good(手機觸控有延遲,寬一點) */ +export const PERFECT_MS = 60; +export const GOOD_MS = 130; +/** 亂按(不在任何一拍附近)每次扣幾分 */ +export const EARLY_PENALTY = 2; + +/** 一小節 8 個半拍:x=要喊、.=不喊。越後面的組越常出現連續的半拍 */ +const EASY = ["x.x.x.x.", "x...x...", "x.x.x...", "x...x.x."]; +const MID = ["x.x.xxx.", "xxx.x...", "x.xxx.x.", "x.x.x.xx"]; +const HARD = ["xxx.xx..", "x.xx.xx.", "xx.xx.x.", "x.xxxxx."]; +/** 最後一小節:凍蒜、凍蒜、凍蒜! */ +const FINALE = "x.x.x..."; + +export type Judge = "perfect" | "good" | "miss"; + +export interface Chart { + bpm: number; + beatMs: number; + /** 每一下的時間(毫秒,從開始算) */ + notes: number[]; + /** 鼓點數(每一拍一下) */ + beats: number; + endMs: number; + /** 外圈提早多久出現 */ + approachMs: number; +} + +const clamp01 = (x: number) => Math.max(0, Math.min(1, Number.isFinite(x) ? x : 0)); + +export function makeChart(seed: number, level: number): Chart { + const r = mulberry32(seed); + const lv = clamp01(level); + const bpm = Math.round(92 + lv * 36); + const beatMs = 60_000 / bpm; + const pHard = Math.max(0, lv - 0.45) * 1.1; + const pMid = Math.min(0.55, 0.1 + lv * 0.6); + const pick = (list: readonly string[]) => list[Math.floor(r() * list.length)]!; + const bars: string[] = []; + for (let b = 0; b < RALLY_BARS; b++) { + if (b === 0) bars.push(pick(EASY)); + else if (b === RALLY_BARS - 1) bars.push(FINALE); + else { + const roll = r(); + bars.push(roll < pHard ? pick(HARD) : roll < pHard + pMid ? pick(MID) : pick(EASY)); + } + } + const notes: number[] = []; + bars.forEach((bar, b) => { + for (let k = 0; k < 8; k++) if (bar[k] === "x") notes.push((RALLY_COUNT_IN + b * 4 + k / 2) * beatMs); + }); + const beats = RALLY_COUNT_IN + RALLY_BARS * 4; + return { bpm, beatMs, notes, beats, endMs: beats * beatMs + GOOD_MS + 300, approachMs: Math.max(700, beatMs * 1.5) }; +} + +export function judgeOffset(ms: number): "perfect" | "good" | null { + const d = Math.abs(ms); + return d <= PERFECT_MS ? "perfect" : d <= GOOD_MS ? "good" : null; +} + +/** + * 分數:(Perfect 1、Good 0.5) 平均 × 90 + 最長連擊比例 × 10,亂按每次 −2。 + * 全部 Perfect 一路連到底=100。 + */ +export function rallyScore(s: { perfect: number; good: number; early: number; maxCombo: number; total: number }): number { + const n = Math.max(1, s.total); + return clampScore(((s.perfect + s.good * 0.5) / n) * 90 + (s.maxCombo / n) * 10 - s.early * EARLY_PENALTY); +} diff --git a/web/src/game/minigames/rally.css b/web/src/game/minigames/rally.css new file mode 100644 index 0000000..57bef67 --- /dev/null +++ b/web/src/game/minigames/rally.css @@ -0,0 +1,289 @@ +/* 造勢喊凍蒜(RallyGame.tsx):晚會舞台。判定圈、台下群眾、按鈕都跟著遊戲區放大(container query) */ +.mg-rally { + --hype: 0; + position: relative; + display: grid; + grid-template-rows: minmax(110px, 0.85fr) minmax(150px, 1.25fr) auto auto; + justify-items: center; + align-items: center; + padding: 0 16px max(16px, env(safe-area-inset-bottom, 0px)); + overflow: hidden; + color: var(--navy-ink); + container-type: size; + touch-action: none; + cursor: pointer; + border-top: 3px solid var(--mg-k); +} +.mg-backdrop { + position: relative; + grid-row: 1; + grid-column: 1; + align-self: stretch; + justify-self: stretch; + margin: 0 -16px; + background: repeating-linear-gradient(90deg, #a5121c 0 26px, #d61f2c 26px 52px); + border-bottom: 6px solid var(--mg-k); +} +.mg-banner { + position: absolute; + top: 12px; + left: 50%; + padding: 2px 18px 4px; + font-family: var(--font-serif); + font-size: clamp(20px, 4.5cqw, 40px); + letter-spacing: 0.15em; + white-space: nowrap; + color: var(--mg-k); + background: var(--signal); + border: 3px solid var(--mg-k); + box-shadow: 4px 4px 0 var(--mg-k); + transform: translateX(-50%) rotate(-1.5deg); +} +.mg-lights { + position: absolute; + inset: auto 0 8px; + height: 14px; + background: radial-gradient(circle, var(--signal) 0 4px, transparent 5px) 0 0 / 28px 14px repeat-x; + opacity: calc(0.35 + var(--hype) * 0.65); + transition: opacity 200ms; +} +.mg-host { + position: relative; + z-index: 2; + grid-row: 1; + grid-column: 1; + align-self: end; + width: clamp(52px, 11cqh, 96px); + aspect-ratio: 0.7; + margin-bottom: 2px; + --shirt: #fffaf0; + --hair: #2a2220; +} +.mg-mic { + position: absolute; + top: 42%; + left: 74%; + width: 40%; + height: auto; + color: var(--mg-k); +} +.mg-bubble { + position: absolute; + bottom: 74%; + left: 96%; + padding: 2px 12px 4px; + font-family: var(--font-serif); + font-size: clamp(16px, 3cqh, 26px); + white-space: nowrap; + color: var(--mg-k); + background: #fff; + border: 3px solid var(--mg-k); + border-radius: 14px 14px 14px 3px; + box-shadow: 3px 3px 0 var(--mg-k); + animation: mg-fade 120ms ease-out; +} + +/* 判定圈:黃圈固定,白色外圈從 2.8 倍縮到 1 倍 */ +.mg-target { + --tz: clamp(130px, min(52cqw, 34cqh), 300px); + position: relative; + z-index: 2; + width: var(--tz); + height: var(--tz); +} +.mg-target .mg-combo { + top: -2px; +} +.mg-judge-ring, +.mg-approach { + position: absolute; + top: 50%; + left: 50%; + width: 50%; + aspect-ratio: 1; + border-radius: 50%; + transform: translate(-50%, -50%); +} +.mg-judge-ring { + background: rgb(255 210 63 / 0.16); + border: clamp(6px, calc(var(--tz) * 0.05), 11px) solid var(--signal); + box-shadow: + 0 0 0 3px var(--mg-k), + inset 0 0 0 3px var(--mg-k); +} +.mg-target.is-now .mg-judge-ring { + background: rgb(255 210 63 / 0.6); +} +.mg-approach { + border: 4px solid #fff; + box-shadow: 0 0 0 2px var(--mg-k); + opacity: 0.95; +} +.mg-lamps { + position: absolute; + top: 2%; + left: 50%; + display: flex; + gap: 12px; + transform: translateX(-50%); +} +.mg-lamps i { + width: 20px; + height: 20px; + background: #2a3448; + border: 3px solid var(--mg-k); + border-radius: 50%; +} +.mg-lamps i.is-on { + background: var(--signal); +} +.mg-judge { + position: absolute; + bottom: -4px; + left: 50%; + font-family: var(--font-num); + font-size: clamp(24px, calc(var(--tz) * 0.15), 38px); + font-weight: 800; + letter-spacing: 0.04em; + white-space: nowrap; + text-shadow: + -2px 0 var(--mg-k), + 2px 0 var(--mg-k), + 0 -2px var(--mg-k), + 0 2px var(--mg-k); + transform: translateX(-50%); + animation: mg-judge 600ms var(--ease-out) forwards; +} +.mg-judge.is-perfect { + color: var(--signal); +} +.mg-judge.is-good { + color: #fff; +} +.mg-judge.is-miss, +.mg-judge.is-early, +.mg-judge.is-late { + color: #ff9a9a; +} + +/* 台下群眾:越嗨跳越高、越多人舉旗 */ +.mg-fans { + z-index: 2; + display: flex; + align-items: flex-end; + justify-content: center; + width: calc(100% + 32px); + height: clamp(56px, 12cqh, 120px); + margin: 0 -16px 8px; + overflow: hidden; + border-bottom: 4px solid var(--mg-k); +} +.mg-fan { + position: relative; + flex: 0 0 clamp(34px, 7.5cqh, 70px); + height: 80%; + margin: 0 -2px; + --shirt: #1b2638; + --hair: #0b0f16; + --skin: #2a3448; + animation: mg-jump 520ms var(--ease-in-out) infinite alternate; + animation-delay: calc(var(--i) * -90ms); +} +.mg-fan:nth-child(odd) { + height: 70%; +} +.mg-fan::after { + content: ""; + position: absolute; + top: -16%; + left: 64%; + width: 40%; + height: 26%; + background: var(--signal); + border: 2px solid var(--mg-k); + box-shadow: -3px 9px 0 -1px var(--mg-k); + opacity: calc(var(--hype) * 1.6 - (var(--i) / 15) * 0.8); + transition: opacity 200ms; +} +.mg-confetti { + position: absolute; + inset: -120px 0 0; + z-index: 1; + pointer-events: none; + background-image: + radial-gradient(circle at 20% 30%, var(--signal) 0 3px, transparent 4px), + radial-gradient(circle at 70% 60%, #fff 0 2px, transparent 3px), + radial-gradient(circle at 45% 85%, #ff4d5a 0 3px, transparent 4px); + background-size: 120px 120px; + opacity: 0.8; + animation: mg-confetti 1.6s linear infinite; +} +.mg-shout { + z-index: 3; + width: min(100%, 440px); + min-height: clamp(68px, 11cqh, 104px); + font-family: var(--font-serif); + font-size: clamp(30px, 5.5cqh, 48px); + letter-spacing: 0.12em; + color: #fff; + background: var(--stamp); + border: 4px solid var(--mg-k); + border-radius: 18px; + box-shadow: 5px 5px 0 var(--mg-k); + cursor: pointer; + transition: transform 80ms var(--ease-out); +} +.mg-shout.is-off { + opacity: 0.55; +} +.mg-rally:active .mg-shout:not(.is-off) { + transform: translate(3px, 3px) scale(0.98); + box-shadow: 2px 2px 0 var(--mg-k); +} + +@keyframes mg-judge { + 0% { + opacity: 0; + transform: translateX(-50%) scale(1.5); + } + 25% { + opacity: 1; + transform: translateX(-50%) scale(1); + } + 80% { + opacity: 1; + } + 100% { + opacity: 0; + transform: translateX(-50%) translateY(-8px); + } +} +@keyframes mg-jump { + from { + transform: translateY(0); + } + to { + transform: translateY(calc(-2px - var(--hype) * 18px)); + } +} +@keyframes mg-confetti { + from { + transform: translateY(0); + } + to { + transform: translateY(120px); + } +} + +@media (prefers-reduced-motion: reduce) { + .mg-fan, + .mg-confetti { + animation: none; + } + .mg-judge { + animation: mg-fade-out 600ms ease-out forwards; + } + .mg-shout { + transition: none; + } +} diff --git a/web/src/game/minigames/records.ts b/web/src/game/minigames/records.ts new file mode 100644 index 0000000..5974d85 --- /dev/null +++ b/web/src/game/minigames/records.ts @@ -0,0 +1,121 @@ +import { GAME_IDS, clampScore, starsFor, type GameId } from "./types.ts"; + +/** + * 小遊戲大廳的最佳紀錄:每個遊戲 × 三級難度,各存最高分和玩過幾次。 + * 存在瀏覽器(tongsuan.minigames.v1),讀寫失敗(私密模式、被擋)就當作沒有紀錄,遊戲照玩。 + * 星等不存,一律從最高分換算,改 localStorage 也改不出不一致的星星。 + */ +export const RECORDS_KEY = "tongsuan.minigames.v1"; + +export const TIERS = [ + { label: "新手", short: "新手", level: 0.2 }, + { label: "老手", short: "老手", level: 0.55 }, + { label: "選戰老將", short: "老將", level: 0.9 }, +] as const; +export type TierIndex = 0 | 1 | 2; +export const TIER_INDEXES: readonly TierIndex[] = [0, 1, 2]; + +/** 前一級拿到幾星才解鎖下一級 */ +export const UNLOCK_STARS = 2; + +export interface TierRecord { + best: number; + plays: number; +} +export type GameRecords = readonly [TierRecord | null, TierRecord | null, TierRecord | null]; +export type Records = Readonly>; + +const EMPTY_GAME: GameRecords = [null, null, null]; + +export function emptyRecords(): Records { + return { handshake: EMPTY_GAME, rally: EMPTY_GAME, billboard: EMPTY_GAME }; +} + +function cleanTier(raw: unknown): TierRecord | null { + if (!raw || typeof raw !== "object") return null; + const { best, plays } = raw as { best?: unknown; plays?: unknown }; + if (typeof best !== "number" || !Number.isFinite(best)) return null; + const n = typeof plays === "number" && Number.isFinite(plays) ? Math.floor(plays) : 1; + return { best: clampScore(best), plays: Math.max(1, Math.min(1_000_000, n)) }; +} + +/** 從儲存空間讀到的東西不一定可信:型別不對、分數超出 0–100、不認得的遊戲都清掉 */ +export function sanitizeRecords(raw: unknown): Records { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return emptyRecords(); + const src = raw as Record; + const out = emptyRecords() as Record; + for (const id of GAME_IDS) { + const list = src[id]; + if (!Array.isArray(list)) continue; + out[id] = [cleanTier(list[0]), cleanTier(list[1]), cleanTier(list[2])]; + } + return out; +} + +export function loadRecords(storage: Pick | null = safeStorage()): Records { + try { + const raw = storage?.getItem(RECORDS_KEY); + return sanitizeRecords(raw ? JSON.parse(raw) : null); + } catch { + return emptyRecords(); + } +} + +export function saveRecords(records: Records, storage: Pick | null = safeStorage()): void { + try { + storage?.setItem(RECORDS_KEY, JSON.stringify(records)); + } catch { + // 存不了就只在這次有效 + } +} + +function safeStorage(): Storage | null { + try { + return typeof localStorage === "undefined" ? null : localStorage; + } catch { + return null; + } +} + +/** 記下一局的分數(不改原本的物件);newBest=比之前的最高分高(第一次玩、分數大於 0 也算) */ +export function recordResult(records: Records, game: GameId, tier: TierIndex, score: number): { records: Records; newBest: boolean } { + const s = clampScore(score); + const prev = records[game][tier]; + const newBest = prev ? s > prev.best : s > 0; + const next: TierRecord = { best: Math.max(prev?.best ?? 0, s), plays: (prev?.plays ?? 0) + 1 }; + const list = records[game].map((r, i) => (i === tier ? next : r)) as unknown as GameRecords; + return { records: { ...records, [game]: list }, newBest }; +} + +export const tierStars = (records: Records, game: GameId, tier: TierIndex): number => { + const r = records[game][tier]; + return r ? starsFor(r.best) : 0; +}; + +export function isUnlocked(records: Records, game: GameId, tier: TierIndex): boolean { + return tier === 0 || tierStars(records, game, (tier - 1) as TierIndex) >= UNLOCK_STARS; +} + +/** 鎖住的原因(「新手拿到 2 星解鎖」);已解鎖回 null */ +export function lockReason(records: Records, game: GameId, tier: TierIndex): string | null { + if (isUnlocked(records, game, tier)) return null; + return `${TIERS[tier - 1]!.label}拿到 ${UNLOCK_STARS} 星解鎖`; +} + +/** 進遊戲時預設的難度:解鎖的最高一級 */ +export function defaultTier(records: Records, game: GameId): TierIndex { + return [...TIER_INDEXES].reverse().find((t) => isUnlocked(records, game, t)) ?? 0; +} + +/** 全部拿到的星星(每個遊戲每級難度最多 3 顆,總共 27 顆) */ +export function totalStars(records: Records): number { + return GAME_IDS.reduce((sum, id) => sum + TIER_INDEXES.reduce((s, t) => s + tierStars(records, id, t), 0), 0); +} + +export const MAX_STARS = GAME_IDS.length * TIERS.length * 3; + +/** 網址上的難度(?t=0|1|2);不合法或還沒解鎖就用預設 */ +export function parseTier(raw: string | null, records: Records, game: GameId): TierIndex { + const t = TIER_INDEXES.find((x) => raw !== null && raw !== "" && Number(raw) === x); + return t !== undefined && isUnlocked(records, game, t) ? t : defaultTier(records, game); +} diff --git a/web/src/game/minigames/registry.ts b/web/src/game/minigames/registry.ts new file mode 100644 index 0000000..1459591 --- /dev/null +++ b/web/src/game/minigames/registry.ts @@ -0,0 +1,14 @@ +import type { ComponentType } from "react"; +import { BILLBOARD_META, BillboardGame } from "./BillboardGame.tsx"; +import { HANDSHAKE_META, HandshakeGame } from "./HandshakeGame.tsx"; +import { RALLY_META, RallyGame } from "./RallyGame.tsx"; +import type { MiniGameMeta, MiniGameProps } from "./types.ts"; + +export type MiniGameId = MiniGameMeta["id"]; + +/** 小遊戲一覽:選戰的「小遊戲」站用 id 找到要掛的元件 */ +export const MINI_GAMES: Record }> = { + handshake: { meta: HANDSHAKE_META, Game: HandshakeGame }, + rally: { meta: RALLY_META, Game: RallyGame }, + billboard: { meta: BILLBOARD_META, Game: BillboardGame }, +}; diff --git a/web/src/game/minigames/sound.ts b/web/src/game/minigames/sound.ts new file mode 100644 index 0000000..2e02e75 --- /dev/null +++ b/web/src/game/minigames/sound.ts @@ -0,0 +1,101 @@ +import { audioContext, loadBuffer } from "../audio/engine.ts"; +import { getSettings } from "../audio/settings.ts"; + +/** + * 小遊戲專用的音效:倒數嗶聲、時間到、星星、新紀錄、快門。 + * 用現有的 CC0 音檔(web/public/assets/sfx,出處見 LICENSES.md),讀不到時用 Web Audio 即時合成。 + * 音效設定關掉時全部不出聲。 + */ +export function mgAudio(): AudioContext | null { + return getSettings().sound ? audioContext() : null; +} + +function tone(a: AudioContext, freq: number, at: number, dur: number, type: OscillatorType = "square", gain = 0.05): void { + const o = a.createOscillator(); + const g = a.createGain(); + o.type = type; + o.frequency.setValueAtTime(freq, at); + g.gain.setValueAtTime(0.0001, at); + g.gain.exponentialRampToValueAtTime(gain, at + 0.01); + g.gain.exponentialRampToValueAtTime(0.0001, at + dur); + o.connect(g).connect(a.destination); + o.start(at); + o.stop(at + dur + 0.03); +} + +function noise(a: AudioContext, at: number, dur: number, gain: number, band: number): void { + const len = Math.max(1, Math.ceil(a.sampleRate * dur)); + const buf = a.createBuffer(1, len, a.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len); + const src = a.createBufferSource(); + src.buffer = buf; + const f = a.createBiquadFilter(); + f.type = "bandpass"; + f.frequency.value = band; + const g = a.createGain(); + g.gain.value = gain; + src.connect(f).connect(g).connect(a.destination); + src.start(at); +} + +function sample(name: string, volume: number, rate = 1, fallback?: (a: AudioContext) => void): void { + const a = mgAudio(); + if (!a) return; + void loadBuffer(name).then((buffer) => { + if (!buffer) return fallback?.(a); + const src = a.createBufferSource(); + src.buffer = buffer; + src.playbackRate.value = rate; + const g = a.createGain(); + g.gain.value = volume; + src.connect(g).connect(a.destination); + src.start(); + }); +} + +export const mgSound = { + /** 倒數 3、2、1 */ + count() { + const a = mgAudio(); + if (a) tone(a, 660, a.currentTime, 0.12, "square", 0.045); + }, + /** 開始! */ + go() { + const a = mgAudio(); + if (!a) return; + tone(a, 988, a.currentTime, 0.1, "square", 0.05); + tone(a, 1319, a.currentTime + 0.08, 0.28, "square", 0.05); + }, + /** 最後幾秒的滴答 */ + tick() { + sample("sfx/timer-tick", 0.6, 1, (a) => tone(a, 1500, a.currentTime, 0.04, "square", 0.04)); + }, + /** 時間到 */ + timesUp() { + sample("sfx/gong-bright", 0.35, 1, (a) => tone(a, 220, a.currentTime, 0.6, "triangle", 0.1)); + }, + /** 結算時一顆一顆亮起來的星星:越後面越高音 */ + star(i: number) { + sample("sfx/bell-ding", 0.45, 1 + i * 0.16, (a) => tone(a, 880 * (1 + i * 0.16), a.currentTime, 0.25, "triangle", 0.08)); + }, + /** 新紀錄、解鎖 */ + record() { + sample("sfx/jingle-steel-up", 0.55); + }, + /** 0 星 */ + flop() { + sample("sfx/jingle-tuba-sad", 0.35); + }, + /** 點錯(點到路人、壓到施工) */ + wrong() { + sample("sfx/buzz-short", 0.4, 1, (a) => tone(a, 180, a.currentTime, 0.12, "sawtooth", 0.05)); + }, + /** 相機快門(被記者拍到) */ + shutter() { + const a = mgAudio(); + if (!a) return; + noise(a, a.currentTime, 0.035, 0.35, 3200); + noise(a, a.currentTime + 0.07, 0.05, 0.3, 2200); + }, +}; diff --git a/web/src/game/minigames/types.ts b/web/src/game/minigames/types.ts new file mode 100644 index 0000000..34059e3 --- /dev/null +++ b/web/src/game/minigames/types.ts @@ -0,0 +1,96 @@ +/** + * 選戰小遊戲(docs/23)的共用介面。每個小遊戲 20–40 秒,玩完回報 0–100 分, + * 分數怎麼換成票數、聲勢由伺服器決定(下一站「小遊戲」)。 + * + * 三個遊戲的分數意義一致:隨手玩約 40–60、玩得好 80–95、滿分要幾乎全對。 + * 星等:40 分 1 星、70 分 2 星、90 分 3 星(starsFor)。 + */ +export interface MiniGameProps { + /** 同一個種子,關卡配置一樣 */ + seed: number; + /** 難度 0–1(第 1 週 0.1、第 7 週 0.9;大廳的新手 0.2、老手 0.55、選戰老將 0.9) */ + level: number; + townName?: string | null; + /** 0–100 的整數,玩完、按結束畫面的按鈕(預設「回到選戰」)才呼叫一次 */ + onFinish: (score: number) => void; + /** 不玩了(不給分) */ + onQuit?: () => void; + /** 蓋掉遊戲名稱(例如「大絕招・選前之夜大造勢」) */ + title?: string; + /** 蓋掉開始畫面的獎勵說明 */ + reward?: string; + /** 結束畫面按鈕的字,預設「回到選戰」 */ + exitLabel?: string; + /** 只有小遊戲大廳會給:最佳紀錄、難度選擇、再玩一次。選戰和大絕招不給,就只能玩一次 */ + practice?: PracticeOptions; +} + +/** 大廳練習用的選項(選戰裡不給) */ +export interface PracticeOptions { + /** 難度名稱,顯示在名牌上(新手、老手、選戰老將) */ + tierLabel: string; + /** 這個難度目前的最佳分數(還沒玩過=null)。開始那一刻記下來,結束時比對是不是新紀錄 */ + best: number | null; + /** 開始畫面的難度按鈕 */ + tiers?: readonly TierChoice[]; + /** 下一級難度的名稱:這一局拿到 2 星就解鎖(已經解鎖或沒有下一級=null) */ + unlocks?: string | null; + /** 一開始就倒數(「再玩一次」不用再看一次規則) */ + autoStart?: boolean; + /** 遊戲一結束就呼叫一次(存最佳紀錄) */ + onResult: (score: number) => void; + /** 再玩一次(換一個新關卡) */ + onReplay: () => void; +} + +export interface TierChoice { + label: string; + /** 這個難度拿過的最高星數 */ + stars: number; + /** 鎖住的原因(解鎖了=null) */ + locked: string | null; + selected: boolean; + onPick: () => void; +} + +export const GAME_IDS = ["handshake", "rally", "billboard"] as const; +export type GameId = (typeof GAME_IDS)[number]; + +export interface MiniGameMeta { + id: GameId; + title: string; + /** 一段話的規則(舊欄位,保留相容) */ + rules: string; + /** 獎勵說明(選戰裡) */ + reward: string; + /** 一句話玩法(大廳卡片) */ + pitch: string; + /** 開始畫面的玩法步驟(三行) */ + steps: readonly string[]; + /** 操作方式(觸控、滑鼠、鍵盤) */ + controls: string; +} + +/** 可重現的亂數(mulberry32):同一個種子產生同一串數字 */ +export function mulberry32(seed: number): () => number { + let a = seed >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export const clampScore = (x: number): number => (Number.isFinite(x) ? Math.max(0, Math.min(100, Math.round(x))) : 0); + +/** 星等門檻:40/70/90 分 */ +export const STAR_CUTS = [40, 70, 90] as const; + +export function starsFor(score: number): 0 | 1 | 2 | 3 { + const s = clampScore(score); + return s >= STAR_CUTS[2] ? 3 : s >= STAR_CUTS[1] ? 2 : s >= STAR_CUTS[0] ? 1 : 0; +} + +export const reducedMotion = (): boolean => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; diff --git a/web/src/game/minigames/useRound.ts b/web/src/game/minigames/useRound.ts new file mode 100644 index 0000000..3d6585c --- /dev/null +++ b/web/src/game/minigames/useRound.ts @@ -0,0 +1,195 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { mgSound } from "./sound.ts"; + +export type Phase = "intro" | "play" | "done"; +/** 遊戲中的停頓:count=3-2-1 倒數中、pause=暫停中 */ +export type Hold = "count" | "pause" | null; + +/** 倒數每一步多久(3、2、1、開始!) */ +export const COUNT_STEP_MS = 650; + +export interface RoundOptions { + /** 遊戲長度(毫秒),時間到自動結束 */ + durationMs: number; + /** 第一次開始前要不要 3-2-1(節奏遊戲自己跟著鼓點數拍,設 false);暫停回來一律會倒數 */ + countdown?: boolean; + /** elapsed 的更新間隔(毫秒);0=每一幀 */ + stepMs?: number; + /** 從暫停回來時倒退幾毫秒(節奏遊戲讓玩家重新抓拍子) */ + rewindMs?: number; + /** 真正開始前的緩衝(毫秒):讓音訊排程趕得上 */ + leadMs?: number; + /** 時鐘開始跑(含暫停後繼續):從第幾毫秒、幾毫秒後開始 */ + onRun?: (fromMs: number, leadMs: number) => void; + /** 時鐘停下來(暫停、結束、離開) */ + onHalt?: () => void; +} + +export interface Round { + phase: Phase; + hold: Hold; + /** 倒數到幾:3、2、1,0=「開始!」,null=沒有在倒數 */ + count: number | null; + /** 從開始到現在幾毫秒(不含暫停) */ + elapsed: number; + /** 現在可以操作:遊戲中、沒有暫停、沒有在倒數 */ + live: boolean; + /** 提前結束(例如看板按了「完成」) */ + endedEarly: boolean; + /** 精確的現在時間(判定用,不等下一幀) */ + now: () => number; + start: () => void; + pause: () => void; + resume: () => void; + finish: (early?: boolean) => void; +} + +/** + * 一局小遊戲的時鐘:開始畫面 → 3-2-1 → 遊戲中(可暫停)→ 結束。 + * 分頁切到背景時自動暫停;暫停回來再倒數一次,不會一回來就漏掉東西。 + */ +export function useRound(options: RoundOptions): Round { + const opts = useRef(options); + opts.current = options; + const [phase, setPhaseState] = useState("intro"); + const [hold, setHoldState] = useState(null); + const [count, setCount] = useState(null); + const [elapsed, setElapsed] = useState(0); + const [endedEarly, setEndedEarly] = useState(false); + const phaseRef = useRef("intro"); + const holdRef = useRef(null); + const base = useRef(0); + const frozen = useRef(0); + const running = useRef(false); + + const setPhase = (p: Phase) => { + phaseRef.current = p; + setPhaseState(p); + }; + const setHold = (h: Hold) => { + holdRef.current = h; + setHoldState(h); + }; + + const now = useCallback(() => (running.current ? performance.now() - base.current : frozen.current), []); + + const run = useCallback(() => { + const lead = opts.current.leadMs ?? 0; + base.current = performance.now() + lead - frozen.current; + running.current = true; + setHold(null); + opts.current.onRun?.(frozen.current, lead); + }, []); + + const halt = useCallback(() => { + if (!running.current) return; + frozen.current = Math.max(0, performance.now() - base.current); + running.current = false; + opts.current.onHalt?.(); + }, []); + + const beginCount = useCallback(() => { + setHold("count"); + setCount(3); + mgSound.count(); + }, []); + + const start = useCallback(() => { + if (phaseRef.current !== "intro") return; + frozen.current = 0; + setElapsed(0); + setPhase("play"); + if (opts.current.countdown === false) run(); + else beginCount(); + }, [run, beginCount]); + + const finish = useCallback( + (early = false) => { + if (phaseRef.current !== "play") return; + halt(); + setPhase("done"); + setHold(null); + setCount(null); + setEndedEarly(early); + }, + [halt], + ); + + const pause = useCallback(() => { + if (phaseRef.current !== "play" || holdRef.current === "pause") return; + halt(); + setHold("pause"); + setCount(null); + }, [halt]); + + const resume = useCallback(() => { + if (phaseRef.current !== "play" || holdRef.current !== "pause") return; + frozen.current = Math.max(0, frozen.current - (opts.current.rewindMs ?? 0)); + setElapsed(frozen.current); + beginCount(); + }, [beginCount]); + + // 3-2-1:每 650 毫秒換一個數字,「開始!」那一刻時鐘起跑 + useEffect(() => { + if (hold !== "count") return; + const ids = [ + setTimeout(() => (setCount(2), mgSound.count()), COUNT_STEP_MS), + setTimeout(() => (setCount(1), mgSound.count()), COUNT_STEP_MS * 2), + setTimeout(() => { + setCount(0); + mgSound.go(); + run(); + }, COUNT_STEP_MS * 3), + ]; + return () => ids.forEach(clearTimeout); + }, [hold, run]); + + // 「開始!」顯示一下就收掉 + useEffect(() => { + if (count !== 0) return; + const id = setTimeout(() => setCount((c) => (c === 0 ? null : c)), 650); + return () => clearTimeout(id); + }, [count]); + + // 遊戲中每一幀更新時間;時間到自動結束 + useEffect(() => { + if (phase !== "play" || hold !== null) return; + let raf = 0; + const tick = () => { + const t = now(); + const d = opts.current.durationMs; + const step = opts.current.stepMs ?? 0; + const shown = Math.min(t, d); + setElapsed(step > 0 && t < d ? Math.floor(shown / step) * step : shown); + if (t >= d) { + finish(false); + return; + } + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [phase, hold, now, finish]); + + // 切到別的分頁、鎖螢幕:自動暫停 + useEffect(() => { + const onVis = () => { + if (document.hidden) pause(); + }; + document.addEventListener("visibilitychange", onVis); + return () => document.removeEventListener("visibilitychange", onVis); + }, [pause]); + + // 離開畫面:停掉時鐘(節奏遊戲會停鼓聲) + useEffect( + () => () => { + if (running.current) { + running.current = false; + opts.current.onHalt?.(); + } + }, + [], + ); + + return { phase, hold, count, elapsed, live: phase === "play" && hold === null, endedEarly, now, start, pause, resume, finish }; +} diff --git a/web/src/game/news/channels.ts b/web/src/game/news/channels.ts new file mode 100644 index 0000000..0396e16 --- /dev/null +++ b/web/src/game/news/channels.ts @@ -0,0 +1,22 @@ +/** + * 遊戲裡的新聞台。台名是諧音惡搞,台標、配色都是原創,不用真實電視台的商標(docs/14)。 + */ +export interface Channel { + id: string; + /** 遙控器上的頻道號碼 */ + number: number; + name: string; + short: string; + /** 台標底色與字色 */ + color: string; + ink: string; + /** 這台比較捧誰(政黨名稱);null 是不分藍綠的網路台 */ + lean: string | null; + slogan: string; +} + +export const CHANNELS: readonly Channel[] = [ + { id: "zy", number: 52, name: "中夭新聞台", short: "中夭", color: "#1d4fa3", ink: "#fff", lean: "中國國民黨", slogan: "夭壽快的第一手消息" }, + { id: "sl", number: 54, name: "三粒新聞台", short: "三粒", color: "#0f8a4a", ink: "#fff", lean: "民主進步黨", slogan: "一粒接一粒的獨家" }, + { id: "xm", number: 0, name: "鄉民直播台", short: "鄉民", color: "#111419", ink: "#ffd23f", lean: null, slogan: "推文比新聞還快" }, +]; diff --git a/web/src/game/parties.ts b/web/src/game/parties.ts new file mode 100644 index 0000000..fdb2094 --- /dev/null +++ b/web/src/game/parties.ts @@ -0,0 +1,48 @@ +import { PARTY_RECORDS, type PartyRecord } from "@election2026/protocol"; + +/** + * 政黨(18 第 52 項):台灣歷屆選舉推出過候選人的政黨都可以選(清單在 protocol/parties.ts,中選會資料)。 + * 民進黨、國民黨、民眾黨用真實政黨色(tokens.css 的 slot 色);其他政黨的政黨色一律用灰色。 + * 黨旗另外看 PartyFlag.tsx:有查證過黨旗的政黨都畫(不只三黨)。 + * 選票模型裡只有這三黨有自己的選民槽位,其他政黨和無黨籍一樣算「其他」。 + */ + +const SLOT: Record = { 民主進步黨: "a", 中國國民黨: "b", 台灣民眾黨: "c" }; + +/** 常見的簡稱;沒有的就用全名 */ +const SHORT: Record = { + 民主進步黨: "民進黨", + 中國國民黨: "國民黨", + 台灣民眾黨: "民眾黨", + 台灣團結聯盟: "台聯", + 無黨團結聯盟: "無盟", + 時代力量: "時力", + 台灣基進: "基進", + 社會民主黨: "社民黨", + 中華統一促進黨: "統促黨", +}; + +export const partySlot = (party: string | null): "a" | "b" | "c" | "other" => (party && SLOT[party]) || "other"; +export const partyColor = (party: string | null): string => `var(--slot-${partySlot(party)})`; +export const partyShort = (party: string | null): string => (party ? (SHORT[party] ?? party) : "無黨籍"); + +/** 畫面上直接列出來的政黨:三大黨,再加上 2020 年以後還有推人參選、推出候選人最多的幾個(其他的用搜尋找) */ +export const FEATURED_PARTIES: readonly string[] = [ + ...Object.keys(SLOT), + ...PARTY_RECORDS.filter((p) => !SLOT[p.name] && (p.last ?? 0) >= 2020) + .slice(0, 6) + .map((p) => p.name), +]; + +/** 「2001–2024 年推出 562 人、當選 203 人」 */ +export function partyFacts(p: PartyRecord): string { + const years = p.first && p.last ? (p.first === p.last ? `${p.first} 年` : `${p.first}–${p.last} 年`) : ""; + return `${years}推出 ${p.candidates.toLocaleString()} 人、當選 ${p.elected.toLocaleString()} 人`; +} + +/** 依名字或簡稱搜尋政黨 */ +export function searchParties(q: string): readonly PartyRecord[] { + const t = q.trim(); + if (!t) return PARTY_RECORDS; + return PARTY_RECORDS.filter((p) => p.name.includes(t) || (SHORT[p.name] ?? "").includes(t)); +} diff --git a/web/src/game/people/Credentials.tsx b/web/src/game/people/Credentials.tsx new file mode 100644 index 0000000..d6d78e0 --- /dev/null +++ b/web/src/game/people/Credentials.tsx @@ -0,0 +1,169 @@ +import type { ElectionRun } from "@election2026/protocol"; +import { ChevronLeft, ChevronRight } from "lucide-react"; +import { useRef, useState, type CSSProperties } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { pct } from "../format.ts"; +import { PartyFlag } from "../PartyFlag.tsx"; +import { isPartyList, kind, mateLabel, partyColor, place } from "./shared.ts"; + +/** + * 歷年參選證:每一次參選一張(中選會選舉資料庫的紀錄:年份、選舉、選區、號次、政黨、得票、當選與否)。 + * 總統副總統多一行「搭檔」,副總統的得票是同一組的票;不分區立委左邊大字是名單排名,得票欄寫政黨票。 + * 最新的在最前面;左右滑或按箭頭翻,上面一排年份可以直接跳。沒收集到的人整排是灰的,字一樣看得清楚。 + */ +export function Credentials({ name, runs, fileNo, gray }: { name: string; runs: readonly ElectionRun[]; fileNo: string; gray: boolean }) { + const list = [...runs].reverse(); + const stripRef = useRef(null); + const [index, setIndex] = useState(0); + + const go = (i: number) => { + const strip = stripRef.current; + const card = strip?.children[i] as HTMLElement | undefined; + if (!strip || !card) return; + sfx.flip(); + const smooth = !matchMedia("(prefers-reduced-motion: reduce)").matches; + strip.scrollTo({ left: card.offsetLeft - strip.offsetLeft - 2, behavior: smooth ? "smooth" : "auto" }); + setIndex(i); + }; + const onScroll = () => { + const strip = stripRef.current; + if (!strip || list.length < 2) return; + const step = strip.scrollWidth / list.length; + setIndex(Math.min(list.length - 1, Math.max(0, Math.round(strip.scrollLeft / step)))); + }; + + return ( +
+
+

歷年參選證

+ {list.length > 1 && ( +
+ + + {index + 1}/{list.length} + + +
+ )} +
+ {list.length > 1 && ( +
+ {list.map((r, i) => ( + + ))} +
+ )} +
    + {list.map((r, i) => { + const listed = isPartyList(r); + const mate = mateLabel(r); + return ( +
  1. +
    + + {r.year} 參選證 + + 投票日 {r.date} +
    +
    +
    + {listed ? "名單" : "號次"} + {(listed ? r.listRank : r.number) ?? "—"} +
    +
    +
    +
    姓名
    +
    {name}
    +
    +
    +
    選舉
    +
    {kind(r)}
    +
    +
    +
    選區
    +
    {place(r)}
    +
    + {mate && ( +
    +
    搭檔
    +
    {mate}
    +
    + )} +
    +
    政黨
    +
    + {r.party ?? "無黨籍"} + {listed && ( + + 名單第 {r.listRank} 名{r.number !== null && <>・政黨號次 {r.number}} + + )} +
    +
    +
    +
    得票
    + {listed ? ( +
    + 不分區沒有個人得票; + + 政黨票 {r.partyVotes === undefined ? "—" : r.partyVotes.toLocaleString("en-US")} 票 + + {r.partyShare !== undefined && ( + + ({pct(r.partyShare, 2)}) + + )} +
    + ) : ( +
    + {r.votes === null ? "—" : r.votes.toLocaleString("en-US")} 票 + {r.share !== null && ( + + (得票率 {pct(r.share, 2)}) + + )} + {r.election === "副總統" && 正副總統同一組的票} +
    + )} +
    +
    +
    結果
    +
    + {r.elected ? "當選" : "未當選"} + {r.incumbent && 現任} +
    +
    +
    +
    +
    + No.{fileNo}-{r.year} +
    + {r.elected && ( + + 當選 + + )} +
  2. + ); + })} +
+
+ ); +} diff --git a/web/src/game/people/FileCard.tsx b/web/src/game/people/FileCard.tsx new file mode 100644 index 0000000..008b972 --- /dev/null +++ b/web/src/game/people/FileCard.tsx @@ -0,0 +1,81 @@ +import type { PersonRecordSummary } from "@election2026/protocol"; +import { Sparkles } from "lucide-react"; +import type { CSSProperties } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { PartyFlag } from "../PartyFlag.tsx"; +import type { PlayedCandidate } from "../rogue/progress.ts"; +import { COVERAGE, fileNo, nameLength, partyColor, SOURCE_NOTE } from "./shared.ts"; + +/** + * 一份檔案夾(收集卡):政黨分類色條+政黨名、名字貼紙、當選章。 + * 玩過這位參選人=彩色,再貼一張「玩過 N 次・最佳評等」;沒玩過=灰階、淡一點,字一樣看得清楚。 + */ +export function FileCard({ p, index, active, played }: { p: PersonRecordSummary; index: number; active: boolean; played: PlayedCandidate | undefined }) { + const span = p.firstYear !== p.lastYear ? `${p.firstYear}–${p.lastYear}` : `${p.firstYear}`; + return ( +
  • + !active && sfx.paper()} + > + + + {p.party ?? "無黨籍"} + + + + 5 ? " is-long" : ""}`}>{p.name} + {p.wins > 0 && ( + + 當選 + + {p.wins}次 + + + )} + + {p.latest} + + + 參選 {p.runs} 次・{span} + + + No.{fileNo(p.id)} + + + {played && ( + + + 玩過 {played.runs} 次{played.grade ? `・最佳 ${played.grade}` : ""} + + )} + {p.confidence === "low" && 比對信心:低} + + +
  • + ); +} + +/** 閱覽桌還沒打開檔案時:一疊檔案夾+說明 */ +export function DeskIdle({ collected }: { collected: number | null }) { + return ( +
    +
    + + + +
    +

    點一份檔案夾,在這裡打開

    +

    每份檔案有歷年參選證,和五項資歷分數(附依據、算法與出處)。

    +

    + 玩過的參選人是彩色的,沒玩過的是灰的;目前收集 {collected ?? "…"} 位,都在「收集冊」。 +

    +

    {COVERAGE}

    +

    {SOURCE_NOTE}

    +
    + ); +} diff --git a/web/src/game/people/PeopleFilters.tsx b/web/src/game/people/PeopleFilters.tsx new file mode 100644 index 0000000..106e98f --- /dev/null +++ b/web/src/game/people/PeopleFilters.tsx @@ -0,0 +1,242 @@ +import type { ElectionOffice } from "@election2026/protocol"; +import { ChevronDown, RotateCcw, Search, X } from "lucide-react"; +import { useEffect, useRef, type ReactNode } from "react"; +import { sfx } from "../audio/sfx.ts"; + +/** 目前的 22 個縣市(舊縣市的紀錄已對到改制後的代碼,例如臺北縣 → 新北市);前 6 個是直轄市 */ +export const COUNTIES: readonly [string, string][] = [ + ["63000", "臺北市"], + ["65000", "新北市"], + ["68000", "桃園市"], + ["66000", "臺中市"], + ["67000", "臺南市"], + ["64000", "高雄市"], + ["10017", "基隆市"], + ["10018", "新竹市"], + ["10020", "嘉義市"], + ["10002", "宜蘭縣"], + ["10004", "新竹縣"], + ["10005", "苗栗縣"], + ["10007", "彰化縣"], + ["10008", "南投縣"], + ["10009", "雲林縣"], + ["10010", "嘉義縣"], + ["10013", "屏東縣"], + ["10014", "臺東縣"], + ["10015", "花蓮縣"], + ["10016", "澎湖縣"], + ["09020", "金門縣"], + ["09007", "連江縣"], +]; +const COUNTY_GROUPS: readonly [string, readonly [string, string][]][] = [ + ["直轄市", COUNTIES.slice(0, 6)], + ["其他縣市", COUNTIES.slice(6)], +]; +const countyName = (code: string): string => COUNTIES.find(([c]) => c === code)?.[1] ?? "全部"; + +export interface Filters { + county: string; + office: "" | ElectionOffice; + year: string; + q: string; + page: number; +} +export const EMPTY_FILTERS: Filters = { county: "", office: "", year: "", q: "", page: 1 }; + +export type Tray = "county" | "year" | null; + +const OFFICES: readonly { value: Filters["office"]; label: string; sub: string }[] = [ + { value: "", label: "全部", sub: "所有選舉" }, + { value: "president", label: "總統", sub: "總統・副總統" }, + { value: "legislator", label: "立委", sub: "區域・原住民・不分區" }, + { value: "mayor", label: "首長", sub: "縣市長・省長" }, + { value: "councilor", label: "議員", sub: "直轄市・縣市・省議員" }, +]; + +/** 檔案櫃上方的分類標籤:全部/總統/立委/首長/議員(選舉種類),最後一張是自己的收集冊 */ +export function OfficeTabs({ + value, + mine, + collected, + onChange, + onMine, +}: { + value: Filters["office"]; + mine: boolean; + collected: number | null; + onChange: (v: Filters["office"]) => void; + onMine: () => void; +}) { + return ( +
    + {OFFICES.map((o) => ( + + ))} + +
    + ); +} + +/** + * 抽屜裡的一排索引貼:縣市、年份(點了拉出一盒索引卡)、名字標籤機(搜尋)、清除。 + * 拉出來的索引盒蓋在檔案上面;按 Esc、點旁邊或選好一張都會收回去(Esc 由 PeopleScreen 統一處理)。 + */ +export function IndexBar({ + filters, + years, + query, + onQuery, + tray, + onTray, + onPick, + onClear, +}: { + filters: Filters; + years: readonly number[]; + query: string; + onQuery: (q: string) => void; + tray: Tray; + onTray: (t: Tray) => void; + onPick: (patch: Partial) => void; + onClear: () => void; +}) { + const dirty = !!(filters.county || filters.office || filters.year || query.trim()); + const toggle = (t: Exclude) => { + sfx.click(); + onTray(tray === t ? null : t); + }; + const pick = (patch: Partial) => { + sfx.card(); + onPick(patch); + onTray(null); + }; + + return ( + <> +
    +
    + toggle("county")} /> + toggle("year")} /> + + {dirty && ( + + )} +
    + + {tray && + (tray === "county" ? ( + onTray(null)}> + pick({ county: "" })} wide> + 全部縣市 + + {COUNTY_GROUPS.map(([group, list]) => ( +
    + {group} +
    + {list.map(([code, name]) => ( + pick({ county: code })}> + {name} + + ))} +
    +
    + ))} +
    + ) : ( + onTray(null)}> + pick({ year: "" })} wide> + 全部年份 + +
    + {years.map((y) => ( + pick({ year: String(y) })} num> + {y} + + ))} +
    +
    + ))} +
    + {tray &&
    onTray(null)} />} + + ); +} + +function IndexSticker({ kind, label, value, open, onClick }: { kind: "county" | "year"; label: string; value: string; open: boolean; onClick: () => void }) { + return ( + + ); +} + +function TrayBox({ id, title, onClose, children }: { id: string; title: string; onClose: () => void; children: ReactNode }) { + const ref = useRef(null); + // 拉出來時把焦點放到目前選的那張(鍵盤可以直接換) + useEffect(() => { + const el = ref.current?.querySelector('[aria-pressed="true"]') ?? ref.current?.querySelector("button"); + el?.focus({ preventScroll: true }); + }, []); + return ( +
    +
    + {title} + +
    +
    {children}
    +
    + ); +} + +function TrayChip({ active, onClick, wide, num, children }: { active: boolean; onClick: () => void; wide?: boolean; num?: boolean; children: ReactNode }) { + return ( + + ); +} diff --git a/web/src/game/people/PeopleScreen.tsx b/web/src/game/people/PeopleScreen.tsx new file mode 100644 index 0000000..8f1c950 --- /dev/null +++ b/web/src/game/people/PeopleScreen.tsx @@ -0,0 +1,281 @@ +import type { PeopleListResponse, PersonRecordSummary } from "@election2026/protocol"; +import { Archive, ChevronLeft, ChevronRight, Sparkles } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { peopleApi } from "../api.ts"; +import { sfx } from "../audio/sfx.ts"; +import { backfillPlayed, playedCandidates, type PlayedCandidate } from "../rogue/progress.ts"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { DeskIdle, FileCard } from "./FileCard.tsx"; +import { EMPTY_FILTERS, IndexBar, OfficeTabs, type Filters, type Tray } from "./PeopleFilters.tsx"; +import { PersonDetail } from "./PersonDetail.tsx"; +import { COVERAGE, SOURCE_NOTE } from "./shared.ts"; +import "./people.css"; + +/** #/people/ 打開某個人的檔案夾;#/people 是檔案櫃 */ +const idFromHash = (): string | null => /^#\/people\/(r-[0-9a-f]{10})$/.exec(location.hash)?.[1] ?? null; + +/** 窄螢幕:檔案夾整個蓋上來(寬螢幕在右邊的閱覽桌打開) */ +const OVERLAY_QUERY = "(max-width: 1023px)"; + +type Played = Record; + +/** 玩過的名字 → 資料庫裡同名的人(同名不同人很少,先一起算) */ +async function findCollected(played: Played): Promise { + const lists = await Promise.all( + Object.keys(played).map((name) => + peopleApi + .list({ q: name }) + .then((r) => r.people.filter((p) => p.name === name)) + .catch(() => []), + ), + ); + return lists.flat().sort((a, b) => b.lastYear - a.lastYear || a.name.localeCompare(b.name, "zh-Hant")); +} + +/** + * 選舉檔案室(#/people):歷屆縣市長、議員(1994–2022)、總統副總統(1996–2024)、立委(1995–2024)的選舉紀錄, + * 做成一本收集卡冊。分類標籤:全部/總統/立委/首長/議員+收集冊。 + * 左邊是檔案櫃(分類標籤、索引貼、名字標籤機,一份份檔案夾),右邊是閱覽桌(打開的檔案夾); + * 手機版檔案夾直接蓋上來。整頁不捲,只有檔案夾清單和檔案內容自己捲。 + * 玩過的參選人(rogue/progress.ts 記的名字)是彩色卡,沒玩過的是灰卡;「收集冊」只列玩過的。 + */ +export function PeopleScreen() { + const [filters, setFilters] = useState(EMPTY_FILTERS); + const [query, setQuery] = useState(""); // 標籤機上的字;停打 300ms 才送出 + const [data, setData] = useState(null); + const [allTotal, setAllTotal] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + const [selected, setSelected] = useState(idFromHash); + const [tray, setTray] = useState(null); + const [mine, setMine] = useState(false); + const [played, setPlayed] = useState(playedCandidates); + const [collected, setCollected] = useState(null); + const filesRef = useRef(null); + const lastOpened = useRef(null); + + useEffect(() => { + const onHash = () => setSelected(idFromHash()); + addEventListener("hashchange", onHash); + return () => removeEventListener("hashchange", onHash); + }, []); + + // 先用存檔畫,再等舊的局補算完更新 + useEffect(() => { + let alive = true; + backfillPlayed() + .then((p) => alive && setPlayed(p)) + .catch(() => undefined); + return () => { + alive = false; + }; + }, []); + + useEffect(() => { + let alive = true; + findCollected(played).then((list) => alive && setCollected(list)); + return () => { + alive = false; + }; + }, [played]); + + // 收起檔案夾:焦點回到剛剛那份檔案夾(還在這一頁的話) + useEffect(() => { + if (selected) { + lastOpened.current = selected; + return; + } + const id = lastOpened.current; + lastOpened.current = null; + const card = id ? filesRef.current?.querySelector(`[data-id="${id}"]`) : null; + if (!card) return; + card.focus({ preventScroll: true }); + card.scrollIntoView({ block: "nearest" }); + }, [selected]); + + useEffect(() => { + const t = setTimeout(() => setFilters((f) => (f.q === query.trim() ? f : { ...f, q: query.trim(), page: 1 })), 300); + return () => clearTimeout(t); + }, [query]); + + useEffect(() => { + let alive = true; + setLoading(true); + const unfiltered = !filters.county && !filters.office && !filters.year && !filters.q; + peopleApi + .list({ + county: filters.county || undefined, + office: filters.office || undefined, + year: filters.year ? Number(filters.year) : undefined, + q: filters.q || undefined, + page: filters.page, + }) + .then((res) => { + if (!alive) return; + setData(res); + setError(null); + if (unfiltered) setAllTotal(res.total); + filesRef.current?.scrollTo({ top: 0 }); + }) + .catch((e: unknown) => alive && setError(e instanceof Error ? e.message : String(e))) + .finally(() => alive && setLoading(false)); + return () => { + alive = false; + }; + }, [filters]); + + const close = () => { + sfx.paper(); + location.hash = "#/people"; + }; + + // Esc:先收索引盒,再收檔案夾 + useEffect(() => { + if (!tray && !selected) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + if (tray) setTray(null); + else close(); + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }, [tray, selected]); + + const set = (patch: Partial) => { + setMine(false); + setFilters((f) => ({ ...f, ...patch, page: patch.page ?? 1 })); + }; + const clear = () => { + setQuery(""); + setFilters(EMPTY_FILTERS); + }; + const openMine = () => { + setTray(null); + setMine(true); + filesRef.current?.scrollTo({ top: 0 }); + }; + const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1; + const filtered = !!(filters.county || filters.office || filters.year || filters.q); + const overlay = typeof matchMedia === "function" && matchMedia(OVERLAY_QUERY).matches; + const count = collected?.length ?? null; + const status = mine ? `收集冊:${count ?? 0} 位` : loading ? "讀取中" : data ? `找到 ${data.total} 份檔案,第 ${filters.page} 頁,共 ${pages} 頁` : ""; + + return ( + } value={`${count ?? "…"}/${allTotal?.toLocaleString("en-US") ?? "…"}`} label="收集" />} + > +
    +
    + set({ office })} onMine={openMine} /> +
    + {mine ? ( +
    + +

    + 玩過的真實參選人會變成彩色卡收進這裡(用名字比對資料庫)。目前收集 {count ?? "…"} 位。 +

    +
    + ) : ( + + )} +

    + {status} +

    +
    + {mine ? ( + + ) : error ? ( +

    {error}

    + ) : !data ? ( +

    打開檔案櫃中…

    + ) : data.total === 0 ? ( +
    + {filtered ? ( + <> +

    這個抽屜裡沒有符合的檔案,換個條件試試。

    + + + ) : ( +

    沒有符合的人。資料庫還沒產生時請在 backend/data/pipeline 執行 election-data records。

    + )} +
    + ) : ( + <> +

    + 這一櫃 {data.total.toLocaleString("en-US")} 份・彩色的是你玩過的 +

    +
      + {data.people.map((p, i) => ( + + ))} +
    + + )} +

    + {COVERAGE} +
    + {SOURCE_NOTE} +

    +
    + {!mine && data && data.total > 0 && ( + + )} +
    +
    + + +
    +
    + ); +} + +/** 收集冊:只列玩過的參選人(彩色卡) */ +function MineGrid({ collected, played, selected }: { collected: PersonRecordSummary[] | null; played: Played; selected: string | null }) { + if (!collected) return

    整理收集冊中…

    ; + if (collected.length === 0) + return ( +
    +

    收集冊還是空的。

    +

    在選戰裡扮演真實參選人打完一局,那位參選人的檔案就會變成彩色卡收進來。

    + + 去選戰 + +
    + ); + return ( +
      + {collected.map((p, i) => ( + + ))} +
    + ); +} diff --git a/web/src/game/people/PersonDetail.tsx b/web/src/game/people/PersonDetail.tsx new file mode 100644 index 0000000..296d274 --- /dev/null +++ b/web/src/game/people/PersonDetail.tsx @@ -0,0 +1,180 @@ +import type { PersonRecordResponse } from "@election2026/protocol"; +import { Sparkles, X } from "lucide-react"; +import { useEffect, useRef, useState, type CSSProperties } from "react"; +import { peopleApi } from "../api.ts"; +import { PartyFlag } from "../PartyFlag.tsx"; +import type { PlayedCandidate } from "../rogue/progress.ts"; +import { Credentials } from "./Credentials.tsx"; +import { fileNo, firstChar, nameLength, partyColor, SCORE_NOTE, SOURCE_NOTE } from "./shared.ts"; + +export { SCORE_NOTE, SOURCE_NOTE }; + +type Person = PersonRecordResponse["person"]; +type Played = Readonly>; + +/** 一個人的檔案夾:讀資料,打開時把焦點放到名字上 */ +export function PersonDetail({ id, played, onClose, focusOnOpen }: { id: string; played: Played; onClose: () => void; focusOnOpen: boolean }) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + let alive = true; + setData(null); + setError(null); + peopleApi + .get(id) + .then((res) => alive && setData(res)) + .catch((e: unknown) => alive && setError(e instanceof Error ? e.message : String(e))); + return () => { + alive = false; + }; + }, [id]); + + return ; +} + +/** 打開的檔案夾(資料由 PersonDetail 讀進來):名字章、收集狀態、歷年參選證、五項資歷分數、出處 */ +export function PersonView({ + id, + data, + error, + played, + onClose, + focusOnOpen = false, +}: { + id: string; + data: PersonRecordResponse | null; + error: string | null; + played: Played; + onClose: () => void; + focusOnOpen?: boolean; +}) { + const p = data?.person; + const mine = p ? played[p.name] : undefined; + const nameRef = useRef(null); + useEffect(() => { + if (p && focusOnOpen) nameRef.current?.focus({ preventScroll: true }); + }, [p, focusOnOpen]); + + return ( +
    +
    + 檔案 + No.{fileNo(id)} +
    +
    + + {!p ? ( +

    {error ?? "翻找檔案中…"}

    + ) : ( + <> +
    + + {firstChar(p.name)} + +
    +

    6 ? "is-long" : undefined}> + {p.name} +

    +

    + {p.parties.map((party) => ( + + {party ?? "無黨籍"} + + ))} + {p.birthYear && {p.birthYear} 年生} +

    +

    + + 參選 {p.stats.runs} 次・當選 {p.stats.wins} 次・ + + {p.stats.firstYear !== p.stats.lastYear ? `${p.stats.firstYear}–${p.stats.lastYear}` : p.stats.firstYear} +

    +
    +
    + +
    +

    + {mine ? ( + <> + + + 已收集:你玩過 {mine.runs} 次{mine.grade ? `・最佳評等 ${mine.grade}` : ""} + + + ) : ( + 還沒收集:在選戰劇本裡扮演這位參選人打完一局,檔案就會上色(不是每位參選人都有劇本)。 + )} +

    + {p.confidence === "low" &&

    比對信心:低。{p.matchNote ?? "有一次參選的資料沒有出生年,是用同名、同縣市串起來的,可能不是同一個人。"}

    } + + +
    +

    {SOURCE_NOTE}

    +
      + {data.sources.map((s) => ( +
    • + {s.title} + {s.retrievedAt ? `(${s.retrievedAt} 取得)` : ""} + {s.license ? `・${s.license}` : ""} +
    • + ))} +
    +
    +
    + + )} +
    +
    + ); +} + +/** 五項資歷分數:每項附刻度條、依據、算法與出處 */ +function Scores({ scores }: { scores: Person["scores"] }) { + return ( +
    +

    資歷分數

    +

    {SCORE_NOTE}

    +

    每項 0–10 分,照固定公式算,附上代入的數字、算法與出處。

    +
      + {scores.map((s, i) => ( +
    • +
      + {s.label} + {s.value === null ? "無資料" : s.value.toFixed(1)} +
      +
      + {!!s.value && } +
      +

      {s.basis}

      +
      + 算法與出處 +

      + 算法: + {s.formula} +

      +

      + 出處: + {s.source} +

      +
      +
    • + ))} +
    +
    + ); +} diff --git a/web/src/game/people/people.css b/web/src/game/people/people.css new file mode 100644 index 0000000..4a27338 --- /dev/null +++ b/web/src/game/people/people.css @@ -0,0 +1,505 @@ +/* + * 選舉檔案室(#/people):GameScene 紙張背景上,左邊一座檔案櫃、右邊一張閱覽桌。 + * 沿用選戰文宣風——粗黑框、硬陰影、螢光黃、圈選章紅;檔案夾是牛皮紙色(木框色混進報紙底色)。 + * 動畫只動 transform、opacity;hover 只在滑鼠上生效;顏色全部來自 theme/tokens.css。 + */ + +.ppl { + --ppl-kraft: color-mix(in oklab, var(--board-wood) 40%, var(--newsprint)); + --ppl-kraft-deep: color-mix(in oklab, var(--board-wood) 62%, var(--newsprint)); +} +.ppl-num { font-family: var(--font-num); font-variant-numeric: tabular-nums; } +.ppl-sr { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } +.ppl-nowrap { white-space: nowrap; } +.ppl-party { display: inline-flex; align-items: center; gap: 5px; font-weight: 700; } + +/* ── 場景配置:手機一整座檔案櫃;寬螢幕右邊多一張閱覽桌 ── */ +.ppl-room { height: 100%; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr); } +.ppl-cabinet { min-width: 0; min-height: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); container: ppl-cabinet / inline-size; } +@media (min-width: 1024px) { + .ppl-room { grid-template-columns: minmax(0, 1fr) clamp(400px, 36vw, 540px); gap: 22px; } +} + +/* ── 分類標籤(選舉種類):插在抽屜上緣,選到的那張和抽屜連在一起 ── */ +/* 六張標籤(全部、總統、立委、首長、議員、收集冊):檔案櫃不夠寬時收掉小字(完整的寫在 title),再不夠就一起縮 */ +.ppl-tabs { display: flex; gap: 6px; padding-left: 20px; min-width: 0; } +.ppl-tab { + position: relative; z-index: 0; flex: 0 1 auto; min-height: 52px; min-width: 0; margin-bottom: -3px; padding: 6px 14px 12px; + display: grid; grid-template-columns: minmax(0, 1fr); justify-items: start; align-content: center; gap: 1px; text-align: left; + font: inherit; color: var(--ink); cursor: pointer; + background: var(--ppl-kraft); border: 3px solid var(--ink); border-bottom: 0; border-radius: 14px 14px 0 0; + transform: translateY(5px); transition: transform 180ms var(--ease-out); +} +.ppl-tab b { font-family: var(--font-serif); font-size: 19px; line-height: 1.1; } +.ppl-tab b { white-space: nowrap; } +.ppl-tab small { max-width: 100%; overflow: hidden; text-overflow: ellipsis; font-size: 11px; font-weight: 800; opacity: 0.8; white-space: nowrap; } +.ppl-tab[aria-pressed="true"] { z-index: 2; background: var(--surface); transform: none; } +.ppl-tab.is-mine { margin-left: auto; margin-right: 18px; } +.ppl-tab.is-mine[aria-pressed="false"] { background: var(--signal); color: var(--signal-ink); } +.ppl-tab:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; z-index: 3; } +@media (hover: hover) and (pointer: fine) { + .ppl-tab[aria-pressed="false"]:hover { transform: translateY(2px); } +} +@container ppl-cabinet (max-width: 759px) { + .ppl-tab small { display: none; } + .ppl-tab { padding-inline: 12px; } +} + +/* ── 抽屜:上面一排索引貼、中間一格格檔案夾(自己捲)、下面換頁 ── */ +.ppl-drawer { + position: relative; z-index: 1; min-height: 0; + display: grid; grid-template-rows: auto minmax(0, 1fr) auto; + background: var(--surface); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--shadow-ink); +} + +.ppl-index { position: relative; z-index: 3; padding: 12px 14px; border-bottom: 3px solid var(--ink); border-radius: 15px 15px 0 0; background: var(--surface); } +.ppl-index-row { display: flex; flex-wrap: wrap; align-items: stretch; gap: 10px; } + +/* 索引貼:上緣圓、下緣方,像貼在抽屜上的分類貼紙 */ +.ppl-sticker { + position: relative; min-height: 52px; min-width: 104px; padding: 4px 32px 5px 12px; + display: grid; justify-items: start; align-content: center; text-align: left; + font: inherit; color: var(--signal-ink); cursor: pointer; + background: var(--signal); border: 3px solid var(--ink); border-radius: 12px 12px 4px 4px; box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.ppl-sticker.is-year { background: var(--surface); color: var(--ink); box-shadow: inset 0 5px 0 var(--stamp), 3px 3px 0 var(--shadow-ink); padding-top: 8px; } +.ppl-sticker small { font-size: 11px; font-weight: 800; letter-spacing: 0.12em; opacity: 0.75; } +.ppl-sticker b { font-family: var(--font-serif); font-size: 19px; line-height: 1.1; white-space: nowrap; } +.ppl-sticker b.ppl-num { font-family: var(--font-num); font-size: 22px; font-weight: 700; } +.ppl-sticker-caret { position: absolute; right: 9px; top: calc(50% - 8px); transition: transform 180ms var(--ease-out); } +.ppl-sticker[aria-expanded="true"] .ppl-sticker-caret { transform: rotate(180deg); } +.ppl-sticker:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.ppl-sticker.is-year:active { box-shadow: inset 0 5px 0 var(--stamp), 1px 1px 0 var(--shadow-ink); } +.ppl-sticker:focus-visible, .ppl-clear:focus-visible, .ppl-chip:focus-visible, .ppl-pg:focus-visible, .ppl-tray-close:focus-visible, .ppl-close:focus-visible { + outline: 4px solid var(--signal); outline-offset: 2px; +} +.ppl-sticker:not(.is-year):focus-visible { outline-color: var(--ink); } +@media (hover: hover) and (pointer: fine) { + .ppl-sticker:hover { transform: translateY(-2px); } + .ppl-sticker:active { transform: translate(2px, 2px); } +} + +/* 名字標籤機:黑色標籤帶上打字 */ +.ppl-labeler { + flex: 1 1 200px; min-width: 150px; min-height: 52px; display: flex; align-items: center; gap: 8px; padding: 0 8px 0 14px; + background: var(--ink); color: var(--surface); border: 3px solid var(--ink); border-radius: 6px; box-shadow: 3px 3px 0 var(--shadow-ink); + cursor: text; +} +.ppl-labeler input { + flex: 1; min-width: 0; min-height: 44px; border: 0; background: none; color: inherit; outline: none; + font-family: var(--font-serif); font-size: 19px; letter-spacing: 0.08em; +} +.ppl-labeler input::placeholder { color: inherit; opacity: 0.6; } +.ppl-labeler:focus-within { outline: 4px solid var(--signal); outline-offset: 2px; } + +.ppl-clear { + min-height: 52px; min-width: 52px; padding: 0 14px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; + font: inherit; font-weight: 800; color: var(--ink); cursor: pointer; + background: var(--surface); border: 3px solid var(--ink); border-radius: 12px; box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.ppl-clear:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } + +/* 拉出來的索引盒(縣市、年份) */ +.ppl-scrim { position: absolute; inset: 0; z-index: 2; border-radius: 15px; background: var(--shadow-ink); opacity: 0.18; animation: ppl-scrim 180ms ease both; } +.ppl-tray { + position: absolute; top: calc(100% + 6px); left: 10px; right: 10px; z-index: 4; + max-height: min(64vh, 480px); display: grid; grid-template-rows: auto minmax(0, 1fr); + background: var(--ppl-kraft); border: 3px solid var(--ink); border-radius: 14px; box-shadow: 6px 6px 0 var(--shadow-ink); + transform-origin: top left; animation: ppl-tray-in 220ms var(--ease-out) both; +} +.ppl-tray-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 6px 6px 6px 16px; border-bottom: 3px solid var(--ink); } +.ppl-tray-head b { font-family: var(--font-serif); font-size: 19px; } +.ppl-tray-close, .ppl-close { + flex: none; width: 46px; height: 46px; display: grid; place-items: center; padding: 0; + color: var(--ink); background: var(--surface); border: 3px solid var(--ink); border-radius: 50%; box-shadow: 2px 2px 0 var(--shadow-ink); cursor: pointer; + transition: transform 140ms var(--ease-out); +} +.ppl-tray-close:active, .ppl-close:active { transform: translate(2px, 2px); box-shadow: none; } +.ppl-tray-body { min-height: 0; overflow-y: auto; overscroll-behavior: contain; display: grid; gap: 14px; padding: 12px 14px 16px; } +.ppl-tray-group { display: grid; gap: 6px; } +.ppl-tray-group > small { font-size: 12px; font-weight: 800; letter-spacing: 0.12em; } +.ppl-tray-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 8px; } +.ppl-tray-grid.is-years { grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); } +.ppl-chip { + min-height: 46px; padding: 4px 8px; font: inherit; font-family: var(--font-serif); font-size: 17px; color: var(--ink); cursor: pointer; + background: var(--surface); border: 3px solid var(--ink); border-radius: 10px 10px 3px 3px; box-shadow: 2px 2px 0 var(--shadow-ink); + transition: transform 120ms var(--ease-out); +} +.ppl-chip.ppl-num { font-family: var(--font-num); font-size: 22px; font-weight: 700; } +.ppl-chip.is-wide { justify-self: start; padding: 4px 20px; } +.ppl-chip[aria-pressed="true"] { background: var(--signal); color: var(--signal-ink); } +.ppl-chip:active { transform: translate(2px, 2px); box-shadow: none; } +@media (hover: hover) and (pointer: fine) { + .ppl-chip:hover { transform: translateY(-2px); } + .ppl-chip:active { transform: translate(2px, 2px); } + .ppl-clear:hover, .ppl-tray-close:hover, .ppl-close:hover, .ppl-pg:hover:not(:disabled) { background: var(--signal); color: var(--signal-ink); } +} + +/* ── 一格格檔案夾 ── */ +.ppl-files { min-height: 0; padding: 18px 16px 12px; background: var(--surface-2); } +.ppl-grid { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px 16px; transition: opacity 160ms ease; } +.ppl-files[aria-busy="true"] .ppl-grid { opacity: 0.55; } +.ppl-grid-item { min-width: 0; animation: ppl-file-in 320ms var(--ease-out) both; animation-delay: calc(var(--i, 0) * 22ms); } + +.ppl-file { height: 100%; display: grid; grid-template-rows: auto 1fr; color: var(--ink); text-decoration: none; transition: transform 180ms var(--ease-out); -webkit-tap-highlight-color: transparent; } +/* 檔案夾的耳朵:上緣一條政黨分類色(文字同時寫出政黨,不只靠顏色) */ +.ppl-file-tab { + position: relative; z-index: 1; justify-self: start; max-width: 82%; margin: 0 0 -3px 0; padding: 9px 12px 4px 10px; + display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 800; white-space: nowrap; + background: var(--ppl-kraft); border: 3px solid var(--ink); border-bottom: 0; border-radius: 10px 10px 0 0; + box-shadow: inset 0 5px 0 var(--party, var(--slot-other)); +} +.ppl-file-tab > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.ppl-file-body { + position: relative; min-width: 0; display: grid; align-content: start; gap: 7px; padding: 12px 12px 10px; + background: var(--ppl-kraft); border: 3px solid var(--ink); border-radius: 0 12px 12px 12px; box-shadow: 4px 4px 0 var(--shadow-ink); +} +.ppl-file-top { position: relative; min-height: 50px; padding-right: 50px; display: flex; align-items: flex-start; } +.ppl-file-label { + max-width: 100%; padding: 3px 10px 4px; background: var(--surface); border: 2px solid var(--ink); border-radius: 4px; + font-family: var(--font-serif); font-size: 22px; line-height: 1.2; overflow-wrap: anywhere; transform: rotate(-1.5deg); +} +.ppl-file-label.is-long { font-size: 15px; } +/* 當選章:雙線框、紅墨、斜蓋 */ +.ppl-file-stamp { + position: absolute; top: -4px; right: -2px; width: 48px; padding: 3px 0 2px; display: grid; justify-items: center; + color: var(--stamp); border: 4px double var(--stamp); border-radius: 8px; + font-family: var(--font-serif); font-size: 12px; line-height: 1.15; transform: rotate(-10deg); +} +.ppl-file-stamp b { font-size: 19px; font-weight: 700; line-height: 1; } +.ppl-file-latest { font-size: 13px; font-weight: 700; line-height: 1.35; overflow-wrap: anywhere; } +.ppl-file-meta { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 2px 8px; font-size: 12px; font-weight: 700; } +.ppl-file-meta b { font-size: 17px; } +.ppl-file-no { font-size: 12px; letter-spacing: 0.06em; opacity: 0.7; } +/* 收集卡:玩過=彩色+「玩過 N 次」貼紙+一道閃光;沒玩過=灰階、淡一點 */ +.ppl-file.is-gray { opacity: 0.8; transition: transform 180ms var(--ease-out), opacity 180ms ease; } +.ppl-file.is-gray .ppl-file-tab, .ppl-file.is-gray .ppl-file-body { filter: grayscale(1); } +.ppl-file.is-gray[aria-current="true"] { opacity: 1; } +.ppl-file.is-gray[aria-current="true"] .ppl-file-tab { filter: none; } +.ppl-file.is-mine .ppl-file-body { overflow: hidden; } +.ppl-file.is-mine .ppl-file-body::after { + content: ""; position: absolute; inset: 0; pointer-events: none; + background: linear-gradient(105deg, transparent 35%, color-mix(in srgb, var(--surface) 60%, transparent) 50%, transparent 65%); + transform: translateX(-110%); animation: ppl-shine 1100ms var(--ease-out) both; animation-delay: calc(300ms + var(--i, 0) * 40ms); +} +.ppl-file-played { + justify-self: start; display: inline-flex; align-items: center; gap: 4px; padding: 2px 9px; font-size: 12px; font-weight: 800; + background: var(--signal); color: var(--signal-ink); border: 2px solid var(--ink); border-radius: 999px; box-shadow: 2px 2px 0 var(--shadow-ink); +} +.ppl-file-played { max-width: 100%; white-space: nowrap; } +.ppl-file-played b { font-size: 15px; } +.ppl-file-low { justify-self: start; padding: 1px 8px; font-size: 11px; font-weight: 800; background: var(--surface); border: 2px solid var(--ink); border-radius: 999px; } + +.ppl-file:focus-visible { outline: none; } +.ppl-file:focus-visible .ppl-file-body { outline: 4px solid var(--signal); outline-offset: 3px; } +.ppl-file:active { transform: translate(2px, 2px); } +.ppl-file:active .ppl-file-body { box-shadow: 2px 2px 0 var(--shadow-ink); } +/* 正在閱覽的那份:抽出來一點、耳朵塗黃 */ +.ppl-file[aria-current="true"] { transform: translateY(-8px); } +.ppl-file[aria-current="true"] .ppl-file-tab { background: var(--signal); color: var(--signal-ink); } +.ppl-file[aria-current="true"] .ppl-file-body { box-shadow: 4px 12px 0 var(--shadow-ink); } +@media (hover: hover) and (pointer: fine) { + .ppl-file:hover { transform: translateY(-5px) rotate(-0.8deg); } + .ppl-file.is-gray:hover { opacity: 1; } + .ppl-year:hover { transform: translateY(-2px); } + .ppl-flip:hover:not(:disabled) { background: var(--signal); color: var(--signal-ink); } + .ppl-file[aria-current="true"]:hover { transform: translateY(-8px); } + .ppl-file:active { transform: translate(2px, 2px); } +} + +.ppl-empty { + display: grid; justify-items: center; gap: 14px; max-width: 460px; margin: 28px auto; padding: 24px; + border: 3px dashed var(--line); border-radius: 14px; color: var(--muted); font-weight: 700; text-align: center; +} +.ppl-empty p { margin: 0; } +.ppl-empty a.ppl-pg { text-decoration: none; } +.ppl-count { margin: -4px 0 14px; font-size: 13px; font-weight: 700; color: var(--muted); } +.ppl-count b { font-size: 17px; color: var(--ink); } +.ppl-mine-head { display: flex; align-items: center; gap: 10px; min-height: 78px; } +.ppl-mine-head p { margin: 0; font-size: 14px; font-weight: 700; } +.ppl-mine-head b { font-size: 18px; } +.ppl-files-note { margin: 26px 0 4px; font-size: 12px; line-height: 1.6; color: var(--muted); text-align: center; } + +/* 換頁 */ +.ppl-pager { display: flex; align-items: center; justify-content: center; gap: 14px; padding: 10px 12px; border-top: 3px solid var(--ink); } +.ppl-pg { + min-height: 46px; padding: 0 16px; display: inline-flex; align-items: center; gap: 4px; + font: inherit; font-weight: 800; color: var(--ink); cursor: pointer; + background: var(--surface); border: 3px solid var(--ink); border-radius: 12px; box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.ppl-pg:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.ppl-pg:disabled { opacity: 0.4; box-shadow: none; cursor: default; } +.ppl-pg-count { font-weight: 800; white-space: nowrap; } +.ppl-pg-count b { font-size: 26px; } +.ppl-pg-count .ppl-num:not(b) { font-size: 18px; } + +/* ── 閱覽桌 ── */ +.ppl-desk { min-width: 0; min-height: 0; display: none; } +@media (min-width: 1024px) { + .ppl-desk { display: grid; } + .ppl-files-note { display: none; } +} + +/* 還沒打開檔案:一疊檔案夾+說明 */ +.ppl-idle { + display: grid; align-content: center; justify-items: center; gap: 10px; padding: 28px; text-align: center; font-size: 14px; + border: 3px dashed color-mix(in srgb, var(--ink) 30%, transparent); border-radius: 18px; +} +.ppl-idle p { margin: 0; max-width: 32em; } +.ppl-idle-title { font-family: var(--font-serif); font-size: 26px; } +.ppl-idle-note { + margin-top: 12px !important; padding: 10px 14px; font-weight: 800; + background: var(--signal); color: var(--signal-ink); border: 3px solid var(--ink); border-radius: 10px; box-shadow: 3px 3px 0 var(--shadow-ink); + transform: rotate(-1deg); +} +.ppl-idle-stack { position: relative; width: 180px; height: 128px; margin-bottom: 16px; } +.ppl-idle-stack i { position: absolute; inset: 18px 0 0; background: var(--ppl-kraft); border: 3px solid var(--ink); border-radius: 0 12px 12px 12px; box-shadow: 4px 4px 0 var(--shadow-ink); } +.ppl-idle-stack i::before { + content: ""; position: absolute; left: -3px; top: -20px; width: 46%; height: 20px; + background: inherit; border: 3px solid var(--ink); border-bottom: 0; border-radius: 10px 10px 0 0; +} +.ppl-idle-stack i:nth-child(1) { transform: translate(-16px, 8px) rotate(-8deg); background: var(--ppl-kraft-deep); } +.ppl-idle-stack i:nth-child(2) { transform: translate(14px, 2px) rotate(5deg); } +.ppl-idle-stack i:nth-child(3) { transform: rotate(-1deg); } + +/* 打開的檔案夾 */ +.ppl-folder { min-width: 0; min-height: 0; height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr); animation: ppl-folder-in 340ms var(--ease-out) both; } +.ppl-folder-tab { + position: relative; z-index: 1; justify-self: start; margin: 0 0 -3px 20px; padding: 11px 18px 6px; + display: inline-flex; align-items: baseline; gap: 8px; font-size: 13px; font-weight: 800; + background: var(--ppl-kraft); border: 3px solid var(--ink); border-bottom: 0; border-radius: 12px 12px 0 0; + box-shadow: inset 0 6px 0 var(--party, var(--slot-other)); +} +.ppl-folder-tab b { font-size: 18px; letter-spacing: 0.06em; } +.ppl-folder-body { + position: relative; min-height: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 14px; padding: 14px; + background: var(--ppl-kraft); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--shadow-ink); +} +.ppl-close { position: absolute; top: 10px; right: 10px; z-index: 2; } +.ppl-folder-wait { margin: 0; padding: 40px 16px; font-weight: 800; text-align: center; } + +.ppl-dossier { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 16px; padding: 4px 56px 0 4px; } +/* 名字第一個字刻成的印章(只有字,不放照片) */ +.ppl-seal { + width: 70px; height: 70px; display: grid; place-items: center; + font-family: var(--font-serif); font-size: 40px; line-height: 1; color: var(--newsprint); + background: var(--stamp); border-radius: 10px; box-shadow: inset 0 0 0 4px var(--stamp), inset 0 0 0 6px var(--newsprint), 3px 3px 0 var(--shadow-ink); + transform: rotate(-4deg); +} +.ppl-dossier-text { display: grid; gap: 4px; min-width: 0; } +.ppl-dossier h2 { margin: 0; font-family: var(--font-serif); font-size: clamp(30px, 3vw, 40px); line-height: 1.1; overflow-wrap: anywhere; } +.ppl-dossier h2.is-long { font-size: 22px; } +.ppl-dossier h2:focus { outline: none; } +.ppl-dossier h2:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.ppl-dossier-meta { margin: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 4px 14px; font-size: 14px; font-weight: 700; } +.ppl-dossier-count { margin: 0; display: flex; flex-wrap: wrap; align-items: baseline; font-size: 14px; font-weight: 700; } +.ppl-dossier-count > span { white-space: nowrap; } +.ppl-dossier-count > .ppl-num { font-size: 16px; } +.ppl-dossier-count b { font-size: 21px; } + +.ppl-sheets { display: grid; align-content: start; gap: 16px; margin: 0 -6px -6px; padding: 2px 6px 10px; } +.ppl-sheet { + display: grid; gap: 10px; padding: 16px 16px 14px; min-width: 0; + background: var(--surface); border: 3px solid var(--ink); border-radius: 6px; box-shadow: 3px 3px 0 var(--shadow-ink); +} +.ppl-sheet h3 { margin: 0; font-family: var(--font-serif); font-size: 22px; } +.ppl-score-note { margin: 0; padding: 8px 12px; font-size: 14px; font-weight: 800; background: var(--signal); color: var(--signal-ink); border: 2px solid var(--ink); border-radius: 8px; } +.ppl-sheet-sub { margin: 0; font-size: 13px; color: var(--muted); } +.ppl-warn { margin: 0; padding: 8px 12px; font-size: 14px; font-weight: 800; color: var(--stamp); background: var(--surface); border: 3px solid var(--stamp); border-radius: 10px; } + +/* 五項資歷分數:刻度條 */ +.ppl-scores { list-style: none; margin: 0; padding: 0; display: grid; } +.ppl-scores > li { display: grid; gap: 6px; padding: 12px 0 2px; border-top: 2px dashed var(--line); min-width: 0; } +.ppl-scores > li:first-child { padding-top: 2px; border-top: 0; } +.ppl-score-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; } +.ppl-score-head b { font-family: var(--font-serif); font-size: 18px; } +.ppl-score-value { font-size: 30px; font-weight: 700; line-height: 1; } +.ppl-score-value.is-none { font-family: var(--font-body); font-size: 15px; font-weight: 800; color: var(--muted); } +.ppl-gauge { position: relative; height: 18px; overflow: hidden; background: var(--surface-2); border: 3px solid var(--ink); border-radius: 999px; } +.ppl-gauge > i { position: absolute; inset: 0; background: var(--signal); transform-origin: left center; animation: ppl-fill 640ms var(--ease-out) both; animation-delay: calc(140ms + var(--i, 0) * 70ms); } +.ppl-gauge::after { + content: ""; position: absolute; inset: 0; + background: repeating-linear-gradient(90deg, transparent 0 calc(10% - 2px), color-mix(in srgb, var(--ink) 28%, transparent) calc(10% - 2px) 10%); +} +.ppl-basis { margin: 0; font-size: 14px; overflow-wrap: anywhere; } +.ppl-scores details { font-size: 13px; color: var(--muted); } +.ppl-scores summary { min-height: 44px; display: flex; align-items: center; gap: 8px; font-weight: 800; color: var(--ink); cursor: pointer; list-style: none; } +.ppl-scores summary::-webkit-details-marker { display: none; } +.ppl-scores summary::before { + content: ""; width: 0; height: 0; border-style: solid; border-width: 6px 0 6px 9px; border-color: transparent transparent transparent var(--stamp); + transition: transform 160ms var(--ease-out); +} +.ppl-scores details[open] > summary::before { transform: rotate(90deg); } +.ppl-scores summary:focus-visible { outline: 4px solid var(--signal); outline-offset: 1px; } +.ppl-scores details p { margin: 0 0 6px; overflow-wrap: anywhere; } + +/* 歷年參選證:一次參選一張,左右翻;左上角是號次(不放照片),當選的蓋紅章 */ +.ppl-creds-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; } +.ppl-creds-flip { display: flex; align-items: center; gap: 8px; font-size: 19px; font-weight: 700; } +.ppl-flip { + width: 44px; height: 44px; display: grid; place-items: center; padding: 0; color: var(--ink); cursor: pointer; + background: var(--surface); border: 3px solid var(--ink); border-radius: 50%; box-shadow: 2px 2px 0 var(--shadow-ink); + transition: transform 140ms var(--ease-out); +} +.ppl-flip:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: none; } +.ppl-flip:disabled { opacity: 0.35; box-shadow: none; cursor: default; } +.ppl-flip:focus-visible, .ppl-year:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.ppl-creds-years { display: flex; flex-wrap: wrap; gap: 6px; } +.ppl-year { + position: relative; min-width: 60px; min-height: 44px; padding: 2px 10px; cursor: pointer; + font: inherit; font-family: var(--font-num); font-size: 20px; font-weight: 700; color: var(--ink); + background: var(--surface-2); border: 2px solid var(--ink); border-radius: 10px 10px 3px 3px; + transition: transform 140ms var(--ease-out); +} +.ppl-year[aria-pressed="true"] { background: var(--signal); color: var(--signal-ink); } +.ppl-year > i { position: absolute; top: -5px; right: -5px; width: 13px; height: 13px; border-radius: 50%; background: var(--stamp); border: 2px solid var(--surface); } +.ppl-year:active { transform: translate(1px, 1px); } + +.ppl-creds { + list-style: none; margin: 0 -16px; padding: 4px 16px 12px; position: relative; + display: grid; grid-auto-flow: column; grid-auto-columns: 88%; gap: 14px; + overflow-x: auto; overscroll-behavior-x: contain; scroll-snap-type: x mandatory; scroll-padding-inline: 16px; scrollbar-width: none; +} +.ppl-creds::-webkit-scrollbar { display: none; } +.ppl-creds:has(> li:only-child) { grid-auto-columns: 100%; } +.ppl-cred { + position: relative; min-width: 0; overflow: hidden; scroll-snap-align: start; + display: grid; grid-template-rows: auto 1fr auto; + background-color: var(--surface); + background-image: repeating-linear-gradient(45deg, color-mix(in srgb, var(--party) 9%, transparent) 0 2px, transparent 2px 10px); + border: 3px solid var(--ink); border-radius: 14px; box-shadow: 4px 4px 0 var(--shadow-ink); +} +.ppl-cred-band { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 10px; background: var(--party); border-bottom: 3px solid var(--ink); } +.ppl-cred-title, .ppl-cred-date { padding: 2px 10px; background: var(--surface); color: var(--ink); border: 2px solid var(--ink); border-radius: 999px; white-space: nowrap; } +.ppl-cred-title { font-family: var(--font-serif); font-size: 15px; } +.ppl-cred-title b { font-size: 21px; font-weight: 700; } +.ppl-cred-date { font-size: 13px; font-weight: 700; } +.ppl-cred-main { display: grid; grid-template-columns: 74px minmax(0, 1fr); align-items: start; gap: 14px; padding: 12px 14px 4px; } +.ppl-cred-no { + width: 74px; height: 92px; display: grid; justify-items: center; align-content: center; + background: var(--surface); border: 3px solid var(--ink); border-radius: 10px; +} +.ppl-cred-no small { font-size: 12px; font-weight: 800; letter-spacing: 0.12em; } +.ppl-cred-no b { font-size: 54px; font-weight: 700; line-height: 1; } +.ppl-cred-fields { margin: 0; display: grid; gap: 3px; } +.ppl-cred-fields > div { display: grid; grid-template-columns: 34px minmax(0, 1fr); align-items: baseline; gap: 8px; padding-bottom: 3px; border-bottom: 1px dashed var(--line); } +.ppl-cred-fields dt { font-size: 12px; font-weight: 800; color: var(--muted); } +.ppl-cred-fields dd { margin: 0; font-size: 14px; font-weight: 700; overflow-wrap: anywhere; } +.ppl-cred-fields dd b { font-size: 17px; } +.ppl-cred-fields dd.ppl-party { display: flex; flex-wrap: wrap; column-gap: 5px; } +/* 參選證的補充小字:不分區的名單排名、政黨票說明,副總統的「同一組的票」 */ +.ppl-cred-sub { display: block; flex-basis: 100%; font-size: 12px; font-weight: 700; color: var(--muted); } +.ppl-cred-sub b { font-size: 13px; } +.ppl-cred-fields dd.ppl-cred-name { font-family: var(--font-serif); font-size: 18px; } +.ppl-cred-fields .ppl-incumbent { margin-left: 8px; padding: 0 7px; font-size: 11px; font-weight: 800; border: 2px solid var(--ink); border-radius: 999px; } +.ppl-cred-foot { min-height: 40px; padding: 10px 14px 8px; font-size: 12px; letter-spacing: 0.08em; color: var(--muted); } +.ppl-cred-stamp { + position: absolute; right: 12px; bottom: 8px; width: 62px; height: 62px; display: grid; place-items: center; + font-family: var(--font-serif); font-size: 18px; color: var(--stamp); border: 4px double var(--stamp); border-radius: 50%; + transform: rotate(-14deg); animation: ppl-stamp 420ms var(--ease-out) both; animation-delay: 320ms; +} +/* 還沒收集:整排證件灰階,字照樣清楚 */ +.ppl-creds.is-gray .ppl-cred { filter: grayscale(1); } +.ppl-folder.is-gray .ppl-seal, .ppl-folder.is-gray .ppl-folder-tab { filter: grayscale(1); } + +/* 收集狀態 */ +.ppl-collect { margin: 0; display: flex; align-items: center; gap: 8px; padding: 8px 12px; font-size: 14px; font-weight: 800; background: var(--surface); border: 2px dashed var(--ink); border-radius: 10px; } +.ppl-collect.is-mine { background: var(--signal); color: var(--signal-ink); border-style: solid; box-shadow: 3px 3px 0 var(--shadow-ink); } +.ppl-collect b { font-size: 18px; } + +.ppl-foot { display: grid; gap: 4px; padding: 0 4px 6px; font-size: 13px; } +.ppl-foot p { margin: 0; font-weight: 800; } +.ppl-foot ul { margin: 0; padding-left: 18px; } + +/* ── 窄螢幕:檔案夾整個蓋上來(場景上方的返回鍵此時是「收起檔案」) ── */ +@media (max-width: 1023px) { + .ppl-room.is-open .ppl-desk { + display: grid; position: absolute; inset: 0; z-index: 6; + padding: 6px 10px max(12px, env(safe-area-inset-bottom, 0px)); + background: color-mix(in srgb, var(--newsprint) 82%, var(--shadow-ink)); + animation: ppl-scrim 200ms ease both; + } + .ppl-folder { animation-name: ppl-folder-up; } +} + +/* ── 手機 ── */ +@media (max-width: 720px) { + .ppl-tabs { padding: 0 6px 0 12px; gap: 4px; } + .ppl-tab { flex: 1 1 auto; min-width: 0; padding: 6px 2px 12px; justify-items: center; text-align: center; } + .ppl-tab b { font-size: 16px; } + .ppl-tab.is-mine { margin: 0 0 -3px; } + .ppl-tab small { display: none; } + .ppl-drawer { border-radius: 16px; box-shadow: 4px 4px 0 var(--shadow-ink); } + .ppl-index { padding: 10px; border-radius: 13px 13px 0 0; } + .ppl-index-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 8px; } + .ppl-sticker { min-width: 0; min-height: 50px; } + .ppl-labeler { grid-column: 1 / -1; grid-row: 2; min-width: 0; min-height: 48px; } + .ppl-clear { min-height: 50px; padding: 0 12px; } + .ppl-clear span { display: none; } + .ppl-scrim { border-radius: 13px; } + .ppl-tray { left: 6px; right: 6px; } + .ppl-tray-grid { grid-template-columns: repeat(auto-fill, minmax(66px, 1fr)); gap: 7px; } + .ppl-tray-body { padding: 10px 12px 14px; gap: 12px; } + .ppl-chip { min-height: 44px; padding: 4px 2px; font-size: 16px; } + .ppl-tray-head { padding: 4px 4px 4px 14px; } + .ppl-chip.is-wide { padding: 4px 18px; } + .ppl-files { padding: 16px 10px 10px; } + .ppl-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 10px; } + .ppl-file-body { padding: 10px 9px 9px; gap: 6px; } + .ppl-file-top { padding-right: 40px; min-height: 46px; } + .ppl-file-label { font-size: 18px; padding: 2px 7px 3px; } + .ppl-file-label.is-long { font-size: 13px; } + .ppl-file-stamp { width: 42px; top: -6px; right: -4px; font-size: 11px; } + .ppl-file-stamp b { font-size: 16px; } + .ppl-file-no { display: none; } + .ppl-pager { gap: 8px; padding: 8px; } + .ppl-pg { padding: 0 12px; } + .ppl-pg-count b { font-size: 22px; } + .ppl-folder-tab { margin-left: 14px; } + .ppl-folder-body { padding: 10px; gap: 10px; border-radius: 16px; box-shadow: 4px 4px 0 var(--shadow-ink); } + .ppl-dossier { gap: 12px; padding-right: 50px; } + .ppl-seal { width: 56px; height: 56px; font-size: 32px; } + .ppl-sheet { padding: 12px 12px 10px; } + .ppl-creds { margin: 0 -12px; padding: 4px 12px 10px; scroll-padding-inline: 12px; grid-auto-columns: 90%; gap: 10px; } + .ppl-cred-main { grid-template-columns: 58px minmax(0, 1fr); gap: 10px; padding: 10px 10px 4px; } + .ppl-cred-no { width: 58px; height: 76px; } + .ppl-cred-no b { font-size: 42px; } + .ppl-cred-band { padding: 7px 8px; } + .ppl-cred-title b { font-size: 18px; } + .ppl-cred-date { font-size: 12px; padding: 2px 7px; } + .ppl-cred-foot { padding: 8px 10px 6px; } + .ppl-cred-stamp { width: 54px; height: 54px; font-size: 15px; } + .ppl-year { min-width: 56px; font-size: 18px; } +} +@media (max-width: 400px) { + /* 兩欄的檔案夾很窄:「玩過 N 次・最佳 A」縮小一點,維持一行 */ + .ppl-file-played { gap: 3px; padding: 2px 6px; font-size: 11px; } + .ppl-file-played b { font-size: 13px; } +} +@media (max-width: 359px) { + .ppl-grid { grid-template-columns: minmax(0, 1fr); } +} + +@keyframes ppl-file-in { from { opacity: 0; transform: translateY(14px); } } +@keyframes ppl-tray-in { from { opacity: 0; transform: translateY(-10px) scale(0.97); } } +@keyframes ppl-scrim { from { opacity: 0; } } +@keyframes ppl-folder-in { from { opacity: 0; transform: translateX(32px) rotate(1.5deg); } } +@keyframes ppl-folder-up { from { opacity: 0; transform: translateY(56px); } } +@keyframes ppl-fill { from { transform: scaleX(0); } } +@keyframes ppl-stamp { + 0% { opacity: 0; transform: scale(1.9) rotate(-12deg); } + 60% { opacity: 1; transform: scale(0.94) rotate(-12deg); } + 100% { opacity: 1; transform: scale(1) rotate(-12deg); } +} +@keyframes ppl-fade { from { opacity: 0; } } +@keyframes ppl-shine { to { transform: translateX(110%); } } + +@media (prefers-reduced-motion: reduce) { + .ppl-grid-item, .ppl-gauge > i, .ppl-cred-stamp, .ppl-file.is-mine .ppl-file-body::after { animation: none; } + .ppl-folder, .ppl-tray { animation: ppl-fade 160ms ease both; } + .ppl-tab, .ppl-sticker, .ppl-sticker-caret, .ppl-chip, .ppl-clear, .ppl-file, .ppl-pg, .ppl-close, .ppl-tray-close, .ppl-scores summary::before, .ppl-flip, .ppl-year { transition: none; } + .ppl-file:hover, .ppl-file[aria-current="true"], .ppl-file[aria-current="true"]:hover { transform: none; } +} diff --git a/web/src/game/people/shared.ts b/web/src/game/people/shared.ts new file mode 100644 index 0000000..4abbf25 --- /dev/null +++ b/web/src/game/people/shared.ts @@ -0,0 +1,31 @@ +import type { ElectionRun } from "@election2026/protocol"; + +/** 分數旁邊一定要有的一句話 */ +export const SCORE_NOTE = "分數是依公開選舉紀錄計算的遊戲數值,不代表對個人的評價"; +export const SOURCE_NOTE = `資料來源:中央選舉委員會選舉資料庫;${SCORE_NOTE}`; + +/** 檔號:id 後六碼(只是給檔案夾一個編號,沒有其他意思) */ +export const fileNo = (id: string): string => id.slice(-6).toUpperCase(); + +/** 分類色:三個政黨用 slot 色(真實政黨色),其他(含無黨籍)用灰 */ +const PARTY_SLOT: Record = { 民主進步黨: "a", 中國國民黨: "b", 台灣民眾黨: "c" }; +export const partyColor = (party: string | null): string => `var(--slot-${(party && PARTY_SLOT[party]) || "other"})`; + +/** 名字的第一個字(做成印章用;用 Array.from 才不會切壞罕用字) */ +export const firstChar = (name: string): string => Array.from(name)[0] ?? ""; +export const nameLength = (name: string): number => Array.from(name).length; + +/** 選區:「臺北市第3選區」;總統副總統、原住民立委、不分區立委是「全國」 */ +export const place = (r: ElectionRun): string => `${r.county}${r.district ?? ""}`; +/** 選舉:「直轄市議員(平地原住民)」「副總統」「不分區立法委員」 */ +export const kind = (r: ElectionRun): string => r.election + (r.indigenous ? `(${r.indigenous})` : ""); + +/** 不分區立委:沒有個人得票,有政黨名單排名 */ +export const isPartyList = (r: ElectionRun): boolean => r.listRank !== undefined; +/** 總統副總統選舉的搭檔:總統候選人的參選證寫「蕭美琴(副總統)」,副總統候選人的寫「賴清德(總統)」 */ +export const mateLabel = (r: ElectionRun): string | null => + r.runningMate ? `${r.runningMate}(${r.election === "副總統" ? "總統" : "副總統"})` : null; + +/** 檔案室收錄的範圍(檔案櫃、閱覽桌的說明都用這一句) */ +export const COVERAGE = + "收錄 1994–2022 年歷屆直轄市長、縣市長、臺灣省長與直轄市、縣市、省議員,1996–2024 年總統副總統,1995–2024 年立法委員(區域、原住民;不分區從 2008 年起)候選人的參選紀錄。"; diff --git a/web/src/game/rogue/Career.tsx b/web/src/game/rogue/Career.tsx new file mode 100644 index 0000000..4084fbd --- /dev/null +++ b/web/src/game/rogue/Career.tsx @@ -0,0 +1,612 @@ +import type { CustomCandidate, RogueVillageList, RogueView, ScenarioSummary } from "@election2026/protocol"; +import { Crown, Map as MapIcon, Play, Sparkles, Star, Trophy, UserRound } from "lucide-react"; +import { useEffect, useMemo, useState } from "react"; +import { api, rogueApi } from "../api.ts"; +import { sfx } from "../audio/sfx.ts"; +import { TermScreen } from "../career/term/TermScreen.tsx"; +import type { Ability, TermResult } from "../career/term/types.ts"; +import type { SavedCharacter } from "../creator/characters.ts"; +import { addPoints, perksForRun, policiesForRun } from "../island/store.ts"; +import { ConfirmDialog } from "../ui/ConfirmDialog.tsx"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { CareerBoard } from "./CareerBoard.tsx"; +import { CareerSetup } from "./CareerSetup.tsx"; +import { CareerSheet } from "./CareerSheet.tsx"; +import { CareerStage } from "./CareerStage.tsx"; +import { AdvisorFace, CardFace } from "./cards.tsx"; +import { ABILITY_IDS, LAST, MAX_LEVEL, ORIGIN_RULES, STAGES, emptyTiers, gainExp, highestOpen, migrate, noCarry, runExp, startAbilities, toNext, withOriginRules, type CareerState } from "./careerRules.ts"; +import "./rogue-career.css"; + +/** + * 政治生涯(docs/23、18 第 44 項):像練等。 + * - 五關:里長、議員、立委、縣市長、總統。每一關都可以重複選;要往上選,上一關至少選上一次、而且等級夠(議員 Lv3、立委 Lv5、縣市長 Lv8、總統 Lv12)。 + * - 每選一場都拿經驗(當選全額、落選四成;逆風越高經驗越多;回去選比較低的關打六折),任期也給經驗。 + * - 經驗滿了升級,每升一級拿 1 個技能點,自己加在五項能力上(每項最高 5 級,可以重新分配)。 + * - 當選後可以挑 2 位幕僚、3 張牌帶到下一場,再做一段任期(政績點、下一場開局聲勢和資金)。 + * 進度存在這台瀏覽器(tongsuan.rogue.career.v3;舊版的進度自動換過來)。 + */ + +const KEY = "tongsuan.rogue.career.v3"; +const OLD_KEYS = ["tongsuan.rogue.career.v2", "tongsuan.rogue.career.v1"]; + +const FAME_MONEY = 150; +const MAX_ADVISORS = 2; +const MAX_CARDS = 3; + +function load(): CareerState | null { + try { + const raw = localStorage.getItem(KEY); + if (raw) { + const c = JSON.parse(raw) as CareerState; + if (c.originRules === ORIGIN_RULES) return c; + // 開局能力換成新規則(出身與黨的資源),寫回存檔 + const next = withOriginRules(c); + save(next); + return next; + } + const v2 = localStorage.getItem(OLD_KEYS[0]!); + if (v2) return withOriginRules(migrate(JSON.parse(v2) as Record, 2)); + const v1 = localStorage.getItem(OLD_KEYS[1]!); + return v1 ? withOriginRules(migrate(JSON.parse(v1) as Record, 1)) : null; + } catch { + return null; + } +} +function save(c: CareerState | null): void { + try { + if (c) localStorage.setItem(KEY, JSON.stringify(c)); + else localStorage.removeItem(KEY); + for (const k of OLD_KEYS) localStorage.removeItem(k); + } catch { + // 私密模式存不了:這次的生涯只留在畫面上 + } +} + +const year = (s: ScenarioSummary) => s.electionDate.slice(0, 4); +const isEven = (s: ScenarioSummary) => s.id.endsWith("-even"); + +/** 地方選舉(里長、議員)用的縣市長劇本:拿那個縣市的選民模型,最新的優先 */ +function mayorScenario(list: readonly ScenarioSummary[], county: string): ScenarioSummary | null { + return list.filter((s) => s.region.kind === "mayor" && s.region.countyCode === county && !isEven(s)).sort((a, b) => b.electionDate.localeCompare(a.electionDate))[0] ?? null; +} + +/** 這一關要選的劇本:同縣市、照年份順序找第一個有的;立委優先找你住的那個區所在的選區 */ +function stageScenario(list: readonly ScenarioSummary[], c: CareerState, stage: number): ScenarioSummary | null { + const def = STAGES[stage - 1]; + if (!def) return null; + if (def.kind === "village" || def.kind === "council") return mayorScenario(list, c.county.code); + for (const y of def.years) { + const pool = list + .filter((s) => s.region.kind === def.kind && year(s) === y && !isEven(s) && (def.kind === "president" || s.region.countyCode === c.county.code)) + .sort((a, b) => a.id.localeCompare(b.id)); + if (def.kind === "legislator") { + const hit = pool.find((s) => s.id === c.district) ?? (c.villageTown ? pool.find((s) => s.region.scope.includes(c.villageTown!)) : undefined); + if (hit) return hit; + } + if (pool[0]) return pool[0]; + } + return null; +} + +/** 自創角色取代劇本裡同黨的候選人(任何政黨都比對名字);沒有同黨的就以新候選人加入(里長、議員的對手是遊戲自己的人物,不取代) */ +function customFor(character: SavedCharacter, scenario: ScenarioSummary, local: boolean): CustomCandidate { + const same = character.party && !local ? scenario.candidates.find((c) => c.party === character.party) : undefined; + const { id: _id, ...rest } = character; + return { ...rest, replace: same?.id ?? null }; +} + +/** 「大寮區潮寮里」→「大寮區」 */ +const townOf = (area: string): string | null => /^(.+?[區鄉鎮市])/.exec(area)?.[1] ?? null; + +export function RogueCareer() { + const [career, setCareer] = useState(load); + const [scenarios, setScenarios] = useState(null); + const [finished, setFinished] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const [effects, setEffects] = useState>(new Map()); + const [selected, setSelected] = useState(() => (career ? highestOpen(career) : 1)); + const [extra, setExtra] = useState(0); + const [keepAdvisors, setKeepAdvisors] = useState([]); + const [keepCards, setKeepCards] = useState([]); + /** 手機:地圖和角色卡切換 */ + const [tab, setTab] = useState<"map" | "char">("map"); + /** 里長關:這個縣市的區和里(自己挑里,18 第 56 項) */ + const [villageList, setVillageList] = useState(null); + + const update = (next: CareerState | null) => { + setCareer(next); + save(next); + }; + + useEffect(() => { + api + .scenarios() + .then(setScenarios) + .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e))); + rogueApi + .catalog() + .then((c) => setEffects(new Map(c.abilities.map((a) => [a.id, a.effect])))) + .catch(() => undefined); + }, []); + + // 從一局打完回來(或重新整理):記下成績、加經驗;選上了還沒挑帶走的東西,就把那一局拿回來 + useEffect(() => { + const c = load(); + const id = c?.pending?.runId ?? c?.pickFrom ?? null; + if (!c || !id) return; + rogueApi + .get(id) + .then((v) => { + if (v.phase !== "finished" || !v.result) return; + setFinished(v); + if (c.pending?.runId !== id) return; + const { stage, extra: runExtra } = c.pending; + const won = v.result.won; + const gain = runExp(c, stage, won, v.result.grade, runExtra); + const t = c.tiers[stage]!; + const better = !t.best || "SABCD".indexOf(v.result.grade) < "SABCD".indexOf(t.best); + const tiers = { + ...c.tiers, + [stage]: { + runs: t.runs + 1, + wins: t.wins + (won ? 1 : 0), + best: won && better ? v.result.grade : t.best, + topExtra: won ? Math.max(t.topExtra, runExtra) : t.topExtra, + }, + }; + const entry = { + stage, + runId: v.runId, + won, + share: v.result.youShare, + grade: v.result.grade, + area: v.area, + exp: gain.exp, + extra: runExtra, + }; + // 里長關:記下你住的里(之後的議員、立委選區跟著它) + const village = c.village ?? (v.scenarioId.startsWith("village:") ? v.scenarioId.slice("village:".length) : null); + const villageTown = c.villageTown ?? (v.scenarioId.startsWith("village:") ? townOf(v.area) : null); + const { next, levels } = gainExp( + { + ...c, + village, + villageTown, + tiers, + pending: null, + history: [...c.history, entry].slice(-40), + pickFrom: won ? id : null, + }, + gain.exp, + ); + update({ + ...next, + report: { + runId: id, + stage, + won, + exp: gain.exp, + levels, + why: gain.why, + }, + }); + if (won) sfx.applause(); + else sfx.bad(); + if (levels) setTimeout(() => sfx.combo(3), 600); + }) + .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e))); + }, []); + + // 里長關的里清單:縣市長劇本決定是哪個縣市 + const villageScenario = career && scenarios ? mayorScenario(scenarios, career.county.code)?.id : undefined; + useEffect(() => { + if (!villageScenario) return; + let off = false; + rogueApi + .villages(villageScenario) + .then((list) => !off && setVillageList(list)) + .catch(() => undefined); + return () => { + off = true; + }; + }, [villageScenario]); + + const counties = useMemo(() => { + const m = new Map(); + for (const s of scenarios ?? []) if (s.region.kind === "mayor") m.set(s.region.countyCode, s.region.countyName); + return [...m].map(([code, name]) => ({ code, name })).sort((a, b) => a.code.localeCompare(b.code)); + }, [scenarios]); + + const districts = useMemo( + () => + career + ? (scenarios ?? []).filter((s) => s.region.kind === "legislator" && year(s) === "2024" && !isEven(s) && s.region.countyCode === career.county.code).sort((a, b) => a.id.localeCompare(b.id)) + : [], + [scenarios, career], + ); + + const startStage = async (c: CareerState, stage: number, runExtra: number) => { + if (!scenarios) return; + const scenario = stageScenario(scenarios, c, stage); + if (!scenario) { + setError("找不到這一關的選舉資料"); + return; + } + const def = STAGES[stage - 1]!; + if (def.kind === "council" && !c.village) { + setError("要先選過里長,才知道你住哪個議員選區"); + return; + } + setBusy(true); + setError(null); + try { + sfx.stamp(); + const local = def.kind === "village" ? ({ kind: "village", village: c.village } as const) : def.kind === "council" ? ({ kind: "council", village: c.village! } as const) : undefined; + const { runId, view } = await rogueApi.create(scenario.id, "custom", { + // 縣市長、立委、總統照真實的選民底盤(伺服器限制最多落後 10 個百分點,靠大絕招有機會翻盤,18 第 57 項); + // 里長、議員的開局由伺服器自己算 + even: false, + ascension: def.ascension + runExtra, + custom: customFor(c.character, scenario, !!local), + career: { stage }, + carry: c.carry, + local, + abilities: c.abilities, + perks: perksForRun(), + policies: policiesForRun(), + }); + // 里長關:記下你住的里,之後的議員、立委選區跟著它 + const village = view.scenarioId.startsWith("village:") ? view.scenarioId.slice("village:".length) : c.village; + const villageTown = view.scenarioId.startsWith("village:") ? townOf(view.area) : c.villageTown; + // 帶過來的幕僚、牌、資金這一場用掉 + save({ + ...c, + village, + villageTown, + carry: noCarry(), + pending: { runId, stage, extra: runExtra }, + report: null, + }); + location.hash = `#/rogue/${runId}`; + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(false); + } + }; + + const begin = (character: SavedCharacter, county: { code: string; name: string }, skip: boolean) => { + const base = startAbilities(character); + const c: CareerState = { + id: `career-${Date.now()}`, + character, + county, + village: null, + villageTown: null, + district: null, + level: skip ? 5 : 1, + exp: 0, + skillPoints: skip ? 4 : 0, + abilities: base, + base, + tiers: emptyTiers(), + skipped: skip ? [1, 2] : [], + carry: noCarry(), + history: [], + pending: null, + originRules: ORIGIN_RULES, + }; + update(c); + setSelected(skip ? 3 : 1); + setExtra(0); + }; + + const plus = (a: Ability) => { + if (!career || !career.skillPoints || career.abilities[a] >= MAX_LEVEL) return; + sfx.combo(career.abilities[a]); + update({ + ...career, + skillPoints: career.skillPoints - 1, + abilities: { ...career.abilities, [a]: career.abilities[a] + 1 }, + }); + }; + const reset = () => { + if (!career) return; + const spent = ABILITY_IDS.reduce((s, id) => s + career.abilities[id] - career.base[id], 0); + update({ + ...career, + abilities: { ...career.base }, + skillPoints: career.skillPoints + spent, + }); + }; + + /** 選上之後:挑好帶走的東西 → 做任期(可以跳過) */ + const toTerm = (doTerm: boolean) => { + if (!career || !finished) return; + const cards = finished.deck.filter((d) => keepCards.includes(d.uid)).map((d) => ({ id: d.id, up: d.up })); + const wins = Object.values(career.tiers).reduce((a, t) => a + t.wins, 0); + const stage = career.history.at(-1)?.stage ?? 1; + const next: CareerState = { + ...career, + carry: { + advisors: keepAdvisors, + cards, + money: Math.min(1000, wins * FAME_MONEY), + momentum: 0, + }, + pickFrom: null, + report: null, + term: doTerm && stage < LAST ? { stage, runId: finished.runId } : null, + }; + update(next); + setFinished(null); + setKeepAdvisors([]); + setKeepCards([]); + }; + + const finishTerm = (r: TermResult | null) => { + if (!career?.term) return; + let next: CareerState = { ...career, term: null }; + if (r) { + const g = gainExp(next, r.exp); + next = { + ...g.next, + carry: { + ...g.next.carry, + money: Math.min(1000, g.next.carry.money + r.bonus.money), + momentum: r.bonus.momentum, + }, + }; + addPoints(r.points, `${STAGES[career.term.stage - 1]?.title}任期政績`, `${career.term.runId}:term`); + next.report = { + runId: career.term.runId, + stage: career.term.stage, + won: true, + exp: r.exp, + levels: g.levels, + why: "任期表現", + }; + } + update(next); + setSelected(highestOpen(next)); + }; + + const [quitting, setQuitting] = useState(false); + const quit = () => { + update(null); + setFinished(null); + setQuitting(false); + }; + + const toggle = (list: string[], id: string, max: number) => (list.includes(id) ? list.filter((x) => x !== id) : list.length >= max ? list : [...list, id]); + + // 任期:整個場景換成任期小遊戲 + if (career?.term) { + const def = STAGES[career.term.stage - 1]!; + return ( + +
    + (a * 31 + ch.charCodeAt(0)) | 0, 7))} + onDone={(r) => finishTerm(r)} + /> + +
    +
    + ); + } + + if (!career) { + return ( + +
    + + {error &&

    {error}

    } +
    +
    + ); + } + + const def = STAGES[selected - 1]!; + const report = career.report; + const lastWin = finished?.result?.won && career.pickFrom === finished.runId; + const scenario = scenarios ? stageScenario(scenarios, career, selected) : null; + const keepable = finished ? finished.deck.filter((d) => d.rarity !== "status" && d.rarity !== "basic" && !d.id.startsWith("policy:")) : []; + const chosen = villageList?.towns.flatMap((t) => t.villages.map((v) => ({ ...v, town: t.name }))).find((v) => v.code === career.village); + const where = + def.kind === "village" + ? chosen + ? `要選的里:${chosen.town}${chosen.name}(選舉人約 ${chosen.electors.toLocaleString()} 人)` + : career.village + ? `你住的里:${career.history.find((h) => h.stage === 1)?.area ?? "已記下"}` + : `下面挑一個${career.county.name}的里;不挑就照人口隨機抽一個` + : def.kind === "council" + ? "你住的那個里所在的議員選區(多席次,贏過最後一席就當選)" + : (scenario?.name.replace(/:.*$/, "") ?? "讀取中…"); + + return ( + + } value={career.level} label="等級" /> + } value={career.skillPoints} label="技能點" /> + + } + > +
    + setQuitting(true)} /> +
    + { + sfx.flip(); + setSelected(s); + setExtra(0); + }} + /> + update({ ...career, district: id })} + busy={busy} + ready={!!scenarios} + onGo={(n) => void startStage(career, selected, n)} + villages={def.kind === "village" ? villageList : null} + onVillage={(code, town) => update({ ...career, village: code, villageTown: town })} + /> +
    + +
    + + {quitting && ( + setQuitting(false)} onConfirm={quit}> +

    + {career.character.name}的等級(Lv {career.level} + )、技能點、各關紀錄都會清掉,回到選角畫面。角色本身還留在衣櫃裡。 +

    +
    + )} + + {(report || lastWin) && ( +
    +
    + {report && ( + <> +
    + + {report.why === "任期表現" ? "任滿" : report.won ? "當選" : "落選"} + +
    + + {STAGES[report.stage - 1]?.title} + {finished?.runId === report.runId && finished.area ? `・${finished.area}` : ""} + +

    + {report.why === "任期表現" ? ( + <> + {STAGES[report.stage - 1]?.title}任期結束 + + ) : report.won ? ( + <> + {STAGES[report.stage - 1]?.title}當選! + + ) : ( + "這次沒選上" + )} +

    + {finished?.runId === report.runId && finished.result && ( +

    + 得票 {(finished.result.youShare * 100).toFixed(1)} + %・評等 {finished.result.grade} +

    + )} +
    +
    +
    +

    + +{report.exp} 經驗{report.why} +

    +
    + +
    + + Lv {career.level}・經驗 {career.exp}/{toNext(career.level)} + +
    + {!report.won &&

    落選也有經驗。多選幾次會升級、拿技能點,能力加上去就更好選。

    } + {report.levels > 0 && ( +

    + 升到 Lv {career.level} + !技能點 +{report.levels},到角色卡加點 +

    + )} + + )} + {lastWin && finished && ( + <> +

    + 帶到下一場的幕僚(最多 {MAX_ADVISORS} 位,已選 {keepAdvisors.length}) +

    +
    + {finished.advisors.length === 0 &&

    這一局沒有幕僚。

    } + {finished.advisors.map((a) => ( + + ))} +
    +

    + 帶到下一場的牌(最多 {MAX_CARDS} 張,已選 {keepCards.length}) +

    +
    + {keepable.length === 0 &&

    這一局沒有可以帶走的牌(基本牌、狀態牌、政策牌不能帶)。

    } + {keepable.map((d) => ( + + ))} +
    + + )} +
    + {lastWin && (report?.stage ?? LAST) < LAST ? ( + <> + + + + ) : lastWin ? ( + + ) : ( + + )} +
    +
    +
    + )} + {error &&

    {error}

    } +
    + ); +} diff --git a/web/src/game/rogue/CareerBoard.tsx b/web/src/game/rogue/CareerBoard.tsx new file mode 100644 index 0000000..f13555e --- /dev/null +++ b/web/src/game/rogue/CareerBoard.tsx @@ -0,0 +1,158 @@ +import { Crown, Flag, Home, Landmark, Lock, Users, type LucideIcon } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { Avatar } from "../art/Avatar.tsx"; +import { createCareerBoard, type CareerBoardHandle, type StopStatus } from "./careerBoard3d.ts"; +import { STAGES, highestOpen, unlockOf, type CareerState } from "./careerRules.ts"; + +/** 每一關的圖示(規則在 careerRules.ts) */ +const STAGE_ICON: Record = { + 1: Home, + 2: Users, + 3: Landmark, + 4: Flag, + 5: Crown, +}; + +export function StageIcon({ stage, size }: { stage: number; size: number }) { + const Icon = STAGE_ICON[stage] ?? Flag; + return ; +} + +/** 每一關現在的狀態:還沒解鎖、可以選、選上過(或跳過) */ +function statusOf(career: CareerState, stage: number): StopStatus { + const t = career.tiers[stage]!; + if (!unlockOf(career, stage).open) return "locked"; + return t.wins > 0 || career.skipped.includes(stage) ? "done" : "open"; +} + +function stopNote(career: CareerState, stage: number): string { + const t = career.tiers[stage]!; + const lock = unlockOf(career, stage); + if (!lock.open) return lock.why; + if (career.skipped.includes(stage) && !t.runs) return "跳過"; + if (t.wins) return `當選 ${t.wins} 次${t.best ? `・最佳 ${t.best}` : ""}`; + if (t.runs) return `參選 ${t.runs} 次・還沒選上`; + return "可以參選"; +} + +/** + * 生涯棋盤(18 第 47 項):3D 紙板桌遊(careerBoard3d.ts),五關的名牌是浮在建築上方的按鈕。 + * 讀不到 WebGL 時改成一排五張關卡牌。 + */ +export function CareerBoard({ career, selected, onSelect }: { career: CareerState; selected: number; onSelect: (stage: number) => void }) { + const here = highestOpen(career); + const [mode, setMode] = useState<"3d" | "2d">("3d"); + const [loading, setLoading] = useState(true); + const wrapRef = useRef(null); + const canvasRef = useRef(null); + const handleRef = useRef(null); + const labelRefs = useRef<(HTMLDivElement | null)[]>([]); + const statuses = STAGES.map((s) => statusOf(career, s.stage)); + const latest = useRef({ statuses, selected, here, onSelect }); + latest.current = { statuses, selected, here, onSelect }; + + useEffect(() => { + if (mode !== "3d") return; + const canvas = canvasRef.current; + const wrap = wrapRef.current; + if (!canvas || !wrap) return; + const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; + const lowPower = matchMedia("(max-width: 720px)").matches || (navigator.hardwareConcurrency ?? 8) <= 4; + const now = latest.current; + const handle = createCareerBoard(canvas, { + stops: now.statuses.map((status) => ({ status })), + selected: now.selected - 1, + here: now.here - 1, + reduceMotion, + lowPower, + onReady: () => setLoading(false), + onError: () => setMode("2d"), + onPick: (i) => latest.current.onSelect(i + 1), + onAnchors: (points) => + points.forEach((p, i) => { + const el = labelRefs.current[i]; + if (el) el.style.transform = `translate(${Math.round(p.x)}px, ${Math.round(p.y)}px)`; + }), + }); + handleRef.current = handle; + const size = () => { + const r = wrap.getBoundingClientRect(); + handle.resize(Math.round(r.width), Math.round(r.height)); + }; + size(); + const ro = new ResizeObserver(size); + ro.observe(wrap); + const onVis = () => handle.setActive(!document.hidden); + document.addEventListener("visibilitychange", onVis); + return () => { + ro.disconnect(); + document.removeEventListener("visibilitychange", onVis); + handle.dispose(); + handleRef.current = null; + }; + }, [mode]); + + const key = statuses.join(","); + useEffect( + () => + handleRef.current?.setStops( + latest.current.statuses.map((status) => ({ status })), + selected - 1, + here - 1, + ), + [key, selected, here], + ); + + if (mode === "2d") { + return ( +
    + {STAGES.map((s, i) => ( +
    + + {s.stage === here && ( + + + + )} +
    + ))} +
    + ); + } + + return ( +
    + + {loading &&

    擺棋盤中…

    } +
    + {STAGES.map((s, i) => ( +
    { + labelRefs.current[i] = el; + }} + className={`cb-stop is-${statuses[i]}${selected === s.stage ? " is-selected" : ""}`} + > +
    + {s.stage === here && ( + + + + )} + +
    +
    + ))} +
    +
    + ); +} diff --git a/web/src/game/rogue/CareerSetup.tsx b/web/src/game/rogue/CareerSetup.tsx new file mode 100644 index 0000000..731fdf6 --- /dev/null +++ b/web/src/game/rogue/CareerSetup.tsx @@ -0,0 +1,299 @@ +import { BACKGROUNDS, PARTY_RECORDS, STAT_BUDGET, type CustomCandidate } from "@election2026/protocol"; +import { ArrowLeft, ArrowRight, Check, Dices, Home, Landmark, Play, Shirt, UserPlus, X } from "lucide-react"; +import { useMemo, useState } from "react"; +import { Avatar, avatarFromSeed } from "../art/Avatar.tsx"; +import { sfx } from "../audio/sfx.ts"; +import { deleteCharacter, loadCharacters, saveCharacter, type SavedCharacter } from "../creator/characters.ts"; +import { partyFacts } from "../parties.ts"; +import { ConfirmDialog } from "../ui/ConfirmDialog.tsx"; +import { partyTone } from "./CareerSheet.tsx"; + +type County = { code: string; name: string }; +/** 快速捏人物直接列出來的政黨;其他政黨在下拉選單裡(歷屆推出過候選人的政黨都有,parties.ts) */ +const QUICK_PARTIES = ["民主進步黨", "中國國民黨", "台灣民眾黨", null] as const; +const STEPS = ["選角色", "家鄉", "起點"] as const; + +/** 快速捏一個角色(完整版在 #/create 更衣間) */ +function QuickCharacter({ onDone, onCancel }: { onDone: (c: SavedCharacter) => void; onCancel: (() => void) | null }) { + const [name, setName] = useState(""); + const [party, setParty] = useState(null); + const [background, setBackground] = useState<(typeof BACKGROUNDS)[number]>("基層里長"); + const [seed, setSeed] = useState(() => `career-${Date.now()}`); + const avatar = useMemo(() => avatarFromSeed(seed), [seed]); + const valid = name.trim().length >= 2 && name.trim().length <= 12; + const per = Math.floor(STAT_BUDGET / 5); + return ( +
    +
    + + +
    +
    + +
    + 政黨 +
    + {QUICK_PARTIES.map((p) => ( + + ))} +
    + +
    +
    + 出身 +
    + {BACKGROUNDS.map((b) => ( + + ))} +
    +
    +
    + {onCancel && ( + + )} + +
    +
    +
    + ); +} + +/** + * 開始一段新的政治生涯(18 第 47 項):像遊戲的選角畫面,三步——選角色、家鄉、起點。 + * 衣櫃裡的角色可以丟掉(要確認);也可以在這裡快速捏一個,或到更衣間仔細捏。 + */ +export function CareerSetup({ counties, onBegin }: { counties: County[]; onBegin: (c: SavedCharacter, county: County, skip: boolean) => void }) { + const [characters, setCharacters] = useState(loadCharacters); + const [picked, setPicked] = useState(null); + const [quick, setQuick] = useState(() => loadCharacters().length === 0); + const [step, setStep] = useState(0); + const [county, setCounty] = useState(""); + const [skip, setSkip] = useState(false); + const [dropping, setDropping] = useState(null); + const groups = useMemo( + () => [ + { title: "直轄市", list: counties.filter((c) => c.code.startsWith("6")) }, + { + title: "其他縣市", + list: counties.filter((c) => !c.code.startsWith("6")), + }, + ], + [counties], + ); + const home = counties.find((c) => c.code === county); + const go = (n: number) => { + sfx.flip(); + setStep(n); + }; + + return ( +
    +
      + {STEPS.map((s, i) => ( +
    1. + {i < step ? : i + 1} + {s} +
    2. + ))} +
    + + {step === 0 && ( +
    + {quick ? ( + { + setCharacters(loadCharacters()); + setPicked(c); + setQuick(false); + }} + onCancel={characters.length ? () => setQuick(false) : null} + /> + ) : ( +
    +
    + +
    + {characters.map((c) => ( +
    + + +
    + ))} +
    + )} + {!quick && ( + + )} +
    + )} + + {step === 1 && picked && ( +
    +

    + + + {picked.name}的家鄉在哪裡?里長、議員、立委都在這裡選 + +

    +
    + {groups.map((g) => ( +
    +

    {g.title}

    +
    + {g.list.map((c) => ( + + ))} +
    +
    + ))} + {!counties.length &&

    讀取縣市清單…

    } +
    +
    + + +
    +
    + )} + + {step === 2 && picked && home && ( +
    +
    + + +
    +
    + + +
    +
    + )} + + {dropping && ( + setDropping(null)} + onConfirm={() => { + deleteCharacter(dropping.id); + const left = loadCharacters(); + setCharacters(left); + if (picked?.id === dropping.id) setPicked(null); + if (!left.length) setQuick(true); + setDropping(null); + }} + > +

    這個角色會從衣櫃(捏人物)裡刪掉。進行中的政治生涯不受影響。

    +
    + )} +
    + ); +} diff --git a/web/src/game/rogue/CareerSheet.tsx b/web/src/game/rogue/CareerSheet.tsx new file mode 100644 index 0000000..b6ec126 --- /dev/null +++ b/web/src/game/rogue/CareerSheet.tsx @@ -0,0 +1,150 @@ +import { Coins, Megaphone, RotateCcw, ShieldCheck, Sparkles, Tv, UserMinus, Users, type LucideIcon } from "lucide-react"; +import { Avatar } from "../art/Avatar.tsx"; +import { PARTY_RESOURCES, originBonusText, partyKind, type Background } from "@election2026/protocol"; +import { partyColor } from "../parties.ts"; +import type { Ability } from "../career/term/types.ts"; +import { ABILITY_IDS, ABILITY_LABELS, MAX_LEVEL, toNext, type CareerState } from "./careerRules.ts"; + +/** 五項能力的圖示與顏色(和標題畫面選單同一組顏色) */ +const ABILITY_LOOK: Record = { + eloquence: { Icon: Megaphone, color: "#d61f2c" }, + organization: { Icon: Users, color: "#1f8a4c" }, + media: { Icon: Tv, color: "#2f6fd1" }, + finance: { Icon: Coins, color: "#c99400" }, + integrity: { Icon: ShieldCheck, color: "#7a5cc4" }, +}; + +/** 政黨色(tokens.css 的政黨槽位色;三大黨以外是灰色,見 parties.ts) */ +export const partyTone = partyColor; + +/** + * 角色卡(18 第 44、47 項):像遊戲的角色面板——頭像名牌、等級徽章、經驗條、技能點、五項能力。 + * 有技能點時能力旁的+會亮;加過的點可以重新分配;最下面可以換人物(結束這段生涯)。 + */ +export function CareerSheet({ + career, + effects, + onPlus, + onReset, + onQuit, +}: { + career: CareerState; + effects: Map; + onPlus: (a: Ability) => void; + onReset: () => void; + onQuit: () => void; +}) { + const need = toNext(career.level); + const spent = ABILITY_IDS.reduce((a, id) => a + career.abilities[id] - career.base[id], 0); + const c = career.character; + return ( + + ); +} + +/** 出身和黨的資源(不能自己點的加成,18 第 53 項):角色卡和捏人物都用這個 */ +export function OriginPerks({ background, party }: { background: Background; party: string | null }) { + const res = PARTY_RESOURCES[partyKind(party)]; + return ( +
    +
    +
    出身・{background}
    +
    {originBonusText(background)}
    +
    +
    +
    黨的資源・{res.label}
    +
    + {res.perks.join("、")} + {res.costs.length > 0 && 代價:{res.costs.join("、")}} +
    +
    +
    + ); +} diff --git a/web/src/game/rogue/CareerStage.tsx b/web/src/game/rogue/CareerStage.tsx new file mode 100644 index 0000000..4416b5d --- /dev/null +++ b/web/src/game/rogue/CareerStage.tsx @@ -0,0 +1,226 @@ +import type { RogueVillageList, ScenarioSummary } from "@election2026/protocol"; +import { useState } from "react"; +import { Check, Coins, Flame, Layers, Lock, MapPin, Play, TrendingUp, Users, X } from "lucide-react"; +import { StageIcon } from "./CareerBoard.tsx"; +import { MAX_EXTRA, STAGES, clamp, runExp, unlockOf, type CareerState } from "./careerRules.ts"; + +/** + * 出征卡(18 第 47 項):選好的那一關——在哪裡選、紀錄、再加逆風、當選拿多少經驗、帶著什麼出發。 + * 還沒解鎖的關列出條件(打勾的已經達成)。 + */ +export function CareerStage({ + career, + stage, + extra, + onExtra, + where, + districts, + district, + onDistrict, + busy, + ready, + onGo, + villages, + onVillage, +}: { + career: CareerState; + stage: number; + extra: number; + onExtra: (n: number) => void; + where: string; + districts: readonly ScenarioSummary[]; + district: string | null; + onDistrict: (id: string) => void; + busy: boolean; + ready: boolean; + onGo: (extra: number) => void; + /** 里長關:這個縣市的區和里;不是里長關是 null */ + villages: RogueVillageList | null; + onVillage: (code: string | null, town: string | null) => void; +}) { + const def = STAGES[stage - 1]!; + const t = career.tiers[stage]!; + const lock = unlockOf(career, stage); + const maxExtra = Math.min(MAX_EXTRA, t.topExtra + 1); + const runExtra = clamp(extra, 0, maxExtra); + const win = runExp(career, stage, true, "B", runExtra).exp; + const lose = runExp(career, stage, false, "C", runExtra).exp; + const carry = career.carry; + const prev = STAGES[stage - 2]; + const prevOk = stage === 1 || career.tiers[stage - 1]!.wins > 0 || career.skipped.includes(stage - 1); + const chips = [`第 ${stage} 關`, `基本逆風 ${def.ascension}`, t.runs ? `參選 ${t.runs} 次` : "還沒參選過", ...(t.wins ? [`當選 ${t.wins} 次`] : []), ...(t.best ? [`最佳 ${t.best}`] : [])]; + + return ( +
    +
    + + {lock.open ? : } + +
    +

    {def.title}

    +
      + {chips.map((c) => ( +
    • {c}
    • + ))} +
    +
    +
    + + {lock.open ? ( + <> +
    +

    + {where} +

    + {villages && } + {def.kind === "legislator" && districts.length > 1 && ( + + )} +
    + 再加逆風 +
    + {Array.from({ length: MAX_EXTRA + 1 }, (_, n) => ( + + ))} +
    +
    + {(carry.advisors.length > 0 || carry.cards.length > 0 || carry.money > 0 || carry.momentum > 0) && ( +
      + {carry.advisors.length > 0 && ( +
    • + 幕僚 {carry.advisors.length} +
    • + )} + {carry.cards.length > 0 && ( +
    • + 牌 {carry.cards.length} +
    • + )} + {carry.money > 0 && ( +
    • + {carry.money} 萬 +
    • + )} + {carry.momentum > 0 && ( +
    • + 聲勢 +{carry.momentum} +
    • + )} +
    + )} +
    +
    +
    + 當選可得 + + +{win} + 經驗 + + 落選也有 +{lose} +
    +
    + {career.pending && ( + + 繼續打到一半的那一局 + + )} + +
    +
    + + ) : ( +
    +

    還沒解鎖。達成下面的條件就能參選:

    +
      + {prev && ( +
    • + {prevOk ? : } 選上{prev.title} +
    • + )} +
    • = def.req ? "is-ok" : ""}> + {career.level >= def.req ? : } 等級 Lv {def.req} + + + + 現在 Lv {career.level} +
    • +
    +

    在前面的關多選幾次,落選也有經驗;回去選比較低的關經驗打六折。

    +
    + )} +
    + ); +} + +/** 里長關挑里:先挑區、再挑里(附選舉人數);不挑就照人口隨機抽 */ +function VillagePicker({ list, village, onVillage }: { list: RogueVillageList; village: string | null; onVillage: (code: string | null, town: string | null) => void }) { + const current = list.towns.find((t) => t.villages.some((v) => v.code === village)); + const [town, setTown] = useState(current?.name ?? ""); + const shown = list.towns.find((t) => t.name === town); + return ( +
    + + {shown && ( + + )} +
    + ); +} diff --git a/web/src/game/rogue/Collection.tsx b/web/src/game/rogue/Collection.tsx new file mode 100644 index 0000000..d255c58 --- /dev/null +++ b/web/src/game/rogue/Collection.tsx @@ -0,0 +1,664 @@ +import type { RogueCatalog } from "@election2026/protocol"; +import { Award, BookOpen, Check, ChevronLeft, ChevronRight, Flame, Layers, Lock, Newspaper, Trophy, Users, X, type LucideIcon } from "lucide-react"; +import { + Fragment, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type KeyboardEvent as ReactKeyboardEvent, + type MouseEvent as ReactMouseEvent, + type PointerEvent as ReactPointerEvent, + type ReactNode, + type RefObject, +} from "react"; +import { createPortal } from "react-dom"; +import { rogueApi } from "../api.ts"; +import { sfx } from "../audio/sfx.ts"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { AdvisorFace, OfferFace, cardKind } from "./cards.tsx"; +import { loadProgress, type Progress } from "./progress.ts"; +import "./collection.css"; + +/** + * 圖鑑與成就(#/rogue/collection):一本選戰卡冊。 + * 右邊(手機在上面)是索引貼:牌、幕僚、每週事件、成就。一頁一頁的卡套,收錄過的全彩, + * 還沒收錄的灰色,但名字、效果照樣看得到,下面寫怎麼拿到。點一格看大張的說明。 + * 翻頁:上一頁/下一頁、鍵盤左右鍵、手機左右滑。資料存在玩家自己的瀏覽器(progress.ts)。 + */ + +type Tab = "cards" | "advisors" | "events" | "feats"; + +const TABS: { id: Tab; label: string; Icon: LucideIcon; note: string }[] = [ + { id: "cards", label: "牌", Icon: Layers, note: "在牌組、獎勵或物資行出現過,就會收進卡冊。" }, + { id: "advisors", label: "幕僚", Icon: Users, note: "在你的團隊、招募或物資行出現過,就會收進卡冊。" }, + { id: "events", label: "每週事件", Icon: Newspaper, note: "遇到一次就會收進卡冊。" }, + { id: "feats", label: "成就", Icon: Award, note: "達成條件,這枚獎章就會亮起來。" }, +]; + +/** 牌依類型分組的順序(類型由牌的標籤決定,和牌面的色條一樣) */ +const KIND_ORDER = ["ground", "rally", "org", "media", "defend", "attack", "money", "status"]; +const RARITY_ORDER = ["basic", "common", "rare", "status"]; +const RARITY_LABEL: Record = { basic: "基本", common: "普通", rare: "稀有", status: "狀態" }; +const SCHOOLS: { id: string; label: string }[] = [ + { id: "ground", label: "地面戰" }, + { id: "air", label: "空戰" }, + { id: "org", label: "組織" }, + { id: "money", label: "資金" }, + { id: "defend", label: "攻防" }, + { id: "any", label: "通用" }, +]; +/** 後端沒給「怎麼拿到」時的說法 */ +const DEFAULT_HOW: Record, string> = { + cards: "拜會地方、競選物資行、地方抉擇", + advisors: "招募幕僚、競選物資行、地方抉擇", + events: "每週開始時隨機發生", +}; + +interface Entry { + id: string; + name: string; + /** 大張說明裡的一句話:牌和幕僚的效果、事件內容;成就是拿到的日期 */ + desc: string; + meta: string; + howLabel: string; + how: string; + got: boolean; + /** 卡套下面的小字 */ + cap: string; + group: string | null; + face: ReactNode; +} + +interface Group { + id: string; + label: string; + start: number; + size: number; + got: number; +} + +interface Section { + entries: Entry[]; + groups: Group[]; + got: number; +} + +const rankOf = (order: readonly string[], id: string) => { + const i = order.indexOf(id); + return i < 0 ? order.length : i; +}; + +/** 分組(已排好序,同組連在一起):每組從第幾格開始、幾格、收錄幾格 */ +function groupsOf(entries: readonly Entry[], labels: ReadonlyMap): Group[] { + const ids = [...new Set(entries.flatMap((e) => (e.group === null ? [] : [e.group])))]; + return ids.map((id) => { + const members = entries.filter((e) => e.group === id); + return { id, label: labels.get(id) ?? "其他", start: entries.findIndex((e) => e.group === id), size: members.length, got: members.filter((e) => e.got).length }; + }); +} + +function section(entries: Entry[], labels: ReadonlyMap = new Map()): Section { + return { entries, groups: groupsOf(entries, labels), got: entries.filter((e) => e.got).length }; +} + +function buildSections(catalog: RogueCatalog, progress: Progress): Record { + const seenCards = new Set(progress.seen.cards); + const seenAdvisors = new Set(progress.seen.advisors); + const seenEvents = new Set(progress.seen.events); + + const sortedCards = catalog.cards + .map((c) => ({ c, kind: cardKind(c.tags) })) + .sort((a, b) => rankOf(KIND_ORDER, a.kind.id) - rankOf(KIND_ORDER, b.kind.id) || rankOf(RARITY_ORDER, a.c.rarity) - rankOf(RARITY_ORDER, b.c.rarity)); + const kindLabels = new Map(sortedCards.map(({ kind }) => [kind.id, kind.label])); + const cards = sortedCards.map(({ c, kind }): Entry => { + const got = seenCards.has(c.id); + const how = c.how ?? DEFAULT_HOW.cards; + const meta = [RARITY_LABEL[c.rarity] ?? "", kind.label, c.cost !== null ? `體力 ${c.cost}` : "", c.money ? `${c.money} 萬` : "", ...c.keywords]; + return { id: c.id, name: c.name, desc: c.text, meta: meta.filter(Boolean).join("・"), howLabel: "怎麼拿到", how, got, cap: got ? "已收錄" : how, group: kind.id, face: }; + }); + + const schoolLabels = new Map(SCHOOLS.map((s) => [s.id, s.label])); + const schoolIds = SCHOOLS.map((s) => s.id); + const advisors = [...catalog.advisors] + .sort((a, b) => rankOf(schoolIds, a.school) - rankOf(schoolIds, b.school)) + .map((a): Entry => { + const got = seenAdvisors.has(a.id); + const how = a.how ?? DEFAULT_HOW.advisors; + const school = schoolLabels.get(a.school) ?? "其他"; + return { id: a.id, name: a.name, desc: a.text, meta: `${school}幕僚`, howLabel: "怎麼拿到", how, got, cap: got ? "已收錄" : how, group: a.school, face: }; + }); + + const events = catalog.events.map((e): Entry => { + const got = seenEvents.has(e.id); + const how = e.how ?? DEFAULT_HOW.events; + return { id: e.id, name: e.title, desc: e.text, meta: "每週事件", howLabel: "怎麼遇到", how, got, cap: got ? "已收錄" : how, group: null, face: }; + }); + + const feats = catalog.feats.map((f): Entry => { + const date = progress.feats[f.id]; + const got = !!date; + return { + id: f.id, + name: f.name, + desc: got ? `${date} 拿到這枚獎章。` : "還沒達成。", + meta: "成就獎章", + howLabel: "達成條件", + how: f.text, + got, + cap: got ? `${date} 拿到` : "還沒達成", + group: null, + face: , + }; + }); + + return { cards: section(cards, kindLabels), advisors: section(advisors, schoolLabels), events: section(events), feats: section(feats) }; +} + +// ── 版面:量卡冊內頁的大小,算出一頁放幾欄幾列、牌多寬(整頁不捲) ── + +const CARD_RATIO = 1.47; +const MAX_CARD_W = 150; + +interface BookLayout { + pages: 1 | 2; + cols: number; + rows: number; + cardW: number; + gap: number; + pad: number; + cap: number; + pagePad: number; + spine: number; +} + +/** 電腦版兩頁攤開、手機一頁;每頁最多 4 欄 3 列。手機盡量多放幾格,電腦版讓牌大一點 */ +function fitBook(w: number, h: number): BookLayout { + const small = w < 440; + const pages = w >= 860 ? 2 : 1; + const m = small ? { gap: 6, pad: 4, cap: 30, pagePad: 2, minW: 84 } : { gap: 14, pad: 8, cap: 36, pagePad: 12, minW: 100 }; + const spine = pages === 2 ? 40 : 0; + const pageW = (w - spine) / pages - m.pagePad * 2; + const pageH = h - m.pagePad * 2; + const fromH = (rows: number) => ((pageH - (rows - 1) * m.gap) / rows - m.pad * 2 - m.cap) / CARD_RATIO; + const fromW = (cols: number) => (pageW - (cols - 1) * m.gap) / cols - m.pad * 2; + const candidates = [1, 2, 3].flatMap((rows) => + [1, 2, 3, 4].map((cols) => ({ rows, cols, cardW: Math.floor(Math.min(fromH(rows), fromW(cols), MAX_CARD_W)) })), + ); + const score = (c: { rows: number; cols: number; cardW: number }) => (small ? c.rows * c.cols * 1000 + c.cardW : c.rows * c.cols * c.cardW * c.cardW); + const best = candidates.filter((c) => c.cardW >= m.minW).sort((a, b) => score(b) - score(a))[0]; + if (best) return { pages, ...best, gap: m.gap, pad: m.pad, cap: m.cap, pagePad: m.pagePad, spine }; + // 很矮的畫面(手機橫放):放一列,牌縮小 + const cardW = Math.max(56, Math.floor(Math.min(fromH(1), MAX_CARD_W))); + const cols = Math.max(1, Math.min(6, Math.floor((pageW + m.gap) / (cardW + m.pad * 2 + m.gap)))); + return { pages, rows: 1, cols, cardW, gap: m.gap, pad: m.pad, cap: m.cap, pagePad: m.pagePad, spine }; +} + +const layoutKey = (l: BookLayout) => `${l.pages}/${l.cols}/${l.rows}/${l.cardW}/${l.gap}`; + +function useBookLayout(el: HTMLElement | null): BookLayout | null { + const [layout, setLayout] = useState(null); + useLayoutEffect(() => { + if (!el) return; + const measure = () => { + const next = fitBook(el.clientWidth, el.clientHeight); + setLayout((prev) => (prev && layoutKey(prev) === layoutKey(next) ? prev : next)); + }; + measure(); + const ro = new ResizeObserver(measure); + ro.observe(el); + return () => ro.disconnect(); + }, [el]); + return layout; +} + +const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; + +/** 手機左右滑:滑超過 48px 算翻頁;follow 給的元素會跟著手指移一點 */ +function useSwipe(onSwipe: (dir: 1 | -1) => void, follow?: RefObject) { + const start = useRef<{ x: number; y: number } | null>(null); + const swiped = useRef(false); + const shift = (dx: number | null) => { + const el = follow?.current; + if (!el) return; + el.classList.toggle("is-dragging", dx !== null); + el.style.transform = dx === null ? "" : `translateX(${dx}px)`; + }; + return { + onPointerDown: (e: ReactPointerEvent) => { + swiped.current = false; + if (e.pointerType === "mouse") return; + start.current = { x: e.clientX, y: e.clientY }; + }, + onPointerMove: (e: ReactPointerEvent) => { + const s = start.current; + if (!s || reducedMotion()) return; + const dx = e.clientX - s.x; + if (Math.abs(dx) > 8 && Math.abs(dx) > Math.abs(e.clientY - s.y)) shift(dx * 0.35); + }, + onPointerUp: (e: ReactPointerEvent) => { + const s = start.current; + start.current = null; + shift(null); + if (!s) return; + const dx = e.clientX - s.x; + if (Math.abs(dx) > 48 && Math.abs(dx) > Math.abs(e.clientY - s.y) * 1.2) { + // 只擋掉緊接著的那一下點擊;手機滑完通常不會有點擊,所以一下子就放掉 + swiped.current = true; + setTimeout(() => (swiped.current = false), 300); + onSwipe(dx < 0 ? 1 : -1); + } + }, + onPointerCancel: () => { + start.current = null; + shift(null); + }, + /** 滑完不要順便點開那一格 */ + onClickCapture: (e: ReactMouseEvent) => { + if (!swiped.current) return; + swiped.current = false; + e.preventDefault(); + e.stopPropagation(); + }, + }; +} + +const ratio = (a: number, b: number) => (b ? a / b : 0); + +export function RogueCollection() { + const [catalog, setCatalog] = useState(null); + const [error, setError] = useState(null); + const [progress] = useState(loadProgress); + const [tab, setTab] = useState("cards"); + /** 每個分頁停在哪一格(換版面大小時,還是停在同一張附近) */ + const [anchors, setAnchors] = useState>({ cards: 0, advisors: 0, events: 0, feats: 0 }); + const [motion, setMotion] = useState<"next" | "prev" | "tab">("tab"); + const [open, setOpen] = useState(null); + const [spreadEl, setSpreadEl] = useState(null); + const dragRef = useRef(null); + const focusAfterFlip = useRef(false); + const layout = useBookLayout(spreadEl); + + useEffect(() => { + rogueApi + .catalog() + .then(setCatalog) + .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e))); + }, []); + + const sections = useMemo(() => (catalog ? buildSections(catalog, progress) : null), [catalog, progress]); + const current = sections?.[tab] ?? null; + const entries = current?.entries ?? []; + const perPage = layout ? layout.cols * layout.rows : 1; + const perSpread = perPage * (layout?.pages ?? 1); + const spreads = Math.max(1, Math.ceil(entries.length / perSpread)); + const page = Math.min(Math.floor(anchors[tab] / perSpread), spreads - 1); + const first = page * perSpread; + + const goTo = (index: number, sound = true) => { + const target = Math.floor(index / perSpread); + if (target !== page) setMotion(target > page ? "next" : "prev"); + setAnchors((a) => ({ ...a, [tab]: index })); + if (sound && target !== page) sfx.paper(); + }; + const flip = (dir: 1 | -1) => { + const next = page + dir; + if (next < 0 || next >= spreads) return; + goTo(next * perSpread); + }; + const selectTab = (t: Tab) => { + if (t === tab) return; + setMotion("tab"); + setTab(t); + sfx.flip(); + }; + const openAt = (i: number) => { + setOpen(i); + sfx.flip(); + }; + const step = (dir: 1 | -1) => { + if (open === null || !entries.length) return; + const i = (open + dir + entries.length) % entries.length; + setOpen(i); + goTo(i, false); + sfx.card(); + }; + const close = () => { + const id = open === null ? null : entries[open]?.id; + setOpen(null); + requestAnimationFrame(() => { + const el = id ? document.querySelector(`.col-pocket[data-col-id="${CSS.escape(id)}"]`) : null; + el?.focus({ preventScroll: true }); + }); + }; + + // 鍵盤:左右鍵翻頁;看大張時左右鍵換一張、Esc 關掉 + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.altKey || e.ctrlKey || e.metaKey) return; + const t = e.target as HTMLElement | null; + if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return; + if (open !== null) { + if (e.key === "Escape") close(); + else if (e.key === "ArrowLeft") step(-1); + else if (e.key === "ArrowRight") step(1); + else return; + e.preventDefault(); + return; + } + const dir = e.key === "ArrowLeft" || e.key === "PageUp" ? -1 : e.key === "ArrowRight" || e.key === "PageDown" ? 1 : 0; + if (!dir) return; + e.preventDefault(); + focusAfterFlip.current = !!spreadEl?.contains(document.activeElement); + flip(dir); + }; + addEventListener("keydown", onKey); + return () => removeEventListener("keydown", onKey); + }); + + // 用鍵盤翻頁時,焦點移到新一頁的第一格 + useEffect(() => { + if (!focusAfterFlip.current) return; + focusAfterFlip.current = false; + spreadEl?.querySelector(".col-pocket[data-col-id]")?.focus({ preventScroll: true }); + }, [page, tab, spreadEl]); + + const swipe = useSwipe(flip, dragRef); + + const onTabKey = (e: ReactKeyboardEvent) => { + const i = TABS.findIndex((t) => t.id === tab); + const next = e.key === "ArrowDown" ? i + 1 : e.key === "ArrowUp" ? i - 1 : e.key === "Home" ? 0 : e.key === "End" ? TABS.length - 1 : null; + if (next === null) return; + e.preventDefault(); + const t = TABS[(next + TABS.length) % TABS.length]!; + selectTab(t.id); + document.getElementById(`col-tab-${t.id}`)?.focus(); + }; + + const all = sections ? Object.values(sections) : []; + const totalGot = all.reduce((n, s) => n + s.got, 0); + const total = all.reduce((n, s) => n + s.entries.length, 0); + const hud = ( + <> + + } value={`${progress.wins}/${progress.runs}`} label="勝場/局數" /> + + + } value={`${progress.ascension} 級`} label="逆風解鎖" /> + + } value={total ? `${Math.round(ratio(totalGot, total) * 100)}%` : "—"} label="卡冊收錄" /> + + ); + + const tabInfo = TABS.find((t) => t.id === tab)!; + const vars = layout + ? ({ + "--col-card-w": `${layout.cardW}px`, + "--col-cols": layout.cols, + "--col-gap": `${layout.gap}px`, + "--col-pad": `${layout.pad}px`, + "--col-cap": `${layout.cap}px`, + "--col-page-pad": `${layout.pagePad}px`, + "--col-spine": `${layout.spine}px`, + } as CSSProperties) + : undefined; + + return ( + +
    +
    + {TABS.map((t) => { + const s = sections?.[t.id]; + return ( + + ); + })} +
    + +
    +
    +
    +
    +

    {tabInfo.label}

    + {current ? `${current.got}/${entries.length}` : "—"} + + + +
    + {tab === "feats" ? ( +

    + + {progress.runs} 局・{progress.wins} 勝・逆風解鎖 {progress.ascension} 級 + + 紀錄只存在這台裝置的瀏覽器裡,清除瀏覽器資料會重來 +

    + ) : current && current.groups.length > 0 ? ( + + ) : ( +

    {tabInfo.note}

    + )} +
    + +
    + {!sections || !layout ? ( +

    {error ?? "翻開卡冊…"}

    + ) : ( +
    + {Array.from({ length: layout.pages }, (_, p) => { + const from = first + p * perPage; + return ( + + {p === 1 && ( +
    + + + + +
    + )} +
    +
      + {Array.from({ length: perPage }, (_, k) => { + const entry = entries[from + k]; + return ( +
    • + {entry ? openAt(from + k)} /> : } +
    • + ); + })} +
    +
    +
    + ); + })} +
    + )} +
    + +
    + +
    + {spreads <= 12 && ( + + {Array.from({ length: spreads }, (_, i) => ( + + ))} + + )} + + 第 {page + 1}/{spreads} 頁 + + + ← → 翻頁 + +
    + +
    +
    +
    +
    + + {open !== null && entries[open] && ( + + )} +
    + ); +} + +/** 卡冊上的一格卡套 */ +function Pocket({ entry, onOpen }: { entry: Entry; onOpen: () => void }) { + const label = `${entry.name}。${entry.desc.replace(/。$/, "")}。${entry.got ? "已收錄" : `還沒收錄,${entry.howLabel}:${entry.how}`}`; + return ( + + ); +} + +/** 每週事件的牌面:像一張報紙頭條 */ +function EventFace({ title, text }: { title: string; text: string }) { + return ( + + + 本週頭條 + + {title} + {text} + + ); +} + +/** 成就獎章 */ +function MedalFace({ name, text, got }: { name: string; text: string; got: boolean }) { + return ( + + {got ? : } + {name} + {text} + + ); +} + +/** 點一格:大張的牌(或幕僚、事件、獎章)+說明、怎麼拿到 */ +function Detail({ entry, index, total, note, onClose, onStep }: { entry: Entry; index: number; total: number; note: string; onClose: () => void; onStep: (dir: 1 | -1) => void }) { + const boxRef = useRef(null); + const closeRef = useRef(null); + const swipe = useSwipe(onStep); + + useEffect(() => { + closeRef.current?.focus({ preventScroll: true }); + }, []); + + // 焦點留在視窗裡 + const trap = (e: ReactKeyboardEvent) => { + if (e.key !== "Tab" || !boxRef.current) return; + const items = [...boxRef.current.querySelectorAll("button:not([disabled])")]; + const firstEl = items[0]; + const lastEl = items.at(-1); + if (!firstEl || !lastEl) return; + if (e.shiftKey && document.activeElement === firstEl) { + e.preventDefault(); + lastEl.focus(); + } else if (!e.shiftKey && document.activeElement === lastEl) { + e.preventDefault(); + firstEl.focus(); + } + }; + + return createPortal( +
    { + if (e.target === e.currentTarget) onClose(); + }} + > +
    + +
    + + {entry.face} + + {!entry.got && ( + + 未收錄 + + )} +
    +
    +

    + {entry.got ? : } + {entry.got ? "已收錄" : "還沒收錄"} +

    +

    {entry.name}

    +

    {entry.meta}

    +

    {entry.desc}

    +
    + {entry.howLabel} +

    {entry.how}

    +
    + {!entry.got &&

    {note}

    } + +
    +
    +
    , + document.body, + ); +} diff --git a/web/src/game/rogue/MinigameStop.tsx b/web/src/game/rogue/MinigameStop.tsx new file mode 100644 index 0000000..db3f039 --- /dev/null +++ b/web/src/game/rogue/MinigameStop.tsx @@ -0,0 +1,28 @@ +import type { RogueStop } from "@election2026/protocol"; +import { MINI_GAMES } from "../minigames/registry.ts"; +import "./ultimate.css"; + +type Stop = Extract; + +/** + * 下一站「選戰小遊戲」(docs/23):玩完把 0–100 分送給伺服器,伺服器換成加票、聲勢或據點。 + * 不玩就是 skip(不給分)。小遊戲比較大,用到才下載(flow.tsx 用 lazy 載入這個檔案)。 + */ +export function MinigameStop({ stop, busy, onChoose }: { stop: Stop; busy: boolean; onChoose: (pick: number | "skip") => void }) { + const { Game } = MINI_GAMES[stop.game]; + // 小遊戲本身是全螢幕(規則、倒數、結算都在遊戲裡);獎勵說明用伺服器寫的那一句 + return ( +
    + !busy && onChoose(Math.max(0, Math.min(100, Math.round(score))))} + onQuit={() => !busy && onChoose("skip")} + /> +
    + ); +} diff --git a/web/src/game/rogue/RogueScreen.tsx b/web/src/game/rogue/RogueScreen.tsx new file mode 100644 index 0000000..b7dfca2 --- /dev/null +++ b/web/src/game/rogue/RogueScreen.tsx @@ -0,0 +1,623 @@ +import type { MiniGameKind, RogueArea, RogueLog, RogueView } from "@election2026/protocol"; +import { AlertTriangle, Flag, List, Map as MapIcon, PanelRightClose, PanelRightOpen, ThumbsUp } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { Topology } from "topojson-specification"; +import { api, rogueApi } from "../api.ts"; +import { actionIcon } from "../art/actionIcons.ts"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { BoardStage } from "../board3d/BoardStage.tsx"; +import { SettingsMenu } from "../hud/SettingsMenu.tsx"; +import { buildGeometry, type StageGeometry } from "../stage/geometry.ts"; +import { loadContext } from "../stage/loadMap.ts"; +import { MapStage, type FloatText, type StageMarker } from "../stage/MapStage.tsx"; +import { NewsTicker, WeekBrief } from "./brief.tsx"; +import { CoachBubble, useCoach } from "./coach.tsx"; +import { Finale } from "./finale.tsx"; +import { RouteOverlay, SceneOverlay } from "./flow.tsx"; +import { ScorePop, flyCard, useShake, type Score } from "./juice.tsx"; +import { INTENT_ICONS, overall, raceLabel, signed, weekLabel } from "./labels.ts"; +import { DeckDrawer, HelpModal } from "./overlays.tsx"; +import { AdvisorRow, EVENT_UID, Hand, IntentList, RogueHud, TownList } from "./parts.tsx"; +import { UltimateButton, UltimateOverlay } from "./Ultimate.tsx"; +import { WeekEnd } from "./weekend.tsx"; +import { markSeen } from "./progress.ts"; +import "./rogue.css"; + +export const LAST_RUN_KEY = "tongsuan.rogue.last"; +const HELPED_KEY = "tongsuan.rogue.helped"; +const WIDE_KEY = "tongsuan.rogue.wide"; + +const storage = { + get(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } + }, + set(key: string, value: string): void { + try { + localStorage.setItem(key, value); + } catch { + // 私密模式存不了,只是少了「繼續上一局」 + } + }, +}; + +const SCENE_TITLE: Record = { press: "記者堵麥", crisis: "匿名黑函", poll: "民調公布", debate: "電視辯論" }; + +/** + * 選戰卡牌(新玩法,docs/21–23):地圖+各區支持度+對手意圖+手牌。 + * 一週只剩三步(docs/23 流程整合):看對手 → 出牌 → 拿獎勵。 + * - 快報在地圖上方跑馬燈(第一週開場才自動播電視);記者堵麥是手牌裡的事件牌;民調自動公布。 + * - 辯論(第 3 週)、黑函(第 6 週)是大場面,全畫面;選完的結果用提示和地圖跳字顯示,不另外跳視窗。 + * - 結束這週:結算在地圖上播,旁邊同一個面板選下一站(門上直接攤開內容)。 + * 規則都在伺服器;每個動作拿回新的狀態,畫面只負責演出。 + */ +export function RogueScreen({ runId }: { runId: string }) { + const [view, setView] = useState(null); + const [geometry, setGeometry] = useState(null); + const [loadError, setLoadError] = useState(null); + const [error, setError] = useState(null); + const [selected, setSelected] = useState(null); + const [busy, setBusy] = useState(false); + const [floats, setFloats] = useState([]); + const [effects, setEffects] = useState<{ key: string; townCode: string; actionId: string }[]>([]); + /** 這週結算的紀錄(週末面板用);開始下一週就清掉 */ + const [weekLog, setWeekLog] = useState(null); + const [lastResolution, setLastResolution] = useState(null); + const [brief, setBrief] = useState(false); + const [score, setScore] = useState(null); + const [toast, setToast] = useState(null); + /** 大絕招面板 */ + const [ultOpen, setUltOpen] = useState(false); + const [help, setHelp] = useState(false); + const [deck, setDeck] = useState(false); + const [focus, setFocus] = useState(null); + const [lastTown, setLastTown] = useState(null); + const [mobileTab, setMobileTab] = useState<"map" | "list">("map"); + // 電腦版:右邊的「各區列表」可以收起來,地圖變全寬;對手這週要做的事改浮在地圖右上角(記在這台瀏覽器) + const [wide, setWide] = useState(() => storage.get(WIDE_KEY) === "1"); + const toggleWide = () => { + sfx.click(); + setWide((w) => { + storage.set(WIDE_KEY, w ? "0" : "1"); + return !w; + }); + }; + const [shakeClass, shake] = useShake(); + const mapRef = useRef(null); + const coach = useCoach(view, selected); + + useEffect(() => { + let alive = true; + rogueApi + .get(runId) + .then(async (v) => { + if (!alive) return; + setView(v); + storage.set(LAST_RUN_KEY, runId); + // 第一週還沒出牌:先看開場電視;第一次玩新玩法、又不是教學關卡時打開說明 + if (v.week === 1 && v.phase === "plan" && v.towns.every((t) => t.played.length === 0)) setBrief(true); + if (!storage.get(HELPED_KEY) && !v.options.tutorial) { + setHelp(true); + storage.set(HELPED_KEY, "1"); + } + if (!v.packId) return; + // 立委選區只畫選區內的村里,地圖放大到選區;選區外的區淡淡地畫在旁邊 + const [topology, context, area] = await Promise.all([api.topology(v.packId), loadContext(), rogueApi.area(runId).catch((): RogueArea => ({ villages: null, groups: null }))]); + if (!alive) return; + // 總統選舉以縣市為單位 + const level = v.countyCode === "00000" ? "county" : "town"; + setGeometry( + buildGeometry(topology as Topology, context, { county: v.countyCode, level, villages: area.villages ? new Set(area.villages) : null, + groups: area.groups ? new Map(Object.entries(area.groups)) : null, + names: new Map(v.towns.map((t) => [t.code, t.name])), + }), + ); + }) + .catch((e: unknown) => alive && setLoadError(e instanceof Error ? e.message : String(e))); + setMusic("planning-loop"); + return () => { + alive = false; + }; + }, [runId]); + + useEffect(() => { + if (view) markSeen(view); + }, [view]); + + // 換週的轉場:新的一週開始時,「第 N 週」橫幅從地圖上掃過去(不擋操作) + const [banner, setBanner] = useState<{ week: number; title: string } | null>(null); + const shownWeek = useRef(null); + useEffect(() => { + if (!view || view.phase === "finished") return; + if (shownWeek.current === view.week) return; + const first = shownWeek.current === null; + shownWeek.current = view.week; + // 第一次進來(含重新整理)有開場電視,不另外掃橫幅 + if (first) return; + setBanner({ week: view.week, title: view.event.title }); + sfx.flip(); + const t = setTimeout(() => setBanner(null), 1600); + return () => clearTimeout(t); + }, [view?.week, view?.phase]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (!toast) return; + // 字多的提示留久一點 + const t = setTimeout(() => setToast(null), Math.min(7000, 2400 + toast.length * 45)); + return () => clearTimeout(t); + }, [toast]); + + const showFloats = useCallback((items: FloatText[]) => { + setFloats(items); + setTimeout(() => setFloats((now) => (now === items ? [] : now)), 1800); + }, []); + + /** 大幅拉票的門檻:約全市投票人數的 0.4% */ + const bigSwing = useMemo(() => (view ? overall(view.towns).voters * 0.004 : Infinity), [view?.runId]); // eslint-disable-line react-hooks/exhaustive-deps + + const onResolveStep = useCallback( + (entry: RogueLog, i: number) => { + if (entry.town && entry.votes !== 0) showFloats([{ key: `r-${i}-${entry.town}`, townCode: entry.town, text: signed(entry.votes), tone: entry.votes > 0 ? "good" : "bad" }]); + if (entry.text.includes("翻")) shake("large"); + else if (entry.side === "rival" && Math.abs(entry.votes) >= bigSwing) shake("small"); + }, + [showFloats, shake, bigSwing], + ); + const closeBrief = useCallback(() => setBrief(false), []); + const closeScore = useCallback(() => setScore(null), []); + + const townAdults = useMemo(() => (view ? new Map(view.towns.map((t) => [t.code, t.voters])) : null), [view?.runId]); // eslint-disable-line react-hooks/exhaustive-deps + + if (loadError) { + return ( +
    +

    {loadError}

    + + 重新開一局 + +
    + ); + } + if (!view) return
    讀取中…
    ; + + const card = view.hand.find((c) => c.uid === selected) ?? null; + const list = card ? (view.previews[card.uid] ?? []) : []; + const previews = new Map(list.map((p) => [p.target, p])); + const best = new Set(card?.target === "town" ? [...list].sort((a, b) => b.votes - a.votes).slice(0, 3).map((p) => p.target) : []); + const cityPreview = card && (card.target === "city" || card.target === "none") ? (previews.get("city") ?? null) : null; + const targeting = card?.target === "intent" ? "intent" : card?.target === "attack" ? "attack" : null; + + /** 請求失敗後重新拿一次這局的狀態(伺服器可能已經做完了,只是回應沒收到) */ + const recover = (e: unknown) => { + setError(e instanceof Error ? e.message : String(e)); + rogueApi + .get(runId) + .then(setView) + .catch(() => undefined); + }; + + const play = async (target: string | null) => { + if (!card || busy) return; + setBusy(true); + setError(null); + const preview = previews.get(target ?? "city"); + const el = document.querySelector(`.rg-hand-card[data-uid="${card.uid}"]`); + try { + const next = await rogueApi.play(runId, card.uid, target); + flyCard(el, mapRef.current); + if (card.tags.includes("rally")) sfx.cheer(); + else if (card.tags.includes("money")) sfx.coin(); + else if (card.tags.includes("attack")) sfx.alert(); + else sfx.place(); + const votes = next.log.reduce((a, e) => a + e.votes, 0); + const flipped = next.log.some((e) => e.text.startsWith("翻轉")); + // 加成說明用伺服器實際結算的(機率牌會寫爆紅或失言),舊版伺服器沒有就用預估的 + const notes = next.notes.length ? next.notes : (preview?.note ?? "").split("・").filter(Boolean); + // 打對台、澄清、事實查核:對手的行動被削弱的部分(週末才會少拉,先在這裡讓你看到) + const blocked = next.intents.filter((i) => i.kind !== "stake").reduce((a, i) => a + i.amount * Math.max(0, (view.intents.find((x) => x.id === i.id)?.cut ?? i.cut) - i.cut), 0); + if (votes !== 0 || notes.length || blocked > 0) setScore({ key: `${card.uid}`, title: card.name, notes, votes, blocked }); + if (flipped) { + sfx.flag(); + shake("large"); + } else if (Math.abs(votes) >= bigSwing * 1.5) shake("small"); + showFloats(next.log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `${card.uid}-${i}`, townCode: e.town!, text: signed(e.votes), tone: e.votes >= 0 ? "good" : "bad" }))); + const city = next.log.filter((e) => !e.town || e.text.startsWith("翻轉")); + if (city.length) setToast(city.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")); + const town = card.target === "town" ? target : card.target === "intent" ? (view.intents.find((i) => i.id === target)?.town ?? null) : null; + if (town) { + setEffects([{ key: card.uid, townCode: town, actionId: card.art }]); + setLastTown(town); + } + setView(next); + setSelected(null); + } catch (e) { + recover(e); + } finally { + setBusy(false); + } + }; + + /** 大絕招:小遊戲玩完把分數送出,地圖跳字、提示、震動 */ + const fireUltimate = async (kind: MiniGameKind, score: number, towns?: string[]) => { + if (busy) return; + setBusy(true); + setError(null); + try { + const next = await rogueApi.ultimate(runId, kind, score, towns); + setUltOpen(false); + sfx.applause(); + shake("large"); + const votes = next.log.reduce((a, e) => a + e.votes, 0); + const title = view.ultimate?.options.find((o) => o.kind === kind)?.name ?? "大絕招"; + setScore({ key: `ult-${next.week}-${kind}-${score}`, title: `大絕招・${title}`, notes: [`小遊戲 ${Math.round(score)} 分`, `落後倍率 ×${(view.ultimate?.mult ?? 1).toFixed(1)}`], votes, blocked: 0 }); + showFloats(next.log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `ult-${i}-${e.town}`, townCode: e.town!, text: signed(e.votes), tone: "good" }))); + setToast(next.log.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")); + setView(next); + } catch (e) { + setUltOpen(false); + recover(e); + } finally { + setBusy(false); + } + }; + + const endWeek = async () => { + if (busy) return; + setBusy(true); + setError(null); + try { + sfx.stamp(); + const next = await rogueApi.endWeek(runId); + setSelected(null); + setView(next); + setWeekLog(next.log); + setLastResolution(next.log); + } catch (e) { + recover(e); + } finally { + setBusy(false); + } + }; + + /** 選完的結果:地圖上跳字+一條提示(不另外跳視窗) */ + const announce = (title: string | null, log: readonly RogueLog[]) => { + const lines = log.filter((e) => e.text); + if (!lines.length) return; + showFloats(log.filter((e) => e.town && e.votes !== 0).map((e, i) => ({ key: `a-${i}-${e.town}`, townCode: e.town!, text: signed(e.votes), tone: e.votes >= 0 ? "good" : "bad" }))); + setToast(`${title ? `${title}:` : ""}${lines.map((e) => `${e.text}${e.votes ? ` ${signed(e.votes)} 票` : ""}`).join(";")}`); + }; + + const choose = async (pick: number | "skip", target: string | null = null, option?: number) => { + if (busy) return; + setBusy(true); + setError(null); + const before = view; + try { + const next = await rogueApi.choose(runId, pick, target, option); + setView(next); + const sceneKind = before.scene && (before.phase === "scene" || before.phase === "plan") ? before.scene.kind : null; + // 堵麥、黑函、地方抉擇、拿到牌或幕僚:結果用提示和跳字(辯論、深入基層在自己的畫面裡顯示) + if (sceneKind === "press" || sceneKind === "crisis") announce(SCENE_TITLE[sceneKind]!, next.log); + else if (before.phase === "route" || (before.phase === "stop" && before.stop?.kind === "event")) announce(null, next.log); + if (pick !== "skip" && (before.phase === "route" || (before.phase === "stop" && (before.stop?.kind === "card" || before.stop?.kind === "advisor" || before.stop?.kind === "upgrade")))) sfx.good(); + if (sceneKind === "crisis" && next.log.some((e) => e.votes < 0)) shake("small"); + if (sceneKind === "press") setSelected(null); + if (next.week > before.week) { + setWeekLog(null); + setFocus(null); + // 民調公布那週:提示一下(不用點) + if (next.poll?.week === next.week) + setToast(`民調公布:${next.you.name} ${(next.poll.you * 100).toFixed(1)}%、${next.rival.name} ${(next.poll.rival * 100).toFixed(1)}%${next.poll.lead ? ",領先:聲勢 +1" : ",落後:手上多一張「悲情催票」"}`); + } + } catch (e) { + recover(e); + } finally { + setBusy(false); + } + }; + + const again = async (ascension?: number) => { + setBusy(true); + try { + const { runId: next } = view.options.tutorial + ? await rogueApi.tutorial() + : await rogueApi.create(view.scenarioId, view.you.id, { ascension: ascension ?? view.options.ascension, even: view.options.even }); + location.hash = `#/rogue/${next}`; + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(false); + } + }; + + const onMapSelect = (code: string) => { + if (card?.target === "town") { + void play(code); + return; + } + setFocus(code); + document.getElementById(`rg-town-${code}`)?.scrollIntoView({ block: "nearest", behavior: "smooth" }); + }; + + const fills = new Map( + view.towns.map((t) => { + const lead = t.you - t.rival; + const color = lead >= 0 ? view.colors.you : view.colors.rival; + const strength = Math.round(18 + Math.min(1, Math.abs(lead) / (t.voters * 0.12 || 1)) * 62); + return [t.code, `color-mix(in srgb, ${color} ${strength}%, var(--map-base, #e8e4da))`]; + }), + ); + const markers: StageMarker[] = [ + ...view.towns.filter((t) => t.flag).map((t) => ({ key: `flag-${t.code}`, townCode: t.code, icon: Flag, color: t.flag === "you" ? view.colors.you : view.colors.rival, label: `${t.flag === "you" ? "你" : view.rival.name}插旗:${t.name}` })), + ...view.intents + .filter((i) => i.town) + .map((i) => ({ key: `intent-${i.id}`, townCode: i.town!, icon: INTENT_ICONS[i.kind], color: view.colors.rival, label: `${view.rival.name}:${i.label}` })), + ...(view.nextBig ? [{ key: "next-big", townCode: view.nextBig.town, icon: AlertTriangle, color: "var(--stamp)", label: `預告:${view.nextBig.label}` }] : []), + ...view.towns.flatMap((t) => t.played.map((p) => ({ key: `played-${t.code}-${p.id}`, townCode: t.code, icon: actionIcon(p.art), color: view.colors.you, label: `你:${p.name}` }))), + ]; + const offices = new Set(view.towns.filter((t) => t.office).map((t) => t.code)); + const rivalTown = view.intents.find((i) => i.big)?.town ?? view.intents.find((i) => i.kind === "rally" && i.town)?.town ?? view.intents.find((i) => i.town)?.town ?? null; + const tokens = [ + ...(lastTown ? [{ key: "me", townCode: lastTown, node: , label: view.you.name, color: view.colors.you }] : []), + ...(rivalTown ? [{ key: "rival", townCode: rivalTown, node: , label: view.rival.name, color: view.colors.rival }] : []), + ]; + + // 開票夜的地圖:還沒開票的區是灰的;開了的區塗上目前領先的顏色,開得越多、差距越大越深;剛開完的那一區框起來、冒出差距 + const voteMap = geometry && view.result + ? (counts: ReadonlyMap, latest: string | null) => { + const final = new Map(view.result!.byTown.map((t) => [t.code, t])); + const fillsNow = new Map( + view.towns.map((t) => { + const c = counts.get(t.code); + if (!c || c.f <= 0) return [t.code, "#8a919c"]; + const total = c.you + c.rival + c.others || 1; + const margin = (c.you - c.rival) / total; + const color = margin >= 0 ? view.colors.you : view.colors.rival; + const strength = (0.35 + 0.65 * c.f) * (45 + Math.min(1, Math.abs(margin) / 0.15) * 55); + return [t.code, `color-mix(in srgb, ${color} ${Math.round(strength)}%, ${c.f >= 1 ? "#ffffff" : "#8a919c"})`]; + }), + ); + const r = latest ? final.get(latest) : undefined; + const floatsNow: FloatText[] = r && latest ? [{ key: `vote-${latest}`, townCode: latest, text: signed(r.you - r.rival), tone: r.you >= r.rival ? "good" : "bad" }] : []; + return ; + } + : undefined; + + // 疊在上面的畫面一次只開一個,照這個順序(週末面板不擋地圖,結算的跳字看得到) + const finale = view.phase === "finished" && view.result && !weekLog; + const overlay = finale + ? "finale" + : brief + ? "brief" + : view.phase === "scene" + ? "scene" + : view.phase === "route" || (view.phase === "finished" && weekLog) + ? "weekend" + : view.phase === "stop" + ? "stop" + : null; + // 記者堵麥:這週要回答的事件牌 + const press = view.phase === "plan" && view.scene?.kind === "press" ? view.scene : null; + const answering = !!press && selected === EVENT_UID; + + return ( +
    + setDeck(true)} onHelp={() => setHelp(true)} /> +
    +
    + {geometry ? ( + + ) : view.packId ? ( +
    地圖讀取中…
    + ) : ( + + )} + {view.phase !== "finished" && setBrief(true)} />} + {banner && ( +
    + {banner.week >= view.totalWeeks ? "最後一週" : `第 ${banner.week} 週`} + {banner.title} +
    + )} + {score && } + {toast && ( +

    + {toast} +

    + )} + {wide && ( +
    + void play(id)} /> +
    + )} +
    + + +
    +
    + +
    + +
    + +
    + {error ? ( +

    {error}

    + ) : answering && press ? ( +
    +

    + 記者問: + {press.question} +

    +
    + {press.choices.map((c, i) => ( + + ))} +
    +
    + ) : !card ? ( +

    + {press ? ( + <> + 記者堵麥:點最左邊的事件牌回答(這週內回答就好)。 + + ) : ( + <> + 挑一張牌。同一區打不同的牌是組合拳;對手要在某區行動時可以打對台或先佈樁擋下來。 + + )} +

    + ) : card.blocked ? ( +

    + {card.name}:{card.blocked} +

    + ) : card.target === "town" ? ( +

    + {card.name}:點地圖或「各區」裡的一區,標 的是最划算的三區。 +

    + ) : card.target === "intent" ? ( +

    + {card.name}:點對手在某一區的行動來打對台。 +

    + ) : card.target === "attack" ? ( +

    + {card.name}:點對手的「批評你的政見」讓它失效。 +

    + ) : ( +

    + + {card.name}: + {cityPreview && cityPreview.votes !== 0 ? `預估 ${signed(cityPreview.votes)} 票${cityPreview.note ? `(${cityPreview.note})` : ""}` : (cityPreview?.note ?? card.text)} + 再點一次這張牌也會打出 + + +

    + )} +
    +
    + { + // 全市的牌:再點一次就打出(不用再按「打出這張牌」) + if (uid === null && card && !card.blocked && (card.target === "city" || card.target === "none")) { + void play(null); + return; + } + if (uid) sfx.flip(); + setSelected(uid); + setError(null); + const next = view.hand.find((c) => c.uid === uid); + // 要選區的牌在手機上切到地圖;打對台、事實查核切到列表 + if (next?.target === "town") setMobileTab("map"); + else if (next?.target === "intent" || next?.target === "attack") setMobileTab("list"); + // 各區重新依預估排序,捲回最上面看最划算的區 + document.querySelector(".rg-side")?.scrollTo({ top: 0, behavior: "smooth" }); + }} + /> +
    + {view.ultimate && view.phase === "plan" && setUltOpen(true)} />} + +
    +
    +
    + + {coach.step && !overlay && } + {overlay === "finale" && void again(asc)} onHome={() => (location.hash = "#/")} />} + {overlay === "brief" && } + {overlay === "scene" && void choose(p)} />} + {overlay === "weekend" && void choose(p, null, option)} onFinale={() => setWeekLog(null)} />} + {overlay === "stop" && void choose(p, t ?? null)} />} + {coach.step && (overlay === "weekend" || overlay === "stop") && } + {ultOpen && view.ultimate && view.phase === "plan" && void fireUltimate(k, score, towns)} onClose={() => setUltOpen(false)} />} + {help && setHelp(false)} />} + {deck && setDeck(false)} />} +
    + ); +} + +/** 新手教學沒有真實地圖:三個里畫成三塊並排的地 */ +function TutorialMap({ view, best, onSelect }: { view: RogueView; best: ReadonlySet; onSelect?: (code: string) => void }) { + return ( +
    + {view.towns.map((t) => { + const lead = t.you - t.rival; + const color = lead >= 0 ? view.colors.you : view.colors.rival; + const strength = Math.round(18 + Math.min(1, Math.abs(lead) / (t.voters * 0.12 || 1)) * 62); + const intents = view.intents.filter((i) => i.town === t.code); + return ( + + ); + })} +
    + ); +} diff --git a/web/src/game/rogue/RogueStart.tsx b/web/src/game/rogue/RogueStart.tsx new file mode 100644 index 0000000..1d7ecfe --- /dev/null +++ b/web/src/game/rogue/RogueStart.tsx @@ -0,0 +1,728 @@ +import type { RogueCatalog, ScenarioSummary } from "@election2026/protocol"; +import { + CalendarDays, + Crown, + GraduationCap, + Lock, + Play, + RotateCcw, + Swords, + X, +} from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { api, rogueApi } from "../api.ts"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { sfx } from "../audio/sfx.ts"; +import { slotColor } from "../format.ts"; +import { + dailyPick, + loadProgress, + todayKey, + type Progress, +} from "./progress.ts"; +import { perksForRun, policiesForRun } from "../island/store.ts"; +import { LAST_RUN_KEY } from "./RogueScreen.tsx"; +import "./rogue.css"; +import "./rogue-start.css"; + +type Kind = ScenarioSummary["region"]["kind"]; +type Candidate = ScenarioSummary["candidates"][number]; + +const KINDS: { id: Kind; label: string }[] = [ + { id: "mayor", label: "縣市長" }, + { id: "legislator", label: "立委" }, + { id: "president", label: "總統" }, +]; + +/** 推薦的第一場:雙方開局拉平,13 個區,資料與平衡報告都齊(docs/21) */ +const RECOMMENDED = "taoyuan-2022-mayor"; +/** 每日一戰固定的逆風等級 */ +const DAILY_ASCENSION = 3; + +const yearOf = (s: ScenarioSummary) => s.electionDate.slice(0, 4); +const isEven = (s: ScenarioSummary) => s.id.endsWith("-even"); +/** 劇本名稱去掉「:歷史重演」,例如「2022 桃園市長」 */ +const raceName = (s: ScenarioSummary) => s.name.replace(/:.*$/, ""); +const isMajor = (c: Candidate) => c.slot === "a" || c.slot === "b"; +/** 主要候選人排前面,其他照號次 */ +const byImportance = (a: Candidate, b: Candidate) => + Number(isMajor(b)) - Number(isMajor(a)) || a.number - b.number; + +/** 勢均力敵有獨立的劇本(id 加 -even)就用那個,最佳成績才不會和真實底盤混在一起 */ +function resolveId( + byId: ReadonlyMap, + id: string, + even: boolean, +): string { + return even && byId.has(`${id}-even`) ? `${id}-even` : id; +} + +interface Daily { + date: string; + scenario: ScenarioSummary; + candidate: Candidate; +} + +/** 今天的題目:縣市長劇本(不含勢均力敵版)依 id 排好,同一天挑同一個 */ +function dailyOf(list: readonly ScenarioSummary[], date: string): Daily | null { + const mayors = list + .filter((s) => s.region.kind === "mayor" && !isEven(s)) + .sort((a, b) => a.id.localeCompare(b.id)); + const scenario = dailyPick(mayors, date); + if (!scenario) return null; + const majors = scenario.candidates + .filter(isMajor) + .sort((a, b) => a.number - b.number); + const candidate = dailyPick( + majors.length ? majors : [...scenario.candidates].sort(byImportance), + `${date}-c`, + ); + return candidate ? { date, scenario, candidate } : null; +} + +const readLastRun = (): string | null => { + try { + return localStorage.getItem(LAST_RUN_KEY); + } catch { + return null; + } +}; + +interface Challenge { + s: string; + c: string; + seed: number; + a: number; + e: boolean; + share: number; + n: string; +} + +/** 朋友傳來的挑戰連結(#/rogue?challenge=…);格式不對就當作沒有 */ +function readChallenge(): Challenge | null { + try { + const code = new URLSearchParams(location.hash.split("?")[1] ?? "").get( + "challenge", + ); + if (!code) return null; + const json = new TextDecoder().decode( + Uint8Array.from(atob(code.replace(/-/g, "+").replace(/_/g, "/")), (ch) => + ch.charCodeAt(0), + ), + ); + const c = JSON.parse(json) as Partial; + if ( + typeof c.s !== "string" || + typeof c.c !== "string" || + !Number.isInteger(c.seed) || + !Number.isInteger(c.a) + ) + return null; + return { + s: c.s, + c: c.c, + seed: c.seed!, + a: Math.max(0, Math.min(10, c.a!)), + e: !!c.e, + share: Number(c.share) || 0, + n: String(c.n ?? ""), + }; + } catch { + return null; + } +} + +/** + * 標題畫面的選單(首頁、#/rogue 都用這個):繼續上一局或開始選戰、每日一戰、自由選戰、政治生涯、新手教學、朋友的挑戰。 + * 自由選戰在畫面上跳出設定,不換頁。 + */ +export function TitleMenu() { + const [challenge] = useState(readChallenge); + const [scenarios, setScenarios] = useState(null); + const [catalog, setCatalog] = useState(null); + const [progress] = useState(loadProgress); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + const [last, setLast] = useState<{ id: string; label: string } | null>(null); + const [freeOpen, setFreeOpen] = useState(false); + + useEffect(() => { + api + .scenarios() + .then(setScenarios) + .catch((e: unknown) => + setError(e instanceof Error ? e.message : String(e)), + ); + rogueApi + .catalog() + .then(setCatalog) + .catch(() => setCatalog(null)); + const id = readLastRun(); + if (id) { + rogueApi + .get(id) + .then( + (v) => + v.phase !== "finished" && + setLast({ id: v.runId, label: `${v.you.name}・第 ${v.week} 週` }), + ) + .catch(() => setLast(null)); + } + }, []); + + const byId = useMemo( + () => new Map((scenarios ?? []).map((s) => [s.id, s])), + [scenarios], + ); + const date = todayKey(); + const daily = useMemo( + () => (scenarios ? dailyOf(scenarios, date) : null), + [scenarios, date], + ); + const todayScore = progress.daily[date]; + + const go = async (key: string, create: () => Promise<{ runId: string }>) => { + setBusy(key); + setError(null); + try { + sfx.stamp(); + const { runId } = await create(); + location.hash = `#/rogue/${runId}`; + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setBusy(null); + } + }; + + const startTutorial = () => void go("tutorial", () => rogueApi.tutorial()); + const startDaily = () => { + if (!daily) return; + void go("daily", () => + rogueApi.create( + resolveId(byId, daily.scenario.id, true), + daily.candidate.id, + { ascension: DAILY_ASCENSION, even: true, daily: daily.date }, + ), + ); + }; + + const primary = last + ? "continue" + : !progress.tutorialDone + ? "tutorial" + : "free"; + const item = (key: string, i: number) => ({ + className: `tmenu-item${primary === key ? " is-primary" : ""}`, + style: { "--i": i } as React.CSSProperties, + }); + return ( + + ); +} + +interface FreeProps { + scenarios: ScenarioSummary[] | null; + byId: ReadonlyMap; + catalog: RogueCatalog | null; + progress: Progress; + busy: string | null; + onStart: (key: string, create: () => Promise<{ runId: string }>) => void; +} + +/** 自由選戰:選舉類型 → 年份 → 地區 → 候選人 → 勢均力敵、逆風難度 → 開始 */ +function FreeSetup({ + scenarios, + byId, + catalog, + progress, + busy, + onStart, +}: FreeProps) { + const races = useMemo( + () => (scenarios ?? []).filter((s) => !isEven(s)), + [scenarios], + ); + const [kind, setKind] = useState("mayor"); + const years = useMemo( + () => + [ + ...new Set(races.filter((s) => s.region.kind === kind).map(yearOf)), + ].sort((a, b) => b.localeCompare(a)), + [races, kind], + ); + const [year, setYear] = useState(null); + const activeYear = year && years.includes(year) ? year : (years[0] ?? null); + const inYear = useMemo( + () => + races + .filter((s) => s.region.kind === kind && yearOf(s) === activeYear) + .sort( + (a, b) => + a.region.countyCode.localeCompare(b.region.countyCode) || + a.id.localeCompare(b.id), + ), + [races, kind, activeYear], + ); + const [scenarioId, setScenarioId] = useState(null); + const scenario = + inYear.find((s) => s.id === scenarioId) ?? + (kind === "president" ? inYear[0] : undefined) ?? + null; + const [candidateId, setCandidateId] = useState(null); + const candidates = useMemo( + () => (scenario ? [...scenario.candidates].sort(byImportance) : []), + [scenario], + ); + const candidate = candidates.find((c) => c.id === candidateId) ?? null; + const [even, setEven] = useState(true); + const [ascension, setAscension] = useState(0); + const [showAll, setShowAll] = useState(false); + const panel = useRef(null); + + useEffect(() => { + panel.current?.scrollIntoView({ + behavior: matchMedia("(prefers-reduced-motion: reduce)").matches + ? "auto" + : "smooth", + block: "start", + }); + }, []); + + const pickKind = (k: Kind) => { + sfx.click(); + setKind(k); + setYear(null); + setScenarioId(null); + setCandidateId(null); + }; + const pickScenario = (id: string) => { + sfx.click(); + setScenarioId(id); + setCandidateId(null); + }; + const recommended = () => { + sfx.click(); + setKind("mayor"); + setYear("2022"); + setScenarioId(RECOMMENDED); + setCandidateId(null); + setEven(true); + }; + const start = () => { + if (!scenario || !candidate) return; + // 自由選戰帶政策島的建築和政策;每日一戰、朋友挑戰大家條件一樣,不帶 + onStart("free", () => + rogueApi.create(resolveId(byId, scenario.id, even), candidate.id, { + ascension, + even, + perks: perksForRun(), + policies: policiesForRun(), + }), + ); + }; + + const asc = catalog?.ascension ?? []; + const best = scenario + ? progress.best[resolveId(byId, scenario.id, even)] + : undefined; + + return ( +
    +
    +

    + 1 哪一種選舉 +

    +
    + {KINDS.map((k) => ( + + ))} +
    + {byId.has(RECOMMENDED) && ( + + )} +
    + +
    +

    + 2 哪一年 +

    + {scenarios ? ( +
    + {years.map((y) => ( + + ))} +
    + ) : ( +

    讀取選舉清單…

    + )} +
    + + {kind !== "president" && ( +
    +

    + 3 {kind === "mayor" ? "哪個縣市" : "哪個選區"} +

    + {kind === "mayor" ? ( +
    + {inYear.map((s) => ( + + ))} +
    + ) : ( +
    + +
    + )} +
    + )} + + {scenario && ( +
    +

    + {kind === "president" ? 3 : 4} 你要當誰 +

    +

    + {raceName(scenario)} + {scenario.region.scope ? `・${scenario.region.scope}` : ""} +

    +
    + {candidates.map((c) => ( + + ))} +
    +
    + )} + + {candidate && ( +
    +

    + {kind === "president" ? 4 : 5} 難度 +

    + +
    + {Array.from({ length: 11 }, (_, n) => { + const locked = n > progress.ascension; + return ( + + ); + })} +
    +

    + {ascension === 0 ? ( + <> + 逆風 0:標準難度。 + {progress.ascension === 0 && "贏一場就解鎖逆風 1 級。"} + + ) : ( + <> + 逆風 {ascension}:+{asc[ascension] ?? "…"} + + )} +

    + {ascension > 1 && ( +
    + setShowAll((e.target as HTMLDetailsElement).open) + } + > + 看全部 {ascension} 個不利條件 +
      + {asc.slice(1, ascension + 1).map((t, i) => ( +
    1. + 逆風 {i + 1}:{t} +
    2. + ))} +
    +
    + )} + {best && ( +

    + 這一場最好的成績:{best.won ? "當選" : "落選"}・ + {(best.share * 100).toFixed(1)}%・{best.grade} 級(逆風{" "} + {best.ascension}) +

    + )} + +
    + )} +
    + ); +} + +/** 立委選區依縣市分組(下拉選單的 optgroup) */ +function groupByCounty( + list: readonly ScenarioSummary[], +): [string, ScenarioSummary[]][] { + const out = new Map(); + for (const s of list) + out.set(s.region.countyName, [...(out.get(s.region.countyName) ?? []), s]); + return [...out]; +} diff --git a/web/src/game/rogue/Ultimate.tsx b/web/src/game/rogue/Ultimate.tsx new file mode 100644 index 0000000..a3f1ae8 --- /dev/null +++ b/web/src/game/rogue/Ultimate.tsx @@ -0,0 +1,187 @@ +import type { MiniGameKind, RogueView } from "@election2026/protocol"; +import { Flame, Megaphone, MapPinned, Signpost, X, type LucideIcon } from "lucide-react"; +import { Suspense, lazy, useEffect, useMemo, useRef, useState } from "react"; +import { sfx } from "../audio/sfx.ts"; +import "../ui/scene.css"; +import "./ultimate.css"; + +const UltimatePlay = lazy(() => import("./UltimatePlay.tsx").then((m) => ({ default: m.UltimatePlay }))); + +type Ult = NonNullable; + +const ICONS: Record = { rally: Megaphone, handshake: MapPinned, billboard: Signpost }; + +/** + * 大絕招(18 第 57 項):集氣條+按鈕。落後越多集越快,集滿了按鈕會亮。 + * 沒集滿時按下去會說明怎麼集氣(不是沒反應)。 + */ +export function UltimateButton({ ult, disabled, onOpen }: { ult: Ult; disabled: boolean; onOpen: () => void }) { + const [tip, setTip] = useState(false); + const left = ult.max - ult.used; + const spent = left <= 0; + const hint = spent + ? "這局的大絕招放完了" + : ult.ready + ? `可以放了!現在落後 ${Math.max(0, ult.deficit).toFixed(1)} 點,威力 ×${ult.mult.toFixed(1)}` + : ult.deficit > 0 + ? `落後 ${ult.deficit.toFixed(1)} 點:每週結算集 ${Math.round(ult.deficit * 8)}%,集滿就能放` + : "領先時集得很慢;落後越多集越快"; + useEffect(() => { + if (!tip) return; + const t = setTimeout(() => setTip(false), 3200); + return () => clearTimeout(t); + }, [tip]); + return ( +
    + + {tip && ( +

    + {hint} +

    + )} +
    + ); +} + +type Step = { kind: "pick" } | { kind: "towns"; game: MiniGameKind } | { kind: "play"; game: MiniGameKind }; + +/** 挑一招 →(掃街馬拉松挑 3 個區)→ 玩小遊戲 → 把分數送出 */ +export function UltimateOverlay({ view, busy, onFire, onClose }: { view: RogueView; busy: boolean; onFire: (kind: MiniGameKind, score: number, towns?: string[]) => void; onClose: () => void }) { + const ult = view.ultimate!; + const [step, setStep] = useState({ kind: "pick" }); + const [towns, setTowns] = useState(() => ult.suggest.slice(0, 3)); + const closeRef = useRef(null); + const seed = useMemo(() => Math.floor(Math.random() * 1_000_000) + view.week * 7919, [view.week]); + // 大絕招是關鍵時刻:小遊戲難度用中等偏難(第 1 週 0.4、最後一週 0.8) + const level = Math.min(0.8, 0.3 + (view.week / Math.max(1, view.totalWeeks)) * 0.5); + useEffect(() => { + if (step.kind !== "play") closeRef.current?.focus(); + const onKey = (e: KeyboardEvent) => e.key === "Escape" && step.kind !== "play" && onClose(); + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [step.kind, onClose]); + const opt = (k: MiniGameKind) => ult.options.find((o) => o.kind === k)!; + const townName = (code: string) => view.towns.find((t) => t.code === code)?.name ?? code; + + if (step.kind === "play") { + const o = opt(step.game); + const where = step.game === "handshake" ? towns.map(townName).join("、") : null; + return ( +
    + 準備小遊戲…

    }> + !busy && onFire(step.game, score, step.game === "handshake" ? towns : undefined)} + onQuit={() => setStep({ kind: "pick" })} + /> +
    +
    + ); + } + + return ( +
    e.target === e.currentTarget && onClose()}> +
    +
    + + + +
    +

    {step.kind === "towns" ? "掃街馬拉松:挑 3 個區" : "大絕招"}

    +

    + {ult.deficit > 0 ? `現在落後 ${ult.deficit.toFixed(1)} 個百分點,威力 ×${ult.mult.toFixed(1)}。` : "現在沒有落後,威力 ×1。"} + 玩小遊戲,分數越高效果越大。{ult.max > 1 ? "這是第二次大絕招。" : ""} +

    +
    + +
    + + {step.kind === "pick" && ( +
    + {ult.options.map((o) => { + const Icon = ICONS[o.kind]; + return ( +
    + +
    + ); + })} +
    + )} + + {step.kind === "towns" && ( + <> +
      + {view.towns.map((t) => { + const cast = t.you + t.rival + t.others || 1; + const gap = ((t.you - t.rival) / cast) * 100; + const on = towns.includes(t.code); + return ( +
    • + +
    • + ); + })} +
    +
    + + +
    + + )} +
    +
    + ); +} diff --git a/web/src/game/rogue/UltimatePlay.tsx b/web/src/game/rogue/UltimatePlay.tsx new file mode 100644 index 0000000..2eb84c3 --- /dev/null +++ b/web/src/game/rogue/UltimatePlay.tsx @@ -0,0 +1,11 @@ +import type { MiniGameKind } from "@election2026/protocol"; +import { MINI_GAMES } from "../minigames/registry.ts"; + +/** + * 大絕招的小遊戲本體(Ultimate.tsx 用 lazy 載入,小遊戲比較大,用到才下載)。 + * 只能玩一次:結束畫面的按鈕是「放出大絕招!」,中途不玩就回到挑招(不算用掉)。 + */ +export function UltimatePlay({ kind, seed, level, title, reward, townName, onFinish, onQuit }: { kind: MiniGameKind; seed: number; level: number; title: string; reward: string; townName: string | null; onFinish: (score: number) => void; onQuit: () => void }) { + const { Game } = MINI_GAMES[kind]; + return ; +} diff --git a/web/src/game/rogue/brief.tsx b/web/src/game/rogue/brief.tsx new file mode 100644 index 0000000..a019215 --- /dev/null +++ b/web/src/game/rogue/brief.tsx @@ -0,0 +1,129 @@ +import type { RogueLog, RogueView } from "@election2026/protocol"; +import { Tv, X } from "lucide-react"; +import { useEffect } from "react"; +import { sfx } from "../audio/sfx.ts"; +import { CHANNELS } from "../news/channels.ts"; +import { overall, pct, raceLabel, signed, weekLabel } from "./labels.ts"; + +const BRIEF_MS = 7000; +/** 不分藍綠的網路台播每週快報 */ +const CHANNEL = CHANNELS.find((c) => c.id === "xm") ?? CHANNELS[0]!; + +/** + * 選情快報(docs/22、23):上週戰果、全市支持度、本週事件、對手動向。 + * 第一週開場自動播電視(七秒後自動關);之後每週只在地圖上方跑馬燈(NewsTicker),點了才打開電視。 + */ +const ABILITY_NAMES = { eloquence: "口才", organization: "組織", media: "媒體", finance: "財務", integrity: "清廉" } as const; +const abilityText = (a: NonNullable): string => + (Object.keys(ABILITY_NAMES) as (keyof typeof ABILITY_NAMES)[]) + .filter((k) => a[k] > 0) + .map((k) => `${ABILITY_NAMES[k]} ${a[k]} 級`) + .join("、") || "沒有"; + +/** 這週的快報內容:標題、上週最大的兩件事、這週的大型行動、跑馬燈(電視快報和地圖上的跑馬燈共用) */ +export function briefNews(view: RogueView, last: readonly RogueLog[] | null) { + const now = overall(view.towns); + const prev = view.history.at(-2); + const lastShare = view.history.at(-1); + const delta = prev && lastShare ? (lastShare.you - lastShare.rival - (prev.you - prev.rival)) * 100 : 0; + const lead = now.youShare - now.rivalShare; + const flags = { you: view.towns.filter((t) => t.flag === "you").length, rival: view.towns.filter((t) => t.flag === "rival").length }; + // 上週最大的兩件事 + const top = [...(last ?? [])].filter((e) => e.votes !== 0).sort((a, b) => Math.abs(b.votes) - Math.abs(a.votes)).slice(0, 2); + const headline = + view.week === 1 + ? `${raceLabel(view)}選戰開打!${view.you.name}對決${view.rival.name}` + : lead >= 0 + ? `${view.you.name}領先 ${(lead * 100).toFixed(1)} 個百分點${delta >= 0.5 ? ",差距拉大" : delta <= -0.5 ? ",對手追上來了" : ""}` + : `${view.you.name}落後 ${(-lead * 100).toFixed(1)} 個百分點${delta >= 0.5 ? ",正在追趕" : delta <= -0.5 ? ",差距擴大" : ""}`; + const big = view.intents.find((i) => i.big); + const poll = view.poll && view.poll.week === view.week ? view.poll : null; + const ticker = [ + // 民調(第 4 週自動公布) + ...(poll ? [`民調公布:${view.you.name} ${pct(poll.you)}、${view.rival.name} ${pct(poll.rival)};${poll.lead ? "你領先,西瓜效應聲勢 +1" : "你落後,手上多一張「悲情催票」"}`] : []), + ...(big ? [`注意!${big.label}就在這週,預計 +${Math.round(big.amount).toLocaleString("en-US")} 票`] : []), + // 多席次(議員):贏過最後一席就當選;門檻是 2022 年真實的最後一席得票率 + ...(view.seats > 1 + ? [`這區選 ${view.seats} 席:贏過最後一席的${view.rival.name}就當選${view.threshold ? `(2022 年最後一席得票率 ${(view.threshold * 100).toFixed(1)}%)` : ""}`] + : []), + // 玩真實候選人:開局能力依公開選舉紀錄換算(只在第一週說) + ...(view.week === 1 && view.options.abilitiesBasis && view.options.abilities ? [`資歷加成:${abilityText(view.options.abilities)};依據:${view.options.abilitiesBasis}`] : []), + // 後期提醒:對手行動變多,開票日聲勢高的一方帶出比較多未表態的票 + ...(view.week >= 5 && view.week < view.totalWeeks ? [`後期對手行動會變多:記得佈樁、打對台擋下來;開票日聲勢高的一方會多帶出未表態的票`] : []), + `本週事件:${view.event.title}——${view.event.text}`, + `${view.rival.name}這週有 ${view.intents.length} 個行動`, + ...(view.nextBig ? [`${view.rival.name}預告第 ${view.nextBig.week} 週在${view.towns.find((t) => t.code === view.nextBig!.town)?.name ?? ""}辦大型造勢`] : []), + `插旗:你 ${flags.you} 區、對手 ${flags.rival} 區`, + ]; + return { now, headline, top, big, ticker }; +} + +/** 地圖上方的新聞跑馬燈:每週的快報不再跳出來,點一下才打開電視 */ +export function NewsTicker({ view, last, onOpen }: { view: RogueView; last: readonly RogueLog[] | null; onOpen: () => void }) { + const { headline, ticker } = briefNews(view, last); + return ( + + ); +} + +export function WeekBrief({ view, last, onDone }: { view: RogueView; last: readonly RogueLog[] | null; onDone: () => void }) { + useEffect(() => { + sfx.channel(); + const t = setTimeout(onDone, BRIEF_MS); + return () => clearTimeout(t); + }, [onDone]); + const { now, headline, top, big, ticker } = briefNews(view, last); + return ( +
    +
    +
    + + {CHANNEL.name} + + LIVE + +
    +

    {weekLabel(view)}選情快報

    +

    {headline}

    +
    + + {view.you.name} {pct(now.youShare)} + + + + + + + + + {pct(now.rivalShare)} {view.rival.name} + +
    + {top.length > 0 && ( +
      + {top.map((e, i) => ( +
    • 0 ? "is-up" : "is-down"}> + {e.text} {signed(e.votes)} +
    • + ))} +
    + )} + {big &&

    注意!{big.label}就在這週,預計 +{Math.round(big.amount).toLocaleString("en-US")} 票

    } +
    + {ticker.join(" | ")} +
    + +
    +
    + ); +} diff --git a/web/src/game/rogue/cards.tsx b/web/src/game/rogue/cards.tsx new file mode 100644 index 0000000..ae7e244 --- /dev/null +++ b/web/src/game/rogue/cards.tsx @@ -0,0 +1,102 @@ +import type { RogueAdvisor, RogueOffer } from "@election2026/protocol"; +import { Banknote, Footprints, Megaphone, Network, ShieldAlert, Sparkles, Swords, type LucideIcon } from "lucide-react"; +import { StaffAvatar } from "../art/StaffAvatar.tsx"; +import { CardArt } from "../art/CardArt.tsx"; +import "./rogue-cards.css"; + +/** + * 選戰卡牌的牌面(docs/22「卡牌重做」):稀有度外框(基本、普通、稀有、狀態)、類型色條與圖示、 + * 左上體力、右上花費、大數字、一句話、關鍵字。升級過的牌名字加+、外框發光。 + */ +export interface FaceData { + name: string; + art: string; + cost: number | null; + money: number | null; + rarity: string; + value: string | null; + text: string; + tags?: readonly string[]; + keywords?: readonly string[]; + up?: boolean; + blocked?: string | null; +} + +/** 牌的類型:看標籤決定色條和圖示 */ +export function cardKind(tags: readonly string[] = []): { id: string; label: string; Icon: LucideIcon } { + if (tags.includes("status")) return { id: "status", label: "狀態", Icon: ShieldAlert }; + if (tags.includes("attack")) return { id: "attack", label: "攻擊", Icon: Swords }; + if (tags.includes("defend") || tags.includes("intel")) return { id: "defend", label: "防守", Icon: ShieldAlert }; + if (tags.includes("money")) return { id: "money", label: "資金", Icon: Banknote }; + if (tags.includes("rally")) return { id: "rally", label: "造勢", Icon: Sparkles }; + if (tags.includes("media") || tags.includes("press")) return { id: "media", label: "空戰", Icon: Megaphone }; + if (tags.includes("org")) return { id: "org", label: "組織", Icon: Network }; + return { id: "ground", label: "地面", Icon: Footprints }; +} + +const RARITY_LABEL: Record = { basic: "基本", common: "普通", rare: "稀有", status: "狀態" }; + +export function CardFace({ card, selected = false, big = false }: { card: FaceData; selected?: boolean; big?: boolean }) { + const kind = cardKind(card.tags); + return ( + + {card.cost !== null && ( + + {card.cost} + + )} + {!!card.money && {card.money} 萬} + + + + {kind.label} + + + {card.name} + {card.value && {card.value}} + {card.blocked ?? card.text} + {(card.keywords?.length ?? 0) > 0 && ( + + {card.keywords!.map((k) => ( + {k} + ))} + + )} + {card.rarity === "rare" && } + + ); +} + +/** 幕僚:虛構人物的漫畫頭像+被動能力 */ +export function AdvisorFace({ advisor, compact = false }: { advisor: Pick; compact?: boolean }) { + return ( + + + {advisor.name} + {advisor.text} + + ); +} + +/** 獎勵、商店、圖鑑上的一個選項 */ +export function OfferFace({ offer }: { offer: RogueOffer }) { + if (offer.kind === "advisor") return ; + return ( + + ); +} diff --git a/web/src/game/rogue/careerBoard3d.ts b/web/src/game/rogue/careerBoard3d.ts new file mode 100644 index 0000000..d13454f --- /dev/null +++ b/web/src/game/rogue/careerBoard3d.ts @@ -0,0 +1,741 @@ +import * as THREE from "three"; +import { GLTFLoader, type GLTF } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { clone as cloneSkinned } from "three/examples/jsm/utils/SkeletonUtils.js"; + +/** + * 政治生涯的棋盤(18 第 47 項):和首頁一樣的紙板桌遊,放在木頭桌上。 + * 一條馬路從左前方繞到右後方,串起五關的廣場:里辦公處、議會、立法院、縣市政府、總統府。 + * 還沒解鎖的建築是灰色的、馬路是土路;選上過的插旗;點哪一關,宣傳車就開到那一關。 + * 名牌是 HTML(CareerBoard.tsx),這裡每一格算出名牌在畫面上的位置交給它。 + * 模型、貼圖都是 CC0(web/public/assets/LICENSES.md);廣場上的人是不具名的 Q 版小人。 + */ + +const A = "/assets/3d/"; +const T = "/assets/textures/"; +const BOARD_W = 21; +const BOARD_D = 11; +const BOARD_H = 0.5; +const LANE = 1.0; +const PLAZA_R = 0.95; + +export type StopStatus = "locked" | "open" | "done"; + +export interface StopState { + status: StopStatus; +} + +/** 每一關的廣場位置(馬路經過廣場中心)和建築 */ +const STOPS: { + x: number; + z: number; + model: string; + w: number; + h: number; + extra?: string; +}[] = [ + { + x: -7, + z: 2.3, + model: "town-houses/building-type-a", + w: 1.6, + h: 1.5, + extra: "town-houses/planter", + }, + { x: -3.5, z: -1.5, model: "town-shops/building-c", w: 1.7, h: 2 }, + { + x: 0, + z: 2.2, + model: "town-shops/building-k", + w: 2.3, + h: 1.9, + extra: "town-shops/detail-parasol-a", + }, + { x: 3.5, z: -1.6, model: "town-shops/building-h", w: 1.8, h: 2.5 }, + { x: 7, z: 1.2, model: "town-shops/building-skyscraper-a", w: 2, h: 3.3 }, +]; +/** 馬路:從板子左前方外面開進來,經過五關,從右後方開出去 */ +const ROAD = new THREE.CatmullRomCurve3([new THREE.Vector3(-11.2, 0, 4.6), ...STOPS.map((s) => new THREE.Vector3(s.x, 0, s.z)), new THREE.Vector3(11.2, 0, -2.6)], false, "centripetal"); +const SAMPLES = 400; +const ROAD_PTS = ROAD.getSpacedPoints(SAMPLES); +/** 每一關在馬路上的位置(0–1) */ +const STOP_U = STOPS.map((s) => { + let best = 0; + let d = Infinity; + ROAD_PTS.forEach((p, i) => { + const k = Math.hypot(p.x - s.x, p.z - s.z); + if (k < d) { + d = k; + best = i / SAMPLES; + } + }); + return best; +}); + +export interface CareerBoardHandle { + resize: (w: number, h: number) => void; + setStops: (stops: readonly StopState[], selected: number, here: number) => void; + setActive: (active: boolean) => void; + dispose: () => void; +} + +interface Options { + stops: readonly StopState[]; + /** 選取的關(0–4) */ + selected: number; + /** 角色現在最高可以選的關 */ + here: number; + reduceMotion: boolean; + lowPower: boolean; + onReady: () => void; + onError: () => void; + onPick: (index: number) => void; + /** 每一關名牌的錨點(建築頂端),畫面座標(CSS px) */ + onAnchors: (points: readonly { x: number; y: number }[]) => void; +} + +/** 縮放到不超過指定的寬、高,底部貼齊 y=0、置中 */ +function fitBox(obj: THREE.Object3D, maxW: number, maxH: number): THREE.Group { + const box = new THREE.Box3().setFromObject(obj); + const dim = box.getSize(new THREE.Vector3()); + obj.scale.multiplyScalar(Math.min(maxW / Math.max(dim.x, dim.z, 0.001), maxH / Math.max(dim.y, 0.001))); + const after = new THREE.Box3().setFromObject(obj); + const center = after.getCenter(new THREE.Vector3()); + obj.position.x -= center.x; + obj.position.z -= center.z; + obj.position.y -= after.min.y; + const wrap = new THREE.Group(); + wrap.add(obj); + return wrap; +} + +function shadows(obj: THREE.Object3D, on: boolean) { + obj.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = on; + o.receiveShadow = on; + } + }); +} + +/** 固定的亂數(樹和草叢每次都種在一樣的地方) */ +function seeded(seed: number): () => number { + let s = seed; + return () => { + s = (s * 16807) % 2147483647; + return (s - 1) / 2147483646; + }; +} + +/** 馬路的切線方向 */ +function tangentAt(u: number): THREE.Vector3 { + return ROAD.getTangentAt(Math.min(1, Math.max(0, u))); +} + +/** 建築放在廣場的哪一邊:沿馬路的法線、往板子後方(遠離鏡頭)那邊 */ +const BUILDING_AT = STOPS.map((s, i) => { + const t = tangentAt(STOP_U[i]!); + let n = new THREE.Vector3(-t.z, 0, t.x); + if (n.z > 0) n = n.negate(); + return new THREE.Vector3(s.x + n.x * 1.75, 0, s.z + n.z * 1.75); +}); + +/** 板面:米色紙板、草地、馬路;已經解鎖的路段是柏油路加黃線,後面還沒解鎖的是土路 */ +function drawBoard(canvas: HTMLCanvasElement, paved: number) { + const g = canvas.getContext("2d")!; + const sx = canvas.width / BOARD_W; + const sz = canvas.height / BOARD_D; + const px = (p: THREE.Vector3) => [(p.x + BOARD_W / 2) * sx, (p.z + BOARD_D / 2) * sz] as const; + g.fillStyle = "#efe6cf"; + g.fillRect(0, 0, canvas.width, canvas.height); + // 草地:沿著四邊一圈,加幾塊大草皮 + g.fillStyle = "#b9d39a"; + const edge = 0.9 * sz; + g.fillRect(0, 0, canvas.width, edge); + g.fillRect(0, canvas.height - edge, canvas.width, edge); + const rand = seeded(47); + for (let i = 0; i < 9; i++) { + g.beginPath(); + g.ellipse(rand() * canvas.width, rand() * canvas.height, (1.2 + rand() * 1.6) * sx, (0.8 + rand()) * sz, rand() * Math.PI, 0, Math.PI * 2); + g.fill(); + } + // 磚地紋 + g.strokeStyle = "rgba(120,90,50,0.12)"; + g.lineWidth = 2; + for (let x = 0; x < canvas.width; x += 0.5 * sx) { + g.beginPath(); + g.moveTo(x, 0); + g.lineTo(x, canvas.height); + g.stroke(); + } + const cut = Math.round(paved * SAMPLES); + const stroke = (from: number, to: number) => { + g.beginPath(); + for (let i = from; i <= to; i++) { + const [x, y] = px(ROAD_PTS[i]!); + if (i === from) g.moveTo(x, y); + else g.lineTo(x, y); + } + g.stroke(); + }; + g.lineCap = "round"; + g.lineJoin = "round"; + // 土路(還沒解鎖):淺棕色、虛線邊 + g.lineWidth = LANE * sx; + g.strokeStyle = "#d9c193"; + stroke(cut, SAMPLES); + g.lineWidth = 3; + g.setLineDash([14, 12]); + g.strokeStyle = "rgba(110,74,42,0.45)"; + stroke(cut, SAMPLES); + g.setLineDash([]); + // 柏油路(已解鎖):黑邊、灰路面、黃色虛線 + g.lineWidth = LANE * sx + 6; + g.strokeStyle = "#2b2f36"; + stroke(0, cut); + g.lineWidth = LANE * sx; + g.strokeStyle = "#5d6675"; + stroke(0, cut); + g.lineWidth = 4; + g.setLineDash([22, 18]); + g.strokeStyle = "#ffd23f"; + stroke(0, cut); + g.setLineDash([]); +} + +/** 灰階:還沒解鎖的建築 */ +function grayscale(mat: THREE.Material): THREE.Material { + const m = mat.clone(); + m.onBeforeCompile = (shader) => { + shader.fragmentShader = shader.fragmentShader.replace( + "#include ", + "#include \n float gray = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor.rgb = mix(vec3(gray), vec3(0.78), 0.35);", + ); + }; + m.customProgramCacheKey = () => "career-gray"; + return m; +} + +export function createCareerBoard(canvas: HTMLCanvasElement, opts: Options): CareerBoardHandle { + const noop: CareerBoardHandle = { + resize: () => {}, + setStops: () => {}, + setActive: () => {}, + dispose: () => {}, + }; + let renderer: THREE.WebGLRenderer; + try { + renderer = new THREE.WebGLRenderer({ + canvas, + antialias: !opts.lowPower, + alpha: true, + powerPreference: "low-power", + }); + } catch { + opts.onError(); + return noop; + } + renderer.setPixelRatio(Math.min(devicePixelRatio, opts.lowPower ? 1.25 : 1.75)); + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = !opts.lowPower; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + + const scene = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(32, 2, 0.1, 200); + + // 燈光:和首頁一樣的黃昏暖光 + scene.add(new THREE.HemisphereLight("#fff4df", "#6b4a2b", 1.1)); + const sun = new THREE.DirectionalLight("#ffe0b0", 2.2); + sun.position.set(-8, 14, 9); + sun.castShadow = !opts.lowPower; + sun.shadow.mapSize.set(1024, 1024); + Object.assign(sun.shadow.camera, { + left: -13, + right: 13, + top: 9, + bottom: -9, + near: 1, + far: 40, + }); + sun.shadow.bias = -0.0008; + scene.add(sun); + const rim = new THREE.DirectionalLight("#9fb8ff", 0.6); + rim.position.set(9, 6, -10); + scene.add(rim); + + const textures: THREE.Texture[] = []; + const texLoader = new THREE.TextureLoader(); + const tex = (url: string, repeat: number, color = true) => { + const t = texLoader.load(url); + if (color) t.colorSpace = THREE.SRGBColorSpace; + t.wrapS = t.wrapT = THREE.RepeatWrapping; + t.repeat.set(repeat, repeat); + textures.push(t); + return t; + }; + + // 木頭桌面 + const table = new THREE.Mesh( + new THREE.PlaneGeometry(90, 90), + new THREE.MeshStandardMaterial({ + map: tex(`${T}wood-table-diff.jpg`, 9), + normalMap: tex(`${T}wood-table-normal.jpg`, 9, false), + roughness: 0.75, + }), + ); + table.rotation.x = -Math.PI / 2; + table.position.y = -BOARD_H; + table.receiveShadow = true; + scene.add(table); + + // 紙板:板面是畫上去的馬路(解鎖到哪裡,柏油路就鋪到哪裡) + const boardCanvas = document.createElement("canvas"); + boardCanvas.width = opts.lowPower ? 1344 : 2048; + boardCanvas.height = Math.round((boardCanvas.width * BOARD_D) / BOARD_W); + const top = new THREE.CanvasTexture(boardCanvas); + top.colorSpace = THREE.SRGBColorSpace; + top.anisotropy = 4; + textures.push(top); + const side = new THREE.MeshStandardMaterial({ + map: tex(`${T}cardboard-diff.jpg`, 1), + roughness: 0.95, + }); + const board = new THREE.Mesh(new THREE.BoxGeometry(BOARD_W, BOARD_H, BOARD_D), [side, side, new THREE.MeshStandardMaterial({ map: top, roughness: 0.9 }), side, side, side]); + board.position.y = -BOARD_H / 2; + board.receiveShadow = true; + scene.add(board); + + // 五關的廣場:黑框圓盤,選上過是黃色、可以選是紙白、還沒解鎖是灰色 + const plazaMat = { + done: new THREE.MeshStandardMaterial({ color: "#ffd23f", roughness: 0.6 }), + open: new THREE.MeshStandardMaterial({ color: "#fffaf0", roughness: 0.7 }), + locked: new THREE.MeshStandardMaterial({ + color: "#c9ccd2", + roughness: 0.8, + }), + }; + const rimMat = new THREE.MeshStandardMaterial({ + color: "#111419", + roughness: 0.6, + }); + interface Stop { + group: THREE.Group; + plaza: THREE.Mesh; + building: THREE.Object3D | null; + flag: THREE.Object3D | null; + top: number; + status: StopStatus | null; + } + const stops: Stop[] = STOPS.map((s, i) => { + const group = new THREE.Group(); + group.userData.stop = i; + const outline = new THREE.Mesh(new THREE.CylinderGeometry(PLAZA_R + 0.09, PLAZA_R + 0.09, 0.1, 40), rimMat); + outline.position.set(s.x, 0.05, s.z); + const plaza = new THREE.Mesh(new THREE.CylinderGeometry(PLAZA_R, PLAZA_R, 0.14, 40), plazaMat.open); + plaza.position.set(s.x, 0.07, s.z); + plaza.receiveShadow = true; + group.add(outline, plaza); + scene.add(group); + return { + group, + plaza, + building: null, + flag: null, + top: STOPS[i]!.h, + status: null, + }; + }); + + // 選取的那一關:廣場外一圈紅色光環 + const ring = new THREE.Mesh(new THREE.TorusGeometry(PLAZA_R + 0.28, 0.07, 10, 48), new THREE.MeshBasicMaterial({ color: "#d61f2c", toneMapped: false })); + ring.rotation.x = -Math.PI / 2; + ring.position.y = 0.12; + scene.add(ring); + + let state = { stops: opts.stops, selected: opts.selected, here: opts.here }; + let paved = -1; + const pavedTo = () => STOP_U[Math.max(0, Math.min(STOPS.length - 1, state.here))]!; + const redrawBoard = () => { + const next = pavedTo(); + if (next === paved) return; + paved = next; + drawBoard(boardCanvas, paved); + top.needsUpdate = true; + }; + redrawBoard(); + + // ── 模型 ── + const loader = new GLTFLoader(); + const load = (path: string) => new Promise((resolve, reject) => loader.load(`${A}${path}.glb`, resolve, undefined, reject)); + const brick = texLoader.load(`${A}town-houses/Textures/variation-b.png`); + brick.flipY = false; + brick.colorSpace = THREE.SRGBColorSpace; + brick.magFilter = THREE.NearestFilter; + textures.push(brick); + const mixers: THREE.AnimationMixer[] = []; + let truck: THREE.Object3D | null = null; + let truckU = STOP_U[opts.selected] ?? 0; + let flagSrc: THREE.Object3D | null = null; + const fans: THREE.Object3D[] = []; + let ready = false; + + /** 建築換成灰階或原色(材質事先各準備一份) */ + const paint = (obj: THREE.Object3D, gray: boolean) => { + obj.traverse((o) => { + const m = o as THREE.Mesh; + if (!m.isMesh) return; + const own = m.userData as { + color?: THREE.Material | THREE.Material[]; + gray?: THREE.Material | THREE.Material[]; + }; + if (!own.color) { + own.color = m.material; + own.gray = Array.isArray(m.material) ? m.material.map(grayscale) : grayscale(m.material); + } + m.material = gray ? own.gray! : own.color; + }); + }; + + const applyStops = () => { + redrawBoard(); + stops.forEach((s, i) => { + const status = state.stops[i]?.status ?? "locked"; + s.plaza.material = plazaMat[status]; + if (s.building && s.status !== status) paint(s.building, status === "locked"); + if (status === "done" && !s.flag && flagSrc) { + const f = flagSrc.clone(); + const b = BUILDING_AT[i]!; + f.position.set(STOPS[i]!.x + (b.x - STOPS[i]!.x) * 0.2 + 0.75, 0.14, STOPS[i]!.z + (b.z - STOPS[i]!.z) * 0.2 + 0.35); + s.group.add(f); + s.flag = f; + } + if (s.flag) s.flag.visible = status === "done"; + s.status = status; + }); + const sel = STOPS[state.selected]; + ring.visible = !!sel; + if (sel) ring.position.set(sel.x, 0.12, sel.z); + // 支持者站在角色現在所在的那一關 + const here = STOPS[state.here]; + if (here) { + const t = tangentAt(STOP_U[state.here]!); + fans.forEach((f, k) => { + const side = k % 2 === 0 ? 1 : -1; + f.position.set(here.x + t.x * (k - 1) * 0.55 + -t.z * side * 1.25, 0, here.z + t.z * (k - 1) * 0.55 + t.x * side * 1.25); + f.lookAt(here.x, 0, here.z); + }); + } + if (opts.reduceMotion || !ready) truckU = STOP_U[state.selected] ?? truckU; + invalidate(); + }; + + const setup = async () => { + const paths = [...new Set(STOPS.flatMap((s) => [s.model, ...(s.extra ? [s.extra] : [])]))]; + const decor = [ + "nature/tree-default", + "nature/tree-oak", + "nature/tree-palm-short", + "nature/plant-bush-large", + "nature/flower-yellow-a", + "nature/rock-small-a", + "town-houses/building-type-b", + "town-houses/building-type-f", + ]; + const people = ["character-female-b", "character-male-c", "character-female-e"]; + const [models, decorModels, truckGltf, flag, chars] = await Promise.all([ + Promise.all(paths.map(load)), + Promise.all(decor.map(load)), + load("vehicles/truck"), + load("props/flag"), + Promise.all(people.map((n) => load(`characters/${n}`))), + ]); + const byPath = new Map(paths.map((p, i) => [p, models[i]!.scene])); + const houseBrick = (o: THREE.Object3D) => + o.traverse((x) => { + const m = x as THREE.Mesh; + if (m.isMesh) m.material = Object.assign((m.material as THREE.MeshStandardMaterial).clone(), { map: brick }); + }); + // 五關的建築 + STOPS.forEach((s, i) => { + const src = byPath.get(s.model)!.clone(); + if (s.model.startsWith("town-houses/building")) houseBrick(src); + const b = fitBox(src, s.w, s.h); + const at = BUILDING_AT[i]!; + b.position.set(at.x, 0, at.z); + // 正面朝向廣場 + b.rotation.y = Math.atan2(s.x - at.x, s.z - at.z); + shadows(b, !opts.lowPower); + stops[i]!.group.add(b); + stops[i]!.building = b; + stops[i]!.top = new THREE.Box3().setFromObject(b).max.y; + if (s.extra) { + const e = fitBox(byPath.get(s.extra)!.clone(), 0.6, 0.7); + e.position.set(at.x + (s.x - at.x) * 0.15 - 1.1, 0, at.z + (s.z - at.z) * 0.15 + 0.2); + shadows(e, !opts.lowPower); + stops[i]!.group.add(e); + } + }); + flagSrc = fitBox(flag.scene, 1.3, 1.3); + shadows(flagSrc, !opts.lowPower); + + // 路邊的樹、草叢、小房子:離馬路、廣場、建築都有距離 + const rand = seeded(2026); + const clear = (x: number, z: number, r: number) => + ROAD_PTS.every((p) => Math.hypot(p.x - x, p.z - z) > LANE / 2 + r + 0.2) && + STOPS.every((s) => Math.hypot(s.x - x, s.z - z) > PLAZA_R + r + 0.5) && + BUILDING_AT.every((b) => Math.hypot(b.x - x, b.z - z) > 1.3 + r); + const placed: { x: number; z: number; r: number }[] = []; + const want = opts.lowPower ? 16 : 26; + for (let tries = 0; tries < 600 && placed.length < want; tries++) { + const kind = placed.length % decor.length; + const house = decor[kind]!.startsWith("town-houses"); + const r = house ? 0.75 : kind < 3 ? 0.45 : 0.3; + const x = (rand() - 0.5) * (BOARD_W - 1.6); + const z = (rand() - 0.5) * (BOARD_D - 1.4); + if (!clear(x, z, r) || placed.some((p) => Math.hypot(p.x - x, p.z - z) < p.r + r + 0.15)) continue; + const src = decorModels[kind]!.scene.clone(); + if (house) houseBrick(src); + const size = house ? 1.2 : kind < 3 ? 1.1 + rand() * 0.5 : 0.5 + rand() * 0.2; + const d = house ? fitBox(src, size, size) : fitBox(src, size * 1.2, size); + d.position.set(x, 0, z); + d.rotation.y = rand() * Math.PI * 2; + shadows(d, !opts.lowPower); + scene.add(d); + placed.push({ x, z, r }); + } + + // 宣傳車:車頂一塊黃色看板 + truck = fitBox(truckGltf.scene, 1.5, 1.2); + shadows(truck, !opts.lowPower); + scene.add(truck); + + // 角色所在那一關的支持者(不具名的小人) + chars.forEach((c, k) => { + const person = fitBox(cloneSkinned(c.scene), 0.9, 0.9); + shadows(person, !opts.lowPower); + scene.add(person); + fans.push(person); + const mixer = new THREE.AnimationMixer(person.children[0]!); + const clip = THREE.AnimationClip.findByName(c.animations, k === 1 ? "emote-yes" : "idle") ?? c.animations[0]; + if (clip) { + const action = mixer.clipAction(clip); + action.time = k * 0.4; + action.play(); + } + mixers.push(mixer); + }); + ready = true; + stops.forEach((s) => (s.status = null)); + applyStops(); + }; + + // ── 鏡頭:依畫面比例決定從哪個方向看,再推遠到五關和名牌都放得下 ── + const target = new THREE.Vector3(); + const dir = new THREE.Vector3(); + let distance = 20; + let view = { w: 1, h: 1 }; + const keyPoints: THREE.Vector3[] = []; + const v = new THREE.Vector3(); + const frameCamera = () => { + const aspect = view.w / Math.max(1, view.h); + // 不夠寬(手機、直立的平板)就從側面看,五關的名牌才不會擠在同一排 + const portrait = aspect < 1.35; + // 直式:從左邊(里長那頭)看過去,五關由下往上排;橫式:從前面看 + const az = portrait ? -Math.PI / 2 : 0.08; + const el = portrait ? 0.98 : 0.8; + dir.set(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)); + camera.fov = portrait ? 40 : 30; + camera.aspect = aspect; + camera.clearViewOffset(); + camera.updateProjectionMatrix(); + keyPoints.length = 0; + STOPS.forEach((s, i) => { + for (const [dx, dz] of [ + [PLAZA_R + 0.3, 0], + [-PLAZA_R - 0.3, 0], + [0, PLAZA_R + 0.3], + [0, -PLAZA_R - 0.3], + ] as const) + keyPoints.push(new THREE.Vector3(s.x + dx, 0, s.z + dz)); + const b = BUILDING_AT[i]!; + // 名牌在建築上方,留一點高度給它 + keyPoints.push(new THREE.Vector3(b.x, (stops[i]?.top ?? s.h) + (portrait ? 2.2 : 1.6), b.z)); + }); + target.set(0, 0.6, 0.2); + const extent = (d: number) => { + camera.position.copy(target).addScaledVector(dir, d); + camera.lookAt(target); + camera.updateMatrixWorld(); + let x0 = Infinity; + let x1 = -Infinity; + let y0 = Infinity; + let y1 = -Infinity; + for (const p of keyPoints) { + v.copy(p).project(camera); + x0 = Math.min(x0, v.x); + x1 = Math.max(x1, v.x); + y0 = Math.min(y0, v.y); + y1 = Math.max(y1, v.y); + } + return { x0, x1, y0, y1 }; + }; + let lo = 6; + let hi = 90; + for (let k = 0; k < 28; k++) { + const mid = (lo + hi) / 2; + const e = extent(mid); + // 左右多留一點給名牌(名牌比建築寬) + if (e.x1 - e.x0 > (portrait ? 1.5 : 1.62) || e.y1 - e.y0 > 1.78) lo = mid; + else hi = mid; + } + distance = hi; + // 把五關的範圍移到畫面正中間 + const e = extent(distance); + const cx = (e.x0 + e.x1) / 2; + const cy = (e.y0 + e.y1) / 2; + camera.setViewOffset(view.w, view.h, (cx * view.w) / 2, (-cy * view.h) / 2, view.w, view.h); + camera.updateProjectionMatrix(); + }; + let pointerX = 0; + const place = (t: number) => { + const sway = opts.reduceMotion ? 0 : Math.sin(t * 0.12) * 0.015 + pointerX * 0.012; + const c = Math.cos(sway); + const s = Math.sin(sway); + camera.position.set(target.x + (dir.x * c + dir.z * s) * distance, target.y + dir.y * distance, target.z + (-dir.x * s + dir.z * c) * distance); + camera.lookAt(target); + }; + + // ── 名牌的位置 ── + const anchors = STOPS.map(() => ({ x: 0, y: 0 })); + const sendAnchors = () => { + camera.updateMatrixWorld(); + STOPS.forEach((_, i) => { + const b = BUILDING_AT[i]!; + v.set(b.x, (stops[i]?.top ?? STOPS[i]!.h) + 0.15, b.z).project(camera); + anchors[i] = { x: ((v.x + 1) / 2) * view.w, y: ((1 - v.y) / 2) * view.h }; + }); + opts.onAnchors(anchors); + }; + + // ── 點建築或廣場選關 ── + const ray = new THREE.Raycaster(); + const ndc = new THREE.Vector2(); + const pick = (e: PointerEvent): number | null => { + const r = canvas.getBoundingClientRect(); + ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + ray.setFromCamera(ndc, camera); + for (const h of ray.intersectObjects( + stops.map((s) => s.group), + true, + )) { + for (let o: THREE.Object3D | null = h.object; o; o = o.parent) { + if (typeof o.userData.stop === "number") return o.userData.stop as number; + } + } + return null; + }; + let down: { x: number; y: number } | null = null; + const onDown = (e: PointerEvent) => { + down = { x: e.clientX, y: e.clientY }; + }; + const onMove = (e: PointerEvent) => { + const r = canvas.getBoundingClientRect(); + pointerX = ((e.clientX - r.left) / r.width - 0.5) * 2; + if (e.pointerType === "mouse") canvas.style.cursor = pick(e) !== null ? "pointer" : "default"; + }; + const onUp = (e: PointerEvent) => { + if (!down || Math.hypot(e.clientX - down.x, e.clientY - down.y) > 8) return; + down = null; + const i = pick(e); + if (i !== null) opts.onPick(i); + }; + canvas.addEventListener("pointerdown", onDown); + canvas.addEventListener("pointermove", onMove); + canvas.addEventListener("pointerup", onUp); + + // ── 繪圖迴圈:減少動態時只在有變化時畫一次 ── + const clock = new THREE.Clock(); + let active = true; + let disposed = false; + let dirty = true; + let raf = 0; + function invalidate() { + dirty = true; + } + const frame = () => { + if (disposed) return; + raf = requestAnimationFrame(frame); + if (!active) return; + const dt = Math.min(clock.getDelta(), 0.05); + const t = clock.elapsedTime; + const animate = ready && !opts.reduceMotion; + if (!animate && !dirty) return; + dirty = false; + place(t); + if (animate) { + for (const m of mixers) m.update(dt); + ring.scale.setScalar(1 + Math.sin(t * 4) * 0.05); + } + if (truck) { + // 宣傳車沿著馬路開到選取的那一關(停在廣場前面一點) + const goal = Math.max(0.01, (STOP_U[state.selected] ?? 0) - 0.03); + const gap = goal - truckU; + if (Math.abs(gap) > 0.0005) { + truckU += Math.sign(gap) * Math.min(Math.abs(gap), dt * 0.32); + dirty = true; + } + const p = ROAD.getPointAt(Math.min(1, Math.max(0, truckU))); + const d = tangentAt(truckU); + truck.position.set(p.x, animate && Math.abs(gap) > 0.001 ? Math.abs(Math.sin(t * 22)) * 0.03 : 0, p.z); + truck.rotation.y = Math.atan2(d.x, d.z) + (gap < 0 ? Math.PI : 0); + } + renderer.render(scene, camera); + sendAnchors(); + }; + + setup() + .then(() => { + if (disposed) return; + frameCamera(); + invalidate(); + opts.onReady(); + }) + .catch(() => !disposed && opts.onError()); + raf = requestAnimationFrame(frame); + + return { + resize(w, h) { + view = { w: Math.max(1, w), h: Math.max(1, h) }; + renderer.setSize(view.w, view.h, false); + frameCamera(); + invalidate(); + }, + setStops(next, selected, here) { + state = { stops: next, selected, here }; + applyStops(); + }, + setActive(on) { + active = on; + if (on) { + clock.getDelta(); + invalidate(); + } + }, + dispose() { + disposed = true; + cancelAnimationFrame(raf); + canvas.removeEventListener("pointerdown", onDown); + canvas.removeEventListener("pointermove", onMove); + canvas.removeEventListener("pointerup", onUp); + textures.forEach((t) => t.dispose()); + scene.traverse((o) => { + const m = o as THREE.Mesh; + m.geometry?.dispose(); + const mats = [m.material, (m.userData as { gray?: unknown }).gray].flat() as (THREE.Material | undefined)[]; + mats.forEach((x) => x?.dispose?.()); + }); + renderer.dispose(); + }, + }; +} diff --git a/web/src/game/rogue/careerRules.ts b/web/src/game/rogue/careerRules.ts new file mode 100644 index 0000000..c91d126 --- /dev/null +++ b/web/src/game/rogue/careerRules.ts @@ -0,0 +1,194 @@ +import { MINOR_EXP_MULT, originAbilities, partyKind, type CareerAbilities } from "@election2026/protocol"; +import type { Ability } from "../career/term/types.ts"; +import type { SavedCharacter } from "../creator/characters.ts"; + +/** + * 政治生涯的練等規則(docs/23、18 第 44 項):純函式,畫面在 Career.tsx。 + * - 五關都可以重複選;往上選要「上一關選上過(或跳過)」+等級夠(議員 Lv3、立委 Lv5、縣市長 Lv8、總統 Lv12)。 + * - 經驗:當選全額、落選四成;逆風每加一級 ×1.15;S 評價 ×1.5、A ×1.25;回去選比較低的關 ×0.6。 + * - 升級要的經驗 40、70、100…(每級多 30);每升一級 +1 技能點。 + */ + +export interface Carry { + advisors: string[]; + cards: { id: string; up: boolean }[]; + money: number; + momentum: number; +} + +export interface TierRecord { + runs: number; + wins: number; + best: string | null; + /** 選上過的最高逆風加碼(0–3);-1 是還沒選上 */ + topExtra: number; +} + +export interface CareerState { + id: string; + character: SavedCharacter; + county: { code: string; name: string }; + /** 你住的里(里長關開局後記下)和它所在的區(找議員、立委選區用) */ + village: string | null; + villageTown: string | null; + /** 立委選區(同一縣市有好幾區時玩家挑的) */ + district: string | null; + level: number; + exp: number; + skillPoints: number; + /** 現在的能力=開局能力 base+自己加的點 */ + abilities: CareerAbilities; + base: CareerAbilities; + tiers: Record; + /** 開局時跳過的關(算成選上過) */ + skipped: number[]; + carry: Carry; + history: { stage: number; runId: string; won: boolean; share: number; grade: string; area?: string; exp: number; extra: number }[]; + /** 正在打的那一局 */ + pending: { runId: string; stage: number; extra: number } | null; + /** 剛選上的那一局:還沒挑要帶走的幕僚和牌 */ + pickFrom?: string | null; + /** 挑完要帶走的東西、正在做任期 */ + term?: { stage: number; runId: string } | null; + /** 剛打完的那一局拿到的經驗(地圖上的戰報) */ + report?: { runId: string; stage: number; won: boolean; exp: number; levels: number; why: string } | null; + /** 開局能力用哪一版規則算的(2=出身與黨的資源,18 第 53 項);舊存檔沒有 */ + originRules?: number; +} + +export const STAGES: readonly { stage: number; title: string; kind: "village" | "council" | "legislator" | "mayor" | "president"; years: readonly string[]; ascension: number; req: number; xp: number; }[] = [ + { stage: 1, title: "里長", kind: "village", years: [], ascension: 0, req: 1, xp: 40 }, + { stage: 2, title: "議員", kind: "council", years: [], ascension: 1, req: 3, xp: 60 }, + { stage: 3, title: "區域立委", kind: "legislator", years: ["2024", "2020"], ascension: 2, req: 5, xp: 90 }, + { stage: 4, title: "縣市長", kind: "mayor", years: ["2022", "2018", "2014"], ascension: 3, req: 8, xp: 130 }, + { stage: 5, title: "總統", kind: "president", years: ["2024"], ascension: 5, req: 12, xp: 200 }, +]; +export const LAST = STAGES.length; +/** 同一關最多可以再加幾級逆風(選上一次解鎖下一級) */ +export const MAX_EXTRA = 3; +export const MAX_LEVEL = 5; +/** 升到下一級要的經驗 */ +export const toNext = (level: number) => 40 + 30 * (level - 1); +export const GRADE_MULT: Record = { S: 1.5, A: 1.25 }; + +export const ABILITY_IDS: Ability[] = ["eloquence", "organization", "media", "finance", "integrity"]; +export const ABILITY_LABELS: Record = { eloquence: "口才", organization: "組織", media: "媒體", finance: "財務", integrity: "清廉" }; + +export const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); +export const emptyTiers = (): Record => Object.fromEntries(STAGES.map((s) => [s.stage, { runs: 0, wins: 0, best: null, topExtra: -1 }])); +export const noCarry = (): Carry => ({ advisors: [], cards: [], money: 0, momentum: 0 }); + +/** 開局能力:照捏人物的點數換算(平均 5 點是 1 級),清廉看出身 */ +/** 開局能力:捏人物點數+出身+黨的資源(規則在 protocol/origins.ts,伺服器的自由選戰用同一份) */ +export function startAbilities(c: SavedCharacter): CareerAbilities { + return originAbilities(c); +} + +/** 舊存檔的開局能力換成新規則(出身與黨的資源):自己加的點保留,開局那部分照新規則重算 */ +export function withOriginRules(c: CareerState): CareerState { + if (c.originRules === ORIGIN_RULES) return c; + const base = startAbilities(c.character); + const abilities = { ...c.abilities }; + for (const id of ABILITY_IDS) abilities[id] = clamp(c.abilities[id] - c.base[id] + base[id], 0, MAX_LEVEL); + return { ...c, base, abilities, originRules: ORIGIN_RULES }; +} +export const ORIGIN_RULES = 2; + +/** 舊版(五關一路往上、或立委起跳三關)的進度換成練等版:選上過的關記下來,等級照選上的關估 */ +export function migrate(raw: Record, version: 1 | 2): CareerState { + const old = raw as unknown as { + id: string; + character: SavedCharacter; + county: { code: string; name: string }; + village?: string | null; + villageTown?: string | null; + district?: string | null; + abilities?: CareerAbilities; + skipped?: number[]; + carry?: Partial; + history?: { stage: number; runId: string; won: boolean; share: number; grade: string; area?: string }[]; + }; + const shift = version === 1 ? 2 : 0; + const tiers = emptyTiers(); + const history = (old.history ?? []).map((h) => ({ ...h, stage: h.stage + shift, exp: 0, extra: 0 })); + for (const h of history) { + const t = tiers[h.stage]; + if (!t) continue; + t.runs += 1; + if (h.won) { + t.wins += 1; + t.topExtra = Math.max(t.topExtra, 0); + } + } + const won = STAGES.filter((s) => tiers[s.stage]!.wins > 0).length; + const base = old.abilities ?? startAbilities(old.character); + return { + id: old.id, + character: old.character, + county: old.county, + village: old.village ?? null, + villageTown: old.villageTown ?? null, + district: old.district ?? null, + level: 1 + won * 3, + exp: 0, + skillPoints: 0, + abilities: base, + base, + tiers, + skipped: version === 1 ? [1, 2] : (old.skipped ?? []), + carry: { ...noCarry(), ...old.carry }, + history, + pending: null, + }; +} + +/** 這一關能不能選:第一關一定可以;之後要上一關選上過(或跳過)、等級夠 */ +export function unlockOf(c: CareerState, stage: number): { open: boolean; why: string } { + const def = STAGES[stage - 1]!; + if (stage === 1 || c.skipped.includes(stage)) return { open: true, why: "" }; + const prev = STAGES[stage - 2]!; + const prevOk = c.tiers[stage - 1]!.wins > 0 || c.skipped.includes(stage - 1); + const lvOk = c.level >= def.req; + if (prevOk && lvOk) return { open: true, why: "" }; + return { open: false, why: [!prevOk && `先選上${prev.title}`, !lvOk && `要 Lv ${def.req}`].filter(Boolean).join("・") }; +} +export const highestOpen = (c: CareerState) => Math.max(...STAGES.filter((s) => unlockOf(c, s.stage).open).map((s) => s.stage)); + +/** 一場選舉拿多少經驗 */ +export function runExp(c: CareerState, stage: number, won: boolean, grade: string, extra: number): { exp: number; why: string } { + const def = STAGES[stage - 1]!; + const parts: string[] = [won ? `當選 ${def.xp}` : `落選 ${Math.round(def.xp * 0.4)}`]; + let exp = def.xp * (won ? 1 : 0.4); + if (extra > 0) { + exp *= 1 + 0.15 * extra; + parts.push(`逆風 +${extra} ×${(1 + 0.15 * extra).toFixed(2)}`); + } + if (won && GRADE_MULT[grade]) { + exp *= GRADE_MULT[grade]!; + parts.push(`${grade} 評價 ×${GRADE_MULT[grade]}`); + } + if (stage < highestOpen(c)) { + exp *= 0.6; + parts.push("回去選低的關 ×0.6"); + } + if (partyKind(c.character.party) === "minor") { + exp *= MINOR_EXP_MULT; + parts.push(`${c.character.party ? "小黨" : "無黨籍"} ×${MINOR_EXP_MULT}`); + } + return { exp: Math.round(exp), why: parts.join("、") }; +} + +/** 加經驗:滿了升級,每升一級 +1 技能點 */ +export function gainExp(c: CareerState, n: number): { next: CareerState; levels: number } { + let { level, exp, skillPoints } = c; + exp += n; + let levels = 0; + while (exp >= toNext(level)) { + exp -= toNext(level); + level += 1; + skillPoints += 1; + levels += 1; + } + return { next: { ...c, level, exp, skillPoints }, levels }; +} + diff --git a/web/src/game/rogue/coach.tsx b/web/src/game/rogue/coach.tsx new file mode 100644 index 0000000..a16c24a --- /dev/null +++ b/web/src/game/rogue/coach.tsx @@ -0,0 +1,126 @@ +import type { RogueView } from "@election2026/protocol"; +import { GraduationCap } from "lucide-react"; +import { useState } from "react"; + +/** + * 新手教學的提示(docs/22):幸福里里長選舉,3 週。照玩家目前做到哪裡給下一步的提示, + * 不擋操作;highlight 是要框起來的地方(RogueScreen 用 data-coach 屬性加外框)。 + */ +interface Step { + id: string; + text: string; + highlight: "hud" | "intents" | "hand" | "map" | "end" | null; + /** 什麼時候出現 */ + when: (v: RogueView) => boolean; + /** 做到了就換下一個;沒有的話要按「知道了」 */ + done?: (v: RogueView, selected: string | null) => boolean; +} + +const played = (v: RogueView) => v.towns.reduce((a, t) => a + t.played.length, 0); +const plan1 = (v: RogueView) => v.week === 1 && v.phase === "plan"; + +const STEPS: readonly Step[] = [ + { + id: "intro", + text: "歡迎來到幸福里!你要在 3 週內贏過連任三屆的老里長。最上面是全里的支持度:左邊是你、右邊是對手,斜線是還沒表態的人。", + highlight: "hud", + when: plan1, + }, + { + id: "intents", + text: "右上角是老里長「這週要做的事」,地圖上也標出來了。這些事週末才執行,你可以先想辦法擋。", + highlight: "intents", + when: plan1, + }, + { + id: "pick", + text: "選一張牌試試看:點手上的「宮廟參拜」。", + highlight: "hand", + when: plan1, + done: (v, selected) => selected !== null || played(v) > 0, + }, + { + id: "play", + text: "地圖和右邊列表會顯示打在每一區加幾票,標大拇指的是最划算的。廟口宮廟多,宮廟牌 ×2!點「廟口」打出去。", + highlight: "map", + when: plan1, + done: (v) => played(v) > 0, + }, + { + id: "combo", + text: "同一週在同一區打「不同的牌」是組合拳:第 2 種 +15%、第 3 種 +30%。再把「菜市場拜票」打在廟口看看。", + highlight: "hand", + when: plan1, + done: (v) => v.towns.some((t) => t.played.length >= 2) || v.energy === 0, + }, + { + id: "energy", + text: "每週 3 點體力,左上角的數字是要花的體力。最後一點可以用「拜託里長佈樁」擋下對手在某一區的行動。", + highlight: "hand", + when: plan1, + done: (v) => v.energy === 0, + }, + { + id: "end", + text: "體力用完了。按「結束這週」,看老里長照計畫行動,你的樁腳會先擋一部分。", + highlight: "end", + when: (v) => plan1(v) && v.energy === 0, + done: (v) => v.phase !== "plan" || v.week > 1, + }, + { + id: "route", + text: "每週結束可以選「下一站」:拿新牌、找幕僚、升級牌、拿掉弱牌……先去「拜會地方」拿一張新牌吧。", + highlight: null, + when: (v) => v.week === 1 && (v.phase === "route" || v.phase === "stop"), + done: (v) => v.week > 1, + }, + { + id: "flags", + text: "某一區領先 8 個百分點就會插上你的旗,每週多 20 萬小額捐款。把對手插旗的區翻過來,聲勢 +1!", + highlight: "map", + when: (v) => v.week === 2 && v.phase === "plan", + }, + { + id: "counter", + text: "對手要在某一區掃街、造勢或佈樁時,用「打對台」讓他只剩四成,你在那區也加票。", + highlight: "intents", + when: (v) => v.week === 2 && v.phase === "plan" && v.hand.some((c) => c.id === "counter"), + }, + { + id: "final", + text: "最後一週!聲勢越高,開票時還沒表態的人越多出來投給你。全力衝刺吧!", + highlight: "hud", + when: (v) => v.week === 3 && v.phase === "plan", + }, +]; + +export function useCoach(view: RogueView | null, selected: string | null) { + const [dismissed, setDismissed] = useState>(new Set()); + const [off, setOff] = useState(false); + if (!view?.options.tutorial || off || view.phase === "finished") return { step: null, dismiss: () => undefined, quit: () => undefined }; + const step = STEPS.find((s) => s.when(view) && !dismissed.has(s.id) && !(s.done?.(view, selected) ?? false)) ?? null; + return { + step, + dismiss: () => step && setDismissed(new Set([...dismissed, step.id])), + quit: () => setOff(true), + }; +} + +export function CoachBubble({ step, onDismiss, onQuit }: { step: Step; onDismiss: () => void; onQuit: () => void }) { + return ( + + ); +} diff --git a/web/src/game/rogue/collection.css b/web/src/game/rogue/collection.css new file mode 100644 index 0000000..2c7dd0c --- /dev/null +++ b/web/src/game/rogue/collection.css @@ -0,0 +1,322 @@ +/* 圖鑑與成就:一本選戰卡冊(Collection.tsx)。紅色封面、白色內頁、一格一格的卡套, + 右邊(手機在上面)是索引貼。顏色只用 theme/tokens.css;動畫只動 transform、opacity。 + 卡套大小由 Collection.tsx 量畫面後用 --col-* 變數給,整頁不捲 */ + +.col-scene .gs-body { display: grid; } +.col-wrap { + min-height: 0; width: min(100%, 1680px); margin-inline: auto; + display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: minmax(0, 1fr); +} +.col-hud-wide { display: contents; } + +/* ── 索引貼 ── */ +.col-tabs { grid-column: 2; grid-row: 1; display: flex; flex-direction: column; gap: 10px; padding-top: 34px; } +.col-tab { + position: relative; z-index: 0; + display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto auto; align-items: center; column-gap: 10px; row-gap: 2px; + width: 168px; min-height: 76px; margin-left: -4px; padding: 8px 14px 9px 18px; + border: 3px solid var(--ink); border-left: 0; border-radius: 0 16px 16px 0; + background: var(--surface-2); color: var(--ink); box-shadow: 4px 4px 0 var(--shadow-ink); + font: inherit; text-align: left; cursor: pointer; + transform: translateX(-10px); transition: transform 200ms var(--ease-out); +} +.col-tab[aria-selected="true"] { z-index: 2; background: var(--signal); color: var(--signal-ink); transform: none; } +.col-tab:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +.col-tab-ic { + grid-row: 1 / 3; width: 38px; height: 38px; display: grid; place-items: center; border-radius: 50%; + background: var(--ink); color: var(--surface); +} +.col-tab[aria-selected="true"] .col-tab-ic { background: var(--stamp); color: var(--navy-ink); } +.col-tab b { font-family: var(--font-serif); font-size: 18px; line-height: 1.1; } +.col-tab small { font-family: var(--font-num); font-weight: 800; font-size: 17px; line-height: 1; font-variant-numeric: tabular-nums; } +.col-tab-bar { grid-column: 1 / -1; height: 6px; margin-top: 4px; border-radius: 999px; overflow: hidden; background: color-mix(in srgb, var(--ink) 14%, transparent); } +.col-tab-bar i, .col-meter i { display: block; height: 100%; transform-origin: left; transform: scaleX(var(--p, 0)); } +.col-tab-bar i { background: var(--stamp); } +@media (hover: hover) and (pointer: fine) { + .col-tab:not([aria-selected="true"]):hover { transform: translateX(-3px); } +} + +/* ── 卡冊:紅色封面+白色內頁 ── */ +.col-book { + position: relative; z-index: 1; grid-column: 1; grid-row: 1; min-width: 0; min-height: 0; + display: grid; grid-template-rows: minmax(0, 1fr); padding: 10px; + background: var(--stamp); border: 3px solid var(--ink); border-radius: 22px 10px 10px 22px; box-shadow: 6px 6px 0 var(--shadow-ink); +} +/* 封面的車線 */ +.col-book::before { + content: ""; position: absolute; inset: 3px; border: 2px dashed color-mix(in srgb, var(--navy-ink) 45%, transparent); + border-radius: 18px 7px 7px 18px; pointer-events: none; +} +.col-sheet { + position: relative; min-width: 0; min-height: 0; + display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: 8px; padding: 10px 14px; + background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 14px 6px 6px 14px; +} + +/* 內頁上面:分類名稱、收錄進度、跳到哪一組 */ +.col-head { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 16px; min-height: 44px; } +.col-title { display: flex; align-items: center; gap: 10px; min-width: 0; } +.col-title h2 { margin: 0; font-family: var(--font-serif); font-size: 26px; line-height: 1; white-space: nowrap; } +.col-count { font-family: var(--font-num); font-weight: 800; font-size: 22px; line-height: 1; font-variant-numeric: tabular-nums; white-space: nowrap; } +.col-meter { width: 120px; height: 12px; border: 2px solid var(--ink); border-radius: 999px; overflow: hidden; background: var(--surface-2); } +.col-meter i { background: var(--signal); } +.col-jump { display: flex; gap: 6px; min-width: 0; overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: none; padding: 3px 2px; } +.col-jump::-webkit-scrollbar { display: none; } +/* 放得下時靠右;放不下時從左邊開始捲(flex-end 會把左邊的擠到捲不到的地方) */ +.col-jump > :first-child { margin-left: auto; } +.col-chip { + flex: none; display: inline-flex; align-items: center; gap: 6px; min-height: 38px; padding: 0 12px; + border: 2px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); + font: inherit; font-weight: 800; font-size: 14px; cursor: pointer; transition: transform 140ms var(--ease-out); +} +.col-chip small { font-family: var(--font-num); font-size: 14px; color: var(--muted); } +.col-chip.is-here { background: var(--ink); color: var(--surface); } +.col-chip.is-here small { color: inherit; opacity: 0.8; } +.col-chip:active { transform: scale(0.96); } +.col-chip:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +@media (pointer: coarse) { .col-chip { min-height: 44px; } } +@media (hover: hover) and (pointer: fine) { + .col-chip:not(.is-here):hover { background: var(--signal); color: var(--signal-ink); } +} +.col-records { justify-self: end; display: grid; justify-items: end; gap: 2px; margin: 0; text-align: right; } +.col-hint { justify-self: end; margin: 0; font-size: 14px; font-weight: 700; color: var(--muted); } +.col-records b { font-size: 15px; } +.col-records small { font-size: 12px; color: var(--muted); } + +/* ── 攤開的兩頁(手機一頁) ── */ +.col-spread { position: relative; min-width: 0; min-height: 0; overflow: hidden; touch-action: pan-y; } +.col-msg { display: grid; place-items: center; height: 100%; margin: 0; color: var(--muted); font-weight: 700; } +.col-drag { height: 100%; display: grid; grid-template-columns: minmax(0, 1fr); transition: transform 220ms var(--ease-out); } +.col-drag.is-dragging { transition: none; } +.col-spread.is-two .col-drag { grid-template-columns: minmax(0, 1fr) var(--col-spine) minmax(0, 1fr); } +.col-page { min-width: 0; min-height: 0; display: grid; place-items: center; padding: var(--col-page-pad); } +.col-spread.is-two .col-page:first-child { background: linear-gradient(90deg, transparent 82%, color-mix(in srgb, var(--ink) 7%, transparent)); } +.col-spread.is-two .col-page:last-child { background: linear-gradient(270deg, transparent 82%, color-mix(in srgb, var(--ink) 7%, transparent)); } +/* 中間的書背和活頁環 */ +.col-spine { + display: grid; align-content: space-evenly; justify-items: center; + border-inline: 2px dashed var(--line); background: color-mix(in srgb, var(--ink) 5%, var(--surface-2)); +} +.col-spine i { + width: 22px; height: 22px; border-radius: 50%; background: var(--paper); border: 3px solid var(--ink); + box-shadow: inset 3px 3px 0 color-mix(in srgb, var(--ink) 22%, transparent); +} +.col-pockets { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--col-cols), auto); gap: var(--col-gap); } + +/* 翻頁:新的一頁從翻的方向滑進來 */ +.col-page.is-in-next { animation: col-in-next 320ms var(--ease-out) both; } +.col-page.is-in-prev { animation: col-in-prev 320ms var(--ease-out) both; } +.col-page.is-in-tab { animation: col-in-tab 280ms var(--ease-out) both; } +.col-spread.is-two .col-page.is-in-next:last-child, .col-spread.is-two .col-page.is-in-prev:first-child { animation-delay: 60ms; } +@keyframes col-in-next { from { opacity: 0; transform: translateX(36px); } } +@keyframes col-in-prev { from { opacity: 0; transform: translateX(-36px); } } +@keyframes col-in-tab { from { opacity: 0; transform: translateY(12px); } } + +/* ── 一格卡套 ── */ +.col-pocket { + --col-face-w: var(--col-card-w); + position: relative; display: grid; grid-template-rows: minmax(0, 1fr) var(--col-cap); justify-items: center; align-items: start; + width: calc(var(--col-card-w) + var(--col-pad) * 2); height: calc(var(--col-card-w) * 1.47 + var(--col-cap) + var(--col-pad) * 2); + padding: var(--col-pad); margin: 0; + border: 2px solid var(--line); border-radius: 12px; + background: linear-gradient(180deg, color-mix(in srgb, var(--surface-2) 55%, transparent), var(--surface-2)); + color: var(--ink); font: inherit; text-align: center; cursor: pointer; + -webkit-tap-highlight-color: transparent; +} +/* 卡套的塑膠反光 */ +.col-pocket::after { + content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none; + background: linear-gradient(118deg, transparent 38%, color-mix(in srgb, var(--navy-ink) 16%, transparent) 46%, transparent 54%); +} +.col-pocket.is-empty { display: block; border-style: dashed; background: transparent; cursor: default; } +.col-pocket.is-empty::after { content: none; } +.col-pocket:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +.col-cap { + align-self: center; width: 100%; display: flex; align-items: flex-start; justify-content: center; gap: 3px; + font-size: 11px; line-height: 1.3; font-weight: 700; color: var(--muted); +} +.col-cap svg { flex: none; margin-top: 1px; } +.col-cap > span { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-align: left; } +.col-pocket.is-got .col-cap { color: var(--good); } +.col-pocket.is-got .col-cap > span { text-align: center; } + +/* 牌面:卡套裡和大張都用 --col-face-w 決定寬度 */ +.col-face { --rg-card-w: var(--col-face-w); display: block; transition: transform 200ms var(--ease-out); } +@media (hover: hover) and (pointer: fine) { + .col-pocket:hover .col-face { transform: translateY(-5px) rotate(-1.5deg); } +} +.col-pocket:active .col-face { transform: scale(0.96); } + +/* 幕僚:做成和牌一樣大小的直式卡 */ +.col-face .rga { + width: var(--col-face-w); height: calc(var(--col-face-w) * 1.47); align-content: start; gap: 4px; + padding: calc(var(--col-face-w) * 0.08) 6px 6px; overflow: hidden; border-radius: 12px; +} +.col-face .rga .staff-avatar { width: calc(var(--col-face-w) * 0.58) !important; height: calc(var(--col-face-w) * 0.58) !important; } +.col-face .rga b { font-size: calc(var(--col-face-w) * 0.135); line-height: 1.15; } +.col-face .rga > span:last-child { + font-size: calc(var(--col-face-w) * 0.092); line-height: 1.35; + display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; +} + +/* 每週事件:報紙頭條 */ +.col-ev { + display: grid; grid-template-rows: auto auto minmax(0, 1fr); gap: calc(var(--col-face-w) * 0.05); + width: var(--col-face-w); height: calc(var(--col-face-w) * 1.47); overflow: hidden; text-align: left; + background: var(--newsprint); color: var(--ink); border: 3px solid var(--ink); border-radius: 12px; box-shadow: 3px 3px 0 var(--shadow-ink); +} +.col-ev-head { + display: flex; align-items: center; gap: 4px; padding: 4px 8px; + background: var(--ink); color: var(--surface); font-size: calc(var(--col-face-w) * 0.085); font-weight: 900; letter-spacing: 0.1em; white-space: nowrap; +} +.col-ev-head svg { width: 1.2em; height: 1.2em; flex: none; } +.col-ev-title { + margin: 0 8px; padding-bottom: 4px; border-bottom: 2px solid var(--ink); + font-family: var(--font-serif); font-size: calc(var(--col-face-w) * 0.135); line-height: 1.2; +} +.col-ev-text { + padding: 0 8px; font-size: calc(var(--col-face-w) * 0.09); line-height: 1.45; color: var(--muted); + display: -webkit-box; -webkit-line-clamp: 6; -webkit-box-orient: vertical; overflow: hidden; +} + +/* 成就獎章 */ +.col-medal { + display: grid; grid-template-rows: auto auto minmax(0, 1fr); justify-items: center; align-content: start; gap: calc(var(--col-face-w) * 0.05); + width: var(--col-face-w); height: calc(var(--col-face-w) * 1.47); padding: calc(var(--col-face-w) * 0.1) 6px 6px; overflow: hidden; + background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 12px; box-shadow: 3px 3px 0 var(--shadow-ink); +} +.col-medal.is-got { background: var(--signal); color: var(--signal-ink); } +.col-medal-disc { + width: calc(var(--col-face-w) * 0.5); aspect-ratio: 1; display: grid; place-items: center; border-radius: 50%; + background: var(--surface-2); color: var(--muted); border: 3px dashed var(--muted); +} +.col-medal.is-got .col-medal-disc { + background: var(--stamp); color: var(--navy-ink); border: 3px solid var(--ink); + box-shadow: inset 0 0 0 4px color-mix(in srgb, var(--signal) 70%, var(--stamp)), 2px 2px 0 var(--shadow-ink); +} +.col-medal-disc svg { width: 50%; height: 50%; } +.col-medal b { font-family: var(--font-serif); font-size: calc(var(--col-face-w) * 0.135); line-height: 1.15; text-align: center; } +.col-medal > span:last-child { + font-size: calc(var(--col-face-w) * 0.092); line-height: 1.35; text-align: center; + display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; +} + +/* ── 還沒收錄:灰色、淡一點,但名字和效果照樣看得到 ── */ +.is-locked .col-face { filter: grayscale(1); } +.is-locked .col-face :is(.rgc, .rga, .col-ev, .col-medal) { + border-color: var(--muted); border-style: dashed; background: var(--surface-2); color: var(--ink); box-shadow: none; +} +.is-locked .col-face :is(.rgc-art, .staff-avatar, .col-ev-head, .col-medal-disc, .rgc-cost, .rgc-money, .rgc-gem, .rgc-keys) { opacity: 0.42; } +.is-locked .col-face .rgc-value { opacity: 0.6; } + +/* ── 內頁下面:翻頁 ── */ +.col-foot { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; } +.col-pager { display: flex; justify-content: center; align-items: center; gap: 12px; min-width: 0; font-weight: 800; font-variant-numeric: tabular-nums; white-space: nowrap; } +.col-dots { display: flex; gap: 6px; } +.col-dots i { width: 11px; height: 11px; border-radius: 50%; border: 2px solid var(--ink); background: var(--surface); } +.col-dots i.is-on { background: var(--stamp); transform: scale(1.2); } +.col-keyhint { display: none; color: var(--muted); font-size: 12px; font-weight: 700; } +.col-keyhint kbd { display: inline-block; min-width: 20px; padding: 0 4px; border: 2px solid var(--line); border-radius: 5px; font: inherit; text-align: center; } +@media (hover: hover) and (pointer: fine) { .col-keyhint { display: inline; } } + +.col-btn { + min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 4px; padding: 0 16px; + border: 3px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); box-shadow: 3px 3px 0 var(--shadow-ink); + font: inherit; font-weight: 800; font-size: 15px; cursor: pointer; transition: transform 140ms var(--ease-out); + -webkit-tap-highlight-color: transparent; +} +.col-btn:active:not(:disabled) { transform: translate(2px, 2px); } +.col-btn:disabled { opacity: 0.35; cursor: default; box-shadow: none; } +.col-btn:focus-visible { outline: 3px solid var(--stamp); outline-offset: 2px; } +@media (hover: hover) and (pointer: fine) { + .col-btn:hover:not(:disabled) { background: var(--signal); color: var(--signal-ink); } +} + +/* ── 點一格:大張的說明 ── */ +.col-modal-back { + position: fixed; inset: 0; z-index: 80; display: grid; place-items: center; + padding: max(16px, env(safe-area-inset-top, 0px)) 16px max(16px, env(safe-area-inset-bottom, 0px)); + background: color-mix(in srgb, var(--navy) 72%, transparent); + animation: col-fade 200ms ease both; +} +.col-modal { + position: relative; display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 32px; + width: min(800px, 100%); max-height: 100%; overflow-y: auto; overscroll-behavior: contain; padding: 30px 30px 26px; + background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 22px; box-shadow: 8px 8px 0 var(--shadow-ink); + animation: col-pop 280ms var(--ease-out) both; +} +.col-modal-x { position: absolute; top: 12px; right: 12px; z-index: 2; padding: 0; } +.col-big { position: relative; justify-self: center; touch-action: pan-y; } +.col-big .col-face { --col-face-w: 230px; transform: rotate(-2deg); animation: col-pop 260ms var(--ease-out) both; } +.col-stamp { + position: absolute; right: -14px; bottom: 16%; padding: 4px 12px; + border: 4px solid var(--stamp); border-radius: 10px; color: var(--stamp); background: color-mix(in srgb, var(--surface) 82%, transparent); + font-family: var(--font-serif); font-size: 22px; letter-spacing: 0.1em; transform: rotate(-14deg); +} +.col-info { display: grid; gap: 10px; align-content: center; min-width: 0; } +.col-state { + justify-self: start; display: inline-flex; align-items: center; gap: 6px; margin: 0; padding: 3px 12px; + border-radius: 999px; background: var(--good); color: var(--navy-ink); font-weight: 800; font-size: 14px; +} +.col-state.is-locked { background: var(--surface-2); color: var(--muted); border: 2px dashed var(--muted); } +.col-info h2 { margin: 0; padding-right: 48px; font-family: var(--font-serif); font-size: clamp(26px, 3.4vw, 34px); line-height: 1.1; } +.col-meta { margin: 0; color: var(--muted); font-weight: 700; font-size: 14px; } +.col-desc { margin: 0; font-size: 17px; line-height: 1.6; } +.col-how { + display: grid; gap: 4px; padding: 12px 14px; border: 3px solid var(--ink); border-radius: 14px; + background: var(--signal); color: var(--signal-ink); box-shadow: 3px 3px 0 var(--shadow-ink); transform: rotate(-0.6deg); +} +.col-how b { font-size: 13px; letter-spacing: 0.12em; } +.col-how p { margin: 0; font-size: 16px; line-height: 1.5; font-weight: 700; } +.col-note { margin: 0; font-size: 13px; color: var(--muted); } +.col-modal-nav { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; margin-top: 4px; } +.col-modal-nav span { text-align: center; font-family: var(--font-num); font-weight: 800; font-size: 18px; font-variant-numeric: tabular-nums; } +@keyframes col-fade { from { opacity: 0; } } +@keyframes col-pop { from { opacity: 0; transform: scale(0.92); } } + +/* ── 平板以下:索引貼移到卡冊上面 ── */ +@media (max-width: 720px) { + .col-wrap { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); } + .col-hud-wide { display: none; } + .col-tabs { grid-column: 1; grid-row: 1; flex-direction: row; gap: 4px; padding: 0 8px; margin-bottom: -3px; } + .col-tab { + flex: 1 1 0; min-width: 0; width: auto; min-height: 52px; margin: 0; padding: 5px 4px 7px; + grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto auto; justify-items: center; row-gap: 1px; text-align: center; + border: 3px solid var(--ink); border-bottom: 0; border-radius: 12px 12px 0 0; box-shadow: none; transform: translateY(5px); + } + .col-tab-ic { display: none; } + .col-tab b { font-size: 14px; white-space: nowrap; } + .col-tab small { font-size: 14px; } + .col-tab-bar { width: 78%; height: 4px; margin-top: 2px; } + .col-book { grid-column: 1; grid-row: 2; padding: 5px; border-radius: 14px; } + .col-book::before { inset: 1px; border-radius: 11px; } + .col-sheet { padding: 6px 6px 6px; gap: 6px; border-radius: 10px; } + /* 分類名稱和數字索引貼上已經有了,這一列只留跳頁、戰績 */ + .col-head { grid-template-columns: minmax(0, 1fr); } + .col-title { display: none; } + .col-records, .col-hint { justify-self: start; justify-items: start; text-align: left; padding-left: 4px; } + .col-hint { font-size: 13px; } + .col-records b { font-size: 13px; } + .col-records small { font-size: 11px; } + .col-cap { font-size: 10px; line-height: 1.25; gap: 2px; } + .col-btn { min-width: 64px; padding: 0 10px; } + .col-foot .col-btn span { display: none; } + .col-pager { gap: 8px; font-size: 14px; } + .col-dots { gap: 4px; } + .col-dots i { width: 9px; height: 9px; } + + .col-modal { grid-template-columns: minmax(0, 1fr); justify-items: stretch; gap: 14px; padding: 18px 16px 16px; border-radius: 18px; } + .col-big .col-face { --col-face-w: 150px; } + .col-stamp { font-size: 17px; right: -18px; } + .col-info { gap: 8px; } + .col-info h2 { font-size: 24px; } + .col-desc { font-size: 15px; line-height: 1.55; } + .col-how p { font-size: 15px; } +} + +@media (prefers-reduced-motion: reduce) { + .col-page.is-in-next, .col-page.is-in-prev, .col-page.is-in-tab { animation: col-fade 160ms ease both; animation-delay: 0ms; } + .col-modal, .col-big .col-face { animation: col-fade 160ms ease both; } + .col-tab, .col-face, .col-drag, .col-btn, .col-chip { transition: none; } + .col-pocket:active .col-face { transform: none; } +} diff --git a/web/src/game/rogue/finale.tsx b/web/src/game/rogue/finale.tsx new file mode 100644 index 0000000..bc743f3 --- /dev/null +++ b/web/src/game/rogue/finale.tsx @@ -0,0 +1,762 @@ +import type { RogueResult, RogueView } from "@election2026/protocol"; +import { ArrowRight, Coins, Flame, Home, Landmark, RotateCcw, Share2, SkipForward, Swords, Trophy } from "lucide-react"; +import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { rogueApi } from "../api.ts"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { BallotStamp } from "../art/BallotStamp.tsx"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { num, pct, raceLabel, signed } from "./labels.ts"; +import { pointsForRun } from "../island/data.ts"; +import { addPoints } from "../island/store.ts"; +import { coinsForRun, earnCoins } from "../shop/wardrobe.ts"; +import { recordRun, todayKey, type RunRecord } from "./progress.ts"; +import "./rogue-finale.css"; + +/** + * 選戰卡牌的最後一幕(docs/22):開票夜一區一區開出來,然後是結果、成就、分享圖卡。 + * view.phase === "finished" 時由 RogueScreen 蓋在地圖上面。 + */ + +export const GRADE_TEXT: Record = { S: "壓倒性勝利", A: "穩穩當選", B: "險勝凍蒜", C: "飲恨落選", D: "大敗" }; + +type TownResult = RogueResult["byTown"][number]; +const townTotal = (t: Pick) => t.you + t.rival + t.others; + +/** 同一局只記一次(重新整理、React 開發模式重跑都不會重複算) */ +const records = new Map(); +function recordOnce(view: RogueView): RunRecord { + const hit = records.get(view.runId); + if (hit) return hit; + const r = recordRun(view); + records.set(view.runId, r); + return r; +} + +/** 選完拿政績點(政策島蓋建築用);同一局只算一次,教學不算 */ +function islandOnce(view: RogueView, record: RunRecord): { points: number; reason: string } | null { + if (!view.result || view.options.tutorial) return null; + const earned = pointsForRun({ won: view.result.won, grade: view.result.grade, newFeats: record.newFeats.length }); + return addPoints(earned.points, earned.reason, view.runId) ? earned : null; +} + +/** 選完發小鎮幣(服裝店買外觀用,docs/24);同一局只發一次,教學不發 */ +function coinsOnce(view: RogueView, record: RunRecord): { coins: number; reason: string } | null { + if (!view.result || view.options.tutorial) return null; + const earned = coinsForRun({ won: view.result.won, grade: view.result.grade, newFeats: record.newFeats.length, daily: Boolean(view.options.daily), career: Boolean(view.options.career) }); + return earnCoins(earned.coins, earned.reason, view.runId) ? earned : null; +} + +let featNames: Promise> | null = null; +function loadFeatNames() { + featNames ??= rogueApi + .catalog() + .then((c) => new Map(c.feats.map((f) => [f.id, { name: f.name, text: f.text }]))) + .catch(() => { + featNames = null; + return new Map(); + }); + return featNames; +} + +function useReducedMotion(): boolean { + const [reduce, setReduce] = useState(() => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches); + useEffect(() => { + if (typeof matchMedia !== "function") return; + const m = matchMedia("(prefers-reduced-motion: reduce)"); + const on = () => setReduce(m.matches); + m.addEventListener("change", on); + return () => m.removeEventListener("change", on); + }, []); + return reduce; +} + +/** 數字從目前的值跳到 target(ease-out);減少動態時直接顯示 */ +function useCountUp(target: number, reduce: boolean, ms = 520): number { + const [value, setValue] = useState(target); + const from = useRef(target); + useEffect(() => { + if (reduce) { + from.current = target; + setValue(target); + return; + } + const start = performance.now(); + const begin = from.current; + let frame = 0; + const tick = (now: number) => { + const t = Math.min(1, (now - start) / ms); + const eased = 1 - (1 - t) ** 3; + const v = begin + (target - begin) * eased; + from.current = v; + setValue(v); + if (t < 1) frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame); + }, [target, reduce, ms]); + return value; +} + +/** + * 開票的節奏:像電視開票,各區同時一點一點開,不是一次開完一區。 + * 每一區有自己的開始、開完時間(小區通常先開完);早開出來的票會稍微偏向某一邊,越開越接近最後結果。 + * 一共 TICKS 格,最後幾格放慢;全部用這一局的 runId 當種子,重看一次節奏一樣。 + */ +const TICKS = 30; +const tickDelay = (t: number): number => (t === 0 ? 900 : t >= TICKS - 2 ? 1100 : t >= TICKS - 5 ? 700 : 380); + +interface TownCount { + you: number; + rival: number; + others: number; + /** 這一區開了幾成(0–1) */ + f: number; +} + +function seeded(text: string): () => number { + let a = 2166136261; + for (let i = 0; i < text.length; i++) a = Math.imul(a ^ text.charCodeAt(i), 16777619); + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), a | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** 每一區的開票曲線:開始、開完(0–1 的時間),早開票的偏向 */ +function countPlan(runId: string, byTown: readonly TownResult[]) { + const rand = seeded(runId); + const biggest = Math.max(1, ...byTown.map(townTotal)); + const plans = byTown.map((t) => { + const size = townTotal(t) / biggest; + const start = rand() * 0.25; + // 大區開得久;最慢的那一區剛好在最後一格開完 + const end = Math.min(1, 0.45 + 0.35 * size + rand() * 0.2); + return { code: t.code, start, end, swing: (rand() - 0.5) * 0.08 }; + }); + const last = plans.reduce((a, p) => (p.end > a.end ? p : a), plans[0]!); + if (last) last.end = 1; + return plans; +} + +const smooth = (x: number) => x * x * (3 - 2 * x); + +/** 第 tick 格時各區開出來的票 */ +function countsAt(tick: number, plans: ReturnType, byTown: readonly TownResult[]): Map { + const time = tick / TICKS; + return new Map( + byTown.map((t, i) => { + const p = plans[i]!; + const f = time >= p.end ? 1 : time <= p.start ? 0 : smooth((time - p.start) / (p.end - p.start)); + const total = townTotal(t) || 1; + if (f >= 1) return [t.code, { you: t.you, rival: t.rival, others: t.others, f: 1 }]; + // 早開出來的票偏向某一邊,越開越接近最後結果 + const lean = p.swing * (1 - f); + const youShare = Math.min(1, Math.max(0, t.you / total + lean)); + const rivalShare = Math.min(1 - youShare, Math.max(0, t.rival / total - lean)); + const counted = total * f; + return [t.code, { you: counted * youShare, rival: counted * rivalShare, others: Math.max(0, counted * (1 - youShare - rivalShare)), f }]; + }), + ); +} + +/** 開票夜的地圖:各區開了幾成、目前誰領先;latest 是剛開完的那一區 */ +export type VoteMap = (counts: ReadonlyMap, latest: string | null) => ReactNode; + +export function Finale({ view, onAgain, onHome, map }: { view: RogueView; onAgain: (ascension?: number) => void; onHome: () => void; map?: VoteMap }) { + const [stage, setStage] = useState<"count" | "result">("count"); + const [record] = useState(() => recordOnce(view)); + const [island] = useState(() => islandOnce(view, record)); + const [coins] = useState(() => coinsOnce(view, record)); + if (!view.result) return null; + return stage === "count" ? setStage("result")} /> : ; +} + +/** 開票夜:各區一點一點開,地圖跟著上色,兩邊的票數往上跳 */ +function VoteNight({ view, onDone, map }: { view: RogueView; onDone: () => void; map?: VoteMap }) { + const r = view.result!; + const reduce = useReducedMotion(); + const names = useMemo(() => new Map(view.towns.map((t) => [t.code, t.name])), [view.towns]); + const plans = useMemo(() => countPlan(view.runId, r.byTown), [view.runId, r.byTown]); + const [tick, setTick] = useState(0); + const [flash, setFlash] = useState(0); + const [final, setFinal] = useState(false); + const started = useRef(false); + const leader = useRef<"you" | "rival" | null>(null); + const doneBefore = useRef(new Set()); + + useEffect(() => { + if (started.current) return; + started.current = true; + setMusic("election-night-tension"); + sfx.drumroll(); + }, []); + + useEffect(() => { + if (tick >= TICKS) return; + const t = setTimeout(() => setTick((x) => x + 1), tickDelay(tick)); + return () => clearTimeout(t); + }, [tick]); + + const counts = useMemo(() => countsAt(tick, plans, r.byTown), [tick, plans, r.byTown]); + const counted = useMemo(() => [...counts.values()].reduce((a, t) => ({ you: a.you + t.you, rival: a.rival + t.rival, others: a.others + t.others }), { you: 0, rival: 0, others: 0 }), [counts]); + const totalBallots = useMemo(() => r.byTown.reduce((a, t) => a + townTotal(t), 0) || 1, [r.byTown]); + const finished = [...counts.values()].filter((c) => c.f >= 1).length; + const progress = (counted.you + counted.rival + counted.others) / totalBallots; + // 這一格剛開完的區(地圖上冒出差距) + const latest = useMemo(() => { + const fresh = r.byTown.filter((t) => counts.get(t.code)!.f >= 1 && !doneBefore.current.has(t.code)).map((t) => t.code); + for (const c of fresh) doneBefore.current.add(c); + return fresh.at(-1) ?? null; + }, [counts, r.byTown]); + + // 換人領先:閃一下、警示音(開票三成以後才算,剛開始票數少、來回換很正常);每格翻一下選票的聲音 + useEffect(() => { + if (tick === 0) return; + const now = counted.you > counted.rival ? "you" : counted.rival > counted.you ? "rival" : null; + if (tick < TICKS) { + if (latest) sfx.stamp(); + else if (tick % 3 === 0) sfx.paper(); + if (progress >= 0.3 && leader.current && now && now !== leader.current) { + sfx.alert(); + setFlash((f) => f + 1); + } + } + if (now) leader.current = now; + }, [tick]); // eslint-disable-line react-hooks/exhaustive-deps + + // 全部開完:蓋章、鞭炮(落選是一聲嘆息) + useEffect(() => { + if (tick < TICKS) return; + const t = setTimeout(() => { + setFinal(true); + if (r.won) { + sfx.stamp(); + sfx.firecracker(); + sfx.applause(); + setMusic("party-disco-loop"); + } else sfx.ooh(); + }, 600); + return () => clearTimeout(t); + }, [tick, r.won]); + + const ms = Math.min(600, tickDelay(tick)); + const you = useCountUp(counted.you, reduce, ms); + const rival = useCountUp(counted.rival, reduce, ms); + const others = useCountUp(counted.others, reduce, ms); + // 百分比跟著畫面上的票數算,票數還是 0 的時候不會先跑出百分比 + const cast = you + rival + others; + const share = (x: number) => (cast > 0 ? x / cast : 0); + const lead = you - rival; + const rows = useMemo(() => [...r.byTown].sort((a, b) => townTotal(b) - townTotal(a)), [r.byTown]); + const mapNode = map?.(counts, latest); + + return ( +
    +
    + {flash > 0 && } + {mapNode && ( +
    + {mapNode} +
    + )} +
    + LIVE +

    開票夜・{raceLabel(view)}

    + + 開票 {Math.round(progress * 100)}% + + 開完 {finished} / {rows.length} 區 + + +
    +
    + 0 && cast > 0} won={final && r.won} /> + VS + 0} won={final && !r.won && r.rival > r.others} /> +
    +
    + + + +
    +
      + {rows.map((t) => { + const c = counts.get(t.code)!; + const total = c.you + c.rival + c.others; + return ( +
    1. = 1 ? "is-done" : c.f > 0 ? "is-counting" : "is-waiting"}${t.code === latest && !final ? " is-new" : ""}`}> + {names.get(t.code) ?? t.code} + + {total > 0 && ( + <> + + + + + )} + + {c.f >= 1 ? "開完" : `${Math.round(c.f * 100)}%`} + = c.rival ? "is-up" : "is-down"}>{total > 0 ? signed(c.you - c.rival) : "—"} +
    2. + ); + })} +
    + {final ? ( +
    + + + + {r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`} + +
    + ) : ( + + )} +
    +
    + ); +} + +function Side({ name, candidate, color, votes, share, leading, won }: { name: string; candidate: RogueView["you"]; color: string; votes: number; share: number; leading: boolean; won: boolean }) { + return ( +
    + + {name} + {num(votes)} + {pct(share)} + {leading && 領先} +
    + ); +} + +/** 結果:評價、得票率、走勢、各區、成就、分享 */ +/** 挑戰連結的內容:劇本、候選人、種子、逆風、勢均力敵,以及這次的得票率(給朋友比) */ +export function challengeLink(view: RogueView): string { + const data = { s: view.scenarioId, c: view.you.id, seed: view.seed, a: view.options.ascension, e: view.options.even, share: Math.round((view.result?.youShare ?? 0) * 10000) / 10000, n: view.you.name }; + const bytes = new TextEncoder().encode(JSON.stringify(data)); + const code = btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + return `${location.origin}${location.pathname}#/rogue?challenge=${code}`; +} + +function ResultPanel({ + view, + record, + island, + coins, + onAgain, + onHome, +}: { + view: RogueView; + record: RunRecord; + island: { points: number; reason: string } | null; + coins: { coins: number; reason: string } | null; + onAgain: (ascension?: number) => void; + onHome: () => void; +}) { + const r = view.result!; + const [feats, setFeats] = useState>(new Map()); + const [sharing, setSharing] = useState(null); + const tutorial = view.options.tutorial; + const names = useMemo(() => new Map(view.towns.map((t) => [t.code, t.name])), [view.towns]); + + useEffect(() => { + let alive = true; + void loadFeatNames().then((m) => alive && setFeats(m)); + if (record.newFeats.length > 0) sfx.good(); + return () => { + alive = false; + }; + }, [record.newFeats.length]); + + /** 朋友挑戰連結:同一場選舉、同一個種子、同樣的逆風等級(同一個區網或上線後才連得到) */ + const copyChallenge = async () => { + const link = challengeLink(view); + try { + await navigator.clipboard.writeText(link); + setSharing("已複製挑戰連結,貼給朋友:同一個開局、同樣的牌序,看誰選得比較好"); + } catch { + setSharing(`挑戰連結:${link}`); + } + }; + + const share = async () => { + setSharing("圖卡產生中…"); + try { + const blob = await drawShareCard(view); + const file = new File([blob], "election-town-result.png", { type: "image/png" }); + const nav = navigator as Navigator & { canShare?: (data: ShareData) => boolean }; + if (nav.share && nav.canShare?.({ files: [file] })) { + try { + await nav.share({ files: [file], title: `${raceLabel(view)}選戰結果` }); + setSharing(null); + return; + } catch (e) { + if (e instanceof DOMException && e.name === "AbortError") { + setSharing(null); + return; + } + } + } + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "election-town-result.png"; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 4000); + setSharing("圖卡已下載"); + } catch { + setSharing("圖卡產生失敗,請再試一次"); + } + }; + + return ( +
    +
    + {tutorial ? ( +
    + +

    教學完成!

    +

    你已經會看對手意圖、疊組合拳、打對台了。開始你的第一場選戰吧。

    +
    + ) : ( +
    + + {r.grade} + {GRADE_TEXT[r.grade]} +
    + )} +

    {r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}

    +

    + {raceLabel(view)} + {view.options.ascension > 0 && 逆風 {view.options.ascension} 級} + {view.options.daily && 每日一戰 {view.options.daily} 完成} + {record.record && !tutorial && {r.won ? "新紀錄" : "個人最佳"}} +

    + {record.unlocked !== null && ( +

    + 解鎖逆風 {record.unlocked} 級! +

    + )} + {island && ( +

    + 政績點 +{island.points}({island.reason}) + 去政策島蓋建築 +

    + )} + {coins && ( +

    + 小鎮幣 +{coins.coins}({coins.reason}) + 去服裝店 +

    + )} +
    + + + {pct(r.youShare, 2)} + {num(r.you)} 票 + + vs + + + {pct(r.rivalShare, 2)} + {num(r.rival)} 票 + +
    + + {r.feats.length > 0 && ( +
    +

    這局拿到的成就

    +
      + {r.feats.map((id, i) => { + const f = feats.get(id); + const fresh = record.newFeats.includes(id); + return ( +
    • + + + {f?.name ?? id} + {f && {f.text}} + + {fresh && NEW} +
    • + ); + })} +
    +
    + )} +
    + 各區開票 +
      + {[...r.byTown] + .sort((a, b) => townTotal(b) - townTotal(a)) + .map((t) => { + const total = townTotal(t) || 1; + return ( +
    • + {names.get(t.code) ?? t.code} + + + + + + = t.rival ? "is-up" : "is-down"}>{signed(t.you - t.rival)} +
    • + ); + })} +
    +
    +
    + {tutorial ? ( + + ) : ( + <> + {view.options.career ? ( + + ) : ( + + )} + {record.unlocked !== null && !view.options.career && ( + + )} + {!view.options.career && ( + + )} + + + )} + +
    + {sharing && ( +

    + {sharing} +

    + )} +
    +
    + ); +} + +/** 每週結束時的支持度走勢(已表態的票裡的比例) */ +function Trend({ view }: { view: RogueView }) { + const h = view.history; + if (h.length < 2) return null; + const W = 320; + const H = 120; + const values = h.flatMap((x) => [x.you, x.rival]); + const lo = Math.min(...values) - 0.01; + const hi = Math.max(...values) + 0.01; + const x = (i: number) => 26 + (i / (h.length - 1)) * (W - 44); + const y = (v: number) => 10 + (1 - (v - lo) / (hi - lo || 1)) * (H - 32); + const line = (key: "you" | "rival") => h.map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(p[key]).toFixed(1)}`).join(" "); + const last = h[h.length - 1]!; + return ( +
    + + + + {h.map((p, i) => ( + + + + + {p.week === 0 ? "開局" : p.week} + + + ))} + +
    + ● {view.you.name} ● {view.rival.name} 每週結束時的支持度 +
    +
    + ); +} + +/** var(--slot-a) 這種寫法換成實際顏色(canvas 不認得 CSS 變數) */ +function resolveColor(value: string, fallback: string): string { + const m = /^var\((--[\w-]+)\)$/.exec(value.trim()); + if (!m) return value || fallback; + const v = getComputedStyle(document.documentElement).getPropertyValue(m[1]!).trim(); + return v || fallback; +} + +const cssVar = (name: string, fallback: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback; + +/** 1080×1350 的結果圖卡(PNG):不用外部圖片、不畫真人照片,右下角標「選舉小鎮・選戰遊戲」 */ +async function drawShareCard(view: RogueView): Promise { + const r = view.result!; + const W = 1080; + const H = 1350; + const canvas = document.createElement("canvas"); + canvas.width = W; + canvas.height = H; + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("瀏覽器不支援 canvas"); + const serif = cssVar("--font-serif", '"Noto Sans TC", sans-serif'); + const numFont = cssVar("--font-num", '"Noto Sans TC", sans-serif'); + try { + await Promise.all([document.fonts.load(`900 64px ${serif}`, `${raceLabel(view)}選戰凍蒜落選`), document.fonts.load(`800 64px ${numFont}`, "0123456789.%")]); + } catch { + // 字型載不到就用系統字 + } + const ink = "#111419"; + const paper = "#ecebe6"; + const stamp = "#d61f2c"; + const signal = "#ffd23f"; + const muted = "#5d646e"; + const youColor = resolveColor(view.colors.you, "#d6457a"); + const rivalColor = resolveColor(view.colors.rival, "#6b4fbb"); + const otherColor = resolveColor("var(--slot-other)", "#858a8f"); + const font = (weight: number, size: number, family = serif) => `${weight} ${size}px ${family}`; + + // 底與頂部紅色看板 + ctx.fillStyle = paper; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = stamp; + ctx.fillRect(0, 0, W, 250); + ctx.fillStyle = ink; + ctx.fillRect(0, 250, W, 10); + ctx.fillStyle = signal; + ctx.font = font(800, 34); + ctx.textBaseline = "alphabetic"; + ctx.fillText("選舉小鎮・選戰卡牌", 64, 86); + ctx.fillStyle = "#ffffff"; + ctx.font = font(900, 84); + fitText(ctx, `${raceLabel(view)}選戰`, 64, 190, W - 128); + + // 雙方 + const sides = [ + { c: view.you, color: youColor, share: r.youShare, votes: r.you, x: 64 }, + { c: view.rival, color: rivalColor, share: r.rivalShare, votes: r.rival, x: W / 2 + 24 }, + ]; + for (const s of sides) { + const cx = s.x + 52; + const cy = 350; + ctx.beginPath(); + ctx.arc(cx, cy, 46, 0, Math.PI * 2); + ctx.fillStyle = s.color; + ctx.fill(); + ctx.lineWidth = 6; + ctx.strokeStyle = ink; + ctx.stroke(); + ctx.fillStyle = "#ffffff"; + ctx.font = font(800, 52, numFont); + ctx.textAlign = "center"; + ctx.fillText(String(s.c.number), cx, cy + 18); + ctx.textAlign = "left"; + ctx.fillStyle = ink; + ctx.font = font(900, 50); + fitText(ctx, s.c.name, s.x + 116, cy + 18, W / 2 - 160); + ctx.fillStyle = s.color; + ctx.font = font(800, 128, numFont); + ctx.fillText(pct(s.share, 2), s.x, 530); + ctx.fillStyle = muted; + ctx.font = font(700, 32); + ctx.fillText(`${num(s.votes)} 票`, s.x + 4, 580); + } + + // 評價 + ctx.fillStyle = r.won ? stamp : muted; + roundRect(ctx, 64, 620, W - 128, 120, 22); + ctx.fill(); + ctx.fillStyle = "#ffffff"; + ctx.font = font(800, 96, numFont); + ctx.fillText(r.grade, 100, 715); + ctx.font = font(900, 54); + fitText(ctx, `${r.won ? `${view.you.name}凍蒜!` : `${view.you.name}落選`}・${GRADE_TEXT[r.grade]}`, 190, 702, W - 300); + + // 各區小長條(最多 13 區,人多的先) + const names = new Map(view.towns.map((t) => [t.code, t.name])); + const towns = [...r.byTown].sort((a, b) => townTotal(b) - townTotal(a)).slice(0, 13); + const top = 790; + const rowH = Math.min(30, Math.floor(330 / Math.max(1, towns.length))); + towns.forEach((t, i) => { + const y = top + i * rowH; + const total = townTotal(t) || 1; + ctx.fillStyle = ink; + ctx.font = font(700, Math.min(24, rowH - 6)); + fitText(ctx, names.get(t.code) ?? t.code, 64, y + rowH - 8, 170); + let x = 250; + const bw = 640; + const bh = rowH - 10; + for (const [v, color] of [ + [t.you, youColor], + [t.others, otherColor], + [t.rival, rivalColor], + ] as const) { + const w = (v / total) * bw; + ctx.fillStyle = color; + ctx.fillRect(x, y + 4, w, bh); + x += w; + } + ctx.strokeStyle = ink; + ctx.lineWidth = 2; + ctx.strokeRect(250, y + 4, bw, bh); + ctx.fillStyle = t.you >= t.rival ? "#1f8a4c" : stamp; + ctx.font = font(700, Math.min(24, rowH - 6), numFont); + ctx.fillText(signed(t.you - t.rival), 910, y + rowH - 8); + }); + + // 標語、日期、逆風、浮水印 + let y = top + towns.length * rowH + 60; + if (view.you.slogan) { + ctx.fillStyle = ink; + ctx.font = font(900, 44); + fitText(ctx, `「${view.you.slogan}」`, 64, Math.min(y, 1220), W - 128); + y += 60; + } + const meta = [todayKey(), view.options.ascension > 0 ? `逆風 ${view.options.ascension} 級` : "", view.options.daily ? "每日一戰" : ""].filter(Boolean).join("・"); + ctx.fillStyle = muted; + ctx.font = font(700, 28); + ctx.fillText(meta, 64, H - 40); + ctx.textAlign = "right"; + ctx.fillText("選舉小鎮・選戰遊戲", W - 64, H - 40); + ctx.textAlign = "left"; + + return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("圖卡產生失敗"))), "image/png")); +} + +/** 太長的字縮小到放得下 */ +function fitText(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, maxWidth: number): void { + const m = /(\d+(?:\.\d+)?)px/.exec(ctx.font); + let size = m ? Number(m[1]) : 32; + const base = ctx.font; + while (size > 14 && ctx.measureText(text).width > maxWidth) { + size -= 2; + ctx.font = base.replace(/\d+(?:\.\d+)?px/, `${size}px`); + } + ctx.fillText(text, x, y); + ctx.font = base; +} + +function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void { + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.arcTo(x + w, y, x + w, y + h, r); + ctx.arcTo(x + w, y + h, x, y + h, r); + ctx.arcTo(x, y + h, x, y, r); + ctx.arcTo(x, y, x + w, y, r); + ctx.closePath(); +} diff --git a/web/src/game/rogue/flow.tsx b/web/src/game/rogue/flow.tsx new file mode 100644 index 0000000..05b70e4 --- /dev/null +++ b/web/src/game/rogue/flow.tsx @@ -0,0 +1,699 @@ +import "./rogue-flow.css"; +import type { RogueChoice, RogueDeckCard, RogueOffer, RogueScene, RogueStop, RogueView } from "@election2026/protocol"; +import { + ArrowRight, + Check, + ChevronsUp, + Coins, + Dices, + FileText, + Footprints, + Gamepad2, + Handshake, + Heart, + MessageCircle, + Mic, + Scissors, + ShieldAlert, + Signpost, + Star, + Store, + Trophy, + Tv, + UserPlus, + X, + type LucideIcon, +} from "lucide-react"; +import { lazy, Suspense, useEffect, useMemo, useState } from "react"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { sfx } from "../audio/sfx.ts"; +import { CardArt } from "../art/CardArt.tsx"; +import { CardFace, OfferFace, type FaceData } from "./cards.tsx"; +import { num, pct, signed } from "./labels.ts"; + +/** + * 選戰卡牌的劇情與下一站(docs/22、23): + * - SceneOverlay:電視辯論、匿名黑函危機這種大場面(記者堵麥平常是手牌裡的事件牌,民調自動公布;舊存檔還可能停在這兩個畫面) + * - RouteOverlay:進到某一站裡面的選擇(物資行、深入基層、升級、拿掉牌、小遊戲);三扇門本身在 weekend.tsx + * 規則都在伺服器,這裡只負責畫面與按鈕。 + */ + +type Choose = (pick: number | "skip") => void; + +/** 外層:半透明遮罩+面板 */ +function Shell({ label, className, children }: { label: string; className?: string; children: React.ReactNode }) { + return ( +
    +
    {children}
    +
    + ); +} + +/** 劇情、地方抉擇的選項:標題、提示、資源不夠就停用、看運氣的加骰子 */ +export function ChoiceList({ choices, busy, onPick }: { choices: readonly RogueChoice[]; busy: boolean; onPick: (i: number) => void }) { + const first = choices.findIndex((c) => !c.blocked); + return ( +
      + {choices.map((c, i) => ( +
    • + +
    • + ))} +
    + ); +} + +// ───────────────────────── 每週開場的劇情 ───────────────────────── + +export function SceneOverlay({ view, busy, onChoose }: { view: RogueView; busy: boolean; onChoose: Choose }) { + const scene = view.scene; + if (!scene) return null; + switch (scene.kind) { + case "press": + return ; + case "debate": + return ; + case "crisis": + return ; + case "poll": + return ; + } +} + +type SceneOf = Extract; + +function PressScene({ view, scene, busy, onChoose }: { view: RogueView; scene: SceneOf<"press">; busy: boolean; onChoose: Choose }) { + useEffect(() => sfx.alert(), []); + return ( + +
    + LIVE + 記者堵麥 + 第 {view.week} 週 +
    +
    + + + + + + +

    + 記者問: + {scene.question} +

    +
    +

    你怎麼回答?

    + +
    + ); +} + +const MOVE_ICONS: Record = { policy: FileText, emotion: Heart, question: MessageCircle }; +const RESULT_LABELS = { win: "說服觀眾", lose: "答非所問", tie: "普通" } as const; +const COMBO_MULT = ["", "×1", "×1.5", "×2"]; + +/** 論點連擊辯論:對手丟出質疑,你從手上的論點挑一張回應;連續答對有連擊 */ +function DebateScene({ view, scene, busy, onChoose }: { view: RogueView; scene: SceneOf<"debate">; busy: boolean; onChoose: Choose }) { + const done = scene.round >= scene.rounds; + const last = scene.history.at(-1); + // 每打完一回合放一次音效;連擊音越來越高;三連擊全勝放掌聲 + useEffect(() => { + if (!last) { + sfx.gong(); + return; + } + if (last.result === "win") sfx.combo(last.combo - 1); + else if (last.result === "lose") sfx.bad(); + else sfx.click(); + if (done && scene.wins === scene.rounds) sfx.applause(); + }, [scene.history.length]); // eslint-disable-line react-hooks/exhaustive-deps + const verdict = scene.wins === scene.rounds ? "三連擊全勝!" : scene.wins > scene.losses ? "辯論佔上風" : scene.wins === scene.losses ? "平分秋色" : "辯論失利"; + return ( + +
    + + 電視辯論 + 第 {view.week} 週 +
    +
    + + + {view.you.name} + + + {scene.wins} + : + {scene.losses} + {scene.combo > 1 && ( + + {scene.combo} 連擊 + + )} + + + + {view.rival.name} + +
    + {!done ? ( + <> +
    +

    + 第 {scene.round + 1} / {scene.rounds} 回合:{scene.topic} +

    +

    + + {scene.challenge} +

    +
    +

    + 挑一張論點回應(用掉就沒了)。連續答對:第 2 回合 ×1.5、第 3 回合 ×2。 + {scene.sure && 標「最好」的是教練建議。} +

    +
      + {scene.moves.map((m) => { + const Icon = MOVE_ICONS[m.id] ?? FileText; + return ( +
    • + + {m.label} + {m.counters}最好 +
    • + ); + })} +
    +
    + {scene.hand.map((a, i) => { + const Icon = MOVE_ICONS[a.kind] ?? FileText; + return ( + + ); + })} +
    + + ) : ( +
    + {scene.wins === scene.rounds && } + {verdict} + {scene.wins === scene.rounds && 手上多了一張「辯論金句」} +
    + )} + {scene.history.length > 0 && ( +
      + {scene.history.map((h, i) => ( +
    1. + + {i + 1}. {h.topic}:{h.text} + + {h.votes ? `${signed(h.votes)} 票` : ""} + + {RESULT_LABELS[h.result]} + {h.result === "win" && h.combo > 1 ? ` ${COMBO_MULT[Math.min(3, h.combo)]}` : ""} + +
    2. + ))} +
    + )} + {done && ( + + )} +
    + ); +} + +function CrisisScene({ scene, busy, onChoose }: { scene: SceneOf<"crisis">; busy: boolean; onChoose: Choose }) { + useEffect(() => sfx.alert(), []); + return ( + +
    + +
    + 匿名黑函危機 +
    +
    +

    + 網路上流傳一份匿名黑函,內容沒有根據、來源不明。不處理的話,預估會掉 {num(scene.amount)} 票。 +

    +

    四種處理方式,各有代價:

    + +
    + ); +} + +function PollScene({ view, scene, busy, onChoose }: { view: RogueView; scene: SceneOf<"poll">; busy: boolean; onChoose: Choose }) { + useEffect(() => (scene.lead ? sfx.good() : sfx.bad()), [scene.lead]); + const top = Math.max(scene.you, scene.rival, 0.01); + return ( + +
    + 民調 + 第 {view.week} 週民調公布 + 誤差 ±1 個百分點 +
    +
    + {[ + { c: view.you, v: scene.you, color: view.colors.you }, + { c: view.rival, v: scene.rival, color: view.colors.rival }, + ].map((row) => ( +
    + + {row.c.name} + + + + {pct(row.v)} +
    + ))} +
    +

    + {scene.lead ? "你領先!西瓜效應:聲勢 +1" : "你落後,支持者危機意識上升:手上多一張「悲情催票」"} +

    + +
    + ); +} + +// ───────────────────────── 下一站 ───────────────────────── + +export const STOP_STYLE: Record = { + card: { Icon: Handshake, color: "#e8833a" }, + advisor: { Icon: UserPlus, color: "#7a5cc4" }, + upgrade: { Icon: ChevronsUp, color: "#c99400" }, + remove: { Icon: Scissors, color: "#2f7f8f" }, + shop: { Icon: Store, color: "#d6457a" }, + encounter: { Icon: Footprints, color: "#a3670f" }, + event: { Icon: Signpost, color: "var(--stamp)" }, + minigame: { Icon: Gamepad2, color: "#1f8a4c" }, +}; + +type ChooseWithTarget = (pick: number | "skip", target?: string | null) => void; + +const MinigameStop = lazy(() => import("./MinigameStop.tsx").then((m) => ({ default: m.MinigameStop }))); + +export function RouteOverlay({ view, busy, onChoose }: { view: RogueView; busy: boolean; onChoose: ChooseWithTarget }) { + if (view.phase === "route" && view.route) return ; + if (view.phase !== "stop" || !view.stop) return null; + const stop = view.stop; + switch (stop.kind) { + case "card": + case "advisor": + return ; + case "upgrade": + return ; + case "remove": + return ; + case "shop": + return ; + case "encounter": + return ; + case "event": + return ; + case "minigame": + return ( + 小遊戲讀取中…}> + + + ); + } +} + +function RouteChooser({ view, busy, onChoose }: { view: RogueView; busy: boolean; onChoose: ChooseWithTarget }) { + useEffect(() => sfx.shuffle(), []); + return ( + +

    第 {view.week} 週結束:下一站去哪裡?

    +

    只能去一站。牌組越來越強,下一週就更好打。

    +
    + {view.route!.map((r, i) => { + const { Icon, color } = STOP_STYLE[r.kind]; + return ( + + ); + })} +
    + +
    + ); +} + +function OfferStop({ view, stop, busy, onChoose }: { view: RogueView; stop: Extract; busy: boolean; onChoose: ChooseWithTarget }) { + useEffect(() => sfx.shuffle(), []); + const card = stop.kind === "card"; + return ( + + +

    {card ? "新牌會放在抽牌堆最上面,下週一定抽到。" : `幕僚是被動能力,整局有效;最多 ${view.advisorSlots} 位,現在有 ${view.advisors.length} 位。`}

    +
    + {stop.options.map((o, i) => ( + + ))} +
    + +
    + ); +} + +function StopHead({ kind, title }: { kind: RogueStop["kind"]; title: string }) { + const { Icon, color } = STOP_STYLE[kind]; + return ( +

    + + + + {title} +

    + ); +} + +/** 牌組裡的牌轉成牌面 */ +const deckFace = (c: RogueDeckCard): FaceData => ({ name: c.name, art: c.art, cost: c.cost, money: c.money, rarity: c.rarity, value: c.value, text: c.text, tags: c.tags, keywords: c.keywords, up: c.up }); +const plusFace = (c: RogueDeckCard): FaceData => ({ ...deckFace(c), name: c.plus!.name, cost: c.plus!.cost, value: c.plus!.value, text: c.plus!.text, up: true }); + +/** 一樣的牌疊在一起顯示(×3),選的時候拿第一張 */ +function groupDeck(cards: readonly RogueDeckCard[]): { card: RogueDeckCard; count: number }[] { + const groups = new Map(); + for (const c of cards) { + const key = `${c.id}|${c.up ? 1 : 0}`; + const g = groups.get(key); + if (g) g.count += 1; + else groups.set(key, { card: c, count: 1 }); + } + return [...groups.values()]; +} + +/** 從牌組挑一張:升級(看前後對照)或拿掉 */ +function DeckPicker({ cards, mode, busy, confirmLabel, onConfirm }: { cards: readonly RogueDeckCard[]; mode: "upgrade" | "remove"; busy: boolean; confirmLabel: string; onConfirm: (uid: string) => void }) { + const groups = useMemo(() => groupDeck(cards), [cards]); + const [picked, setPicked] = useState(null); + const card = cards.find((c) => c.uid === picked) ?? null; + if (groups.length === 0) return

    {mode === "upgrade" ? "牌組裡沒有可以升級的牌。" : "牌組是空的。"}

    ; + return ( +
    +
    + {groups.map(({ card: c, count }) => ( + + ))} +
    + {card && ( +
    + {mode === "upgrade" && card.plus ? ( +
    + + + +
    + ) : ( +

    + 拿掉「{card.name}」?這局不會再抽到這張牌。 +

    + )} +
    + + +
    +
    + )} +
    + ); +} + +function DeckStop({ view, mode, busy, onChoose }: { view: RogueView; mode: "upgrade" | "remove"; busy: boolean; onChoose: ChooseWithTarget }) { + const cards = mode === "upgrade" ? view.deck.filter((c) => c.plus !== null) : view.deck; + return ( + + +

    {mode === "upgrade" ? "升級後名字加+,效果約多三成,有些牌還會少花體力。" : "牌組越精簡,好牌越常抽到。「人情包袱」只能在這裡拿掉。"}

    + { + if (mode === "upgrade") sfx.good(); + else sfx.click(); + onChoose(0, uid); + }} + /> + +
    + ); +} + +function ShopStop({ view, stop, busy, onChoose }: { view: RogueView; stop: Extract; busy: boolean; onChoose: ChooseWithTarget }) { + const [removing, setRemoving] = useState(null); + // 伺服器回來之後(買完刪牌),回到商品列表 + useEffect(() => setRemoving(null), [stop]); + const buy = (i: number, item: RogueOffer) => { + if (item.kind === "remove") { + sfx.flip(); + setRemoving(i); + return; + } + sfx.coin(); + onChoose(i); + }; + return ( + + +

    + 資金 {num(view.money)} 萬 + 可以買好幾樣,買完按「離開」 +

    + {removing === null ? ( +
    + {stop.items.map((item, i) => { + const short = item.price !== null && item.price > view.money; + return ( + + ); + })} +
    + ) : ( + <> +

    刪牌服務({num(stop.items[removing]?.price ?? 0)} 萬):選一張要拿掉的牌。

    + { + sfx.coin(); + onChoose(removing, uid); + }} + /> + + + )} + +
    + ); +} + +/** 應對分數換成星星(和舊玩法的拜票副本一樣) */ +const starsOf = (score: number): number => (score >= 4 ? 3 : score >= 1 ? 2 : score >= -1 ? 1 : 0); + +function EncounterStop({ stop, busy, onChoose }: { stop: Extract; busy: boolean; onChoose: ChooseWithTarget }) { + const done = stop.current === null; + const stars = starsOf(stop.score); + useEffect(() => { + if (!done) return; + if (stars >= 2) sfx.applause(); + else if (stars === 0) sfx.bad(); + }, [done, stars]); + return ( + + +
      + {Array.from({ length: stop.total }, (_, i) => ( +
    1. + ))} +
    + {stop.current ? ( +
    +

    + 第 {stop.step + 1} / {stop.total} 個人:{stop.current.who} +

    +

    {stop.current.line}

    +
      + {stop.current.options.map((o, i) => ( +
    • + +
    • + ))} +
    +
    + ) : ( +
    + + {Array.from({ length: 3 }, (_, i) => ( + + ))} + + {stars >= 3 ? "鄉親口耳相傳!" : stars === 2 ? "這趟跑得不錯" : stars === 1 ? "普普通通" : "這趟有點糟"} + + 應對分數 {stop.score >= 0 ? "+" : ""} + {stop.score};{stop.townName}的加票已經算進去了 + +
    + )} + {stop.notes.length > 0 && ( +
      + {stop.notes.map((n, i) => ( +
    1. {n}
    2. + ))} +
    + )} + {done && ( + + )} +
    + ); +} + +function EventStop({ stop, busy, onChoose }: { stop: Extract; busy: boolean; onChoose: ChooseWithTarget }) { + useEffect(() => sfx.paper(), []); + return ( + + +
    + +
    +

    {stop.text}

    + onChoose(i)} /> +
    + ); +} diff --git a/web/src/game/rogue/juice.tsx b/web/src/game/rogue/juice.tsx new file mode 100644 index 0000000..8926991 --- /dev/null +++ b/web/src/game/rogue/juice.tsx @@ -0,0 +1,100 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { getSettings } from "../audio/settings.ts"; +import { sfx } from "../audio/sfx.ts"; +import { signed } from "./labels.ts"; + +/** + * 手感(docs/22,參考 game-feel 的分級回饋):出牌飛到地圖、爆分時加成一個一個跳出來、 + * 被大幅拉票時畫面輕微震動。震動可以在設定關掉;系統設定「減少動態效果」時不震動、不飛牌。 + */ + +const reducedMotion = (): boolean => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; + +/** 畫面震動:small(一般重擊)、large(翻盤、大型造勢) */ +export function useShake(): [string, (level: "small" | "large") => void] { + const [cls, setCls] = useState(""); + const timer = useRef | null>(null); + const shake = useCallback((level: "small" | "large") => { + if (!getSettings().shake || reducedMotion()) return; + if (timer.current) clearTimeout(timer.current); + // 先拿掉再加回去,連續震動也會重播 + setCls(""); + requestAnimationFrame(() => setCls(level === "large" ? "is-shake-l" : "is-shake-s")); + timer.current = setTimeout(() => setCls(""), level === "large" ? 460 : 300); + }, []); + useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); + return [cls, shake]; +} + +/** 出牌:手上那張牌飛向地圖、縮小淡出(只動 transform 和 opacity) */ +export function flyCard(from: Element | null, to: Element | null): void { + if (!from || !to || reducedMotion() || typeof from.animate !== "function") return; + const a = from.getBoundingClientRect(); + const b = to.getBoundingClientRect(); + const ghost = from.cloneNode(true) as HTMLElement; + Object.assign(ghost.style, { position: "fixed", left: `${a.left}px`, top: `${a.top}px`, width: `${a.width}px`, height: `${a.height}px`, margin: "0", zIndex: "60", pointerEvents: "none" }); + document.body.appendChild(ghost); + const dx = b.left + b.width / 2 - (a.left + a.width / 2); + const dy = b.top + b.height / 2 - (a.top + a.height / 2); + const anim = ghost.animate( + [ + { transform: "translate(0, 0) rotate(0deg) scale(1)", opacity: 1 }, + { transform: `translate(${dx * 0.55}px, ${dy * 0.55 - 60}px) rotate(-6deg) scale(0.8)`, opacity: 1, offset: 0.55 }, + { transform: `translate(${dx}px, ${dy}px) rotate(4deg) scale(0.35)`, opacity: 0 }, + ], + { duration: 520, easing: "cubic-bezier(0.23, 1, 0.32, 1)" }, + ); + anim.onfinish = () => ghost.remove(); + anim.oncancel = () => ghost.remove(); +} + +export interface Score { + key: string; + title: string; + /** 加成說明,例如「宮廟多 ×2」「組合拳 +15%」 */ + notes: string[]; + votes: number; + /** 這張牌讓對手少拉的票(打對台、澄清、事實查核) */ + blocked?: number; +} + +/** + * 爆分:牌名 → 加成一個一個跳出來(音越來越高)→ 總票數蹦出來。 + * 像《小丑牌》的計分,但整段不到一秒半,不擋操作。 + */ +export function ScorePop({ score, onDone }: { score: Score; onDone: () => void }) { + const [shown, setShown] = useState(0); + const notes = score.notes.slice(0, 6); + const done = shown > notes.length; + useEffect(() => { + if (reducedMotion()) { + setShown(notes.length + 1); + return; + } + if (done) return; + const t = setTimeout(() => { + if (shown < notes.length) sfx.combo(shown); + setShown(shown + 1); + }, shown === 0 ? 120 : 110); + return () => clearTimeout(t); + }, [shown, done, notes.length]); + useEffect(() => { + if (!done) return; + const t = setTimeout(onDone, 900); + return () => clearTimeout(t); + }, [done, onDone]); + return ( +
    + {score.title} + + {notes.slice(0, shown).map((n, i) => ( + + {n} + + ))} + + {done && {signed(score.votes)} 票} + {done && !!score.blocked && 擋下 {Math.round(score.blocked).toLocaleString("en-US")} 票} +
    + ); +} diff --git a/web/src/game/rogue/labels.ts b/web/src/game/rogue/labels.ts new file mode 100644 index 0000000..9ac4f21 --- /dev/null +++ b/web/src/game/rogue/labels.ts @@ -0,0 +1,51 @@ +import type { RogueIntent, RogueTown, RogueTrait, RogueView } from "@election2026/protocol"; +import { Footprints, Megaphone, MessageSquareWarning, Shield, Smartphone, Tv, UserMinus, type LucideIcon } from "lucide-react"; + +/** 畫面用的名稱與圖示(規則在伺服器,這裡只有字和圖) */ +export const TRAIT_LABELS: Record = { + young: "年輕人多", + old: "長輩多", + temples: "宮廟多", + dense: "人口密集", + rural: "地廣人稀", + hakka: "客家庄", +}; + +export const INTENT_ICONS: Record = { + canvass: Footprints, + rally: Megaphone, + tv: Tv, + online: Smartphone, + attack: MessageSquareWarning, + smear: UserMinus, + stake: Shield, +}; + +/** 可以打對台的對手行動:打在某一區、還沒被打過 */ +export const counterable = (i: RogueIntent): boolean => i.town !== null && i.cut >= 1 && ["canvass", "rally", "smear", "stake"].includes(i.kind); +/** 事實查核可以讓它失效的:對手全市的批評 */ +export const attackable = (i: RogueIntent): boolean => i.kind === "attack" && i.cut > 0; + +/** 票數:+1,940/−1,200 */ +export const signed = (n: number): string => `${n >= 0 ? "+" : "−"}${Math.abs(Math.round(n)).toLocaleString("en-US")}`; +export const num = (n: number): string => Math.round(n).toLocaleString("en-US"); +export const pct = (x: number, d = 1): string => `${(x * 100).toFixed(d)}%`; + +/** 全市:已表態的票裡你和對手各佔多少,還有多少人沒表態 */ +export function overall(towns: readonly RogueTown[]) { + const t = towns.reduce((a, x) => ({ you: a.you + x.you, rival: a.rival + x.rival, others: a.others + x.others, undecided: a.undecided + x.undecided }), { you: 0, rival: 0, others: 0, undecided: 0 }); + const committed = t.you + t.rival + t.others || 1; + const voters = committed + t.undecided || 1; + return { ...t, voters, youShare: t.you / committed, rivalShare: t.rival / committed, undecidedShare: t.undecided / voters }; +} + +/** 這區已表態的票裡你的比例 */ +export const townShare = (t: RogueTown) => { + const committed = t.you + t.rival + t.others || 1; + return { you: t.you / committed, rival: t.rival / committed }; +}; + +/** 這場選舉的名稱:高雄市市長、高雄市第 4 選舉區立委、總統 */ +export const raceLabel = (v: Pick): string => (v.office === "總統" ? "總統" : `${v.area}${v.office === "立法委員" ? "立委" : v.office}`); + +export const weekLabel = (v: Pick): string => (v.week >= v.totalWeeks ? "最後一週" : `第 ${v.week} 週`); diff --git a/web/src/game/rogue/overlays.tsx b/web/src/game/rogue/overlays.tsx new file mode 100644 index 0000000..e79628f --- /dev/null +++ b/web/src/game/rogue/overlays.tsx @@ -0,0 +1,79 @@ +import type { RogueView } from "@election2026/protocol"; +import { X } from "lucide-react"; +import { CardFace } from "./cards.tsx"; + +export function HelpModal({ onClose }: { onClose: () => void }) { + return ( +
    +
    e.stopPropagation()}> + +

    怎麼玩

    +
      +
    1. 看對手要做什麼。對手這週的行動一開始就亮在右上角和地圖上,週末才會執行。
    2. +
    3. 出牌。每週 3 點體力、5 張牌。選一張牌,地圖和右邊的區會顯示「打在這裡會加幾票」,標大拇指的是最划算的三區。
    4. +
    5. 結束這週。對手照計畫行動,你的樁腳會先擋下一部分;結果直接在地圖上跳出來。
    6. +
    7. 拿獎勵。同一個畫面選下一站:拿新牌、找幕僚、地方抉擇直接點;升級、拿掉弱牌、物資行、深入基層、小遊戲點了再進去。
    8. +
    9. 記者堵麥。手牌最左邊的紅色事件牌,這週內回答就好(結束這週前要回答)。
    10. +
    11. 特別的週。第 3 週電視辯論、第 4 週民調自動公布、第 6 週匿名黑函危機、最後一週選前之夜,然後開票。地圖上方的跑馬燈是每週快報,點一下看電視。
    12. +
    +

    讓票數翻倍的方法

    +
      +
    • 地區特色:宮廟多的區打宮廟牌 ×2、長輩多的區打市場牌 ×1.5、客家庄打客家庄拜會 ×2.2。
    • +
    • 組合拳:同一週在同一區打不同的牌,第 2 種 +15%、第 3 種 +30%、第 4 種起 +40%。
    • +
    • 擴散:造勢、宣傳車會擴散到隔壁的區。
    • +
    • 插旗與翻轉:領先 8 個百分點就插旗,每面旗每週 20 萬;把對手的旗翻過來,聲勢 +1。
    • +
    • 打對台、樁腳:讓對手在某區的行動剩四成;拜託里長佈樁擋下對手這週在那區的行動。
    • +
    • 聲勢:每點聲勢讓你的牌 +8%,開票時也會多帶出一些還沒表態的人。每週自然掉 1。
    • +
    • 記者追問:對手批評你沒擋下來,牌組會多一張;花 1 點體力回應就移除,留著過週末會掉票。
    • +
    • 升級:「+」版效果約多三成半,有些少 1 點體力。
    • +
    • 大絕招:落後越多集得越快(落後 1 個百分點每週集 8%),集滿就能放:選前之夜大造勢、掃街馬拉松、看板大作戰三招各接一個小遊戲,分數越高效果越大,落後越多威力越大(最多 ×2.5)。一局基本 1 次;倒數第 3 週還落後超過 8 點,可以再放一次。
    • +
    +

    關鍵字

    +
      +
    • 消耗:這局用一次就沒了。保留:週末留在手上。虛無:週末還在手上就消失。不能打:只會佔手牌。
    • +
    +

    開局各區的人數、年齡、宮廟、客家人口與政黨底盤來自真實資料(內政部、中選會);之後的變化都是牌面上的遊戲數字。

    +
    +
    + ); +} + +const PILES = [ + { id: "hand", label: "手上" }, + { id: "draw", label: "抽牌堆" }, + { id: "discard", label: "棄牌堆" }, +] as const; + +export function DeckDrawer({ view, onClose }: { view: RogueView; onClose: () => void }) { + return ( +
    +
    e.stopPropagation()}> + +

    牌組({view.deck.length} 張)

    +

    + 抽牌堆 {view.drawCount} 張・棄牌堆 {view.discardCount} 張・手上 {view.hand.length} 張{view.exhaustedCount ? `・這局用掉的消耗牌 ${view.exhaustedCount} 張` : ""}。抽完會把棄牌堆洗回來;新拿到的牌放在抽牌堆最上面,下週一定抽到。 +

    + {PILES.map((p) => { + const cards = view.deck.filter((c) => c.pile === p.id); + if (cards.length === 0) return null; + return ( +
    +

    + {p.label}({cards.length}) +

    +
    + {cards.map((c) => ( + + ))} +
    +
    + ); + })} +
    +
    + ); +} diff --git a/web/src/game/rogue/parts.tsx b/web/src/game/rogue/parts.tsx new file mode 100644 index 0000000..db9d987 --- /dev/null +++ b/web/src/game/rogue/parts.tsx @@ -0,0 +1,320 @@ +import type { RogueCard, RogueIntent, RoguePreview, RogueTown, RogueView } from "@election2026/protocol"; +import { AlertTriangle, BookOpen, CircleHelp, Coins, Flag, Layers, Mic, Shield, ThumbsUp, Wind, Zap } from "lucide-react"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { CardArt } from "../art/CardArt.tsx"; +import { AdvisorFace, CardFace } from "./cards.tsx"; +import { INTENT_ICONS, TRAIT_LABELS, attackable, counterable, num, overall, pct, signed, townShare, raceLabel, weekLabel } from "./labels.ts"; + +/** 頂部狀態列:週次與事件、體力、資金、聲勢、把柄、全市支持度、對手性格 */ +export function RogueHud({ view, onDeck, onHelp }: { view: RogueView; onDeck: () => void; onHelp: () => void }) { + const o = overall(view.towns); + const width = (n: number) => `${(n / o.voters) * 100}%`; + const flags = { you: view.towns.filter((t) => t.flag === "you").length, rival: view.towns.filter((t) => t.flag === "rival").length }; + return ( +
    +
    +

    {raceLabel(view)}

    +
      + {Array.from({ length: view.totalWeeks }, (_, i) => ( +
    1. + {i + 1} +
    2. + ))} +
    3. 開票
    4. +
    +

    + + {weekLabel(view)}・{view.event.title} + {view.options.ascension > 0 && ( + + 逆風 {view.options.ascension} + + )} + {view.options.daily && 每日一戰} + + {view.event.text} +

    +
    +
    +
    +
    體力
    +
    + {Array.from({ length: Math.max(view.energyMax, view.energy) }, (_, i) => ( + + ))} +
    +
    +
    +
    資金
    +
    + {num(view.money)} 萬 +
    +
    +
    +
    聲勢
    +
    + + +
    +
    +
    +
    插旗
    +
    + {flags.you} + : + {flags.rival} +
    +
    +
    +
    把柄
    +
    {view.leverage}
    +
    +
    +
    +
    + + {view.you.name} {pct(o.youShare)} + + + {pct(o.rivalShare)} {view.rival.name} + +
    +
    + + + + +
    + + {view.phase === "plan" && view.tally.gained > 0 ? ( + + 本週已拉到 +{num(view.tally.gained)} 票{view.tally.lost > 0 && <>・被拉走 −{num(view.tally.lost)}} + + ) : ( + + 今天開票預估:你 {pct(view.forecast.you)}・對手 {pct(view.forecast.rival)} + = view.forecast.rival ? "is-up" : "is-down"}> + {view.forecast.you >= view.forecast.rival ? "領先" : "落後"} {Math.abs((view.forecast.you - view.forecast.rival) * 100).toFixed(1)} + + (含聲勢帶出的未表態) + + )} + +
    +
    + + +
    +
    + ); +} + +function Momentum({ value, max, color, label }: { value: number; max: number; color: string; label: string }) { + return ( + + {label} + {Array.from({ length: max }, (_, i) => ( + + ))} + + ); +} + +/** 對手這週要做的事;選到「打對台」「事實查核」時可以點 */ +export function IntentList({ view, previews, onPick, targeting }: { view: RogueView; previews: Map | null; onPick: (id: string) => void; targeting: "intent" | "attack" | null }) { + const nextBigTown = view.nextBig ? view.towns.find((t) => t.code === view.nextBig!.town)?.name : null; + return ( +
    +

    + {view.rival.name}這週要做 + + {view.rivalTrait.name} + +

    +
      + {view.intents.map((i) => { + const p = previews?.get(i.id); + const Icon = INTENT_ICONS[i.kind]; + const can = !!p && (targeting === "attack" ? attackable(i) : counterable(i)); + return ( +
    • + +
    • + ); + })} +
    + {view.nextBig && ( +

    + 預告:第 {view.nextBig.week} 週在{nextBigTown}辦大型造勢(約 +{num(view.nextBig.amount)}),提早在那區佈樁、設服務處吧 +

    + )} + {view.intents.some((i) => i.kind === "attack") &&

    全市的批評樁腳擋不了:用「澄清記者會」「事實查核」,沒擋下會多一張「記者追問」。

    } +

    {view.rivalTrait.name}:{view.rivalTrait.text}

    +
    + ); +} + +/** 各區:支持度條、特色、插旗、對手意圖、樁腳;選到要打在某區的牌時顯示預估,前三名打星號 */ +export function TownList({ view, previews, best, onPick, focus }: { view: RogueView; previews: Map | null; best: ReadonlySet; onPick: (code: string) => void; focus: string | null }) { + // 選到牌時最划算的排最上面;沒選牌時依投票人數 + const score = (code: string) => previews?.get(code)?.votes ?? Number.NEGATIVE_INFINITY; + const towns = [...view.towns].sort((a, b) => (previews ? score(b.code) - score(a.code) : 0) || b.voters - a.voters); + return ( +
      + {towns.map((t) => ( + onPick(t.code)} /> + ))} +
    + ); +} + +function TownRow({ view, town: t, preview, best, focus, onPick }: { view: RogueView; town: RogueTown; preview: RoguePreview | null; best: boolean; focus: boolean; onPick: () => void }) { + const share = townShare(t); + const width = (n: number) => `${(n / (t.voters || 1)) * 100}%`; + const intents = view.intents.filter((i) => i.town === t.code); + const big = view.nextBig?.town === t.code; + return ( +
  • + +
  • + ); +} + +function IntentChip({ intent: i }: { intent: RogueIntent }) { + const Icon = INTENT_ICONS[i.kind]; + const amount = i.kind === "stake" ? `盾 ${num(i.amount * i.cut)}` : i.kind === "smear" ? signed(-i.amount * i.cut) : `+${num(i.amount * i.cut)}`; + return ( + + {amount} + + ); +} + +/** 手牌:記者堵麥這種要在這週處理的事件,變成手牌最前面的一張「事件牌」(uid 是 EVENT_UID) */ +export const EVENT_UID = "event"; + +export function Hand({ cards, selected, onSelect, event }: { cards: readonly RogueCard[]; selected: string | null; onSelect: (uid: string | null) => void; event?: { title: string; text: string } | null }) { + if (cards.length === 0 && !event) return

    這週的牌打完了,按「結束這週」。

    ; + const mid = (cards.length - 1) / 2; + return ( +
    + {event && ( + + )} + {cards.map((c, i) => ( + + ))} +
    + ); +} + +export function AdvisorRow({ view }: { view: RogueView }) { + return ( +
    + {view.advisors.map((a) => ( + + + + ))} + {Array.from({ length: Math.max(0, view.advisorSlots - view.advisors.length) }, (_, i) => ( + + 幕僚空位 + + ))} + {[...view.powers, ...view.buffs].map((p, i) => ( + + {p} + + ))} +
    + ); +} diff --git a/web/src/game/rogue/progress.ts b/web/src/game/rogue/progress.ts new file mode 100644 index 0000000..8c582a1 --- /dev/null +++ b/web/src/game/rogue/progress.ts @@ -0,0 +1,211 @@ +import type { RogueView } from "@election2026/protocol"; +import { rogueApi } from "../api.ts"; + +/** + * 選戰卡牌的進度(docs/22):成就、逆風難度解鎖、圖鑑看過的東西、每日一戰成績。 + * 只存在玩家自己的瀏覽器(localStorage);讀不到(私密模式)就當作第一次玩。 + */ +export interface Progress { + /** 拿到的成就 → 第一次拿到的日期 */ + feats: Record; + /** 解鎖到第幾級逆風(贏了第 n 級開第 n+1 級) */ + ascension: number; + seen: { cards: string[]; advisors: string[]; events: string[] }; + runs: number; + wins: number; + /** 各劇本最好的成績(得票率) */ + best: Record; + /** 每日一戰:日期 → 成績 */ + daily: Record; + /** 已經記錄過的局(重新整理結果畫面不會重複算) */ + recorded: string[]; + /** 玩過的真實參選人(參選人卡冊用,玩過才上色):名字 → 局數、勝場、最好評等、玩過的劇本 */ + played: Record; + /** 舊存檔已經從記錄過的局補過 played */ + playedBackfilled?: boolean; + tutorialDone: boolean; +} + +export interface PlayedCandidate { + runs: number; + wins: number; + grade: string | null; + scenarios: string[]; +} + +const KEY = "tongsuan.rogue.progress.v1"; +const MAX_ASCENSION = 10; + +const empty = (): Progress => ({ + feats: {}, + ascension: 0, + seen: { cards: [], advisors: [], events: [] }, + runs: 0, + wins: 0, + best: {}, + daily: {}, + recorded: [], + played: {}, + tutorialDone: false, +}); + +export function loadProgress(): Progress { + try { + const raw = localStorage.getItem(KEY); + if (!raw) return empty(); + const p = JSON.parse(raw) as Partial; + const base = empty(); + return { ...base, ...p, seen: { ...base.seen, ...(p.seen ?? {}) } }; + } catch { + return empty(); + } +} + +function saveProgress(p: Progress): void { + try { + localStorage.setItem(KEY, JSON.stringify(p)); + } catch { + // 私密模式存不了:這次的進度只留在畫面上 + } +} + +/** 今天的日期(玩家當地時間),每日一戰用 */ +export function todayKey(now = new Date()): string { + const y = now.getFullYear(); + const m = String(now.getMonth() + 1).padStart(2, "0"); + const d = String(now.getDate()).padStart(2, "0"); + return `${y}-${m}-${d}`; +} + +/** 每日一戰的題目:同一天從清單裡挑同一個(清單順序要固定) */ +export function dailyPick(items: readonly T[], date: string): T | undefined { + let h = 2166136261; + for (const ch of date) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); + return items[(h >>> 0) % Math.max(1, items.length)]; +} + +/** 記下看過的牌、幕僚、事件(圖鑑用) */ +export function markSeen(view: RogueView): void { + const p = loadProgress(); + const add = (list: string[], ids: readonly string[]) => { + const set = new Set(list); + let changed = false; + for (const id of ids) { + if (!set.has(id)) { + set.add(id); + changed = true; + } + } + return changed ? [...set] : list; + }; + const offers = view.stop && "options" in view.stop ? view.stop.options : view.stop?.kind === "shop" ? view.stop.items : []; + const cards = add(p.seen.cards, [...view.deck.map((c) => c.id), ...offers.filter((o) => o.kind === "card").map((o) => o.id)]); + const advisors = add(p.seen.advisors, [...view.advisors.map((a) => a.id), ...offers.filter((o) => o.kind === "advisor").map((o) => o.id)]); + const events = add(p.seen.events, [view.event.id]); + if (cards === p.seen.cards && advisors === p.seen.advisors && events === p.seen.events) return; + saveProgress({ ...p, seen: { cards, advisors, events } }); +} + +export interface RunRecord { + /** 這局第一次拿到的成就 */ + newFeats: string[]; + /** 這局解鎖的逆風等級(沒有是 null) */ + unlocked: number | null; + /** 這個劇本的新紀錄 */ + record: boolean; + progress: Progress; +} + +function playedAfter(prev: PlayedCandidate | undefined, scenarioId: string, won: boolean, grade: string): PlayedCandidate { + const p = prev ?? { runs: 0, wins: 0, grade: null, scenarios: [] }; + const better = !p.grade || "SABCD".indexOf(grade) < "SABCD".indexOf(p.grade); + return { + runs: p.runs + 1, + wins: p.wins + (won ? 1 : 0), + grade: better ? grade : p.grade, + scenarios: p.scenarios.includes(scenarioId) ? p.scenarios : [...p.scenarios, scenarioId], + }; +} + +/** 玩過的真實參選人(名字 → 紀錄),參選人卡冊用 */ +export function playedCandidates(): Record { + return loadProgress().played; +} + +/** 有 played 之前就玩過的局:從記錄過的局補一次(只做一次;讀不到的局略過) */ +export async function backfillPlayed(): Promise> { + const p = loadProgress(); + if (p.playedBackfilled) return p.played; + const views = await Promise.all(p.recorded.map((id) => rogueApi.get(id).catch(() => null))); + let played = p.played; + for (const v of views) { + if (!v?.result || v.options.tutorial || v.you.id === "custom") continue; + played = { + ...played, + [v.you.name]: playedAfter(played[v.you.name], v.scenarioId, v.result.won, v.result.grade), + }; + } + // 補的這段時間可能又打完一局:以最新的存檔為準,只補它還沒有的人 + const now = loadProgress(); + const merged = { ...played, ...now.played }; + saveProgress({ ...now, played: merged, playedBackfilled: true }); + return merged; +} + +/** 一局打完:記成就、解鎖下一級逆風、最佳成績、每日一戰。同一局只算一次 */ +export function recordRun(view: RogueView): RunRecord { + const p = loadProgress(); + const r = view.result; + if (!r || p.recorded.includes(view.runId)) return { newFeats: [], unlocked: null, record: false, progress: p }; + const today = todayKey(); + const newFeats = r.feats.filter((f) => !p.feats[f]); + const feats = { + ...p.feats, + ...Object.fromEntries(newFeats.map((f) => [f, today])), + }; + const tutorial = view.options.tutorial; + const level = view.options.ascension; + const unlocked = r.won && !tutorial && level >= p.ascension && level < MAX_ASCENSION ? level + 1 : null; + const prev = p.best[view.scenarioId]; + const record = !tutorial && (!prev || r.youShare > prev.share); + const next: Progress = { + ...p, + feats, + ascension: unlocked ?? p.ascension, + runs: p.runs + (tutorial ? 0 : 1), + wins: p.wins + (r.won && !tutorial ? 1 : 0), + best: record + ? { + ...p.best, + [view.scenarioId]: { + share: r.youShare, + grade: r.grade, + ascension: level, + won: r.won, + }, + } + : p.best, + daily: + view.options.daily && !p.daily[view.options.daily] + ? { + ...p.daily, + [view.options.daily]: { + share: r.youShare, + won: r.won, + grade: r.grade, + }, + } + : p.daily, + recorded: [...p.recorded, view.runId].slice(-60), + played: + tutorial || view.you.id === "custom" + ? p.played + : { + ...p.played, + [view.you.name]: playedAfter(p.played[view.you.name], view.scenarioId, r.won, r.grade), + }, + tutorialDone: p.tutorialDone || tutorial, + }; + saveProgress(next); + return { newFeats, unlocked, record, progress: next }; +} diff --git a/web/src/game/rogue/rogue-cards.css b/web/src/game/rogue/rogue-cards.css new file mode 100644 index 0000000..f4a9d4d --- /dev/null +++ b/web/src/game/rogue/rogue-cards.css @@ -0,0 +1,84 @@ +/* 選戰卡牌的牌面:稀有度外框+類型色條。顏色只用 tokens.css 和這裡的類型色,不用政黨色 */ +.rgc { + --k: #e8833a; + --rgc-w: var(--rg-card-w, 128px); + position: relative; + display: grid; + grid-template-rows: auto auto auto 1fr auto; + justify-items: center; + gap: 2px; + width: var(--rgc-w); + height: calc(var(--rgc-w) * 1.47); + padding: 5px 5px 6px; + text-align: center; + background: var(--surface); + color: var(--ink); + border: 3px solid var(--ink); + border-radius: 12px; + box-shadow: 3px 3px 0 var(--shadow-ink); +} +.rgc.k-ground { --k: #e8833a; } +.rgc.k-rally { --k: #d6457a; } +.rgc.k-media { --k: #7a5cc4; } +.rgc.k-org { --k: #a3670f; } +.rgc.k-defend { --k: #2f7f8f; } +.rgc.k-attack { --k: var(--stamp); } +.rgc.k-money { --k: #c99400; } +.rgc.k-status { --k: var(--muted); } + +/* 稀有度:基本是素面、普通有類型色邊、稀有金框+寶石、狀態是虛線 */ +.rgc.r-common { box-shadow: inset 0 0 0 2px var(--k), 3px 3px 0 var(--shadow-ink); } +.rgc.r-rare { + border-color: #b8860b; + background: linear-gradient(180deg, color-mix(in srgb, #f2c94c 30%, var(--surface)), var(--surface) 55%); + box-shadow: inset 0 0 0 2px #f2c94c, 3px 3px 0 var(--shadow-ink); +} +.rgc.r-status { border-style: dashed; background: color-mix(in srgb, var(--muted) 10%, var(--surface)); } +.rgc.is-up { box-shadow: 0 0 0 3px #f2c94c, 0 0 18px 2px color-mix(in srgb, #f2c94c 70%, transparent), 3px 3px 0 var(--shadow-ink); } +.rgc.is-up .rgc-name { color: #8a5a00; } +:root[data-theme="dark"] .rgc.is-up .rgc-name { color: #f2c94c; } +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) .rgc.is-up .rgc-name { color: #f2c94c; } +} + +.rgc-art { position: relative; width: 100%; } +.rgc-art .card-art { display: block; width: 100%; aspect-ratio: 16 / 10; border-radius: 7px; overflow: hidden; border-bottom: 4px solid var(--k); background: color-mix(in srgb, var(--k) 18%, var(--surface-2)); } +.rgc-art .card-art img { width: 100%; height: 100%; object-fit: cover; display: block; } +.rgc-art .card-art svg { width: 40%; height: 60%; margin: 8% auto; display: block; color: var(--k); } +.rgc-kind { + position: absolute; left: 4px; bottom: 6px; display: inline-flex; align-items: center; gap: 2px; + padding: 0 5px; border-radius: 999px; background: var(--k); color: #fff; font-size: 10px; font-weight: 800; line-height: 16px; +} +.rgc-name { font-family: var(--font-serif); font-size: calc(var(--rgc-w) * 0.115); line-height: 1.15; } +.rgc-value { font-family: var(--font-num); font-weight: 800; font-size: calc(var(--rgc-w) * 0.18); line-height: 1; color: var(--k); font-variant-numeric: tabular-nums; } +.rgc.k-ground .rgc-value, .rgc.k-org .rgc-value { color: color-mix(in srgb, var(--k) 80%, var(--ink)); } +.rgc-text { + font-size: calc(var(--rgc-w) * 0.084); line-height: 1.35; color: var(--muted); align-self: start; + display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; +} +.rgc-keys { display: flex; flex-wrap: wrap; justify-content: center; gap: 3px; } +.rgc-keys i { font-style: normal; font-size: 10px; font-weight: 800; padding: 0 5px; border-radius: 4px; background: var(--ink); color: var(--surface); line-height: 15px; } +.rgc-cost { + position: absolute; z-index: 2; top: -11px; left: -11px; width: 30px; height: 30px; display: grid; place-items: center; + border-radius: 50%; background: #f2a900; color: #111419; border: 2px solid var(--ink); + font-family: var(--font-num); font-weight: 800; font-size: 17px; box-shadow: 1px 2px 0 var(--shadow-ink); +} +.rgc-money { position: absolute; z-index: 2; top: -9px; right: -6px; padding: 0 6px; border-radius: 999px; background: var(--ink); color: var(--surface); font-size: 11px; font-weight: 700; line-height: 18px; } +.rgc-gem { position: absolute; top: 6px; right: 6px; width: 12px; height: 12px; rotate: 45deg; background: #f2c94c; border: 2px solid #8a5a00; border-radius: 2px; } +.rgc.is-blocked { filter: grayscale(0.9); opacity: 0.62; } +.rgc.is-blocked .rgc-text { color: var(--stamp); font-weight: 700; } +.rgc.is-selected { box-shadow: 0 0 0 3px var(--stamp), 0 16px 28px -12px rgb(0 0 0 / 0.5); } +.rgc.is-big { --rgc-w: 168px; } + +/* 幕僚 */ +.rga { + display: grid; justify-items: center; gap: 6px; width: 170px; padding: 12px 10px; text-align: center; + background: var(--signal); color: #111419; border: 3px solid var(--ink); border-radius: 14px; box-shadow: 3px 3px 0 var(--shadow-ink); +} +.rga .staff-avatar { border-radius: 50%; overflow: hidden; border: 2px solid var(--ink); background: #fff8e1; } +.rga b { font-family: var(--font-serif); font-size: 18px; } +.rga > span:last-child { font-size: 13px; line-height: 1.4; } +.rga.is-compact { display: inline-grid; grid-template-columns: auto auto; grid-template-rows: auto auto; justify-items: start; column-gap: 6px; row-gap: 0; width: auto; max-width: 240px; padding: 3px 10px 3px 3px; border-radius: 999px; text-align: left; box-shadow: none; border-width: 2px; } +.rga.is-compact .staff-avatar { grid-row: 1 / 3; } +.rga.is-compact b { font-size: 13px; line-height: 1.1; } +.rga.is-compact > span:last-child { font-size: 11px; line-height: 1.2; opacity: 0.85; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/web/src/game/rogue/rogue-career.css b/web/src/game/rogue/rogue-career.css new file mode 100644 index 0000000..f3e757f --- /dev/null +++ b/web/src/game/rogue/rogue-career.css @@ -0,0 +1,295 @@ +/* 政治生涯(18 第 44、47 項):沿用選戰畫面的樣式語言(粗黑框、硬陰影、黃紅),顏色字型都用 tokens.css。 + 淺色底的厚框元件(名牌、卡片、按鈕)字一律用 #111419,深色模式也看得清楚。 */ + +/* ── 版面:左邊角色卡,右邊棋盤+出征卡;手機用下面的分頁切換 ── */ +.cm-layout { height: 100%; display: grid; grid-template-columns: minmax(290px, 330px) minmax(0, 1fr); gap: 16px; } +.cm-world { min-height: 0; display: grid; grid-template-rows: minmax(0, 1fr) auto; gap: 12px; } +.cm-tabs { display: none; } + +/* ── 棋盤(CareerBoard.tsx、careerBoard3d.ts) ── */ +.cb { position: relative; min-height: 0; border: 3px solid #111419; border-radius: 20px; overflow: hidden; box-shadow: 5px 5px 0 #111419; background: radial-gradient(ellipse at 50% 40%, #6e4a2a, #3c2616); } +.cb-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: manipulation; } +.cb-loading { position: absolute; inset: 0; display: grid; place-items: center; margin: 0; color: #fffaf0; font-weight: 900; font-size: 18px; text-shadow: 2px 2px 0 #111419; } +.cb-labels { position: absolute; inset: 0; pointer-events: none; } +.cb.is-loading .cb-labels { visibility: hidden; } +.cb-stop { position: absolute; left: 0; top: 0; will-change: transform; } +.cb-stop-in { display: grid; justify-items: center; gap: 4px; transform: translate(-50%, calc(-100% - 10px)); } +.cb-stop button { pointer-events: auto; position: relative; display: grid; grid-template-columns: auto auto; grid-template-rows: auto auto; align-items: center; column-gap: 7px; padding: 3px 14px 4px 4px; text-align: left; white-space: nowrap; font: inherit; cursor: pointer; background: #fffaf0; color: #111419; border: 3px solid #111419; border-radius: 999px; box-shadow: 3px 3px 0 #111419; transition: transform 160ms var(--ease-out), background-color 150ms ease; } +.cb-stop button::after { content: ""; position: absolute; left: 50%; top: 100%; width: 12px; height: 12px; translate: -50% -5px; rotate: 45deg; background: inherit; border-right: 3px solid #111419; border-bottom: 3px solid #111419; } +.cb-ic { grid-row: span 2; width: 32px; height: 32px; display: grid; place-items: center; border-radius: 50%; background: var(--stamp); color: #fff; border: 2px solid #111419; } +.cb-stop b { font-family: var(--font-serif); font-size: 16px; line-height: 1.1; } +.cb-stop small { font-size: 11px; font-weight: 800; color: #5d646e; line-height: 1.2; } +.cb-stop.is-done button { background: var(--signal); } +.cb-stop.is-done small { color: #3a3a3a; } +.cb-stop.is-locked button { background: #d9dbe0; color: #4a5058; } +.cb-stop.is-locked .cb-ic { background: #8a9099; } +.cb-stop.is-selected { z-index: 2; } +.cb-stop.is-selected button { transform: scale(1.08); outline: 4px solid var(--stamp); outline-offset: 2px; } +.cb-stop button:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +@media (hover: hover) and (pointer: fine) { + .cb-stop button:hover { transform: scale(1.06); } + .cb-stop.is-selected button:hover { transform: scale(1.08); } +} +.cb-token { display: grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; overflow: hidden; border: 3px solid #111419; background: #fff; box-shadow: 2px 2px 0 #111419; animation: cm-bob 1.8s ease-in-out infinite; } +@keyframes cm-bob { 50% { transform: translateY(-5px); } } + +/* 沒有 WebGL:一排五張關卡牌 */ +.cb-flat { min-height: 0; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); align-items: center; gap: 10px; padding: 16px; border: 3px solid #111419; border-radius: 20px; box-shadow: 5px 5px 0 #111419; background: radial-gradient(ellipse at 50% 40%, #6e4a2a, #3c2616); } +.cb-flat-stop { position: relative; display: grid; } +.cb-flat-stop button { display: grid; justify-items: center; gap: 6px; padding: 16px 8px; font: inherit; cursor: pointer; background: #fffaf0; color: #111419; border: 3px solid #111419; border-radius: 18px; box-shadow: 4px 4px 0 #111419; } +.cb-flat-stop .cb-ic { width: 46px; height: 46px; } +.cb-flat-stop b { font-family: var(--font-serif); font-size: 18px; } +.cb-flat-stop small { font-size: 12px; font-weight: 800; color: #5d646e; text-align: center; } +.cb-flat-stop.is-done button { background: var(--signal); } +.cb-flat-stop.is-locked button { background: #d9dbe0; } +.cb-flat-stop.is-locked .cb-ic { background: #8a9099; } +.cb-flat-stop.is-selected button { outline: 4px solid var(--stamp); outline-offset: 3px; } +.cb-flat-stop .cb-token { position: absolute; top: -26px; left: 50%; translate: -50% 0; width: 42px; height: 42px; } + +/* ── 角色卡(CareerSheet.tsx) ── */ +.cs { min-height: 0; display: grid; align-content: start; gap: 12px; padding: 16px 14px 12px; overflow-y: auto; scrollbar-width: thin; } +.cs-id { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 16px; } +.cs-portrait { position: relative; width: 92px; height: 92px; display: grid; place-items: end center; border: 3px solid #111419; border-radius: 20px; background: color-mix(in srgb, var(--party) 28%, #fffaf0); box-shadow: inset 0 -9px 0 var(--party), 4px 4px 0 #111419; } +.cs-portrait > :first-child { border-radius: 0 0 17px 17px; } +.cs-lv { position: absolute; right: -14px; bottom: -12px; display: grid; justify-items: center; width: 48px; padding: 1px 0 3px; background: var(--signal); color: #111419; border: 3px solid #111419; border-radius: 12px; box-shadow: 2px 2px 0 #111419; transform: rotate(-6deg); } +.cs-lv small { font-size: 10px; font-weight: 900; line-height: 1; } +.cs-lv b { font-family: var(--font-num); font-size: 28px; line-height: 0.9; } +.cs-name { display: grid; justify-items: start; gap: 4px; min-width: 0; } +.cs-name b { max-width: 100%; font-family: var(--font-serif); font-size: 26px; line-height: 1.1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cs-name small { font-size: 12px; font-weight: 700; color: var(--muted); } +.cs-party { padding: 1px 10px; border-radius: 999px; background: var(--party); color: #fff; font-size: 12px; font-weight: 900; } +.cs-xp-bar { height: 18px; border: 3px solid #111419; border-radius: 999px; background: var(--surface-2); overflow: hidden; } +.cs-xp-bar i { display: block; height: 100%; transform-origin: left; background: repeating-linear-gradient(135deg, #3fb36b 0 10px, #2f9a58 10px 20px); transition: transform 600ms var(--ease-out); } +.cs-xp small { display: flex; justify-content: space-between; margin-top: 4px; font-size: 12px; font-weight: 800; color: var(--muted); } +.cs-xp small b { font-family: var(--font-num); font-size: 15px; color: var(--ink); } +.cs-sp { margin: 0; display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; column-gap: 8px; padding: 8px 12px; border: 3px solid #111419; border-radius: 14px; background: var(--signal); color: #111419; box-shadow: 3px 3px 0 #111419; font-weight: 900; animation: cm-glow 1.6s ease-in-out infinite; } +.cs-sp b { font-family: var(--font-num); font-size: 22px; } +.cs-sp small { grid-column: 2; font-size: 12px; font-weight: 800; color: #3a3a3a; } +.cs-sp.is-idle { display: flex; gap: 6px; padding: 6px 10px; border: 2px dashed var(--line); background: none; color: var(--muted); box-shadow: none; font-size: 13px; font-weight: 700; animation: none; } +.cs-abilities { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.cs-abilities li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; padding: 8px; border-radius: 14px; background: var(--surface-2); } +.cs-ab-ic { width: 38px; height: 38px; display: grid; place-items: center; border-radius: 50%; background: var(--ab); color: #fff; border: 2px solid #111419; } +.cs-ab-main { min-width: 0; } +.cs-ab-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.cs-ab-top b { font-family: var(--font-serif); font-size: 17px; } +.cs-ab-main small { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 2px; font-size: 11.5px; line-height: 1.35; color: var(--muted); } +.cs-bar { display: inline-flex; gap: 3px; } +.cs-bar i { width: 17px; height: 12px; border: 2px solid #111419; border-radius: 4px; background: var(--surface); transform: skewX(-12deg); } +.cs-bar i.is-base { background: color-mix(in srgb, var(--ab) 50%, #fff); } +.cs-bar i.is-on { background: var(--ab); } +.cs-plus { width: 40px; height: 40px; border-radius: 50%; border: 2px solid var(--line); background: none; color: var(--line); font: inherit; font-weight: 900; font-size: 20px; line-height: 1; cursor: default; } +.cs-plus.is-hot { border: 3px solid #111419; background: var(--signal); color: #111419; box-shadow: 2px 2px 0 #111419; cursor: pointer; transition: transform 140ms var(--ease-out); } +.cs-plus.is-hot:active { transform: translate(1px, 1px); box-shadow: 1px 1px 0 #111419; } +.cs-plus:focus-visible { outline: 4px solid var(--stamp); outline-offset: 2px; } +.cs-foot { display: grid; justify-items: start; gap: 2px; padding-top: 6px; border-top: 2px dashed var(--line); } +.cs-link { display: inline-flex; align-items: center; gap: 6px; min-height: 40px; padding: 4px 2px; border: 0; background: none; color: var(--ink); font: inherit; font-weight: 800; font-size: 13px; cursor: pointer; text-decoration: underline; text-underline-offset: 3px; } +.cs-link.is-quit { color: var(--stamp); } + +/* ── 出征卡(CareerStage.tsx) ── */ +.sc { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "head side" "main side"; column-gap: 20px; row-gap: 10px; padding: 14px 18px 16px; } +.sc-main, +.sc-lock { grid-area: main; min-width: 0; display: grid; align-content: start; gap: 10px; } +.sc-side { grid-area: side; display: grid; align-content: end; justify-items: end; gap: 12px; } +.sc-head { grid-area: head; display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 14px; } +.sc-emblem { width: 58px; height: 58px; display: grid; place-items: center; border-radius: 16px; background: var(--stamp); color: #fff; border: 3px solid #111419; box-shadow: 3px 3px 0 #111419; transform: rotate(-4deg); } +.sc.is-locked .sc-emblem { background: #8a9099; } +.sc-title h2 { margin: 0; font-family: var(--font-serif); font-size: 30px; line-height: 1; } +.sc-chips { list-style: none; margin: 6px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; } +.sc-chips li { padding: 1px 9px; border: 2px solid var(--line); border-radius: 999px; background: var(--surface-2); font-size: 12px; font-weight: 800; } +.sc-where { margin: 0; display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 700; } +.sc-where svg { flex: none; color: var(--stamp); } +.sc-select { justify-self: start; max-width: 100%; min-height: 44px; padding: 4px 12px; border: 3px solid #111419; border-radius: 12px; background: #fffaf0; color: #111419; font: inherit; font-weight: 700; } +.sc-label { display: block; margin-bottom: 4px; font-size: 12px; font-weight: 900; letter-spacing: 0.06em; color: var(--muted); } +.sc-seg { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); max-width: 360px; border: 3px solid #111419; border-radius: 14px; overflow: hidden; } +.sc-seg button { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 1px; border: 0; border-left: 2px solid #111419; background: #fffaf0; color: #111419; font: inherit; font-weight: 900; cursor: pointer; transition: background-color 150ms ease; } +.sc-seg button:first-child { border-left: 0; } +.sc-seg button svg { color: var(--stamp); } +.sc-seg button[aria-checked="true"] { background: #111419; color: var(--signal); } +.sc-seg button[aria-checked="true"] svg { color: var(--signal); } +.sc-seg button:disabled { cursor: default; background: repeating-linear-gradient(135deg, #e6e4de 0 6px, #f3f2ee 6px 12px); } +.sc-seg button:disabled svg { color: #b8b8b8; } +.sc-seg button:focus-visible { outline: 4px solid var(--stamp); outline-offset: -4px; } +.sc-reward { display: grid; justify-items: end; text-align: right; } +.sc-reward b { font-family: var(--font-num); font-size: 42px; line-height: 0.9; color: #1f8a4c; } +.sc-reward b small { margin-left: 3px; font-family: var(--font-body); font-size: 14px; color: var(--ink); } +.sc-reward > small { font-size: 12px; font-weight: 700; color: var(--muted); } +.sc-carry { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; } +.sc-carry li { display: inline-flex; align-items: center; gap: 4px; padding: 2px 10px; border: 2px solid #111419; border-radius: 999px; background: color-mix(in srgb, var(--signal) 35%, #fffaf0); color: #111419; font-size: 13px; font-weight: 800; } +.sc-go-row { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 10px; } +.sc-go { min-height: 62px; padding: 8px 30px; border-radius: 16px; box-shadow: 4px 4px 0 #111419; font-family: var(--font-serif); font-size: 24px; } +.sc-go span { display: grid; text-align: left; line-height: 1.05; } +.sc-go small { font-family: var(--font-body); font-size: 12px; font-weight: 800; opacity: 0.7; } +.sc-lock { gap: 0; } +.sc-lock p { margin: 0; font-weight: 700; } +.sc-lock ul { list-style: none; margin: 8px 0; padding: 0; display: grid; gap: 6px; } +.sc-lock li { display: flex; align-items: center; gap: 8px; font-weight: 800; color: var(--stamp); } +.sc-lock li.is-ok { color: #1f8a4c; } +.sc-lv { flex: 0 0 96px; height: 12px; border: 2px solid #111419; border-radius: 999px; background: var(--surface-2); overflow: hidden; } +.sc-lv i { display: block; height: 100%; transform-origin: left; background: var(--signal); } +.sc-lock li small { color: var(--muted); font-weight: 700; } +.sc-tip { font-size: 13px; color: var(--muted); font-weight: 600 !important; } + +/* ── 選角(CareerSetup.tsx):三步——選角色、家鄉、起點 ── */ +.cs-setup-wrap { height: 100%; min-height: 0; display: grid; justify-items: center; align-items: center; } +.cs-setup { width: min(980px, 100%); min-height: 0; max-height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 14px; padding: 16px 20px 18px; } +.cs-steps { list-style: none; margin: 0; padding: 0; display: flex; justify-content: center; gap: 8px; } +.cs-steps li { display: flex; align-items: center; gap: 6px; padding: 4px 14px 4px 4px; border: 2px solid var(--line); border-radius: 999px; color: var(--muted); font-weight: 900; } +.cs-steps li > span { width: 28px; height: 28px; display: grid; place-items: center; border: 2px solid var(--line); border-radius: 50%; background: var(--surface-2); font-family: var(--font-num); font-size: 16px; } +.cs-steps li.is-now { border: 3px solid #111419; background: var(--signal); color: #111419; box-shadow: 3px 3px 0 #111419; } +.cs-steps li.is-now > span { border-color: #111419; background: #111419; color: var(--signal); } +.cs-steps li.is-done { border-color: var(--ink); color: var(--ink); } +.cs-steps li.is-done > span { border-color: #111419; background: #1f8a4c; color: #fff; } +.cs-step { min-height: 0; display: flex; flex-direction: column; gap: 14px; animation: gs-in 280ms var(--ease-out) both; } +.cs-step > .gs-scroll { flex: 1 1 auto; } +.cs-step-foot { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 10px; } +.cs-step-foot > :only-child { margin-left: auto; } + +.cs-roster { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); align-content: start; gap: 16px; padding: 12px 12px 12px 4px; } +.cs-card-slot { position: relative; } +.cs-card { --party: var(--slot-other); position: relative; width: 100%; height: 100%; display: grid; justify-items: center; align-content: start; gap: 5px; padding: 14px 10px 12px; font: inherit; cursor: pointer; background: linear-gradient(180deg, color-mix(in srgb, var(--party) 26%, #fffaf0) 0 44%, #fffaf0 44%); color: #111419; border: 3px solid #111419; border-radius: 18px; box-shadow: 4px 4px 0 #111419; transition: transform 160ms var(--ease-out); } +.cs-card-face { width: 92px; height: 92px; display: grid; place-items: center; overflow: hidden; border: 3px solid #111419; border-radius: 50%; background: #fff; } +.cs-card b { font-family: var(--font-serif); font-size: 20px; line-height: 1.15; } +.cs-card small { font-size: 12px; font-weight: 700; color: #5d646e; } +.cs-card[aria-pressed="true"] { transform: translateY(-4px); background: linear-gradient(180deg, var(--signal) 0 44%, #fffaf0 44%); outline: 4px solid var(--stamp); outline-offset: 3px; } +.cs-card:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.cs-card-check { position: absolute; top: 8px; left: 8px; width: 30px; height: 30px; display: grid; place-items: center; border: 2px solid #111419; border-radius: 50%; background: var(--stamp); color: #fff; animation: gs-pop 200ms var(--ease-out) both; } +.cs-card.is-new { border-style: dashed; background: var(--surface-2); color: var(--ink); box-shadow: none; } +.cs-card-plus { width: 92px; height: 92px; display: grid; place-items: center; border: 3px dashed currentColor; border-radius: 50%; } +.cs-card.is-new small { color: var(--muted); } +.cs-card-drop { position: absolute; top: -12px; right: -12px; width: 40px; height: 40px; display: grid; place-items: center; border: 3px solid #111419; border-radius: 50%; background: #fffaf0; color: #111419; box-shadow: 2px 2px 0 #111419; cursor: pointer; } +.cs-card-drop:focus-visible { outline: 4px solid var(--stamp); outline-offset: 2px; } +@media (hover: hover) and (pointer: fine) { + .cs-card:hover { transform: translateY(-3px); } + .cs-card-drop:hover { background: var(--stamp); color: #fff; } +} + +.cs-ask { margin: 0; display: flex; align-items: center; gap: 10px; font-weight: 800; } +.cs-ask > :first-child { flex: none; border: 3px solid #111419; border-radius: 50%; overflow: hidden; } +.cs-ask b { font-family: var(--font-serif); font-size: 20px; } +.cs-counties { padding: 2px 8px 8px 2px; } +.cs-counties h3 { margin: 4px 0 8px; font-size: 14px; letter-spacing: 0.08em; color: var(--muted); } +.cs-county-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 10px; margin-bottom: 8px; } +.cs-county-grid button { min-height: 52px; border: 3px solid #111419; border-radius: 14px; background: #fffaf0; color: #111419; font: inherit; font-family: var(--font-serif); font-size: 18px; cursor: pointer; box-shadow: 3px 3px 0 #111419; transition: transform 140ms var(--ease-out), background-color 150ms ease; } +.cs-county-grid button[aria-pressed="true"] { background: var(--signal); transform: translate(-1px, -2px); box-shadow: 4px 5px 0 #111419; } +.cs-county-grid button:focus-visible { outline: 4px solid var(--stamp); outline-offset: 2px; } + +.cs-start { flex: 1 1 auto; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: center; gap: 18px; } +.cs-start button { position: relative; display: grid; justify-items: center; gap: 8px; padding: 24px 18px; text-align: center; font: inherit; cursor: pointer; background: #fffaf0; color: #111419; border: 3px solid #111419; border-radius: 20px; box-shadow: 4px 4px 0 #111419; transition: transform 160ms var(--ease-out); } +.cs-start button[aria-checked="true"] { background: var(--signal); outline: 4px solid var(--stamp); outline-offset: 3px; transform: translateY(-3px); } +.cs-start-ic { width: 64px; height: 64px; display: grid; place-items: center; border: 3px solid #111419; border-radius: 18px; background: var(--stamp); color: #fff; transform: rotate(-4deg); } +.cs-start b { font-family: var(--font-serif); font-size: 26px; } +.cs-start em { position: absolute; top: -13px; right: 18px; padding: 2px 12px; border: 2px solid #111419; border-radius: 999px; background: var(--stamp); color: #fff; font-style: normal; font-weight: 900; transform: rotate(4deg); } +.cs-start small { max-width: 22em; font-size: 14px; font-weight: 700; color: #5d646e; } +.cs-begin { min-height: 58px; padding-inline: 30px; font-size: 20px; } + +.cs-quick { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: auto minmax(0, 1fr); align-content: start; gap: 22px; padding: 4px; } +.cs-quick-face { display: grid; justify-items: center; align-content: start; gap: 12px; } +.cs-quick-face > :first-child { border: 4px solid #111419; border-radius: 50%; overflow: hidden; box-shadow: 0 0 0 6px var(--party), 5px 5px 0 6px #111419; } +.cs-quick-fields { display: grid; align-content: start; gap: 14px; } +.cs-field { display: grid; gap: 6px; } +.cs-field > span { font-size: 14px; font-weight: 900; } +.cs-field input { min-height: 50px; padding: 6px 14px; border: 3px solid #111419; border-radius: 12px; background: #fffaf0; color: #111419; font: inherit; font-size: 18px; } +.cs-field input:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.cs-chips { display: flex; flex-wrap: wrap; gap: 8px; } +.cs-chips button { min-height: 42px; display: inline-flex; align-items: center; gap: 6px; padding: 4px 14px; border: 2px solid #111419; border-radius: 999px; background: #fffaf0; color: #111419; font: inherit; font-weight: 800; cursor: pointer; } +.cs-chips button i { width: 12px; height: 12px; border: 2px solid #111419; border-radius: 50%; background: var(--party); } +.cs-chips button[aria-pressed="true"] { background: #111419; color: #fff; } +.cs-chips button[aria-pressed="true"] i { border-color: #fff; } +.cs-quick-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; } + +.rgc-keep { display: flex; flex-wrap: wrap; gap: 12px; padding: 10px 4px; } +.rgc-keep.is-cards { --rg-card-w: 116px; padding-top: 16px; } +.rgc-keep button { padding: 0; border: 0; background: none; cursor: pointer; border-radius: 16px; transition: transform 160ms var(--ease-out); } +.rgc-keep button[aria-pressed="true"] { outline: 4px solid var(--stamp); outline-offset: 3px; } +.rgc-keep button:active { transform: scale(0.97); } + +.cm-report-wrap { z-index: 50; } +.cm-report { width: min(760px, 100%); max-height: calc(100dvh - 32px); overflow-y: auto; display: grid; gap: 10px; padding: 18px 20px; animation: cm-pop 320ms var(--ease-out) both; } +.cm-report.is-won { background: linear-gradient(180deg, color-mix(in srgb, var(--signal) 45%, var(--surface)), var(--surface) 55%); } +.cm-report-head { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 18px; } +.cm-report-head small { font-size: 13px; font-weight: 800; color: var(--muted); } +.cm-report h2 { margin: 0; display: flex; align-items: center; gap: 8px; font-family: var(--font-serif); font-size: 30px; line-height: 1.1; } +.cm-report h2 svg { color: #b8860b; } +.cm-report h3 { margin: 4px 0 0; font-size: 16px; } +.cm-report-share { margin: 4px 0 0; font-weight: 800; } +.cm-stamp { width: 92px; height: 92px; display: grid; place-items: center; border: 6px double var(--stamp); border-radius: 50%; color: var(--stamp); font-family: var(--font-serif); font-size: 28px; transform: rotate(-12deg); animation: cm-stamp 360ms var(--ease-out) 120ms both; } +.cm-stamp.is-lost { border-color: #8a9099; color: #8a9099; } +@keyframes cm-stamp { from { opacity: 0; transform: rotate(-12deg) scale(1.35); } } +.cm-report-exp { display: grid; gap: 6px; padding: 10px 14px; border: 2px solid var(--line); border-radius: 14px; background: var(--surface-2); } +.cm-report-exp p { margin: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; font-weight: 800; } +.cm-report-exp b { font-family: var(--font-num); font-size: 36px; line-height: 1; color: #1f8a4c; } +.cm-report-exp p small { color: var(--muted); font-weight: 700; } +.cm-report-exp > small { font-size: 12px; font-weight: 800; color: var(--muted); } +.cm-report-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; } +@keyframes cm-pop { from { opacity: 0; transform: scale(0.94); } } + +.cm-term { height: 100%; display: grid; align-content: start; gap: 10px; } +.cm-skip-term { justify-self: center; } +/* 場景名牌已經寫了「議員任期」,任期畫面自己的標題收起來 */ +.cm-term .tm-screen-head > small, +.cm-term .tm-screen-head > h2 { display: none; } +.cm-error { position: absolute; left: 50%; bottom: 60px; translate: -50% 0; z-index: 30; } +@keyframes cm-glow { 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--signal) 50%, transparent), 3px 3px 0 #111419; } } + +/* ── 手機、窄螢幕:棋盤和角色卡用下面的分頁切換,整頁不捲 ── */ +@media (max-width: 900px) { + .cm-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; gap: 10px; } + .cm-layout > .cs { display: none; } + .cm-layout.show-char > .cs { display: grid; } + .cm-layout.show-char > .cm-world { display: none; } + .cm-world { gap: 10px; } + .cm-tabs { display: grid; grid-template-columns: 1fr 1fr; border: 3px solid #111419; border-radius: 14px; overflow: hidden; box-shadow: 3px 3px 0 #111419; } + .cm-tabs button { position: relative; min-height: 46px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 0; border-left: 2px solid #111419; background: #fffaf0; color: #111419; font: inherit; font-weight: 900; cursor: pointer; } + .cm-tabs button:first-child { border-left: 0; } + .cm-tabs button[aria-pressed="true"] { background: #111419; color: var(--signal); } + .cm-tabs em { min-width: 22px; padding: 0 6px; border-radius: 999px; background: var(--stamp); color: #fff; font-style: normal; font-size: 12px; } + .cb-flat { grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); overflow-y: auto; align-content: start; padding-top: 30px; } + .sc { grid-template-columns: minmax(0, 1fr); grid-template-areas: "head" "main" "side"; row-gap: 8px; padding: 10px 12px 12px; } + .sc-main { gap: 8px; } + .sc-side { grid-template-columns: auto minmax(0, 1fr); align-items: center; justify-items: stretch; gap: 12px; } + .sc-reward { justify-items: start; text-align: left; } + .sc-go-row { flex-wrap: nowrap; } + .sc-head { gap: 10px; } + .sc-emblem { width: 44px; height: 44px; border-radius: 12px; } + .sc-title h2 { font-size: 24px; } + .sc-chips li:nth-child(n + 4) { display: none; } + .sc-where { font-size: 13px; } + .sc-reward b { font-size: 32px; } + .sc-go { min-height: 54px; font-size: 20px; padding-inline: 22px; flex: 1 1 auto; justify-content: center; } + .cs-setup { padding: 12px; gap: 10px; } + .cs-steps li { padding-right: 10px; font-size: 13px; } + .cs-roster { grid-template-columns: repeat(auto-fill, minmax(124px, 1fr)); gap: 14px; } + .cs-card-face, + .cs-card-plus { width: 72px; height: 72px; } + .cs-card b { font-size: 17px; } + .cs-start { grid-template-columns: minmax(0, 1fr); align-content: start; gap: 16px; padding-top: 10px; } + .cs-start button { padding: 16px 14px; } + .cs-quick { grid-template-columns: minmax(0, 1fr); gap: 14px; } +} +@media (max-width: 420px) { + .cb-stop b { font-size: 14px; } + .cb-stop small { font-size: 10px; } + .cb-ic { width: 26px; height: 26px; } + .cb-ic svg { width: 14px; height: 14px; } + .cb-token { width: 40px; height: 40px; } + .sc-reward b { font-size: 28px; } + .sc-go { font-size: 18px; padding-inline: 14px; } +} +@media (prefers-reduced-motion: reduce) { + .cb-token, + .cs-sp { animation: none; } + .cs-step, + .cs-card-check { animation: gs-fade 200ms ease both; } + .cm-report, + .cm-levelup, + .cm-stamp { animation: gs-fade 200ms ease both; } + .cs-xp-bar i { transition: none; } +} +.cs-party-select { justify-self: start; max-width: 100%; min-height: 44px; margin-top: 6px; padding: 4px 12px; border: 2px solid #111419; border-radius: 12px; background: #fffaf0; color: #111419; font: inherit; font-weight: 700; } +.cs-party-select:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.sc-village { display: flex; flex-wrap: wrap; gap: 8px; } +.cs-perks { margin: 0; display: grid; gap: 6px; padding: 8px 10px; border: 2px dashed var(--line); border-radius: 12px; font-size: 12.5px; line-height: 1.45; } +.cs-perks div { display: grid; gap: 1px; } +.cs-perks dt { font-weight: 900; } +.cs-perks dd { margin: 0; color: var(--muted); font-weight: 600; } +.cs-cost { display: block; color: var(--stamp); } diff --git a/web/src/game/rogue/rogue-finale.css b/web/src/game/rogue/rogue-finale.css new file mode 100644 index 0000000..6a67f02 --- /dev/null +++ b/web/src/game/rogue/rogue-finale.css @@ -0,0 +1,159 @@ +/* 選戰卡牌的最後一幕:開票夜(電視台深藍底)、結果、成就。顏色沿用 theme/tokens.css */ +.rgn-overlay { + position: fixed; inset: 0; z-index: 45; + display: grid; place-items: start center; overflow-y: auto; + padding: max(16px, env(safe-area-inset-top, 0px)) max(16px, env(safe-area-inset-right, 0px)) 24px max(16px, env(safe-area-inset-left, 0px)); + background: radial-gradient(120% 80% at 50% 0%, var(--navy-2), var(--tv-bg) 70%); + color: var(--tv-ink); + animation: rgn-fade 240ms ease-out both; +} +.rgn-overlay.is-result { background: rgb(17 20 25 / 0.72); } +@keyframes rgn-fade { from { opacity: 0; } } + +/* ── 開票夜 ── */ +.rgn-night { position: relative; width: min(960px, 100%); display: grid; gap: 14px; padding: 8px 0 12px; } +/* 有地圖時:電腦版地圖在右邊、計票在左邊;手機版地圖在最上面 */ +.rgn-night.has-map { width: min(1200px, 100%); grid-template-columns: minmax(0, 1fr) minmax(0, 0.9fr); align-items: start; column-gap: 20px; } +.rgn-night.has-map > :not(.rgn-map):not(.rgn-flash) { grid-column: 1; } +.rgn-map { grid-column: 2; grid-row: 1 / span 8; position: sticky; top: 12px; border: 3px solid #000; border-radius: 18px; overflow: hidden; background: var(--sea, #cfe0ea); box-shadow: 4px 4px 0 #000; } +.rgn-map .stage { display: block; width: 100%; height: auto; max-height: 78vh; } +.rgn-map .town-label { font-size: 15px; } +@media (max-width: 860px) { + .rgn-night.has-map { grid-template-columns: minmax(0, 1fr); } + .rgn-map { grid-column: 1; grid-row: auto; position: static; order: -1; } + .rgn-map .stage { max-height: 34vh; } +} +.rgn-night-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; } +.rgn-night-head h2 { margin: 0; font-family: var(--font-serif); font-size: clamp(22px, 4.6vw, 34px); color: #fff; text-shadow: 3px 3px 0 #000; } +.rgn-live { padding: 2px 10px; border-radius: 6px; background: var(--stamp); color: #fff; font-family: var(--font-num); font-weight: 800; letter-spacing: 0.12em; animation: rgn-blink 1.2s ease-in-out infinite; } +@keyframes rgn-blink { 50% { opacity: 0.45; } } +.rgn-progress { margin-left: auto; font-size: 15px; color: color-mix(in srgb, var(--tv-ink) 75%, transparent); } +.rgn-progress b { font-family: var(--font-num); font-size: 24px; color: var(--signal); font-variant-numeric: tabular-nums; } +.rgn-progress small { display: block; text-align: right; font-size: 12px; } + +.rgn-board { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: stretch; gap: 12px; } +.rgn-vs { align-self: center; font-family: var(--font-num); font-weight: 800; font-size: 28px; color: var(--signal); } +.rgn-side { + --c: var(--slot-other); + position: relative; display: grid; justify-items: center; gap: 4px; padding: 16px 10px 14px; + background: color-mix(in srgb, var(--c) 22%, #0b1424); border: 3px solid color-mix(in srgb, var(--c) 70%, #000); + border-radius: 18px; box-shadow: 5px 5px 0 #000; transition: transform 240ms var(--ease-out), box-shadow 240ms var(--ease-out); +} +.rgn-side.is-leading { box-shadow: 0 0 0 3px var(--signal), 5px 5px 0 #000; } +.rgn-side.is-won { transform: translateY(-4px); box-shadow: 0 0 0 4px var(--signal), 0 0 34px 4px color-mix(in srgb, var(--signal) 55%, transparent), 5px 5px 0 #000; } +.rgn-name { font-family: var(--font-serif); font-size: clamp(18px, 3.6vw, 26px); color: #fff; text-align: center; } +.rgn-votes { font-family: var(--font-num); font-weight: 800; font-size: clamp(34px, 8vw, 64px); line-height: 1; color: #fff; font-variant-numeric: tabular-nums; } +.rgn-share { font-family: var(--font-num); font-weight: 800; font-size: clamp(20px, 4.4vw, 30px); color: var(--signal); font-variant-numeric: tabular-nums; } +.rgn-lead { position: absolute; top: -12px; right: 10px; padding: 1px 10px; border-radius: 999px; background: var(--signal); color: #111419; font-style: normal; font-weight: 900; font-size: 13px; border: 2px solid #000; } + +.rgn-tug { display: flex; height: 18px; border-radius: 9px; overflow: hidden; border: 2px solid #000; background: rgb(255 255 255 / 0.12); } +.rgn-tug i, .rgn-bar i { display: block; height: 100%; transition: width 480ms var(--ease-out); } + +.rgn-towns { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; max-height: min(42vh, 380px); overflow-y: auto; scrollbar-width: thin; } +.rgn-towns li { + display: grid; grid-template-columns: 88px minmax(0, 1fr) 44px 76px; align-items: center; gap: 10px; + padding: 6px 12px; border-radius: 10px; background: rgb(255 255 255 / 0.07); font-size: 15px; +} +.rgn-towns li b { font-family: var(--font-serif); color: #fff; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rgn-towns li small { text-align: right; font-family: var(--font-num); font-weight: 800; font-size: 17px; font-variant-numeric: tabular-nums; } +.rgn-towns li.is-waiting { opacity: 0.55; } +.rgn-towns li.is-done { background: rgb(255 255 255 / 0.12); } +/* 剛開完的那一區亮一下 */ +.rgn-towns li.is-new { animation: rgn-row 900ms ease-out both; } +@keyframes rgn-row { from { background-color: color-mix(in srgb, var(--signal) 45%, transparent); } } +.rgn-town-f { font-size: 12px; font-weight: 800; text-align: right; color: color-mix(in srgb, var(--tv-ink) 70%, transparent); font-variant-numeric: tabular-nums; } +.rgn-bar { display: flex; height: 12px; border-radius: 6px; overflow: hidden; background: rgb(255 255 255 / 0.15); } +.rgn-overlay .is-up { color: #6fe3a0; } +.rgn-overlay .is-down { color: #ff8a8a; } + +.rgn-flash { position: absolute; inset: -8px; z-index: 3; pointer-events: none; border-radius: 22px; background: var(--signal); opacity: 0; animation: rgn-flash 560ms ease-out; } +@keyframes rgn-flash { 0% { opacity: 0.55; } 100% { opacity: 0; } } + +.rgn-skip { justify-self: center; color: var(--tv-ink); border-color: color-mix(in srgb, var(--tv-ink) 40%, transparent); } +.rgn-final { display: grid; justify-items: center; gap: 8px; padding: 6px 0; } +.rgn-final strong { font-family: var(--font-serif); font-size: clamp(28px, 6vw, 46px); color: #fff; text-shadow: 3px 3px 0 #000; } +.rgn-final.is-won strong { color: var(--signal); } +.rgn-stamp { display: grid; place-items: center; width: 116px; height: 116px; border-radius: 50%; background: #fff; border: 3px solid #000; box-shadow: 4px 4px 0 #000; animation: rgn-thump 320ms var(--ease-out) both; } +@keyframes rgn-thump { from { opacity: 0; transform: scale(1.45) rotate(-12deg); } } + +/* ── 結果 ── */ +.rgn-result { + width: min(700px, 100%); display: grid; justify-items: center; gap: 12px; padding: 22px 22px 18px; text-align: center; + background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 20px; box-shadow: 6px 6px 0 #000; + animation: rgn-pop 280ms var(--ease-out) both; +} +@keyframes rgn-pop { from { opacity: 0; transform: translateY(12px) scale(0.98); } } +.rgn-grade { display: grid; grid-template-columns: auto auto; grid-template-rows: auto auto; align-items: center; column-gap: 12px; } +.rgn-grade > :first-child { grid-row: 1 / 3; } +.rgn-grade b { font-family: var(--font-num); font-size: 60px; line-height: 1; color: var(--stamp); } +.rgn-grade.g-C b, .rgn-grade.g-D b { color: var(--muted); } +.rgn-grade span { font-family: var(--font-serif); font-size: 19px; font-weight: 800; } +.rgn-tutorial { display: grid; justify-items: center; gap: 6px; color: var(--ink); } +.rgn-tutorial svg { color: #c99400; } +.rgn-tutorial h2 { margin: 0; font-family: var(--font-serif); font-size: 30px; } +.rgn-tutorial p { margin: 0; max-width: 26em; } +.rgn-title { margin: 0; font-family: var(--font-serif); font-size: clamp(26px, 5vw, 34px); } +.rgn-tags { margin: 0; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 6px; color: var(--muted); font-weight: 700; } +.rgn-tag { padding: 1px 10px; border-radius: 999px; font-size: 13px; border: 2px solid var(--ink); color: var(--ink); } +.rgn-tag.is-asc { background: color-mix(in srgb, var(--stamp) 16%, var(--surface)); } +.rgn-tag.is-daily { background: color-mix(in srgb, var(--signal) 40%, var(--surface)); } +.rgn-tag.is-record { background: var(--signal); color: #111419; } +.rgn-unlock { margin: 0; display: inline-flex; align-items: center; gap: 6px; padding: 6px 16px; border-radius: 999px; background: var(--stamp); color: #fff; font-weight: 900; font-size: 17px; border: 2px solid var(--ink); box-shadow: 3px 3px 0 var(--shadow-ink); animation: rgn-pop 320ms var(--ease-out) 200ms both; } +.rgn-final-score { display: flex; align-items: center; justify-content: center; gap: 18px; flex-wrap: wrap; } +.rgn-final-score > span { display: grid; justify-items: center; gap: 2px; } +.rgn-final-score b { font-family: var(--font-num); font-size: 38px; font-variant-numeric: tabular-nums; } +.rgn-final-score small { color: var(--muted); font-variant-numeric: tabular-nums; } +.rgn-vs-small { font-family: var(--font-serif); color: var(--muted); } +.rgn-trend { margin: 0; width: min(380px, 100%); } +.rgn-trend svg { width: 100%; height: auto; color: var(--ink); } +.rgn-trend figcaption { font-size: 12px; color: var(--muted); } + +.rgn-feats { width: 100%; display: grid; gap: 6px; text-align: left; } +.rgn-feats h3 { margin: 0; font-family: var(--font-serif); font-size: 17px; } +.rgn-feats ul { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 6px; } +.rgn-feats li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 12px; background: var(--surface-2); border: 2px solid var(--line); animation: rgn-pop 300ms var(--ease-out) calc(var(--i, 0) * 70ms) both; } +.rgn-feats li svg { color: #c99400; } +.rgn-feats li span { display: grid; min-width: 0; } +.rgn-feats li b { font-size: 14px; } +.rgn-feats li small { font-size: 12px; color: var(--muted); } +.rgn-feats li.is-new { background: color-mix(in srgb, var(--signal) 35%, var(--surface)); border-color: var(--ink); } +.rgn-feats li em { font-style: normal; font-family: var(--font-num); font-weight: 800; font-size: 12px; padding: 0 6px; border-radius: 4px; background: var(--stamp); color: #fff; } + +.rgn-bytown { width: 100%; text-align: left; } +.rgn-bytown summary { cursor: pointer; font-weight: 700; } +.rgn-bytown ul { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 4px; } +.rgn-bytown li { display: grid; grid-template-columns: 70px minmax(0, 1fr) 78px; align-items: center; gap: 8px; font-size: 13px; } +.rgn-bytown li small { text-align: right; font-family: var(--font-num); font-variant-numeric: tabular-nums; } +.rgn-bytown .rgn-bar { background: var(--surface-2); } +.rgn-result .is-up { color: #1f8a4c; } +.rgn-result .is-down { color: var(--stamp); } + +.rgn-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 10px; } +.rgn-asc-btn { background: var(--stamp); color: #fff; border: 3px solid var(--ink); box-shadow: 3px 3px 0 var(--shadow-ink); } +.rgn-sub { margin: 0; color: var(--muted); font-size: 13px; } + +@media (max-width: 560px) { + .rgn-board { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } + .rgn-vs { display: none; } + .rgn-side { padding: 12px 6px 10px; } + .rgn-towns li { grid-template-columns: 60px minmax(0, 1fr) 36px 64px; gap: 6px; padding: 5px 8px; font-size: 13px; } + .rgn-progress { margin-left: 0; } + .rgn-result { padding: 18px 14px 14px; } + .rgn-actions .btn { flex: 1 1 100%; justify-content: center; } +} + +@media (prefers-reduced-motion: reduce) { + .rgn-live { animation: none; } + .rgn-towns li.is-new, .rgn-result, .rgn-unlock, .rgn-feats li { animation: rgn-fade 200ms ease both; } + .rgn-stamp { animation: rgn-fade 200ms ease both; } + .rgn-tug i, .rgn-bar i, .rgn-side { transition: none; } +} +/* 頭像下面的號次章會凸出來,名字往下讓一點 */ +.rgn-side .cand-badge { margin-bottom: 8px; } + +/* 政績點:連到政策島 */ +.rgn-unlock.is-island { flex-wrap: wrap; justify-content: center; border-radius: 16px; background: #1f8a4c; font-size: 15px; } +.rgn-unlock.is-island a { font-weight: 900; color: inherit; text-decoration: underline; text-underline-offset: 3px; } +/* 小鎮幣(服裝店,docs/24) */ +.rgn-unlock.is-coins { flex-wrap: wrap; justify-content: center; border-radius: 16px; background: var(--signal); color: var(--signal-ink); font-size: 15px; animation-delay: 320ms; } +.rgn-unlock.is-coins a { font-weight: 900; color: inherit; text-decoration: underline; text-underline-offset: 3px; } diff --git a/web/src/game/rogue/rogue-flow.css b/web/src/game/rogue/rogue-flow.css new file mode 100644 index 0000000..bc5c45f --- /dev/null +++ b/web/src/game/rogue/rogue-flow.css @@ -0,0 +1,246 @@ +/* 選戰卡牌的劇情與下一站(flow.tsx):沿用 rogue.css 的 .rg-overlay/.rg-panel,這裡只放 rgf- 開頭的部分 */ +.rgf-panel { width: min(760px, 100%); } +.rgf-panel h2 { margin: 0; font-family: var(--font-serif); font-size: 24px; line-height: 1.25; } + +/* ── 選項按鈕 ── */ +.rgf-choices { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.rgf-choices li { animation: rgf-rise 240ms var(--ease-out) calc(var(--i, 0) * 50ms) both; } +.rgf-choice { + width: 100%; min-height: 52px; display: grid; gap: 2px; padding: 10px 14px; text-align: left; + border: 3px solid var(--ink); border-radius: 14px; background: var(--surface); color: var(--ink); font: inherit; + box-shadow: 3px 3px 0 var(--shadow-ink); cursor: pointer; + transition: transform 140ms var(--ease-out), background-color 150ms ease; +} +.rgf-choice-label { display: flex; align-items: center; gap: 6px; } +.rgf-choice-label b { font-size: 16px; } +.rgf-choice small { color: var(--muted); font-size: 13px; line-height: 1.4; } +.rgf-choice.is-risky .rgf-choice-label svg { color: var(--stamp); flex: none; } +.rgf-choice:active:not(:disabled) { transform: scale(0.98); } +.rgf-choice:disabled { cursor: default; opacity: 0.55; box-shadow: none; } +.rgf-choice:disabled small { color: var(--stamp); font-weight: 700; } +@media (hover: hover) and (pointer: fine) { + .rgf-choice:hover:not(:disabled) { background: color-mix(in srgb, var(--signal) 30%, var(--surface)); } +} + +.rgf-next { justify-self: center; } +.rgf-skip { justify-self: center; } + +/* ── 電視風格的標頭(堵麥、辯論、民調) ── */ +.rgf-tv { + display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; + background: #111419; color: #fff; border-radius: 10px; border: 3px solid var(--ink); +} +.rgf-tv b { font-family: var(--font-serif); font-size: 20px; } +.rgf-tv small { margin-left: auto; font-size: 12px; opacity: 0.75; } +.rgf-live { padding: 1px 8px; border-radius: 4px; background: var(--stamp); color: #fff; font-weight: 900; font-size: 13px; letter-spacing: 0.08em; } + +/* 堵麥:候選人被麥克風圍住,記者的問題在對話框 */ +.rgf-scrum { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px 16px; position: relative; padding: 18px 4px 4px; } +.rgf-scrum > .cand-badge { grid-column: 1; grid-row: 1 / 3; } +.rgf-mics { position: absolute; top: 0; left: 6px; display: flex; gap: 2px; color: var(--ink); } +.rgf-mics svg:nth-child(1) { rotate: -25deg; } +.rgf-mics svg:nth-child(3) { rotate: 25deg; } +.rgf-bubble { + position: relative; margin: 0; padding: 12px 16px; border: 3px solid var(--ink); border-radius: 16px; + background: var(--signal); color: #111419; font-size: 17px; font-weight: 700; line-height: 1.5; + box-shadow: 3px 3px 0 var(--shadow-ink); +} +.rgf-bubble small { display: block; font-size: 12px; font-weight: 800; opacity: 0.7; } +.rgf-scrum .rgf-bubble { grid-column: 2; grid-row: 1 / 3; } + +/* ── 辯論 ── */ +.rgf-score { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 10px; } +.rgf-score > span { display: grid; justify-items: center; gap: 2px; padding: 6px; border-radius: 12px; border-bottom: 5px solid var(--c); background: var(--surface-2); } +.rgf-score > span small { font-weight: 700; font-size: 13px; } +/* 頭像下面的號次章會凸出來,名字往下讓一點 */ +.rgf-score .cand-badge { margin-bottom: 10px; } +.rgf-score > b { font-family: var(--font-num); font-size: 44px; line-height: 1; font-variant-numeric: tabular-nums; } +.rgf-score > b i { font-style: normal; margin: 0 4px; color: var(--muted); } +.rgf-round { display: grid; gap: 6px; animation: rgf-rise 260ms var(--ease-out) both; } +.rgf-topic { margin: 0; font-size: 16px; } +.rgf-topic b { font-family: var(--font-serif); font-size: 22px; } +.rgf-tell { + margin: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 12px; + border: 2px dashed var(--ink); border-radius: 12px; background: var(--surface-2); font-size: 15px; +} +.rgf-score > b { position: relative; } +.rgf-combo { + position: absolute; left: 50%; top: 100%; translate: -50% 4px; white-space: nowrap; font-style: normal; font-family: var(--font-sans, inherit); + font-size: 13px; font-weight: 900; padding: 2px 10px; border-radius: 999px; background: var(--stamp); color: #fff; + animation: rgf-pop 240ms var(--ease-out) both; +} +.rgf-sure { color: #1f8a4c; } +.rgf-legend { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; font-size: 12px; } +.rgf-legend li { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 999px; background: var(--surface-2); } +.rgf-legend small { color: var(--muted); font-weight: 700; } +.rgf-legend .m-policy svg, .rgf-arg.m-policy svg { color: #2f7f8f; } +.rgf-legend .m-emotion svg, .rgf-arg.m-emotion svg { color: #d6457a; } +.rgf-legend .m-question svg, .rgf-arg.m-question svg { color: #a3670f; } +.rgf-args { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } +.rgf-arg { position: relative; min-height: 104px; align-content: start; justify-items: start; text-align: left; padding: 10px 12px; animation: rgf-rise 220ms var(--ease-out) both; animation-delay: calc(var(--i, 0) * 40ms); } +.rgf-arg-kind { display: inline-flex; align-items: center; gap: 6px; } +.rgf-arg small { font-size: 14px; color: var(--ink); font-weight: 500; line-height: 1.4; } +.rgf-arg-tag { font-style: normal; font-size: 11px; font-weight: 900; padding: 1px 8px; border-radius: 999px; background: var(--signal); color: var(--ink); } +.rgf-arg-tag.is-best { background: #1f8a4c; color: #fff; } +.rgf-arg.is-best { border-color: #1f8a4c; box-shadow: 4px 4px 0 #1f8a4c; } +.rgf-history li .is-down { color: var(--stamp); } +.rgf-move { + min-height: 96px; display: grid; justify-items: center; align-content: center; gap: 4px; padding: 10px 6px; + border: 3px solid var(--ink); border-radius: 16px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; + box-shadow: 4px 4px 0 var(--shadow-ink); transition: transform 140ms var(--ease-out), background-color 150ms ease; +} +.rgf-move b { font-family: var(--font-serif); font-size: 18px; } +.rgf-move small { font-size: 12px; color: var(--muted); font-weight: 700; } +.rgf-move.m-policy svg { color: #2f7f8f; } +.rgf-move.m-emotion svg { color: #d6457a; } +.rgf-move.m-question svg { color: #a3670f; } +.rgf-move:active:not(:disabled) { transform: scale(0.97); } +.rgf-move:disabled { opacity: 0.55; cursor: default; } +@media (hover: hover) and (pointer: fine) { + .rgf-move:hover:not(:disabled) { transform: translateY(-3px); background: color-mix(in srgb, var(--signal) 30%, var(--surface)); } +} +.rgf-history { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; } +.rgf-history li { + display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 8px; + padding: 5px 10px; border-radius: 10px; background: var(--surface-2); font-size: 14px; + animation: rgf-rise 220ms var(--ease-out) both; +} +.rgf-history li b { padding: 0 8px; border-radius: 999px; font-size: 12px; background: var(--muted); color: var(--surface); } +.rgf-history li.r-win b { background: #1f8a4c; color: #fff; } +.rgf-history li.r-lose b { background: var(--stamp); color: #fff; } + +.rgf-verdict { display: grid; justify-items: center; gap: 6px; padding: 12px; text-align: center; animation: rgf-pop 280ms var(--ease-out) both; } +.rgf-verdict b { font-family: var(--font-serif); font-size: 30px; } +.rgf-verdict > span { color: var(--muted); } +.rgf-verdict.is-sweep { background: color-mix(in srgb, var(--signal) 45%, var(--surface)); border: 3px solid var(--ink); border-radius: 16px; } +.rgf-verdict.is-sweep svg { color: #b8860b; } +.rgf-stars { display: flex; gap: 4px; } +.rgf-stars svg { color: var(--line); fill: currentColor; } +.rgf-stars svg.is-on { color: #f2a900; } + +/* ── 黑函 ── */ +.rgf-alarm { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border: 3px solid var(--ink); border-radius: 12px; background: var(--stamp); color: #fff; } +.rgf-alarm div { display: grid; } +.rgf-alarm b { font-family: var(--font-serif); font-size: 22px; } +.rgf-alarm small { font-size: 12px; opacity: 0.85; } +.rgf-crisis-text { margin: 0; font-size: 16px; line-height: 1.7; } +.rgf-crisis-text b.is-down { font-family: var(--font-num); font-size: 20px; } + +/* ── 民調 ── */ +.rgf-pollbars { display: grid; gap: 10px; } +.rgf-pollrow { display: grid; grid-template-columns: auto 5.5em minmax(0, 1fr) auto; align-items: center; gap: 8px; } +.rgf-pollname { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rgf-polltrack { height: 22px; border: 2px solid var(--ink); border-radius: 8px; background: var(--surface-2); overflow: hidden; } +.rgf-polltrack i { display: block; height: 100%; width: 100%; transform-origin: left center; transform: scaleX(var(--w, 0)); animation: rgf-grow 600ms var(--ease-out) both; } +.rgf-pollrow b { font-family: var(--font-num); font-size: 22px; font-variant-numeric: tabular-nums; } +.rgf-pollnote { margin: 0; padding: 8px 12px; border-radius: 12px; background: var(--surface-2); font-weight: 800; text-align: center; } +.rgf-pollnote.is-lead { background: color-mix(in srgb, var(--signal) 50%, var(--surface)); } + +/* ── 下一站:三扇門 ── */ +.rgf-doors { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; } +.rgf-door { + display: grid; justify-items: center; align-content: start; gap: 6px; min-height: 170px; padding: 16px 12px 14px; + border: 3px solid var(--ink); border-radius: 18px 18px 12px 12px; color: var(--ink); font: inherit; cursor: pointer; text-align: center; + background: linear-gradient(180deg, color-mix(in srgb, var(--door) 28%, var(--surface)), var(--surface) 75%); + box-shadow: 4px 4px 0 var(--shadow-ink); + transition: transform 160ms var(--ease-out); + animation: rgf-rise 300ms var(--ease-out) calc(var(--i, 0) * 70ms) both; +} +.rgf-door b { font-family: var(--font-serif); font-size: 20px; } +.rgf-door small { color: var(--muted); font-size: 13px; line-height: 1.4; } +.rgf-door-icon { display: grid; place-items: center; width: 64px; height: 64px; border-radius: 50%; background: var(--door); color: #fff; border: 3px solid var(--ink); } +.rgf-door-icon.is-small { width: 38px; height: 38px; border-width: 2px; flex: none; } +.rgf-door:active:not(:disabled) { transform: scale(0.97); } +.rgf-door:disabled { opacity: 0.6; cursor: default; } +@media (hover: hover) and (pointer: fine) { + .rgf-door:hover:not(:disabled) { transform: translateY(-5px); } +} +.rgf-stophead { display: flex; align-items: center; gap: 10px; } + +/* ── 選牌、幕僚 ── */ +.rgf-options { display: flex; flex-wrap: wrap; justify-content: center; gap: 14px; padding: 12px 0 4px; } +.rgf-option { padding: 0; border: 0; background: none; cursor: pointer; transition: transform 160ms var(--ease-out); animation: rgf-rise 320ms var(--ease-out) calc(var(--i, 0) * 80ms) both; } +.rgf-option .rgc { --rgc-w: 150px; } +.rgf-option:active:not(:disabled) { transform: scale(0.97); } +@media (hover: hover) and (pointer: fine) { + .rgf-option:hover:not(:disabled) { transform: translateY(-6px); } +} + +/* ── 從牌組挑一張 ── */ +.rgf-picker { display: grid; gap: 12px; } +.rgf-deckgrid { display: flex; flex-wrap: wrap; justify-content: center; gap: 16px 12px; padding: 12px 4px 4px; max-height: 46vh; overflow-y: auto; } +.rgf-deckcard { position: relative; padding: 0; border: 0; background: none; cursor: pointer; transition: transform 140ms var(--ease-out); } +.rgf-deckcard .rgc { --rgc-w: 104px; } +.rgf-deckcard[aria-selected="true"] { transform: translateY(-6px); } +.rgf-deckcard:disabled { cursor: default; } +.rgf-count { position: absolute; right: -6px; bottom: -6px; z-index: 3; padding: 0 7px; border-radius: 999px; border: 2px solid var(--ink); background: var(--signal); color: #111419; font-family: var(--font-num); font-weight: 800; font-size: 13px; } +.rgf-confirm { display: grid; justify-items: center; gap: 10px; padding: 12px; border: 3px solid var(--ink); border-radius: 16px; background: var(--surface-2); animation: rgf-pop 240ms var(--ease-out) both; } +.rgf-compare { display: flex; align-items: center; justify-content: center; gap: 10px; flex-wrap: wrap; padding-top: 10px; } +.rgf-compare .rgc { --rgc-w: 128px; } +.rgf-remove-note { margin: 0; font-size: 16px; } +.rgf-confirm-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; } +.rgf-empty { margin: 0; padding: 16px; text-align: center; color: var(--muted); } + +/* ── 商店 ── */ +.rgf-wallet { margin: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 16px; } +.rgf-wallet b { font-family: var(--font-num); font-size: 24px; font-variant-numeric: tabular-nums; } +.rgf-wallet small { color: var(--muted); font-size: 12px; margin-left: 6px; } +.rgf-shelf { display: flex; flex-wrap: wrap; justify-content: center; gap: 18px 14px; padding: 12px 0 4px; } +.rgf-item { position: relative; display: grid; justify-items: center; gap: 8px; padding: 0; border: 0; background: none; color: var(--ink); font: inherit; cursor: pointer; transition: transform 160ms var(--ease-out); animation: rgf-rise 300ms var(--ease-out) calc(var(--i, 0) * 60ms) both; } +.rgf-item .rgc { --rgc-w: 128px; } +.rgf-item .rga { width: 150px; } +.rgf-price { padding: 2px 12px; border-radius: 999px; border: 2px solid var(--ink); background: var(--signal); color: #111419; font-family: var(--font-num); font-weight: 800; font-size: 15px; } +.rgf-price.is-short { background: var(--surface-2); color: var(--stamp); } +.rgf-item:disabled { cursor: default; } +.rgf-item:disabled:not(.is-sold) > :first-child { filter: grayscale(0.8); opacity: 0.6; } +.rgf-item.is-sold > :first-child { opacity: 0.35; } +.rgf-sold { position: absolute; inset: 0 0 34px; display: grid; place-items: center; color: #1f8a4c; } +.rgf-item:active:not(:disabled) { transform: scale(0.97); } +@media (hover: hover) and (pointer: fine) { + .rgf-item:hover:not(:disabled) { transform: translateY(-5px); } +} + +/* ── 深入基層 ── */ +.rgf-steps { list-style: none; margin: 0; padding: 0; display: flex; justify-content: center; gap: 8px; } +.rgf-steps li { width: 34px; height: 8px; border-radius: 4px; background: var(--surface-2); border: 1.5px solid var(--line); } +.rgf-steps li.is-done { background: var(--ink); border-color: var(--ink); } +.rgf-steps li.is-now { background: var(--signal); border-color: var(--ink); } +.rgf-meet { display: grid; gap: 10px; animation: rgf-rise 260ms var(--ease-out) both; } +.rgf-who { margin: 0; font-size: 15px; } +.rgf-who b { font-family: var(--font-serif); font-size: 19px; } +.rgf-notes { margin: 0; padding-left: 1.3em; display: grid; gap: 4px; font-size: 14px; color: var(--muted); } + +/* ── 地方抉擇 ── */ +.rgf-event-art .card-art { display: block; width: 100%; aspect-ratio: 21 / 9; border-radius: 12px; overflow: hidden; border: 3px solid var(--ink); background: var(--surface-2); } +.rgf-event-art .card-art img { width: 100%; height: 100%; object-fit: cover; display: block; } +.rgf-event-art .card-art svg { display: block; margin: 24px auto; width: 56px; height: 56px; color: var(--muted); } +.rgf-event-text { margin: 0; font-size: 17px; line-height: 1.6; } + +@keyframes rgf-rise { from { opacity: 0; transform: translateY(10px); } } +@keyframes rgf-pop { from { opacity: 0; transform: scale(0.96); } } +@keyframes rgf-grow { from { transform: scaleX(0); } } + +@media (max-width: 560px) { + .rgf-panel { padding: 16px 14px; } + .rgf-panel h2 { font-size: 20px; } + .rgf-scrum { grid-template-columns: minmax(0, 1fr); justify-items: center; } + .rgf-scrum .rgf-bubble { grid-column: 1; grid-row: auto; font-size: 16px; } + .rgf-score > b { font-size: 34px; } + .rgf-args { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; } + .rgf-arg { min-height: 88px; padding: 8px 10px; } + .rgf-move { min-height: 84px; padding: 8px 4px; } + .rgf-move b { font-size: 16px; } + .rgf-doors { grid-template-columns: minmax(0, 1fr); } + .rgf-door { min-height: 0; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; justify-items: start; text-align: left; column-gap: 12px; row-gap: 2px; padding: 12px; } + .rgf-door .rgf-door-icon { grid-row: 1 / 3; width: 52px; height: 52px; } + .rgf-option .rgc, .rgf-item .rgc, .rgf-compare .rgc { --rgc-w: 118px; } + .rgf-deckcard .rgc { --rgc-w: 92px; } + .rgf-pollrow { grid-template-columns: auto minmax(0, 1fr) auto; } + .rgf-pollrow .rgf-polltrack { grid-column: 1 / -1; grid-row: 2; } +} + +@media (prefers-reduced-motion: reduce) { + .rgf-choices li, .rgf-round, .rgf-history li, .rgf-verdict, .rgf-arg, .rgf-combo, .rgf-door, .rgf-option, .rgf-confirm, .rgf-item, .rgf-meet { animation: rg-fade 200ms ease both; } + .rgf-polltrack i { animation: none; } + .rgf-choice, .rgf-move, .rgf-door, .rgf-option, .rgf-deckcard, .rgf-item { transition: none; } +} diff --git a/web/src/game/rogue/rogue-start.css b/web/src/game/rogue/rogue-start.css new file mode 100644 index 0000000..4ecb0d9 --- /dev/null +++ b/web/src/game/rogue/rogue-start.css @@ -0,0 +1,76 @@ +/* 選戰卡牌:開始畫面(新手教學、每日一戰、自由選戰)與圖鑑。沿用 rogue.css 的 .rg-start 版型與 tokens.css 的顏色 */ + +/* ── 自由選戰設定 ── */ +.rgs-free { + display: grid; gap: 18px; padding: 18px; scroll-margin-top: 12px; + background: var(--surface); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 4px 4px 0 var(--shadow-ink); + animation: rgs-in 240ms var(--ease-out) both; +} +@keyframes rgs-in { from { opacity: 0; transform: translateY(8px); } } +.rgs-step { display: grid; gap: 10px; } +.rgs-step h2 { margin: 0; display: flex; align-items: center; gap: 8px; font-family: var(--font-serif); font-size: 19px; } +.rgs-step h2 i { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--stamp); color: #fff; font-style: normal; font-family: var(--font-num); font-size: 15px; } +.rgs-seg { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border: 3px solid var(--ink); border-radius: 14px; overflow: hidden; } +.rgs-seg button { min-height: 46px; border: 0; border-left: 2px solid var(--ink); background: var(--surface); color: var(--ink); font: inherit; font-weight: 800; font-size: 16px; cursor: pointer; transition: background-color 150ms ease; } +.rgs-seg button:first-child { border-left: 0; } +.rgs-seg button[aria-pressed="true"] { background: var(--ink); color: var(--surface); } +.rgs-reco { justify-self: start; min-height: 40px; padding: 6px 14px; border: 2px dashed var(--stamp); border-radius: 999px; background: color-mix(in srgb, var(--stamp) 8%, var(--surface)); color: var(--stamp); font: inherit; font-weight: 800; font-size: 14px; cursor: pointer; } +.rgs-chips { display: flex; flex-wrap: wrap; gap: 8px; } +.rgs-chips.is-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(88px, 1fr)); } +.rgs-chips button { + min-height: 44px; padding: 6px 14px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); + font: inherit; font-weight: 700; font-size: 15px; cursor: pointer; transition: background-color 150ms ease, transform 140ms var(--ease-out); +} +.rgs-chips button[aria-pressed="true"] { background: var(--signal); color: var(--signal-ink); box-shadow: 2px 2px 0 var(--shadow-ink); } +.rgs-chips button:active { transform: scale(0.97); } +.rgs-select select { + width: 100%; min-height: 48px; padding: 8px 12px; border: 3px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); + font: inherit; font-size: 16px; font-weight: 700; +} +.rgs-cands { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; } +.rgs-cand { + display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px; min-height: 64px; padding: 10px 14px; text-align: left; + border: 2px solid var(--line); border-radius: 14px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; + transition: transform 140ms var(--ease-out), border-color 150ms ease, background-color 150ms ease; +} +.rgs-cand.is-major { border: 3px solid var(--ink); background: linear-gradient(90deg, color-mix(in srgb, var(--party) 18%, var(--surface)), var(--surface) 70%); } +.rgs-cand[aria-pressed="true"] { border-color: var(--stamp); box-shadow: 0 0 0 3px var(--stamp); } +.rgs-cand:active { transform: scale(0.985); } +.rgs-cand > span:last-child { display: grid; gap: 2px; min-width: 0; } +.rgs-cand b { font-family: var(--font-serif); font-size: 18px; } +.rgs-cand small { color: var(--muted); } +.rgs-cand q { font-size: 13px; font-weight: 700; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.rgs-switch { + display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px; min-height: 56px; padding: 10px 14px; text-align: left; + border: 2px solid var(--ink); border-radius: 14px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; +} +.rgs-switch > span:last-child { display: grid; gap: 2px; } +.rgs-switch small { color: var(--muted); font-size: 13px; } +.rgs-knob { position: relative; width: 50px; height: 28px; border-radius: 999px; border: 2px solid var(--ink); background: var(--surface-2); transition: background-color 180ms ease; } +.rgs-knob::after { content: ""; position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; border-radius: 50%; background: var(--ink); transition: transform 200ms var(--ease-out); } +.rgs-switch[aria-checked="true"] .rgs-knob { background: var(--signal); } +.rgs-switch[aria-checked="true"] .rgs-knob::after { transform: translateX(22px); } +.rgs-asc { display: grid; grid-template-columns: repeat(11, minmax(0, 1fr)); gap: 4px; } +.rgs-asc button { + min-height: 44px; display: grid; place-items: center; padding: 0; border: 2px solid var(--ink); border-radius: 10px; + background: var(--surface); color: var(--ink); font: inherit; font-family: var(--font-num); font-weight: 800; font-size: 16px; cursor: pointer; +} +.rgs-asc button[aria-pressed="true"] { background: var(--stamp); color: #fff; } +.rgs-asc button:disabled { border-style: dashed; border-color: var(--line); color: var(--muted); cursor: not-allowed; } +.rgs-asc-text { margin: 0; font-size: 14px; } +.rgs-asc-all summary { cursor: pointer; font-weight: 700; font-size: 14px; min-height: 32px; display: flex; align-items: center; } +.rgs-asc-all ol { margin: 4px 0 0; padding-left: 1.2em; display: grid; gap: 2px; font-size: 13px; color: var(--muted); } + +/* ── 圖鑑頁 ── */ + +@media (min-width: 760px) { + .rgs-cands { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +@media (max-width: 420px) { + .rgs-asc { grid-template-columns: repeat(6, minmax(0, 1fr)); } +} +@media (prefers-reduced-motion: reduce) { + .rgs-free { animation: rg-fade 200ms ease both; } + .rgs-knob::after, .rgs-cand, .rgs-chips button { transition: none; } +} diff --git a/web/src/game/rogue/rogue.css b/web/src/game/rogue/rogue.css new file mode 100644 index 0000000..2a04da5 --- /dev/null +++ b/web/src/game/rogue/rogue.css @@ -0,0 +1,499 @@ +/* 選戰卡牌(新玩法試玩版):上面狀態列、中間地圖+各區、下面幕僚與手牌。顏色全部沿用 theme/tokens.css */ +.rg { + --rg-gap: 12px; + --rg-card-w: 128px; + display: grid; + grid-template-rows: auto minmax(0, 1fr) auto; + gap: var(--rg-gap); + /* 電腦版一個畫面放得下:地圖和右邊的區吃掉剩下的高度 */ + height: 100dvh; + min-height: 640px; + padding: 10px max(14px, env(safe-area-inset-right, 0px)) 12px max(14px, env(safe-area-inset-left, 0px)); + background: var(--paper); + color: var(--ink); +} +.rg .card-art.is-chip { width: 34px; height: 26px; border-radius: 4px; overflow: hidden; display: grid; place-items: center; } +.rg .card-art.is-chip img { width: 100%; height: 100%; object-fit: cover; } +.rg .card-art.is-chip svg { width: 18px; height: 18px; } + +/* ── 狀態列 ── */ +.rg-hud { + display: grid; + grid-template-columns: minmax(0, 1.2fr) auto minmax(0, 1.4fr) auto; + align-items: center; + gap: 16px; + padding: 10px 14px; + background: var(--surface); + border: 3px solid var(--ink); + border-radius: 16px; + box-shadow: 4px 4px 0 var(--shadow-ink); +} +.rg-hud-week { display: grid; gap: 4px; min-width: 0; } +.rg-race { margin: 0; font-size: 12px; font-weight: 800; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.rg-weeks { display: flex; gap: 4px; list-style: none; margin: 0; padding: 0; } +.rg-weeks li { min-width: 26px; padding: 1px 6px; border-radius: 6px; text-align: center; font-family: var(--font-num); font-weight: 700; font-size: 14px; background: var(--surface-2); color: var(--muted); } +.rg-weeks li.is-done { background: color-mix(in srgb, var(--ink) 18%, var(--surface)); color: var(--ink); } +.rg-weeks li.is-now { background: var(--signal); color: #111419; box-shadow: 0 0 0 2px var(--ink); } +.rg-weeks li.is-vote { background: color-mix(in srgb, var(--stamp) 15%, var(--surface)); color: var(--stamp); } +.rg-weeks li.is-vote.is-now { background: var(--stamp); color: #fff; } +.rg-event { margin: 0; display: grid; font-size: 13px; line-height: 1.4; min-width: 0; } +.rg-event b { font-family: var(--font-serif); font-size: 16px; } +.rg-event span { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rg-stats { display: flex; gap: 14px; margin: 0; } +.rg-stats > div { display: grid; gap: 2px; } +.rg-stats dt { font-size: 11px; color: var(--muted); letter-spacing: 0.06em; } +.rg-stats dd { margin: 0; display: flex; align-items: center; gap: 4px; font-family: var(--font-num); font-weight: 700; font-size: 18px; font-variant-numeric: tabular-nums; } +.rg-pips svg { color: var(--line); fill: currentColor; } +.rg-pips svg.is-on { color: #f2a900; } +.rg-momentum { flex-direction: column; align-items: flex-start !important; gap: 2px !important; } +.rg-mom { display: inline-flex; align-items: center; gap: 2px; } +.rg-mom small { font-family: var(--font-body); font-size: 10px; color: var(--muted); width: 22px; } +.rg-mom i { width: 9px; height: 9px; border-radius: 2px; background: var(--surface-2); border: 1px solid var(--line); } +.rg-poll { display: grid; gap: 4px; min-width: 0; } +.rg-poll-names { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 14px; font-weight: 700; } +.rg-poll-names span { display: inline-flex; align-items: center; gap: 6px; min-width: 0; } +.rg-poll-names b { font-family: var(--font-num); font-size: 22px; font-variant-numeric: tabular-nums; } +.rg-poll small { color: var(--muted); font-size: 11px; } +.rg-hud-tools { display: flex; gap: 6px; } +.rg-tool { display: inline-flex; align-items: center; gap: 4px; padding: 6px 10px; border: 2px solid var(--ink); border-radius: 10px; background: var(--surface); color: var(--ink); font: inherit; font-size: 13px; font-weight: 700; cursor: pointer; } + +/* 支持度條:你|還沒表態|其他人|對手 */ +.rg-bar { display: flex; height: 10px; border-radius: 5px; overflow: hidden; background: var(--surface-2); } +.rg-bar.is-big { height: 16px; border: 2px solid var(--ink); } +.rg-bar i { display: block; height: 100%; transition: width 420ms var(--ease-out); } +.rg-bar i.is-undecided { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--muted) 22%, var(--surface)) 0 4px, color-mix(in srgb, var(--muted) 10%, var(--surface)) 4px 8px); } + +/* ── 中間:地圖+右側 ── */ +.rg-board { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(330px, 1fr); gap: var(--rg-gap); min-height: 0; } +.rg-map { position: relative; min-height: 0; border: 3px solid var(--ink); border-radius: 18px; overflow: hidden; background: var(--surface-2); box-shadow: 4px 4px 0 var(--shadow-ink); } +.rg-map > * { height: 100%; } +.rg-map .map-loading { display: grid; place-items: center; color: var(--muted); } +.rg-toast { + position: absolute; left: 50%; bottom: 14px; translate: -50% 0; z-index: 5; + max-width: calc(100% - 28px); height: auto !important; + margin: 0; padding: 8px 16px; border: 2px solid var(--ink); border-radius: 999px; + background: var(--signal); color: #111419; font-weight: 800; font-size: 14px; text-align: center; + box-shadow: 3px 3px 0 var(--shadow-ink); + animation: rg-toast-in 260ms var(--ease-out) both; +} +@keyframes rg-toast-in { from { opacity: 0; transform: translateY(8px); } } +.rg-side { display: grid; align-content: start; gap: 10px; min-height: 0; overflow-y: auto; padding-right: 4px; scrollbar-width: thin; } + +.rg-intents { background: var(--surface); border: 3px solid var(--ink); border-radius: 14px; padding: 10px 12px; display: grid; gap: 6px; } +.rg-intents h3 { margin: 0; display: flex; align-items: center; gap: 6px; font-family: var(--font-serif); font-size: 16px; } +.rg-intents ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; } +.rg-intent { + width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto auto; align-items: center; gap: 6px; + padding: 5px 8px; border: 1.5px solid var(--line); border-radius: 10px; background: var(--surface-2); color: var(--ink); + font: inherit; font-size: 14px; text-align: left; +} +.rg-intent b { font-family: var(--font-num); font-variant-numeric: tabular-nums; } +.rg-intent.k-attack, .rg-intent.k-smear { border-color: color-mix(in srgb, var(--stamp) 50%, var(--line)); } +.rg-intent.is-cut b { text-decoration: line-through; opacity: 0.55; } +.rg-intent small { color: var(--good, #1f8a4c); font-weight: 700; } +.rg-intent.is-pickable { cursor: pointer; border: 2px solid var(--ink); background: color-mix(in srgb, var(--signal) 30%, var(--surface)); } +.rg-hint { margin: 0; font-size: 12px; color: var(--muted); } + +.rg-towns { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.rg-town > button { + width: 100%; display: grid; gap: 5px; padding: 8px 10px; text-align: left; + border: 2px solid var(--line); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; + transition: transform 140ms var(--ease-out), background-color 150ms ease, border-color 150ms ease; +} +.rg-town > button:disabled { cursor: default; } +.rg-town.is-pickable > button { cursor: pointer; border-color: var(--ink); } +.rg-town.is-best > button { background: color-mix(in srgb, var(--signal) 35%, var(--surface)); box-shadow: 3px 3px 0 var(--shadow-ink); } +.rg-town.is-focus > button { border-color: var(--stamp); } +.rg-town.is-pickable > button:active { transform: scale(0.985); } +@media (hover: hover) and (pointer: fine) { + .rg-town.is-pickable > button:hover { background: color-mix(in srgb, var(--signal) 22%, var(--surface)); } + .rg-town.is-best > button:hover { background: color-mix(in srgb, var(--signal) 50%, var(--surface)); } +} +.rg-town-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.rg-town-head > b { font-family: var(--font-serif); font-size: 16px; } +.rg-office { display: inline-flex; align-items: center; gap: 2px; font-size: 11px; font-weight: 800; padding: 0 6px; border-radius: 999px; background: var(--ink); color: var(--surface); } +.rg-traits { display: inline-flex; flex-wrap: wrap; gap: 4px; } +.rg-trait { font-style: normal; font-size: 11px; font-weight: 700; padding: 0 6px; border-radius: 999px; background: var(--surface-2); color: var(--muted); border: 1px solid var(--line); } +.rg-trait.t-temples { color: #a3480f; border-color: color-mix(in srgb, #a3480f 40%, var(--line)); } +.rg-trait.t-young { color: #1f6fb2; border-color: color-mix(in srgb, #1f6fb2 40%, var(--line)); } +.rg-trait.t-old { color: #7a4fa3; border-color: color-mix(in srgb, #7a4fa3 40%, var(--line)); } +.rg-preview { margin-left: auto; display: inline-flex; align-items: center; gap: 2px; font-style: normal; font-family: var(--font-num); font-weight: 800; font-size: 20px; color: #1f8a4c; font-variant-numeric: tabular-nums; } +.rg-town-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 13px; } +.rg-share { font-family: var(--font-num); font-weight: 700; font-variant-numeric: tabular-nums; } +.rg-share small { font-family: var(--font-body); font-weight: 500; color: var(--muted); font-size: 11px; } +.rg-chip { display: inline-flex; align-items: center; gap: 3px; padding: 0 7px; border-radius: 999px; font-size: 12px; font-weight: 800; font-family: var(--font-num); } +.rg-chip.is-rival { background: color-mix(in srgb, var(--stamp) 14%, var(--surface)); color: var(--stamp); border: 1px solid color-mix(in srgb, var(--stamp) 40%, var(--line)); } +.rg-chip.is-rival.is-cut { text-decoration: line-through; opacity: 0.6; } +.rg-chip.is-shield { background: color-mix(in srgb, #1f8a4c 15%, var(--surface)); color: #1f8a4c; border: 1px solid color-mix(in srgb, #1f8a4c 40%, var(--line)); } +.rg-played .card-art.is-chip { width: 26px; height: 20px; } +.rg-note { font-size: 12px; color: var(--muted); } + +/* ── 下面:幕僚、提示、手牌 ── */ +.rg-bottom { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 6px 16px; } +.rg-bottom > .rg-hand-row { grid-column: 1 / -1; } +.rg-advisors { display: flex; flex-wrap: wrap; gap: 6px; } +.rg-advisor { display: inline-grid; grid-template-columns: auto auto; grid-template-rows: auto auto; column-gap: 6px; align-items: center; padding: 3px 10px 3px 3px; border: 2px solid var(--ink); border-radius: 999px; background: var(--signal); color: #111419; max-width: 240px; } +.rg-advisor .card-art { grid-row: 1 / 3; border-radius: 50%; width: 30px; height: 30px; } +.rg-advisor b { font-size: 13px; line-height: 1.1; } +.rg-advisor small { font-size: 11px; line-height: 1.2; opacity: 0.85; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rg-advisor.is-empty { display: inline-flex; gap: 4px; padding: 6px 12px; background: transparent; color: var(--muted); border-style: dashed; border-color: var(--line); font-size: 12px; } +.rg-action { min-height: 38px; display: flex; align-items: center; } +.rg-action p { margin: 0; font-size: 14px; } +.rg-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.rg-hand-row { display: flex; align-items: flex-end; gap: 14px; } +.rg-hand { flex: 1; display: flex; justify-content: safe center; align-items: flex-end; min-height: 214px; padding: 28px 8px 4px; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; } +.rg-hand.is-empty { align-items: center; justify-content: center; color: var(--muted); margin: 0; } +.rg-hand-card { flex: none; padding: 0; margin: 0 -4px; border: 0; background: none; cursor: pointer; transform: translateY(var(--lift, 0)) rotate(var(--fan, 0deg)); transform-origin: 50% 130%; transition: transform 200ms var(--ease-out); animation: rg-deal 360ms var(--ease-out) calc(var(--i, 0) * 60ms) both; } +@keyframes rg-deal { from { opacity: 0; transform: translateY(40px) rotate(0deg); } } +.rg-hand-card[aria-selected="true"] { transform: translateY(-18px) rotate(0deg); z-index: 2; } +@media (hover: hover) and (pointer: fine) { + .rg-hand-card:hover:not([aria-selected="true"]) { transform: translateY(-10px) rotate(0deg); z-index: 1; } +} +.rg-end { flex: none; display: grid; justify-items: center; gap: 2px; min-width: 160px; padding: 14px 18px; background: var(--stamp); color: #fff; border: 3px solid var(--ink); box-shadow: 4px 4px 0 var(--shadow-ink); } +.rg-end svg { margin-bottom: 2px; } +.rg-end small { font-size: 12px; font-weight: 600; opacity: 0.9; } +.rg-end-label { display: inline-flex; gap: 0.25em; } +.rg-end:disabled { opacity: 0.5; } + +/* ── 疊在上面的視窗 ── */ +.rg-overlay { position: fixed; inset: 0; z-index: 40; display: grid; place-items: center; padding: 16px; background: rgb(17 20 25 / 0.55); animation: rg-fade 200ms ease-out both; } +@keyframes rg-fade { from { opacity: 0; } } +.rg-panel { position: relative; width: min(680px, 100%); max-height: calc(100dvh - 32px); overflow-y: auto; display: grid; gap: 12px; padding: 20px 22px; background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--shadow-ink); animation: rg-pop 260ms var(--ease-out) both; } +@keyframes rg-pop { from { opacity: 0; transform: translateY(10px) scale(0.98); } } +.rg-panel h2 { margin: 0; font-family: var(--font-serif); font-size: 24px; } +.rg-sub { margin: 0; color: var(--muted); font-size: 13px; } +.rg-close { position: absolute; top: 10px; right: 10px; display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; border: 2px solid var(--ink); background: var(--surface); color: var(--ink); cursor: pointer; } +.is-up { color: #1f8a4c; } +.is-down { color: var(--stamp); } +.rg-help ol, .rg-help ul { margin: 0; padding-left: 1.2em; display: grid; gap: 6px; font-size: 14px; line-height: 1.6; } +.rg-help h3 { margin: 4px 0 0; font-family: var(--font-serif); } +.rg-deck ul { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 6px; } +.rg-deck li { padding: 6px 10px; border-radius: 10px; background: var(--surface-2); font-size: 14px; } + +/* ── 開始畫面 ── */ + +@media (max-width: 1100px) { + .rg-hud { grid-template-columns: minmax(0, 1fr) auto; } + .rg-poll { grid-column: 1 / -1; grid-row: 2; } +} +@media (max-width: 900px), (max-height: 640px) { + .rg { --rg-card-w: 112px; height: auto; min-height: 100dvh; } + .rg-bottom { grid-template-columns: minmax(0, 1fr); } + .rg-board { grid-template-columns: minmax(0, 1fr); } + .rg-map { min-height: 46vh; } + .rg-side { max-height: none; overflow: visible; } + .rg-hand-row { flex-direction: column; align-items: stretch; } + .rg-hand { justify-content: flex-start; min-height: 196px; } + .rg-hand-card { transform: none; margin: 0 2px; } + .rg-end { width: 100%; } +} +@media (max-width: 560px) { + .rg-stats { gap: 10px; flex-wrap: wrap; } +} +@media (prefers-reduced-motion: reduce) { + .rg-hand-card, .rg-panel, .rg-toast { animation: rg-fade 200ms ease both; } + .rg-hand-card, .rg-bar i { transition: none; } +} + +/* ── 第二版(docs/22):插旗、預告、爆分、震動、快報、教學、手機 ── */ +.rg-asc { display: inline-flex; align-items: center; gap: 2px; margin-left: 6px; padding: 0 6px; border-radius: 999px; background: var(--ink); color: var(--surface); font-family: var(--font-body); font-size: 11px; vertical-align: 2px; } +.rg-asc.is-daily { background: var(--stamp); color: #fff; } +.rg-flags { gap: 3px !important; } +.rg-flags span { color: var(--muted); } +.rg-flag { flex: none; } +.rg-trait-chip { margin-left: auto; padding: 0 8px; border-radius: 999px; background: color-mix(in srgb, var(--stamp) 14%, var(--surface)); color: var(--stamp); border: 1px solid color-mix(in srgb, var(--stamp) 40%, var(--line)); font-family: var(--font-body); font-size: 12px; font-weight: 800; } +.rg-intent.is-big { border: 2px solid var(--stamp); background: color-mix(in srgb, var(--stamp) 12%, var(--surface)); } +.rg-bigwarn { margin: 0; display: flex; gap: 6px; align-items: flex-start; padding: 6px 8px; border-radius: 8px; background: color-mix(in srgb, var(--stamp) 12%, var(--surface)); color: var(--stamp); font-size: 12px; font-weight: 700; } +.rg-bigwarn svg { flex: none; margin-top: 2px; } +.rg-office.is-warn { background: var(--stamp); } +.rg-power { display: inline-flex; align-items: center; gap: 3px; padding: 4px 10px; border-radius: 999px; border: 2px dashed var(--ink); font-size: 12px; font-weight: 800; } +.rg-corner { position: absolute; top: 8px; right: 8px; z-index: 6; height: auto !important; } +.rg-deck-pile h3 { margin: 6px 0; font-family: var(--font-serif); font-size: 16px; } +.rg-deck-grid { display: flex; flex-wrap: wrap; gap: 16px 12px; padding: 12px 6px 6px; --rg-card-w: 112px; } + +/* 爆分:牌名、加成一個一個跳出來、總票數 */ +.rg-score { + position: absolute; z-index: 7; left: 50%; top: 14px; translate: -50% 0; height: auto !important; + display: grid; justify-items: center; gap: 6px; max-width: calc(100% - 24px); + padding: 10px 16px 12px; border: 3px solid var(--ink); border-radius: 16px; background: var(--surface); box-shadow: 4px 4px 0 var(--shadow-ink); + animation: rg-score-in 220ms var(--ease-out) both; pointer-events: none; +} +@keyframes rg-score-in { from { opacity: 0; transform: translateY(-10px) scale(0.96); } } +.rg-score-title { font-family: var(--font-serif); font-size: 18px; } +.rg-score-notes { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px; } +.rg-score-notes i { font-style: normal; font-size: 12px; font-weight: 800; padding: 1px 8px; border-radius: 999px; background: var(--signal); color: #111419; border: 1.5px solid var(--ink); animation: rg-chip-pop 200ms var(--ease-out) both; } +@keyframes rg-chip-pop { from { opacity: 0; transform: scale(0.9) translateY(4px); } } +.rg-score-total { font-family: var(--font-num); font-size: 34px; line-height: 1; color: #1f8a4c; font-variant-numeric: tabular-nums; animation: rg-total-pop 320ms cubic-bezier(0.34, 1.56, 0.64, 1) both; } +.rg-score-total.is-down { color: var(--stamp); } +@keyframes rg-total-pop { from { opacity: 0; transform: scale(0.6); } } + +/* 畫面震動:只動 transform,設定裡可以關 */ +.rg.is-shake-s .rg-board { animation: rg-shake-s 280ms ease-out; } +.rg.is-shake-l .rg-board { animation: rg-shake-l 440ms ease-out; } +@keyframes rg-shake-s { 20% { transform: translate(-4px, 1px); } 40% { transform: translate(3px, -2px); } 60% { transform: translate(-2px, 1px); } 80% { transform: translate(1px, 0); } } +@keyframes rg-shake-l { 15% { transform: translate(-9px, 3px) rotate(-0.4deg); } 30% { transform: translate(8px, -4px) rotate(0.3deg); } 45% { transform: translate(-6px, 2px); } 60% { transform: translate(4px, -1px); } 80% { transform: translate(-2px, 1px); } } + +/* 每週電視快報 */ +.rg-brief-wrap { z-index: 46; cursor: pointer; } +.rg-brief { + position: relative; width: min(640px, 100%); display: grid; gap: 10px; padding: 0 0 14px; overflow: hidden; cursor: default; + background: #111419; color: #f5f2ea; border: 4px solid #111419; border-radius: 18px; box-shadow: 0 0 0 3px var(--signal), 8px 8px 0 var(--shadow-ink); + animation: rg-tv-on 320ms var(--ease-out) both; +} +@keyframes rg-tv-on { from { opacity: 0; transform: scaleY(0.04) scaleX(0.8); } 60% { opacity: 1; transform: scaleY(1.02) scaleX(1); } } +.rg-brief header { display: flex; align-items: center; gap: 8px; padding: 8px 52px 8px 12px; background: var(--ch); color: var(--ch-ink); font-weight: 800; } +.rg-brief .rg-close { top: 4px; right: 6px; width: 30px; height: 30px; } +.rg-brief-logo { display: inline-flex; align-items: center; gap: 4px; } +.rg-brief-live { padding: 0 6px; border-radius: 4px; background: var(--stamp); color: #fff; font-size: 12px; animation: rg-blink 1.2s steps(2) infinite; } +@keyframes rg-blink { 50% { opacity: 0.4; } } +.rg-brief-kicker { margin: 0 16px; color: var(--signal); font-weight: 800; letter-spacing: 0.1em; font-size: 14px; } +.rg-brief h2 { margin: 0 16px; font-family: var(--font-serif); font-size: clamp(22px, 4.6vw, 30px); line-height: 1.25; } +.rg-brief-poll { margin: 0 16px; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; font-weight: 800; } +.rg-brief-poll b { font-family: var(--font-num); font-size: 22px; } +.rg-brief-poll .rg-bar { border-color: #f5f2ea; } +.rg-brief-top { list-style: none; margin: 0 16px; padding: 0; display: grid; gap: 4px; } +.rg-brief-top li { display: flex; justify-content: space-between; gap: 10px; padding: 4px 10px; border-radius: 8px; background: rgb(255 255 255 / 0.08); font-size: 14px; } +.rg-brief-top li.is-up b { color: #6fdc8c; } +.rg-brief-top li.is-down b { color: #ff8a80; } +.rg-brief-alert { margin: 0 16px; padding: 6px 10px; border-radius: 8px; background: var(--stamp); color: #fff; font-weight: 800; } +.rg-brief-ticker { margin-top: 4px; overflow: hidden; white-space: nowrap; background: var(--signal); color: #111419; font-weight: 700; font-size: 14px; padding: 4px 0; } +.rg-brief-ticker span { display: inline-block; padding-left: 100%; animation: rg-ticker 16s linear infinite; } +@keyframes rg-ticker { to { transform: translateX(-100%); } } +.rg-brief-timer { position: absolute; left: 0; bottom: 0; height: 4px; width: 100%; background: var(--signal); transform-origin: left; animation: rg-timer linear both; } +@keyframes rg-timer { from { transform: scaleX(1); } to { transform: scaleX(0); } } + +/* 新手教學的提示 */ +.rg-coach { + position: fixed; z-index: 47; left: 50%; bottom: calc(env(safe-area-inset-bottom, 0px) + 252px); translate: -50% 0; + width: min(560px, calc(100% - 24px)); display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 6px 10px; align-items: start; + padding: 12px 14px; border: 3px solid var(--ink); border-radius: 16px; background: var(--signal); color: #111419; box-shadow: 5px 5px 0 var(--shadow-ink); + animation: rg-pop 260ms var(--ease-out) both; +} +.rg-coach p { margin: 0; font-size: 15px; line-height: 1.55; font-weight: 600; } +.rg-coach-actions { grid-column: 1 / -1; display: flex; justify-content: flex-end; gap: 8px; } +.rg-coach-actions .btn { min-height: 40px; } +.rg[data-coach="hud"] [data-coach-area="hud"], +.rg[data-coach="intents"] [data-coach-area="intents"], +.rg[data-coach="hand"] [data-coach-area="hand"], +.rg[data-coach="map"] [data-coach-area="map"], +.rg[data-coach="end"] [data-coach-area="end"] { outline: 4px dashed var(--stamp); outline-offset: 3px; } + +/* 教學關卡的地圖:三個里並排 */ +.rg-tmap { display: flex; gap: 10px; padding: 14px; align-items: stretch; background: var(--surface-2); } +.rg-tmap-town { + flex: 1 1 0; min-width: 0; display: grid; align-content: center; justify-items: center; gap: 6px; padding: 12px 6px; + border: 3px solid var(--ink); border-radius: 16px; color: #111419; font: inherit; cursor: pointer; box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 160ms var(--ease-out); +} +.rg-tmap-town b { font-family: var(--font-serif); font-size: 22px; } +.rg-tmap-town small { font-family: var(--font-num); } +.rg-tmap-town.is-best { box-shadow: 0 0 0 4px var(--signal), 3px 3px 0 var(--shadow-ink); } +.rg-tmap-town:disabled { cursor: default; } +.rg-tmap-town:active:not(:disabled) { transform: scale(0.98); } +.rg-tmap-intent { display: inline-flex; align-items: center; gap: 3px; padding: 1px 8px; border-radius: 999px; color: #fff; font-size: 12px; font-weight: 800; } +.rg-map.is-targeting .rg-tmap-town:not(:disabled) { outline: 2px dashed var(--ink); } + +/* 手機:地圖和各區用分頁切換,手牌固定在下面 */ +.rg-tabs { display: none; } +@media (max-width: 760px) { + .rg { --rg-card-w: 92px; --rg-gap: 6px; padding: 6px 8px calc(env(safe-area-inset-bottom, 0px) + 6px); height: 100dvh; min-height: 0; grid-template-rows: auto minmax(0, 1fr) auto auto; } + .rg-hud { grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "week tools" "stats stats" "poll poll"; gap: 4px 8px; padding: 6px 10px; border-radius: 12px; } + .rg-hud-week { grid-area: week; } + .rg-hud-tools { grid-area: tools; align-self: start; } + .rg-tool { padding: 4px 8px; } + .rg-stats { grid-area: stats; justify-content: space-between; gap: 6px; flex-wrap: nowrap; } + .rg-poll { grid-area: poll; } + .rg-weeks li { min-width: 18px; padding: 0 3px; font-size: 12px; } + .rg-event span { display: none; } + .rg-event b { font-size: 14px; } + .rg-stats dt { font-size: 10px; } + .rg-stats dd { font-size: 14px; } + .rg-stats dd svg { width: 13px; height: 13px; } + .rg-pips svg { width: 14px; height: 14px; } + .rg-mom small { width: 18px; font-size: 9px; } + .rg-mom i { width: 7px; height: 7px; } + .rg-poll small { display: none; } + .rg-poll-names { font-size: 13px; } + .rg-poll-names b { font-size: 17px; } + .rg-poll .cand-badge { display: none; } + .rg-board { grid-template-columns: minmax(0, 1fr); min-height: 0; } + .rg-map { min-height: 0; border-radius: 14px; } + .rg-side { display: none; overflow-y: auto; max-height: none; } + .rg.show-list .rg-map { display: none; } + .rg.show-list .rg-side { display: grid; } + .rg-tabs { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; } + .rg-tabs button { min-height: 40px; display: inline-flex; align-items: center; justify-content: center; gap: 4px; border: 2px solid var(--ink); border-radius: 10px; background: var(--surface); color: var(--ink); font: inherit; font-weight: 800; } + .rg-tabs button[aria-pressed="true"] { background: var(--ink); color: var(--surface); } + .rg-bottom { grid-template-columns: minmax(0, 1fr); gap: 2px; } + .rg-advisors { flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; } + .rg-advisor.is-empty { display: none; } + .rg-action { min-height: 0; } + .rg-action p { font-size: 12px; line-height: 1.4; } + .rg-hand-row { flex-direction: row; align-items: center; gap: 6px; } + .rg-hand { min-height: 150px; padding: 14px 2px 2px; justify-content: flex-start; } + .rg-hand-card { transform: none; margin: 0 2px; } + .rg-hand-card[aria-selected="true"] { transform: translateY(-8px); } + .rg-end { width: 84px; min-width: 0; padding: 10px 6px; font-size: 14px; line-height: 1.25; } + .rg-end-label { flex-direction: column; align-items: center; gap: 0; white-space: nowrap; } + .rg-end small { display: none; } + .rg-coach { bottom: calc(env(safe-area-inset-bottom, 0px) + 186px); } + .rg-score { top: 8px; padding: 8px 12px 10px; } + .rg-score-total { font-size: 26px; } + .rg-corner { top: 6px; right: 6px; } +} +@media (prefers-reduced-motion: reduce) { + .rg-score, .rg-score-notes i, .rg-score-total, .rg-brief, .rg-coach { animation: rg-fade 200ms ease both; } + .rg-brief-ticker span { animation: none; padding-left: 0; } + .rg.is-shake-s .rg-board, .rg.is-shake-l .rg-board { animation: none; } +} + +/* 本週戰果:拉到、被拉走、擋下(18 第 31 項:攻守的效果要看得到) */ +.rg-tally { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } +.rg-tally > span { display: grid; justify-items: center; gap: 2px; padding: 10px 6px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface-2); } +.rg-tally small { font-size: 12px; font-weight: 700; color: var(--muted); } +.rg-tally b { font-family: var(--font-num); font-size: 26px; font-variant-numeric: tabular-nums; } +.rg-tally > span.is-up { background: color-mix(in srgb, #1f8a4c 14%, var(--surface)); } +.rg-tally > span.is-down { background: color-mix(in srgb, var(--stamp) 12%, var(--surface)); } +.rg-tally > span.is-block { background: color-mix(in srgb, #2f7f8f 16%, var(--surface)); } +.rg-tally p { grid-column: 1 / -1; margin: 0; text-align: center; font-size: 14px; } +.rg-tally p b { font-family: var(--font-num); font-size: 16px; } +.is-block { color: #2f7f8f; } +.rg-week-tally { color: var(--ink); font-weight: 700; font-size: 13px; } +.rg-week-tally b { color: #1f8a4c; font-family: var(--font-num); } +.rg-score-block { font-family: var(--font-num); font-size: 20px; color: #2f7f8f; animation: rg-total-pop 320ms cubic-bezier(0.34, 1.56, 0.64, 1) 80ms both; } +@media (max-width: 760px) { + .rg-poll .rg-poll-note:has(.rg-week-tally) { display: block; } + .rg-tally b { font-size: 21px; } +} + +/* 狀態列:今天開票預估(含聲勢帶出的未表態) */ +.rg-forecast b { font-variant-numeric: tabular-nums; } +.rg-forecast em { font-style: normal; font-weight: 900; margin-left: 4px; } +.rg-forecast em.is-up { color: #1f8a4c; } +.rg-forecast em.is-down { color: var(--stamp); } + +/* 地圖上方的新聞跑馬燈(每週快報不再跳出來,點一下打開電視) */ +.rg-map > .rg-news { + position: absolute; top: 8px; left: 8px; right: 180px; z-index: 3; height: auto; + display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: 8px; + padding: 4px 10px 4px 4px; border: 2px solid var(--ink); border-radius: 999px; + background: color-mix(in srgb, var(--surface) 92%, transparent); color: var(--ink); font: inherit; font-size: 13px; text-align: left; cursor: pointer; + box-shadow: 2px 2px 0 var(--shadow-ink); +} +.rg-news-tag { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 999px; background: var(--stamp); color: #fff; font-weight: 800; white-space: nowrap; } +.rg-news-head { white-space: nowrap; font-weight: 900; } +.rg-news-run { overflow: hidden; white-space: nowrap; color: var(--muted); mask-image: linear-gradient(90deg, transparent, #000 4%, #000 96%, transparent); } +.rg-news-run span { display: inline-block; padding-left: 100%; animation: rg-ticker 28s linear infinite; } +@media (max-width: 760px) { + .rg-map > .rg-news { grid-template-columns: auto minmax(0, 1fr); right: 56px; } + .rg-news-run { display: none; } + .rg-news-head { overflow: hidden; text-overflow: ellipsis; } +} +@media (prefers-reduced-motion: reduce) { .rg-news-run span { animation: none; padding-left: 0; } } + +/* 事件牌(記者堵麥):手牌最前面,紅框、麥克風,點了在手牌上方回答 */ +/* 事件牌和牌之間留空,不疊在第一張牌上 */ +.rg-event-card { width: var(--rg-card-w); margin-right: 26px; } +.rg-event-face { + display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: 6px; width: var(--rg-card-w); aspect-ratio: 5 / 7; padding: 10px; + border: 3px solid var(--stamp); border-radius: 14px; background: color-mix(in srgb, var(--stamp) 10%, var(--surface)); color: var(--ink); + box-shadow: 3px 3px 0 var(--shadow-ink); text-align: left; +} +.rg-event-card[aria-selected="true"] .rg-event-face { box-shadow: 0 0 0 4px var(--signal), 3px 3px 0 var(--shadow-ink); } +.rg-event-kind { display: inline-flex; align-items: center; gap: 4px; font-weight: 900; color: var(--stamp); font-size: 14px; } +.rg-event-text { font-size: 13px; line-height: 1.45; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 6; -webkit-box-orient: vertical; } +.rg-event-face em { font-style: normal; justify-self: start; padding: 1px 8px; border-radius: 999px; background: var(--stamp); color: #fff; font-size: 12px; font-weight: 800; animation: rg-blink 1.6s ease-in-out infinite; } +/* 回答記者:選項排在手牌上方 */ +.rg-answer { display: grid; gap: 6px; width: 100%; } +.rg-answer-q { margin: 0; font-size: 14px; } +.rg-answer-list { display: flex; flex-wrap: wrap; gap: 6px; } +.rg-answer-list button { display: grid; gap: 2px; text-align: left; padding: 6px 12px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; max-width: 340px; } +.rg-answer-list button b { font-size: 14px; } +.rg-answer-list button small { font-size: 12px; color: var(--muted); } +.rg-answer-list button:disabled { opacity: 0.5; cursor: default; } +@media (hover: hover) and (pointer: fine) { .rg-answer-list button:hover:not(:disabled) { background: color-mix(in srgb, var(--signal) 30%, var(--surface)); } } +@media (prefers-reduced-motion: reduce) { .rg-event-face em { animation: none; } } + +/* 週末面板:結算+下一站,放在右邊(手機在下面),不擋地圖上的跳字 */ +.rg-weekend { + /* 放在狀態列下面,不蓋住狀態列 */ + position: fixed; z-index: 40; top: 132px; bottom: 12px; right: max(12px, env(safe-area-inset-right, 0px)); width: min(500px, 46vw); + display: grid; align-content: start; gap: 10px; padding: 14px; overflow-y: auto; overscroll-behavior: contain; + background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--shadow-ink); + animation: rg-sheet 260ms var(--ease-out) both; +} +@keyframes rg-sheet { from { opacity: 0; transform: translateX(24px); } } +.rg-weekend-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 4px 10px; } +.rg-weekend-head h2 { margin: 0; font-family: var(--font-serif); font-size: 22px; } +.rg-weekend-head span { font-weight: 800; font-size: 14px; } +.rg-weekend-head .is-up { color: #1f8a4c; } +.rg-weekend-head .is-down { color: var(--stamp); } +.rg-tally.is-compact > span { padding: 6px 4px; } +.rg-tally.is-compact b { font-size: 20px; } +.rg-weekend-toggle { justify-self: start; display: inline-flex; align-items: center; gap: 4px; padding: 2px 6px; border: 0; background: none; color: var(--muted); font: inherit; font-size: 13px; font-weight: 700; cursor: pointer; } +.rg-weekend-toggle[aria-expanded="true"] svg { transform: rotate(180deg); } +.rg-weekend-log { display: grid; gap: 4px; } +.rg-weekend-log ol { list-style: none; margin: 0; padding: 0; display: grid; gap: 3px; max-height: 220px; overflow-y: auto; } +.rg-weekend-log li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 8px; font-size: 13px; padding: 3px 6px; border-radius: 8px; background: var(--surface-2); } +.rg-weekend-log li .is-up { color: #1f8a4c; } +.rg-weekend-log li .is-down { color: var(--stamp); } +.rg-weekend-log li .is-block { color: #2f7f8f; } +.rg-weekend-sub { margin: 4px 0 0; font-size: 15px; } +.rg-weekend-go { justify-self: stretch; } +.rg-weekend-skip { justify-self: start; } +.rg-doors { display: grid; gap: 10px; } +.rg-door { display: grid; gap: 8px; padding: 10px; border: 2px solid var(--door); border-radius: 14px; background: color-mix(in srgb, var(--door) 8%, var(--surface)); animation: rg-sheet 260ms var(--ease-out) calc(var(--i, 0) * 60ms) both; } +.rg-door > header { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 2px 8px; } +.rg-door > header small { grid-column: 2; color: var(--muted); font-size: 12px; } +.rg-door-icon { grid-row: span 2; width: 34px; height: 34px; display: grid; place-items: center; border-radius: 10px; background: var(--door); color: #fff; } +.rg-door-go { justify-self: start; } +.rg-door-offers { --rg-card-w: 112px; display: flex; gap: 8px; overflow-x: auto; padding: 4px 2px 6px; } +.rg-door-offer { flex: none; padding: 0; border: 0; background: none; cursor: pointer; border-radius: 14px; transition: transform 160ms var(--ease-out); } +.rg-door-offer:active:not(:disabled) { transform: scale(0.97); } +.rg-door-offer:disabled { opacity: 0.5; cursor: default; } +@media (hover: hover) and (pointer: fine) { .rg-door-offer:hover:not(:disabled) { transform: translateY(-4px); } } +.rg-door-event { display: grid; gap: 6px; } +.rg-door-event p { margin: 0; font-size: 14px; } +.rg-again { display: block; color: var(--muted); font-size: 12px; } +@media (max-width: 760px) { + .rg-weekend { top: auto; left: max(8px, env(safe-area-inset-left, 0px)); right: max(8px, env(safe-area-inset-right, 0px)); bottom: calc(env(safe-area-inset-bottom, 0px) + 8px); width: auto; max-height: 78dvh; animation-name: rg-sheet-up; } + .rg-door-offers { --rg-card-w: 98px; } +} +@keyframes rg-sheet-up { from { opacity: 0; transform: translateY(24px); } } +@media (prefers-reduced-motion: reduce) { .rg-weekend, .rg-door { animation: rg-fade 200ms ease both; } } + +/* 門裡的幕僚:和牌一樣寬,不撐滿面板 */ +.rg-door-offer .rga { width: calc(var(--rg-card-w) * 1.25); } + +/* 換週的轉場:「第 N 週」橫幅從左掃到右(只動 transform、opacity,不擋操作) */ +.rg-weekbanner { + position: absolute; z-index: 5; left: 0; right: 0; top: 38%; height: auto; pointer-events: none; + display: flex; align-items: baseline; justify-content: center; gap: 14px; padding: 12px 20px; + background: var(--stamp); color: #fff; border-block: 4px solid #111419; box-shadow: 0 6px 0 rgb(0 0 0 / 0.25); + animation: rg-banner 1600ms var(--ease-out) both; +} +.rg-weekbanner b { font-family: var(--font-serif); font-size: clamp(32px, 5vw, 56px); text-shadow: 3px 3px 0 #111419; } +.rg-weekbanner span { font-weight: 900; font-size: clamp(16px, 2vw, 22px); } +@keyframes rg-banner { + 0% { opacity: 0; transform: translateX(-60%) skewX(-8deg); } + 18% { opacity: 1; transform: translateX(0) skewX(-8deg); } + 78% { opacity: 1; transform: translateX(0) skewX(-8deg); } + 100% { opacity: 0; transform: translateX(60%) skewX(-8deg); } +} +@media (prefers-reduced-motion: reduce) { .rg-weekbanner { animation: rg-banner-fade 1600ms ease both; } } +@keyframes rg-banner-fade { 0%, 100% { opacity: 0; } 15%, 80% { opacity: 1; } } + +/* 電腦版:收起右邊的各區列表,地圖全寬;對手這週要做的事浮在地圖右上角 */ +.rg-corner { display: flex; gap: 6px; align-items: center; } +.rg-wide-toggle { display: inline-flex; align-items: center; gap: 4px; min-height: 40px; padding: 4px 10px; border: 2px solid var(--ink); border-radius: 999px; background: var(--surface); color: var(--ink); font: inherit; font-weight: 800; font-size: 13px; cursor: pointer; box-shadow: 2px 2px 0 var(--shadow-ink); } +.rg-wide-toggle[aria-pressed="true"] { background: var(--signal); color: #111419; } +.rg.is-wide .rg-board { grid-template-columns: minmax(0, 1fr); } +.rg.is-wide .rg-side { display: none; } +.rg-map > .rg-float-intents { position: absolute; z-index: 4; top: 56px; right: 10px; width: min(360px, 40%); height: auto; max-height: calc(100% - 70px); overflow-y: auto; scrollbar-width: thin; animation: rg-fade 200ms ease both; } +.rg-float-intents .rg-intents { box-shadow: 4px 4px 0 var(--shadow-ink); background: color-mix(in srgb, var(--surface) 94%, transparent); } +@media (max-width: 900px) { + .rg-wide-toggle { display: none; } + .rg.is-wide .rg-side { display: grid; } + .rg.is-wide .rg-board { grid-template-columns: minmax(0, 1fr); } + .rg-map > .rg-float-intents { display: none; } +} diff --git a/web/src/game/rogue/ultimate.css b/web/src/game/rogue/ultimate.css new file mode 100644 index 0000000..28325a3 --- /dev/null +++ b/web/src/game/rogue/ultimate.css @@ -0,0 +1,76 @@ +/* 大絕招(Ultimate.tsx):集氣圈、挑招面板、小遊戲全螢幕。粗黑框、硬陰影,集滿時發光 */ +.ult-btn-wrap { position: relative; align-self: stretch; display: grid; } +.ult-btn { display: grid; grid-template-columns: auto auto; align-items: center; gap: 8px; min-height: 56px; padding: 6px 14px 6px 6px; border: 3px solid #111419; border-radius: 16px; background: #fffaf0; color: #111419; box-shadow: 3px 3px 0 #111419; font: inherit; cursor: pointer; transition: transform 140ms var(--ease-out); } +.ult-btn:disabled { cursor: default; opacity: 0.55; } +.ult-btn:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #111419; } +.ult-btn:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.ult-ring { --p: 0; width: 42px; height: 42px; display: grid; place-items: center; border-radius: 50%; color: var(--stamp); background: radial-gradient(closest-side, #fffaf0 72%, transparent 73%), conic-gradient(var(--stamp) calc(var(--p) * 1%), #e4e1d8 0); } +.ult-label { display: grid; text-align: left; line-height: 1.1; } +.ult-label b { font-family: var(--font-serif); font-size: 16px; } +.ult-label small { font-family: var(--font-num); font-size: 15px; font-weight: 800; color: #5d646e; } +.ult-btn-wrap.is-ready .ult-btn { background: var(--stamp); color: #fff; animation: ult-pulse 1.6s ease-in-out infinite; } +.ult-btn-wrap.is-ready .ult-ring { color: #111419; background: radial-gradient(closest-side, var(--signal) 72%, transparent 73%), conic-gradient(#fff 100%, #fff 0); } +.ult-btn-wrap.is-ready .ult-label small { color: #ffe9a8; } +@keyframes ult-pulse { 50% { box-shadow: 3px 3px 0 #111419, 0 0 0 6px color-mix(in srgb, var(--stamp) 35%, transparent); } } +.ult-tip { position: absolute; bottom: calc(100% + 8px); left: 0; z-index: 6; width: max-content; max-width: 260px; margin: 0; padding: 8px 12px; border: 2px solid #111419; border-radius: 12px; background: #111419; color: #fff; font-size: 13px; font-weight: 700; line-height: 1.4; box-shadow: 3px 3px 0 rgb(0 0 0 / 0.25); animation: gs-fade 160ms ease both; } + +.ult-overlay { z-index: 60; } +.ult-overlay.is-play { padding: 0; place-items: stretch; background: rgb(10 14 22 / 0.86); } +.ult-overlay.is-play > .mg { width: 100%; height: 100%; } +.ult-loading { margin: auto; color: #fff; font-weight: 900; } +.ult-panel { width: min(860px, 100%); max-height: calc(100dvh - 32px); overflow-y: auto; display: grid; gap: 16px; padding: 18px 20px 20px; animation: ult-in 260ms var(--ease-out) both; } +@keyframes ult-in { from { opacity: 0; transform: scale(0.96); } } +.ult-head { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: start; gap: 14px; } +.ult-head h2 { margin: 0; font-family: var(--font-serif); font-size: 28px; } +.ult-head p { margin: 4px 0 0; color: var(--muted); font-weight: 600; } +.ult-burst { width: 56px; height: 56px; display: grid; place-items: center; border: 3px solid #111419; border-radius: 16px; background: var(--stamp); color: #fff; transform: rotate(-6deg); box-shadow: 3px 3px 0 #111419; } +.ult-close { width: 44px; height: 44px; display: grid; place-items: center; border: 3px solid #111419; border-radius: 50%; background: #fffaf0; color: #111419; cursor: pointer; } +.ult-close:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } +.ult-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; } +.ult-card { width: 100%; height: 100%; display: grid; justify-items: start; align-content: start; gap: 6px; padding: 16px; text-align: left; border: 3px solid #111419; border-radius: 18px; background: #fffaf0; color: #111419; box-shadow: 4px 4px 0 #111419; font: inherit; cursor: pointer; transition: transform 160ms var(--ease-out); } +.ult-card:active { transform: translate(2px, 2px); box-shadow: 2px 2px 0 #111419; } +.ult-card:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.ult-card-ic { width: 54px; height: 54px; display: grid; place-items: center; border: 3px solid #111419; border-radius: 14px; color: #fff; } +.ult-card.is-rally .ult-card-ic { background: var(--stamp); } +.ult-card.is-handshake .ult-card-ic { background: #1f8a4c; } +.ult-card.is-billboard .ult-card-ic { background: #2f6fd1; } +.ult-card b { font-family: var(--font-serif); font-size: 21px; } +.ult-card-game { padding: 0 8px; border-radius: 999px; background: var(--signal); font-size: 12px; font-weight: 900; } +.ult-card small { color: #5d646e; font-size: 14px; font-weight: 700; } +@media (hover: hover) and (pointer: fine) { .ult-card:hover { transform: translateY(-3px); } } +.ult-towns { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; max-height: 46vh; overflow-y: auto; } +.ult-towns button { width: 100%; min-height: 52px; display: grid; gap: 2px; padding: 6px 12px; text-align: left; border: 2px solid var(--line); border-radius: 12px; background: var(--surface); color: var(--ink); font: inherit; cursor: pointer; } +.ult-towns button[aria-pressed="true"] { border: 3px solid #111419; background: var(--signal); color: #111419; } +.ult-towns button:disabled { opacity: 0.45; cursor: default; } +.ult-towns b { font-size: 15px; } +.ult-towns small { font-size: 12px; font-weight: 800; } +.ult-towns .is-ahead { color: var(--good); } +.ult-towns .is-behind { color: var(--stamp); } +.ult-towns button[aria-pressed="true"] small { color: #111419; } +.ult-foot { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; } +@media (max-width: 720px) { + .ult-cards { grid-template-columns: minmax(0, 1fr); } + .ult-card { grid-template-columns: auto minmax(0, 1fr); column-gap: 12px; } + .ult-card-ic { grid-row: span 3; } + .ult-btn { padding-right: 10px; } + .ult-label b { font-size: 14px; } +} +@media (prefers-reduced-motion: reduce) { + .ult-btn-wrap.is-ready .ult-btn { animation: none; } + .ult-panel { animation: gs-fade 200ms ease both; } +} + +/* 疊在「結束這週」上面 */ +.rg-end-col { flex: none; display: grid; gap: 8px; align-content: end; } +.rg-end-col .ult-btn-wrap { align-self: auto; } +.rg-end-col .ult-btn { width: 100%; justify-content: center; } +@media (max-width: 720px) { + .rg-end-col { gap: 6px; } + .rg-end-col .ult-btn { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 2px; min-height: 0; padding: 6px 4px; } + .rg-end-col .ult-ring { width: 32px; height: 32px; } + .rg-end-col .ult-ring svg { width: 16px; height: 16px; } + .rg-end-col .ult-label { text-align: center; } + .rg-end-col .ult-label b { font-size: 13px; } + .rg-end-col .ult-label small { font-size: 12px; } + .ult-tip { left: auto; right: 0; } +} diff --git a/web/src/game/rogue/weekend.tsx b/web/src/game/rogue/weekend.tsx new file mode 100644 index 0000000..faa7084 --- /dev/null +++ b/web/src/game/rogue/weekend.tsx @@ -0,0 +1,213 @@ +import type { RogueLog, RogueRoute, RogueStop, RogueView } from "@election2026/protocol"; +import { ArrowRight, ChevronDown, Coins, Flag, Shield } from "lucide-react"; +import { useEffect, useState } from "react"; +import { CandidateBadge } from "../art/Badge.tsx"; +import { sfx } from "../audio/sfx.ts"; +import { OfferFace } from "./cards.tsx"; +import { ChoiceList, STOP_STYLE } from "./flow.tsx"; +import { num, overall, signed } from "./labels.ts"; + +/** + * 週末(docs/23 流程整合):結算和下一站放在同一個畫面。 + * - 結算一筆一筆在地圖上冒出票數(onStep),不用按繼續;旁邊一張「本週戰果」。 + * - 下一站三扇門直接攤開內容:拜會地方的三張牌、幕僚、地方抉擇的選項,點一下就拿到;其他站點了再進門。 + * - 最後一週:只有戰果和「開票!」。 + * 面板放在畫面右邊(手機在下面),地圖上的跳字看得到。 + */ + +const STEP_MS = 260; +const lead = (x: number) => (x >= 0 ? `領先 ${(x * 100).toFixed(1)}` : `落後 ${(-x * 100).toFixed(1)}`); + +type Choose = (pick: number | "skip", option?: number) => void; + +export function WeekEnd({ + view, + log, + busy, + onStep, + onChoose, + onFinale, +}: { + view: RogueView; + /** 這週結算的紀錄(剛結束這週時有;重新整理後是 null,只顯示下一站) */ + log: readonly RogueLog[] | null; + busy: boolean; + onStep: (entry: RogueLog, i: number) => void; + onChoose: Choose; + onFinale: () => void; +}) { + const entries = log ?? []; + const [shown, setShown] = useState(0); + const [open, setOpen] = useState(false); + const playing = shown < entries.length; + // 結算在地圖上一筆一筆播(不擋操作,隨時可以選下一站) + useEffect(() => { + if (!playing) return; + const t = setTimeout(() => { + const e = entries[shown]!; + onStep(e, shown); + if (e.text.includes("翻轉")) sfx.flag(); + else if (e.side === "rival" && Math.abs(e.votes) > 0) sfx.bad(); + setShown(shown + 1); + }, shown === 0 ? 200 : STEP_MS); + return () => clearTimeout(t); + }, [shown, playing, entries, onStep]); + useEffect(() => sfx.shuffle(), []); + + const finished = view.phase === "finished"; + const t = view.tally; + const now = overall(view.towns); + const before = t.startYou - t.startRival; + const after = now.youShare - now.rivalShare; + return ( + + ); +} + +/** 一扇門:能直接選的(牌、幕僚、地方抉擇)把內容攤開;其他的點了進門 */ +function Door({ route, index, view, busy, onChoose }: { route: RogueRoute; index: number; view: RogueView; busy: boolean; onChoose: Choose }) { + const { Icon, color } = STOP_STYLE[route.kind]; + const preview = route.preview; + return ( +
    +
    + + + + {route.title} + {route.text} +
    + {preview ? ( + onChoose(index, k)} /> + ) : ( + + )} +
    + ); +} + +function DoorPreview({ preview, view, busy, onPick }: { preview: RogueStop; view: RogueView; busy: boolean; onPick: (k: number) => void }) { + if (preview.kind === "card" || preview.kind === "advisor") { + const full = preview.kind === "advisor" && view.advisors.length >= view.advisorSlots; + return ( +
    + {preview.options.map((o, k) => ( + + ))} + {full &&

    幕僚已經滿了。

    } +
    + ); + } + if (preview.kind === "event") { + return ( +
    +

    + {preview.title} {preview.text} +

    + +
    + ); + } + return null; +} diff --git a/web/src/game/screens.css b/web/src/game/screens.css new file mode 100644 index 0000000..7508bb2 --- /dev/null +++ b/web/src/game/screens.css @@ -0,0 +1,71 @@ +/* 場景卡、快訊、總部、民調中心、結局、標題插圖、設定 */ + +/* ── 競選總部 ── */ +.hq { display: grid; gap: 14px; } +.hq h2 { margin: 0; font-family: var(--font-serif); font-size: 22px; } +.staff-avatar { border-radius: 50%; overflow: hidden; display: inline-block; flex: none; background: var(--surface-2); } +.staff-avatar .avatar { display: block; width: 100%; height: auto; transform: translateY(6%) scale(1.25); } + +/* ── 標題插圖 ── */ +.hero { position: relative; padding: 0; border-radius: 18px; overflow: hidden; box-shadow: 0 10px 40px rgb(60 40 20 / 0.15); } +.hero .scene { display: block; } + +/* ── 設定 ── */ +.settings { position: relative; } +.settings-menu { position: absolute; right: 0; top: calc(100% + 6px); background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; box-shadow: 0 10px 30px rgb(0 0 0 / 0.15); display: grid; gap: 8px; min-width: 200px; z-index: 10; transform-origin: top right; animation: modal-in 160ms var(--ease-out); } +.settings-menu label { display: flex; align-items: center; justify-content: space-between; gap: 12px; font-size: 14px; } +.settings-menu select { min-height: 44px; padding: 2px 8px; border: 2px solid var(--ink); border-radius: 8px; background: var(--surface); color: var(--ink); font: inherit; font-size: 14px; } +.icon-btn { display: inline-grid; place-items: center; width: 34px; height: 34px; border-radius: 10px; background: var(--surface-2); border: 1px solid var(--line); color: var(--ink); } + +/* ── 開始畫面:選舉種類、縣市、選區 ── */ +.creator-cta { display: grid; grid-template-columns: 1fr auto; gap: 8px 14px; align-items: center; background: var(--surface-2); border: 1px dashed var(--line); border-radius: 14px; padding: 12px 14px; } +.creator-cta p { margin: 2px 0 0; } + +/* ── 捏人物 ── */ +.creator { max-width: 1180px; margin: 0 auto; padding: 16px; display: grid; gap: 14px; } +.creator-head { display: flex; align-items: center; gap: 14px; } +.creator-head h1 { margin: 0; font-family: var(--font-serif); font-size: 28px; } +.creator-grid { display: grid; grid-template-columns: minmax(240px, 320px) minmax(0, 1fr); gap: 18px; align-items: start; } +@media (max-width: 820px) { .creator-grid { grid-template-columns: minmax(0, 1fr); } } +.creator-preview { position: sticky; top: 12px; display: grid; gap: 12px; justify-items: center; background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 16px; } +@media (max-width: 820px) { .creator-preview { position: static; } } +.creator-preview .avatar { border-radius: 18px; max-width: 100%; height: auto; } +.creator-preview .poster { width: 100%; } +.creator-form { display: grid; gap: 14px; } +.creator-form fieldset { border: 1px solid var(--line); border-radius: 14px; background: var(--surface); padding: 12px 14px; display: grid; gap: 12px; margin: 0; } +.creator-form legend { font-weight: 900; font-family: var(--font-serif); font-size: 18px; padding: 0 6px; } +.field { display: grid; gap: 6px; font-size: 14px; font-weight: 700; } +.field small { font-weight: 400; } +.chips { display: flex; flex-wrap: wrap; gap: 6px; } +.bg-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 6px; } +.bg-card { display: grid; gap: 2px; text-align: left; background: var(--surface-2); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; } +.bg-card small { color: var(--muted); font-size: 12px; font-weight: 400; } +.bg-card.is-on { border-color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); } +.creator-actions { display: flex; justify-content: flex-end; gap: 10px; } + +/* ── 手牌與出牌桌 ── */ +.hand { display: flex; justify-content: safe center; align-items: flex-start; gap: 0; padding: 18px 14px 4px; height: 218px; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; } +.hand.is-empty { align-items: center; color: var(--muted); font-size: 14px; min-height: 80px; } +.card-art { display: grid; place-items: center; aspect-ratio: 4 / 3; max-width: 100%; background: color-mix(in srgb, var(--ink) 10%, var(--surface-2)); color: var(--muted); overflow: hidden; border-radius: 8px; } +.card-art img { width: 100%; height: 100%; object-fit: cover; display: block; } +.card-art.is-large { aspect-ratio: 16 / 9; border-radius: 12px; } +.card-art.is-mini { width: 44px; height: 33px; aspect-ratio: auto; border-radius: 6px; flex: none; } +.card-art.is-scene { aspect-ratio: 4 / 3; border-radius: 0; width: 100%; } +@media (max-width: 720px) { + .hand { justify-content: flex-start; height: 196px; padding-top: 14px; } + .hand .card-art { aspect-ratio: 16 / 11; } +} +.stage.is-targeting .districts path { cursor: crosshair; } +@media (hover: hover) and (pointer: fine) { + .stage.is-targeting .districts path:hover { filter: brightness(1.18) saturate(1.2); } +} +.played { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.played li { display: flex; align-items: center; gap: 8px; background: var(--surface-2); border-radius: 10px; padding: 5px 6px; } +.played li > span { display: grid; flex: 1; min-width: 0; font-size: 14px; } +.played small { color: var(--muted); font-size: 12px; } + +/* ── 表態卡 ── */ +.card-art.is-event { aspect-ratio: 16 / 9; border-radius: 12px; } + +/* 虛構對決 */ +.creator-cta.is-lineup { margin-bottom: 10px; } diff --git a/web/src/game/shop/ShopScreen.tsx b/web/src/game/shop/ShopScreen.tsx new file mode 100644 index 0000000..8b79dc2 --- /dev/null +++ b/web/src/game/shop/ShopScreen.tsx @@ -0,0 +1,397 @@ +import { AVATAR_CATALOG, avatarSlot, shopShelf, shopWeekStart, wearItem, wearSlots, type AvatarItem } from "@election2026/protocol"; +import { Check, Coins, Lock, ReceiptText, Shirt, ShoppingBag, Sparkles, UserRoundPlus } from "lucide-react"; +import { useEffect, useMemo, useState, type KeyboardEvent } from "react"; +import { Avatar, PARTY_HEX, avatarFromSeed, type AvatarSpec } from "../art/Avatar.tsx"; +import { setMusic } from "../audio/music.ts"; +import { sfx } from "../audio/sfx.ts"; +import { loadCharacters, saveCharacter } from "../creator/characters.ts"; +import { partySlot } from "../parties.ts"; +import { loadProgress } from "../rogue/progress.ts"; +import { ConfirmDialog } from "../ui/ConfirmDialog.tsx"; +import { GameScene, SceneStat } from "../ui/GameScene.tsx"; +import { RARITY_TEXT, itemState, wear } from "./unlocks.ts"; +import { buyItem, onShelf, totalCoins, useWardrobe } from "./wardrobe.ts"; +import "./shop.css"; + +/** + * 服裝店(docs/24 第 4 節):用小鎮幣買外觀。直接買、可以先試穿、不抽獎。 + * 每週一換貨:本週上架 6 件(用週數當亂數,所有人看到一樣)、基本款一直都在、選舉季限定每年同一個時候回來; + * 每件一年內一定會再上架。左邊是試衣間(自己存的角色當模特兒),右邊是貨架、全部部件(沒拿到的寫怎麼拿到)和小鎮幣紀錄。 + */ + +type ShelfTab = "shop" | "all" | "log"; +const TABS: { id: ShelfTab; label: string }[] = [ + { id: "shop", label: "店裡" }, + { id: "all", label: "全部部件" }, + { id: "log", label: "小鎮幣紀錄" }, +]; + +const MANNEQUIN = avatarFromSeed("shop-mannequin", { female: false, outfit: "suit" }); +const ZOOM: Record = { hat: "is-head", mask: "is-face" }; + +const md = (date: string) => `${Number(date.slice(5, 7))} 月 ${Number(date.slice(8, 10))} 日`; + +/** 下一次上架是哪一週的星期一(一年內一定找得到) */ +function nextShelfDate(item: AvatarItem, now: Date): string | null { + for (let k = 1; k <= 60; k++) { + const t = +now + k * 7 * 86_400_000; + if (onShelf(item, t)) return shopWeekStart(shopShelf(t).week); + } + return null; +} + +export function ShopScreen({ initialItem }: { initialItem: string | null }) { + const wardrobe = useWardrobe(); + const [progress] = useState(loadProgress); + const [chars, setChars] = useState(loadCharacters); + const [charId, setCharId] = useState(chars[0]?.id ?? null); + const [tab, setTab] = useState("shop"); + const [picked, setPicked] = useState(initialItem && wearItem(initialItem) ? initialItem : null); + const [asking, setAsking] = useState(false); + const [msg, setMsg] = useState(null); + const [now] = useState(() => new Date()); + const shelf = useMemo(() => shopShelf(now), [now]); + + useEffect(() => setMusic("theme-march"), []); + + const char = chars.find((c) => c.id === charId) ?? null; + const base: AvatarSpec = char?.avatar ?? MANNEQUIN; + const partyColor = PARTY_HEX[partySlot(char?.party ?? null)]; + const print = { name: char?.name ?? null }; + const item = picked ? wearItem(picked) : undefined; + const trial = item ? wear(base, item.slot, item.id) : base; + const coins = totalCoins(wardrobe); + const state = (i: AvatarItem) => itemState(i, progress, wardrobe); + + const pick = (id: string) => { + sfx.click(); + setMsg(null); + setPicked((p) => (p === id ? null : id)); + }; + + const buy = () => { + if (!item) return; + setAsking(false); + const r = buyItem(item.id); + if (r.ok) { + sfx.coin(); + setMsg(char ? `買到「${item.name}」了!按「穿上」給${char.name}穿。` : `買到「${item.name}」了!`); + } else { + sfx.bad(); + setMsg(r.reason === "poor" ? "小鎮幣不夠,再去打幾場選戰吧" : r.reason === "owned" ? "已經有了" : "這件這週沒有上架"); + } + }; + + const putOn = (on: boolean) => { + if (!item || !char) return; + saveCharacter({ ...char, avatar: wear(char.avatar, item.slot, on ? item.id : null) }); + setChars(loadCharacters()); + sfx.good(); + setMsg(on ? `${char.name}穿上「${item.name}」了` : `${char.name}脫掉「${item.name}」了`); + }; + + const onTabKey = (e: KeyboardEvent) => { + const i = TABS.findIndex((t) => t.id === tab); + const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0; + if (!step) return; + e.preventDefault(); + const next = TABS[(i + step + TABS.length) % TABS.length]!; + setTab(next.id); + document.getElementById(`sh-tab-${next.id}`)?.focus(); + }; + + const card = (i: AvatarItem) => { + const st = state(i); + const sale = i.get.type === "shop" && onShelf(i, now); + const on = picked === i.id; + const wornNow = base.wear?.[i.slot] === i.id; + return ( +
  • + +
  • + ); + }; + + const nextWeek = md(shopWeekStart(shelf.week + 1)); + + return ( + } value={coins} label="小鎮幣" />} + > +
    +
    +
    +
    + + +
    + {item && !state(item).owned && 試穿中} +
    +
    + {item ? ( + <> +

    + {avatarSlot(item.slot)?.name}・{RARITY_TEXT[item.rarity]} +

    +

    {item.name}

    + {item.desc &&

    {item.desc}

    } + setAsking(true)} + onWear={putOn} + /> + + ) : ( + <> +

    試衣間

    +

    點右邊的衣服就能試穿;喜歡再買。小鎮幣打完一局選戰就會發。

    + + )} + {msg &&

    {msg}

    } +
    +
    + {chars.length === 0 ? ( + sfx.click()}> + 先去捏一個角色,買了才能穿 + + ) : ( + chars.map((c) => ( + + )) + )} +
    +
    + +
    +
    + {TABS.map((t) => ( + + ))} +
    +
    + {tab === "shop" && ( + <> + {shelf.limited.length > 0 && ( + <> +

    + 選舉季限定 每年 11、12 月回來 +

    +
      {shelf.limited.map(card)}
    + + )} +

    + 本週上架 {nextWeek}(星期一)換貨・每件一年內一定會再上架 +

    +
      {shelf.weekly.map(card)}
    +

    + 基本款 一直都買得到 +

    +
      {shelf.always.map(card)}
    + + )} + {tab === "all" && + wearSlots().map((s) => { + const list = AVATAR_CATALOG.items.filter((i) => i.slot === s.id && i.status === "active"); + const got = list.filter((i) => state(i).owned).length; + return ( +
    +

    + {s.name}{" "} + + 拿到 {got}/{list.length} + +

    +
      {list.map(card)}
    +
    + ); + })} + {tab === "log" && } +
    +

    小鎮幣打選戰就會拿到,只能買外觀,不能買變強的東西;不能轉送、不能換現金,沒有使用期限。

    +
    +
    + {asking && item && item.get.type === "shop" && ( + setAsking(false)}> +

    + 買了就是你的,所有自創角色都能穿。現在有 {coins} 小鎮幣,買完剩 {coins - item.get.price}。 +

    +
    + )} +
    + ); +} + +function ItemActions({ + item, + owned, + how, + sale, + coins, + worn, + hasChar, + next, + onBuy, + onWear, +}: { + item: AvatarItem; + owned: boolean; + how: string; + sale: boolean; + coins: number; + worn: boolean; + hasChar: boolean; + next: string | null; + onBuy: () => void; + onWear: (on: boolean) => void; +}) { + if (owned) { + return ( +
    + + 已擁有 + + {hasChar && + (worn ? ( + + ) : ( + + ))} +
    + ); + } + if (item.get.type === "shop") { + const price = item.get.price; + if (!sale) + return ( +
    + + 這週沒有上架{next ? `,${md(next)}那一週回來` : ""} + +
    + ); + return ( +
    + + {coins < price && 還差 {price - coins} 枚} +
    + ); + } + return ( +
    + + 怎麼拿到:{how} + +
    + ); +} + +/** 小鎮幣紀錄:兩本帳(免費取得、付費取得)和每一筆收支 */ +function CoinLog() { + const w = useWardrobe(); + const rows = [...w.log].reverse().slice(0, 60); + return ( +
    +
    + + 免費取得 + {w.coins.free} + + + 付費取得 + {w.coins.paid} + +
    + {rows.length === 0 ? ( +

    還沒有紀錄。打完一局選戰(當選、落選都有)就會發小鎮幣。

    + ) : ( +
      + {rows.map((e, i) => { + const n = e.free + e.paid; + return ( +
    1. + + + {e.reason} + {new Date(e.at).toLocaleString("zh-TW", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })} + + = 0 ? "is-plus" : "is-minus"}> + {n >= 0 ? `+${n}` : n} + +
    2. + ); + })} +
    + )} +
    + ); +} diff --git a/web/src/game/shop/shop.css b/web/src/game/shop/shop.css new file mode 100644 index 0000000..fb71f4a --- /dev/null +++ b/web/src/game/shop/shop.css @@ -0,0 +1,140 @@ +/* 服裝店(ShopScreen.tsx):整頁不捲。左邊試衣間、右邊貨架(只有貨架自己捲);手機版試衣間在上、貨架在下。 + 顏色一律用 tokens.css;動畫只動 transform、opacity。 */ + +.sh-room { + height: 100%; min-height: 0; + display: grid; gap: 14px 18px; + grid-template-columns: minmax(320px, 0.85fr) minmax(0, 1.35fr); + grid-template-rows: minmax(0, 1fr); +} + +/* ── 試衣間 ── */ +.sh-fit { min-height: 0; display: grid; grid-template-rows: minmax(0, 1fr) auto auto; gap: 10px; padding: 14px; overflow: hidden; } +.sh-mirror { position: relative; min-height: 0; display: grid; place-items: end center; container-type: size; } +.sh-figure { position: relative; height: min(100cqh, 110cqw); aspect-ratio: 200 / 220; } +.sh-backdrop { + position: absolute; left: 6%; top: 2%; width: 88%; aspect-ratio: 1; border-radius: 50%; + border: 4px solid var(--ink); box-shadow: 0 0 0 6px color-mix(in srgb, var(--signal) 55%, transparent); +} +.sh-figure .avatar { position: relative; display: block; width: 100%; height: 100%; } +.sh-trying { + position: absolute; top: 6px; right: 6px; padding: 3px 12px; border: 3px solid var(--ink); border-radius: 999px; + background: var(--signal); color: var(--signal-ink); font-weight: 900; font-size: 14px; transform: rotate(4deg); + animation: sh-pop 260ms var(--ease-out) both; +} +.sh-detail { display: grid; gap: 6px; min-height: 0; } +.sh-detail h2 { margin: 0; font-family: var(--font-serif); font-size: clamp(22px, 2.4vw, 30px); line-height: 1.1; } +.sh-detail-kicker { margin: 0; color: var(--muted); font-size: 13px; font-weight: 800; } +.sh-rarity-text.is-rare { color: #7a5cc4; } +.sh-rarity-text.is-limited { color: var(--stamp); } +.sh-desc { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.5; } +.sh-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-top: 2px; } +.sh-state { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border: 2px dashed var(--muted); border-radius: 999px; color: var(--muted); font-size: 14px; font-weight: 800; } +.sh-state.is-owned { border-style: solid; border-color: var(--good); color: var(--good); } +.sh-msg { margin: 0; padding: 6px 12px; border-radius: 12px; background: color-mix(in srgb, var(--signal) 30%, transparent); font-weight: 800; font-size: 14px; animation: sh-pop 240ms var(--ease-out) both; } + +.sh-models { display: flex; gap: 10px; overflow-x: auto; overscroll-behavior: contain; padding: 4px 2px 6px; scrollbar-width: thin; } +.sh-model { flex: none; display: grid; justify-items: center; gap: 2px; width: 64px; padding: 0; border: 0; background: none; color: var(--ink); font: inherit; font-size: 12px; font-weight: 800; cursor: pointer; transition: transform 140ms var(--ease-out); } +.sh-model-face { width: 52px; height: 52px; display: grid; place-items: end center; overflow: hidden; border-radius: 50%; border: 3px solid var(--ink); box-shadow: 2px 2px 0 var(--shadow-ink); } +.sh-model-face .avatar { display: block; width: 116%; height: auto; transform: translateY(14%); } +.sh-model-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sh-model.is-on .sh-model-face { box-shadow: 0 0 0 3px var(--surface), 0 0 0 6px var(--stamp); } +.sh-model.is-on .sh-model-name { color: var(--stamp); } +.sh-model:active { transform: scale(0.95); } +.sh-model:focus-visible { outline: none; } +.sh-model:focus-visible .sh-model-face { outline: 4px solid var(--signal); outline-offset: 3px; } +.sh-model-new { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 6px 14px; border: 2px dashed var(--ink); border-radius: 12px; color: var(--ink); font-weight: 800; text-decoration: none; } +.sh-model-new:focus-visible { outline: 4px solid var(--signal); outline-offset: 2px; } + +/* ── 貨架 ── */ +.sh-shelf { min-height: 0; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; overflow: hidden; } +.sh-tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; padding: 8px; background: var(--navy); border-bottom: 3px solid var(--ink); } +.sh-tab { + min-height: 46px; padding: 4px 6px; border: 2px solid transparent; border-radius: 12px; background: none; color: var(--navy-ink); + font: inherit; font-weight: 900; font-size: 15px; opacity: 0.78; cursor: pointer; transition: transform 140ms var(--ease-out), opacity 140ms ease; +} +.sh-tab.is-on { opacity: 1; background: var(--signal); color: var(--signal-ink); border-color: var(--signal-ink); box-shadow: 0 3px 0 var(--signal-ink); transform: translateY(-2px); } +.sh-tab:active { transform: scale(0.96); } +.sh-tab:focus-visible { outline: 3px solid var(--signal); outline-offset: 1px; } +.sh-panel { min-height: 0; display: grid; align-content: start; gap: 12px; padding: 14px 16px 18px; animation: sh-in 220ms var(--ease-out) both; } +.sh-h { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: 4px 0 0; font-family: var(--font-serif); font-size: 18px; } +.sh-h small { color: var(--muted); font-family: var(--font-body); font-size: 12px; font-weight: 700; } +.sh-group { display: grid; gap: 10px; } +.sh-grid { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: 14px 12px; } +.sh-card { + position: relative; width: 100%; display: grid; justify-items: center; gap: 4px; padding: 6px 6px 8px; + border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); color: var(--ink); + box-shadow: 3px 3px 0 var(--shadow-ink); font: inherit; text-align: center; cursor: pointer; + transition: transform 140ms var(--ease-out); +} +.sh-card-art { width: 100%; aspect-ratio: 1; display: grid; place-items: center; overflow: hidden; border-radius: 10px; background: color-mix(in srgb, var(--ink) 7%, transparent); } +.sh-card-art .avatar { display: block; width: 100%; height: auto; transform: translateY(5%); } +.sh-card-art.is-head .avatar { transform: translateY(17%) scale(1.35); } +.sh-card-art.is-face .avatar { transform: translateY(8%) scale(1.75); } +.sh-card-name { font-weight: 900; font-size: 14px; line-height: 1.2; } +.sh-card-tag { display: inline-flex; align-items: center; gap: 4px; padding: 1px 10px; border-radius: 999px; background: var(--signal); color: var(--signal-ink); font: 800 14px/1.4 var(--font-num); } +.sh-card.is-owned .sh-card-tag { background: var(--good); color: #fff; font-family: var(--font-body); font-size: 12px; } +.sh-card.is-locked { border-style: dashed; border-color: var(--muted); box-shadow: none; } +.sh-card.is-locked .sh-card-art { filter: grayscale(1); opacity: 0.55; } +.sh-card.is-locked .sh-card-tag { background: var(--surface); color: var(--muted); border: 2px dashed var(--muted); font-family: var(--font-body); font-size: 12px; } +.sh-card.is-on { background: var(--signal); color: var(--signal-ink); transform: translateY(-3px); box-shadow: 3px 6px 0 var(--shadow-ink); } +.sh-card.is-on .sh-card-art { background: color-mix(in srgb, var(--tv-ink) 70%, transparent); filter: none; opacity: 1; } +.sh-card.is-on .sh-card-tag { background: var(--tv-ink); color: var(--signal-ink); } +.sh-card:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.sh-card:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.sh-rarity { + position: absolute; top: -9px; left: -7px; padding: 1px 8px; border: 2px solid var(--ink); border-radius: 999px; + background: #7a5cc4; color: #fff; font-size: 12px; font-weight: 900; letter-spacing: 0.06em; transform: rotate(-6deg); +} +.sh-rarity.is-limited { background: var(--stamp); } +.sh-foot { margin: 0; padding: 8px 14px 10px; border-top: 2px solid var(--line); color: var(--muted); font-size: 12px; font-weight: 700; line-height: 1.45; } + +/* 紀錄 */ +.sh-log { display: grid; gap: 12px; } +.sh-books { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } +.sh-books span { display: grid; gap: 2px; padding: 10px 14px; border: 3px solid var(--ink); border-radius: 14px; background: var(--surface-2); } +.sh-books small { color: var(--muted); font-size: 12px; font-weight: 800; } +.sh-books b { font: 900 28px/1 var(--font-num); font-variant-numeric: tabular-nums; } +.sh-log-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.sh-log-list li { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; padding: 8px 12px; border-radius: 12px; background: var(--surface-2); } +.sh-log-reason { display: grid; font-size: 14px; font-weight: 700; } +.sh-log-reason small { color: var(--muted); font-size: 12px; font-weight: 600; } +.sh-log-list b { font: 900 20px/1 var(--font-num); font-variant-numeric: tabular-nums; } +.sh-log-list b.is-plus { color: var(--good); } +.sh-log-list b.is-minus { color: var(--stamp); } + +@media (hover: hover) and (pointer: fine) { + .sh-card:not(.is-on):hover { transform: translateY(-3px); } + .sh-tab:not(.is-on):hover { opacity: 1; } + .sh-model:hover { transform: translateY(-2px); } +} + +@keyframes sh-pop { from { opacity: 0; transform: scale(0.85); } } +@keyframes sh-in { from { opacity: 0; transform: translateY(8px); } } + +/* 手機、窄螢幕:試衣間在上(人物和說明並排)、貨架在下 */ +@media (max-width: 820px) { + .sh-room { gap: 10px; grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 40fr) minmax(0, 60fr); } + .sh-fit { grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr); grid-template-rows: minmax(0, 1fr) auto; gap: 6px 10px; padding: 10px; } + .sh-mirror { grid-row: 1; grid-column: 1; } + .sh-detail { grid-row: 1; grid-column: 2; align-content: center; overflow-y: auto; } + .sh-models { grid-row: 2; grid-column: 1 / -1; padding-bottom: 2px; } + .sh-detail h2 { font-size: 20px; } + .sh-desc { font-size: 13px; } + .sh-trying { font-size: 12px; padding: 2px 8px; } + .sh-model { width: 52px; } + .sh-model-face { width: 44px; height: 44px; } + .sh-model-name { display: none; } + .sh-tab { font-size: 14px; } + .sh-panel { padding: 12px 10px 14px; } + .sh-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 12px 10px; } + .sh-card-name { font-size: 13px; } + .sh-foot { padding: 6px 10px 8px; font-size: 11px; } + .sh-actions .gs-btn { min-height: 44px; padding: 6px 12px; font-size: 14px; } +} + +@media (prefers-reduced-motion: reduce) { + .sh-panel, .sh-msg, .sh-trying { animation: sh-fade 200ms ease both; } + .sh-card, .sh-tab, .sh-model { transition: none; } +} +@keyframes sh-fade { from { opacity: 0; } } diff --git a/web/src/game/shop/unlocks.ts b/web/src/game/shop/unlocks.ts new file mode 100644 index 0000000..7c3b46e --- /dev/null +++ b/web/src/game/shop/unlocks.ts @@ -0,0 +1,55 @@ +import { stampAvatarVersion, type AvatarItem, type AvatarSpecData } from "@election2026/protocol"; +import type { Progress } from "../rogue/progress.ts"; +import type { WardrobeState } from "./wardrobe.ts"; + +/** + * 部件拿到了沒、怎麼拿到(沒拿到的格子灰色、寫怎麼拿到,跟圖鑑灰卡一樣)。 + * 免費的一開始就有;成就、累積成績解鎖的看選戰卡牌的進度(rogue/progress.ts,只讀);商店的看衣櫥。 + */ + +export type UnlockProgress = Pick; + +export interface ItemState { + owned: boolean; + /** 怎麼拿到(給灰格子和說明用) */ + how: string; + /** 商店價格 */ + price: number | null; +} + +export const RARITY_TEXT: Record = { common: "普通", rare: "稀有", limited: "限定" }; + +export function itemState(item: AvatarItem, progress: UnlockProgress, wardrobe: Pick): ItemState { + const g = item.get; + switch (g.type) { + case "free": + return { owned: true, how: "免費", price: null }; + case "shop": + return { owned: Boolean(wardrobe.owned[item.id]), how: `服裝店 ${g.price} 小鎮幣${item.available?.months ? `(每年 ${item.available.months.join("、")} 月上架)` : ""}`, price: g.price }; + case "feat": + return { owned: Boolean(progress.feats[g.feat]), how: g.text, price: null }; + case "stat": { + const value = g.stat === "wins" ? progress.wins : g.stat === "runs" ? progress.runs : Math.max(0, progress.runs - progress.wins); + return { owned: value >= g.min, how: g.text, price: null }; + } + } +} + +/** 穿上(id 是 null 就脫掉)某個新部位:連那個部位的換色一起清掉,標上第 2 版 */ +export function wear(spec: AvatarSpecData, slot: string, id: string | null): AvatarSpecData { + const wearMap = { ...(spec.wear ?? {}) }; + if (id) wearMap[slot] = id; + else delete wearMap[slot]; + const tint = Object.fromEntries(Object.entries(spec.tint ?? {}).filter(([k]) => !k.startsWith(`${slot}.`))); + const { wear: _w, tint: _t, ...rest } = spec; + return stampAvatarVersion({ ...rest, ...(Object.keys(wearMap).length ? { wear: wearMap } : {}), ...(Object.keys(tint).length ? { tint } : {}) }); +} + +/** 某個新部位換色(color 是 null 就回到預設色) */ +export function setTint(spec: AvatarSpecData, slot: string, key: string, color: string | null): AvatarSpecData { + const tint = { ...(spec.tint ?? {}) }; + if (color) tint[`${slot}.${key}`] = color; + else delete tint[`${slot}.${key}`]; + const { tint: _t, ...rest } = spec; + return stampAvatarVersion({ ...rest, ...(Object.keys(tint).length ? { tint } : {}) }); +} diff --git a/web/src/game/shop/wardrobe.ts b/web/src/game/shop/wardrobe.ts new file mode 100644 index 0000000..e1b5567 --- /dev/null +++ b/web/src/game/shop/wardrobe.ts @@ -0,0 +1,174 @@ +import { shopShelf, wearItem, type AvatarItem } from "@election2026/protocol"; +import { useEffect, useState } from "react"; + +/** + * 衣櫥:小鎮幣和買過的外觀(docs/24 第 4 節)。只存在玩家自己的瀏覽器(localStorage),讀不到就當作空的。 + * - 小鎮幣只能買外觀,不能買變強的東西;不能轉送、不能換現金;沒有使用期限。 + * - 記帳分兩本:「免費取得」和「付費取得」(現在只有免費,付費那本留給以後開真錢)。花的時候先扣免費的。 + * - 每一筆拿到、花掉都留紀錄(以後退款、客服、查帳要用);同一局只發一次(靠紀錄裡的 runId)。 + * 每個寫入都是「讀 → 算出新的一份 → 存 → 通知畫面」,不改舊的物件(跟政策島 island/store.ts 一樣)。 + */ + +export interface CoinEntry { + /** 時間(ISO) */ + at: string; + /** 免費那本的變化(正的是拿到,負的是花掉) */ + free: number; + /** 付費那本的變化 */ + paid: number; + reason: string; + /** 哪一局發的;同一局只發一次 */ + runId?: string; + /** 買了哪件 */ + itemId?: string; +} + +export interface WardrobeState { + coins: { free: number; paid: number }; + /** 用小鎮幣買到的部件代號 → 什麼時候買的 */ + owned: Record; + log: CoinEntry[]; +} + +export const WARDROBE_KEY = "tongsuan.wardrobe.v1"; +const EVENT = "tongsuan:wardrobe"; +/** 紀錄最多留這麼多筆(大約好幾百局) */ +export const MAX_LOG = 1000; +const ID = /^[a-z0-9][a-z0-9-]{0,39}$/; + +const empty = (): WardrobeState => ({ coins: { free: 0, paid: 0 }, owned: {}, log: [] }); +const count = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.floor(v)) : 0); +const delta = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0); + +/** 存檔是玩家瀏覽器裡的資料,可能被改過或是舊版:逐欄檢查,不對的丟掉。看不懂的部件代號照留(可能是新版加的) */ +export function sanitizeWardrobe(raw: unknown): WardrobeState { + if (!raw || typeof raw !== "object") return empty(); + const r = raw as Partial>; + const c = (r.coins && typeof r.coins === "object" ? r.coins : {}) as Record; + const owned: WardrobeState["owned"] = {}; + if (r.owned && typeof r.owned === "object" && !Array.isArray(r.owned)) { + for (const [id, v] of Object.entries(r.owned as Record)) { + if (!ID.test(id)) continue; + const at = v && typeof v === "object" && typeof (v as { at?: unknown }).at === "string" ? (v as { at: string }).at.slice(0, 40) : ""; + owned[id] = { at }; + } + } + const log = (Array.isArray(r.log) ? r.log : []) + .filter((e): e is CoinEntry => !!e && typeof e === "object" && typeof (e as CoinEntry).reason === "string" && typeof (e as CoinEntry).at === "string") + .map((e) => ({ + at: e.at.slice(0, 40), + free: delta(e.free), + paid: delta(e.paid), + reason: e.reason.slice(0, 80), + ...(typeof e.runId === "string" ? { runId: e.runId.slice(0, 64) } : {}), + ...(typeof e.itemId === "string" && ID.test(e.itemId) ? { itemId: e.itemId } : {}), + })) + .slice(-MAX_LOG); + return { coins: { free: count(c.free), paid: count(c.paid) }, owned, log }; +} + +export function loadWardrobe(): WardrobeState { + try { + const raw = localStorage.getItem(WARDROBE_KEY); + return raw ? sanitizeWardrobe(JSON.parse(raw)) : empty(); + } catch { + return empty(); + } +} + +function save(state: WardrobeState): WardrobeState { + try { + localStorage.setItem(WARDROBE_KEY, JSON.stringify(state)); + } catch { + // 私密模式存不了:這次的進度只留在畫面上 + } + try { + dispatchEvent(new CustomEvent(EVENT)); + } catch { + // 沒有 window(測試環境) + } + return state; +} + +export const totalCoins = (s: Pick): number => s.coins.free + s.coins.paid; + +/** 一局打完發幾枚小鎮幣:當選 3、落選 2、S 評價 +2、第一次拿到的成就每個 +1、每日一戰 +2、政治生涯過關 +2 */ +export function coinsForRun(r: { won: boolean; grade?: string | null; newFeats?: number; daily?: boolean; career?: boolean }): { coins: number; reason: string } { + const parts = [r.won ? "當選 +3" : "落選也打完 +2"]; + let coins = r.won ? 3 : 2; + if (r.grade === "S") { + coins += 2; + parts.push("S 評價 +2"); + } + const feats = count(r.newFeats); + if (feats > 0) { + coins += feats; + parts.push(`新成就 +${feats}`); + } + if (r.daily) { + coins += 2; + parts.push("每日一戰 +2"); + } + if (r.career && r.won) { + coins += 2; + parts.push("政治生涯過關 +2"); + } + return { coins, reason: parts.join("、") }; +} + +/** 發小鎮幣(免費那本);同一個 runId 只發一次。回傳有沒有真的發 */ +export function earnCoins(amount: number, reason: string, runId?: string, now = new Date()): boolean { + const n = Math.floor(amount); + if (!Number.isFinite(n) || n <= 0) return false; + const s = loadWardrobe(); + if (runId && s.log.some((e) => e.runId === runId)) return false; + const entry: CoinEntry = { at: now.toISOString(), free: n, paid: 0, reason, ...(runId ? { runId } : {}) }; + save({ ...s, coins: { ...s.coins, free: s.coins.free + n }, log: [...s.log, entry].slice(-MAX_LOG) }); + return true; +} + +/** 這件現在服裝店有沒有上架(本週輪替、基本款常駐、限定期間) */ +export function onShelf(item: AvatarItem, now: Date | number = Date.now()): boolean { + const shelf = shopShelf(now); + return [...shelf.weekly, ...shelf.always, ...shelf.limited].some((i) => i.id === item.id); +} + +export type BuyResult = { ok: true } | { ok: false; reason: "unknown" | "notForSale" | "owned" | "poor" }; + +/** 用小鎮幣買一件;先扣免費那本,不夠再扣付費那本 */ +export function buyItem(id: string, now = new Date()): BuyResult { + const item = wearItem(id); + if (!item || item.get.type !== "shop") return { ok: false, reason: "unknown" }; + const s = loadWardrobe(); + if (s.owned[id]) return { ok: false, reason: "owned" }; + if (!onShelf(item, now)) return { ok: false, reason: "notForSale" }; + const price = item.get.price; + if (totalCoins(s) < price) return { ok: false, reason: "poor" }; + const fromFree = Math.min(price, s.coins.free); + const fromPaid = price - fromFree; + const entry: CoinEntry = { at: now.toISOString(), free: -fromFree, paid: -fromPaid, reason: `買「${item.name}」`, itemId: id }; + save({ + coins: { free: s.coins.free - fromFree, paid: s.coins.paid - fromPaid }, + owned: { ...s.owned, [id]: { at: now.toISOString() } }, + log: [...s.log, entry].slice(-MAX_LOG), + }); + return { ok: true }; +} + +/** 畫面用:目前的衣櫥,別的分頁或元件改了也會跟著更新 */ +export function useWardrobe(): WardrobeState { + const [state, setState] = useState(loadWardrobe); + useEffect(() => { + const update = () => setState(loadWardrobe()); + const onStorage = (e: StorageEvent) => { + if (e.key === WARDROBE_KEY) update(); + }; + addEventListener(EVENT, update); + addEventListener("storage", onStorage); + return () => { + removeEventListener(EVENT, update); + removeEventListener("storage", onStorage); + }; + }, []); + return state; +} diff --git a/web/src/game/stage/MapStage.tsx b/web/src/game/stage/MapStage.tsx new file mode 100644 index 0000000..31f0df0 --- /dev/null +++ b/web/src/game/stage/MapStage.tsx @@ -0,0 +1,255 @@ +import type { LucideIcon } from "lucide-react"; +import { memo, type ReactNode } from "react"; +import type { StageGeometry } from "./geometry.ts"; + +export interface StageMarker { + key: string; + townCode: string; + icon: LucideIcon; + /** 圖示底色:自己陣營用政黨色,對手用對手的政黨色 */ + color: string; + label: string; + /** 播放中剛出現的標記,帶進場動畫 */ + fresh?: boolean; + /** 這個標記是哪個行動(立體盤面用來挑演出) */ + actionId?: string; +} + +export interface StageToken { + key: string; + townCode: string; + node: ReactNode; + label: string; + /** 立體盤面上棋子的顏色(政黨色);平面地圖不用 */ + color?: string; +} + +export interface FloatText { + key: string; + townCode: string; + text: string; + tone: "good" | "bad" | "neutral"; +} + +interface Props { + geometry: StageGeometry; + /** 區代碼 → 底色 */ + townFills: ReadonlyMap; + /** 村里代碼 → 底色(開票夜逐里上色);有值時蓋過區的底色 */ + villageFills?: ReadonlyMap; + selected?: string | null; + onSelect?: (townCode: string) => void; + highlight?: ReadonlySet; + offices?: ReadonlySet; + markers?: readonly StageMarker[]; + tokens?: readonly StageToken[]; + floats?: readonly FloatText[]; + showLandmarks?: boolean; + ariaLabel?: string; + /** 出牌時選到要打在某一區的牌:每一區都可以點,滑過時亮起來 */ + highlightAll?: boolean; +} + +const MAX_ICONS = 4; + +/** 縣市地圖舞台:海、鄰近縣市、各區、地標、行程圖示、棋子 */ +export function MapStage({ + geometry: g, + townFills, + villageFills, + selected = null, + onSelect, + highlight, + offices, + markers = [], + tokens = [], + floats = [], + showLandmarks = true, + ariaLabel = "地圖", + highlightAll = false, +}: Props) { + const towns = new Map(g.towns.map((t) => [t.code, t])); + const townNames = useTownNames(g); + const byTown = new Map(); + for (const m of markers) byTown.set(m.townCode, [...(byTown.get(m.townCode) ?? []), m]); + const tokensByTown = new Map(); + for (const t of tokens) tokensByTown.set(t.townCode, [...(tokensByTown.get(t.townCode) ?? []), t]); + + return ( + + + + + + + + + + + + + + + + {g.seas.map((sea) => ( + + {sea.name} + + ))} + {g.insets.map((i) => ( + // 縣市名由區的標籤負責,小框只畫框 + + {i.name} + + ))} + + {g.context.map((c) => ( + + + {c.cx > 0 && c.cx < g.width && c.cy > 0 && c.cy < g.height && ( + + {c.name} + + )} + + ))} + + + {/* 復興區是山區:加一層斜線紋理代表地形 */} + {g.towns + .filter((t) => t.name === "復興區") + .map((t) => ( + + ))} + + + + {g.towns + .filter((t) => highlight?.has(t.code)) + .map((t) => ( + + ))} + {g.towns + .filter((t) => t.code === selected) + .map((t) => ( + + ))} + + {showLandmarks && + g.landmarks.map((l) => { + const Icon = l.icon; + return ( + + + + + ); + })} + + {g.towns.map((t) => ( + + {offices?.has(t.code) ? "⚑" : ""} + {t.name.replace(/區$/, "")} + + ))} + + {[...byTown].map(([code, list]) => { + const t = towns.get(code); + if (!t) return null; + const shown = list.slice(0, MAX_ICONS); + const width = shown.length * 18 + (list.length > MAX_ICONS ? 18 : 0); + return ( + + {shown.map((m, i) => { + const Icon = m.icon; + return ( + + + + {m.label} + + ); + })} + {list.length > MAX_ICONS && ( + + +{list.length - MAX_ICONS} + + )} + + ); + })} + + {tokens.map((tok) => { + const t = towns.get(tok.townCode); + if (!t) return null; + const group = tokensByTown.get(tok.townCode) ?? [tok]; + const i = group.indexOf(tok); + const x = t.cx + (i - (group.length - 1) / 2) * 24; + const y = t.cy + 30; + return ( + // 棋子用 transform 定位,換區時以 CSS transition 滑過去 + + +
    + {tok.node} +
    +
    +
    + ); + })} + + {floats.map((f) => { + const t = towns.get(f.townCode); + if (!t) return null; + return ( + + {f.text} + + ); + })} +
    + ); +} + +const namesCache = new WeakMap>(); +/** 區代碼 → 區名;同一份地圖只建一次,讓村里圖層的 memo 有效 */ +function useTownNames(g: StageGeometry): ReadonlyMap { + let names = namesCache.get(g); + if (!names) { + names = new Map(g.towns.map((t) => [t.code, t.name])); + namesCache.set(g, names); + } + return names; +} + +interface VillageLayerProps { + villages: StageGeometry["villages"]; + townFills: ReadonlyMap; + villageFills?: ReadonlyMap; + names: ReadonlyMap; + onSelect?: (townCode: string) => void; +} + +/** 村里圖層:全國地圖有近八千個里,只在底色或地圖改變時才重畫(行程圖示、棋子移動不會動到這層) */ +const VillageLayer = memo(function VillageLayer({ villages, townFills, villageFills, names, onSelect }: VillageLayerProps) { + return ( + + {villages.map((v) => { + const fill = villageFills?.get(v.code) ?? townFills.get(v.town) ?? "var(--neutral)"; + return ( + onSelect(v.town) : undefined} + > + {names.get(v.town) ?? v.town} + + ); + })} + + ); +}); diff --git a/web/src/game/stage/geometry.ts b/web/src/game/stage/geometry.ts new file mode 100644 index 0000000..eb9835b --- /dev/null +++ b/web/src/game/stage/geometry.ts @@ -0,0 +1,306 @@ +import { geoArea, geoMercator, geoPath, geoTransform } from "d3-geo"; +import type { Feature, FeatureCollection, Geometry, MultiPolygon, Polygon as GeoPolygon, Position } from "geojson"; +import { feature, merge, mesh } from "topojson-client"; +import type { GeometryCollection, Polygon, MultiPolygon as TopoMultiPolygon, Topology } from "topojson-specification"; +import { LABEL_AT, LANDMARKS, seaNames, type LandmarkDef } from "./landmarks.ts"; + +type VillageProps = { code: string; name: string; townCode?: string; townName?: string }; +type ContextProps = { name: string; county: string }; +type VillageGeom = (Polygon | TopoMultiPolygon) & { properties: VillageProps }; + +/** 投影後的平面座標點(舞台座標,760 × 640) */ +export type StagePoint = [number, number]; +/** 多邊形清單:每個多邊形的第一個環是外圈,其餘是洞(立體盤面擠出地形用) */ +export type StagePolygons = StagePoint[][][]; + +export interface StageGeometry { + width: number; + height: number; + villages: { code: string; town: string; d: string }[]; + /** 遊戲裡的「區」:縣市長、立委是鄉鎮市區,總統是縣市 */ + towns: { code: string; name: string; d: string; cx: number; cy: number; rings: StagePolygons }[]; + /** 區界(不含外框) */ + borders: string; + /** 選舉範圍的外框 */ + outline: string; + /** 底圖:鄰近縣市,以及立委選區外的同縣市各區;rings 已裁到舞台範圍內 */ + context: { name: string; d: string; cx: number; cy: number; rings: StagePolygons }[]; + landmarks: (LandmarkDef & { x: number; y: number; townCode: string | null })[]; + seas: { name: string; x: number; y: number }[]; + /** 全國地圖上的離島小框(金門、馬祖) */ + insets: { name: string; x: number; y: number; w: number; h: number }[]; +} + +/** 這場選舉的地圖範圍 */ +export interface MapScope { + /** 縣市代碼;總統選舉是 00000 */ + county: string; + level: "town" | "county"; + /** 立委選區內的村里;null 表示整份資料包 */ + villages: ReadonlySet | null; + /** 區代碼 → 名稱(玩家視角的 towns) */ + names: ReadonlyMap; + /** 議員選區把村里分群時:村里 → 遊戲裡的區代碼(G1、G2…);沒有就照行政區 */ + groups?: ReadonlyMap | null; +} + +/** d3-geo 把逆時針的外環當成「整個地球減掉這塊」;面積超過半球的多邊形就把環反轉 */ +export function rewind

    (f: Feature): Feature { + const fix = (rings: Position[][]) => + geoArea({ type: "Polygon", coordinates: rings }) > 2 * Math.PI ? rings.map((r) => [...r].reverse()) : rings; + const g = f.geometry; + if (g.type === "Polygon") return { ...f, geometry: { ...g, coordinates: fix(g.coordinates) } }; + if (g.type === "MultiPolygon") return { ...f, geometry: { ...g, coordinates: g.coordinates.map(fix) } }; + return f; +} + +export const STAGE_WIDTH = 760; +export const STAGE_HEIGHT = 640; +const PAD_X = 36; +const PAD_Y = 24; + +export const regionOf = (code: string, level: "town" | "county"): string => (level === "county" ? `${code.slice(0, 5)}000` : code.slice(0, 8)); + +/** 全國地圖的離島小框:依經緯度判斷(烏坵雖屬金門縣,位置在臺灣海峽中間,留在本島地圖上) */ +const INSETS = [ + { name: "連江縣", box: { x: 16, y: 16, w: 150, h: 128 }, test: (lon: number, lat: number) => lat > 25.8 && lon < 121 }, + { name: "金門縣", box: { x: 16, y: 156, w: 150, h: 112 }, test: (lon: number, lat: number) => lon < 118.7 }, +] as const; + +type Box = { x: number; y: number; w: number; h: number }; + +function fitTo(bounds: Bounds, box: Box, pad: number) { + const corners = { type: "MultiPoint" as const, coordinates: bounds }; + return geoMercator().fitExtent( + [ + [box.x + pad, box.y + pad], + [box.x + box.w - pad, box.y + box.h - pad], + ], + corners, + ); +} + +type Bounds = [[number, number], [number, number]]; + +/** 多邊形的每一塊(外環):平面面積與範圍。資料都在東經、北緯,用經緯度平面計算就夠了,也不受環的方向影響 */ +function partsOf(features: readonly Feature[]): { area: number; bounds: Bounds }[] { + const out: { area: number; bounds: Bounds }[] = []; + const add = (ring: Position[]) => { + let area = 0; + let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [x, y] = ring[i]!; + area += (ring[j]![0]! - x!) * (ring[j]![1]! + y!); + x0 = Math.min(x0, x!); + y0 = Math.min(y0, y!); + x1 = Math.max(x1, x!); + y1 = Math.max(y1, y!); + } + out.push({ area: Math.abs(area) / 2, bounds: [[x0, y0], [x1, y1]] }); + }; + for (const f of features) { + const g = f.geometry; + if (g.type === "Polygon") add(g.coordinates[0]!); + else if (g.type === "MultiPolygon") for (const poly of g.coordinates) add(poly[0]!); + } + return out; +} + +const union = (a: Bounds, b: Bounds): Bounds => [ + [Math.min(a[0][0], b[0][0]), Math.min(a[0][1], b[0][1])], + [Math.max(a[1][0], b[1][0]), Math.max(a[1][1], b[1][1])], +]; +const EMPTY: Bounds = [[Infinity, Infinity], [-Infinity, -Infinity]]; + +/** + * 地圖要框住的範圍(傳入合併後的陸塊,不是一個個村里):先取面積前 95% 的陸地當主體,再加上離主體不遠的小島。 + * 遠方的離島(宜蘭頭城的釣魚台、基隆的彭佳嶼、金門的烏坵)不算進去,免得整張地圖縮成一小塊。 + */ +function fitBounds(features: readonly Feature[]): Bounds { + const parts = partsOf(features).sort((a, b) => b.area - a.area); + const total = parts.reduce((s, p) => s + p.area, 0); + let core = EMPTY; + let acc = 0; + for (const p of parts) { + if (acc >= total * 0.95) break; + core = union(core, p.bounds); + acc += p.area; + } + const margin = 0.25 * Math.max(core[1][0] - core[0][0], core[1][1] - core[0][1]); + const near = (b: Bounds) => b[0][0] >= core[0][0] - margin && b[1][0] <= core[1][0] + margin && b[0][1] >= core[0][1] - margin && b[1][1] <= core[1][1] + margin; + return parts.filter((p) => near(p.bounds)).reduce((b, p) => union(b, p.bounds), core); +} + +const centerOf = (f: Feature): [number, number] => { + const [[x0, y0], [x1, y1]] = partsOf([f]).reduce((b, p) => union(b, p.bounds), EMPTY); + return [(x0 + x1) / 2, (y0 + y1) / 2]; +}; + +/** 多塊陸地裡面積最大的那一塊(含它的洞) */ +function largestPart(f: Feature): Feature { + const polys = f.geometry.coordinates; + const areas = partsOf(polys.map((coordinates) => ({ type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates } }))); + const best = areas.reduce((bi, p, i) => (p.area > areas[bi]!.area ? i : bi), 0); + return { type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates: polys[best] ?? [] } }; +} + +/** 平面的點在多邊形內(奇偶規則,洞也算對) */ +function contains(g: Geometry, [x, y]: [number, number]): boolean { + const polys = g.type === "Polygon" ? [g.coordinates] : g.type === "MultiPolygon" ? g.coordinates : []; + let inside = false; + for (const rings of polys) + for (const ring of rings) + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, yi] = ring[i]!; + const [xj, yj] = ring[j]!; + if (yi! > y !== yj! > y && x < ((xj! - xi!) * (y - yi!)) / (yj! - yi!) + xi!) inside = !inside; + } + return inside; +} + +/** 去掉相鄰太近的點(立體盤面不需要比半個像素更細的邊),也去掉重複的收尾點 */ +function thin(ring: StagePoint[], minGap = 0.6): StagePoint[] { + const out: StagePoint[] = []; + for (const pt of ring) { + const last = out[out.length - 1]; + if (!last || Math.abs(pt[0] - last[0]) + Math.abs(pt[1] - last[1]) >= minGap) out.push(pt); + } + const first = out[0]; + const last = out[out.length - 1]; + if (first && last && out.length > 1 && first[0] === last[0] && first[1] === last[1]) out.pop(); + return out; +} + +/** 把環裁到矩形裡(Sutherland–Hodgman);鄰近縣市超出盤面的部分不畫 */ +function clipRing(ring: StagePoint[], x0: number, y0: number, x1: number, y1: number): StagePoint[] { + const edges: [(p: StagePoint) => boolean, (a: StagePoint, b: StagePoint) => StagePoint][] = [ + [(p) => p[0] >= x0, (a, b) => [x0, a[1] + ((b[1] - a[1]) * (x0 - a[0])) / (b[0] - a[0])]], + [(p) => p[0] <= x1, (a, b) => [x1, a[1] + ((b[1] - a[1]) * (x1 - a[0])) / (b[0] - a[0])]], + [(p) => p[1] >= y0, (a, b) => [a[0] + ((b[0] - a[0]) * (y0 - a[1])) / (b[1] - a[1]), y0]], + [(p) => p[1] <= y1, (a, b) => [a[0] + ((b[0] - a[0]) * (y1 - a[1])) / (b[1] - a[1]), y1]], + ]; + let out = ring; + for (const [inside, cut] of edges) { + const input = out; + out = []; + for (let i = 0; i < input.length; i++) { + const cur = input[i]!; + const prev = input[(i + input.length - 1) % input.length]!; + if (inside(cur)) { + if (!inside(prev)) out.push(cut(prev, cur)); + out.push(cur); + } else if (inside(prev)) out.push(cut(prev, cur)); + } + if (out.length === 0) break; + } + return out; +} + +/** + * 由資料包的 TopoJSON 與全台縣市底圖建立舞台用的形狀。 + * 縣市長:整個縣市;立委:只上色選區內的里,投影以選區為準,縣市其他區當底圖; + * 總統:各縣市是一區,金門、馬祖放進左上角的小框。 + */ +export function buildGeometry(topology: Topology, context: FeatureCollection | null, scope: MapScope): StageGeometry { + const all = (topology.objects.villages as GeometryCollection).geometries as VillageGeom[]; + const inScope = (g: VillageGeom) => !scope.villages || scope.villages.has(g.properties.code); + const active = all.filter(inScope); + const outside = scope.villages ? all.filter((g) => !inScope(g)) : []; + const activeObj: GeometryCollection = { type: "GeometryCollection", geometries: active }; + const region = (g: { properties: VillageProps }) => scope.groups?.get(g.properties.code) ?? regionOf(g.properties.code, scope.level); + const villageFeatures = feature(topology, activeObj).features; + + // 區:把同一區的里合併成一塊 + const byRegion = new Map(); + for (const g of active) byRegion.set(region(g), [...(byRegion.get(region(g)) ?? []), g]); + const regionFeatures = [...byRegion].map(([code, geoms]) => ({ + code, + name: scope.names.get(code) ?? geoms[0]!.properties.townName ?? code, + feature: { type: "Feature", properties: {}, geometry: merge(topology, geoms) } as Feature, + })); + + // 投影:用合併後的陸塊決定範圍(島嶼才分得出來);全國地圖把金門、馬祖放進小框,其餘照本島縮放 + const national = scope.level === "county"; + const insetOf = (lon: number, lat: number) => (national ? INSETS.findIndex((i) => i.test(lon, lat)) : -1); + const groups = INSETS.map(() => [] as Feature[]); + const main: Feature[] = []; + for (const r of regionFeatures) { + const i = insetOf(...centerOf(largestPart(r.feature))); + (i >= 0 ? groups[i]! : main).push(r.feature); + } + const mainProjection = fitTo(fitBounds(main), { x: PAD_X, y: PAD_Y, w: STAGE_WIDTH - 2 * PAD_X, h: STAGE_HEIGHT - 2 * PAD_Y }, 0); + const insetProjections = INSETS.map((inset, i) => (groups[i]!.length ? fitTo(fitBounds(groups[i]!), inset.box, 12) : null)); + const project = (lon: number, lat: number): [number, number] => { + const i = insetOf(lon, lat); + return (i >= 0 ? insetProjections[i] : null)?.([lon, lat]) ?? mainProjection([lon, lat]) ?? [0, 0]; + }; + // 平面轉換:各點各自投影(離島與本島用不同的投影),不做球面裁切 + const path = geoPath( + geoTransform({ + point(x, y) { + const [px, py] = project(x, y); + this.stream.point(px, py); + }, + }), + ).digits(1); + // 標籤放在最大那一塊的重心:頭城鎮不會被釣魚台拉到海上,金門縣不會被烏坵拉出小框 + const labelAt = (f: Feature) => path.centroid(largestPart(f)); + // 立體盤面用的多邊形:和 path 用同一個投影,所以和 SVG 的形狀完全對齊 + const ringsOf = (g: Geometry, clip = false): StagePolygons => { + const polys = g.type === "Polygon" ? [g.coordinates] : g.type === "MultiPolygon" ? g.coordinates : []; + return polys + .map((rings) => + rings + .map((r) => thin(r.map(([lon, lat]) => project(lon!, lat!)))) + .map((r) => (clip ? clipRing(r, 0, 0, STAGE_WIDTH, STAGE_HEIGHT) : r)) + .filter((r) => r.length >= 3), + ) + .filter((rings) => rings.length > 0); + }; + + const towns = regionFeatures.map(({ code, name, feature: f }) => { + const at = LABEL_AT[code]; + const [cx, cy] = at ? project(at[0], at[1]) : labelAt(f); + // 遠方的離島(例如宜蘭的釣魚台)投影在舞台外,立體盤面不畫,和平面地圖被裁掉一樣 + return { code, name, d: path(f) ?? "", cx, cy, rings: ringsOf(f.geometry, true) }; + }); + + // 立委選區外的同縣市各區:當底圖,標區名 + const outsideByTown = new Map(); + for (const g of outside) outsideByTown.set(regionOf(g.properties.code, "town"), [...(outsideByTown.get(regionOf(g.properties.code, "town")) ?? []), g]); + const outsideTowns = [...outsideByTown.values()].map((geoms) => { + const f: Feature = { type: "Feature", properties: {}, geometry: merge(topology, geoms) }; + const [cx, cy] = labelAt(f); + return { name: geoms[0]!.properties.townName ?? "", d: path(f) ?? "", cx, cy, rings: ringsOf(f.geometry, true) }; + }); + const neighbors = national + ? [] + : (context?.features ?? []) + .filter((f) => f.properties.county !== scope.county) + .map(rewind) + .map((f) => { + const [cx, cy] = path.centroid(f); + return { name: f.properties.name, d: path(f) ?? "", cx, cy, rings: ringsOf(f.geometry, true) }; + }); + + const landmarks = (LANDMARKS[scope.county] ?? []).flatMap((l) => { + const town = regionFeatures.find((r) => contains(r.feature.geometry, [l.lon, l.lat])); + const [x, y] = project(l.lon, l.lat); + // 座標落在選舉範圍外就不畫,避免標錯位置 + return town ? [{ ...l, x, y, townCode: town.code }] : []; + }); + + const seas = seaNames(scope.county); + return { + width: STAGE_WIDTH, + height: STAGE_HEIGHT, + villages: villageFeatures.map((f) => ({ code: f.properties.code, town: scope.groups?.get(f.properties.code) ?? regionOf(f.properties.code, scope.level), d: path(f) ?? "" })), + towns, + borders: path(mesh(topology, activeObj, (a, b) => a !== b && region(a as VillageGeom) !== region(b as VillageGeom))) ?? "", + outline: path(mesh(topology, activeObj, (a, b) => a === b)) ?? "", + context: [...neighbors, ...outsideTowns], + landmarks, + seas: national ? [{ name: seas[0] ?? "", x: 110, y: 470 }, { name: "太平洋", x: 660, y: 420 }] : seas.slice(0, 1).map((name) => ({ name, x: 70, y: 70 })), + insets: national ? INSETS.filter((_, i) => insetProjections[i]).map((i) => ({ name: i.name, ...i.box })) : [], + }; +} diff --git a/web/src/game/stage/landmarks.ts b/web/src/game/stage/landmarks.ts new file mode 100644 index 0000000..eae345c --- /dev/null +++ b/web/src/game/stage/landmarks.ts @@ -0,0 +1,121 @@ +import { Anchor, Building2, Castle, Droplets, Flower2, Landmark, Mountain, Plane, Store, Sun, TrainFront, TreePine, Waves, type LucideIcon } from "lucide-react"; + +/** + * 各縣市的地標:只是地圖上的裝飾,座標取概略位置。 + * 地圖會用區界檢查每個地標落在哪一區,落在縣市外面的會被略過,不會畫錯地方。 + */ +export interface LandmarkDef { + name: string; + lon: number; + lat: number; + icon: LucideIcon; +} + +const L = (name: string, lon: number, lat: number, icon: LucideIcon): LandmarkDef => ({ name, lon, lat, icon }); + +export const LANDMARKS: Readonly> = { + // 全國地圖(總統選舉):各地一個代表性地標 + "00000": [ + L("台北 101", 121.5645, 25.034, Building2), + L("日月潭", 120.916, 23.856, Waves), + L("阿里山", 120.805, 23.51, Mountain), + L("太魯閣", 121.62, 24.158, Mountain), + L("墾丁", 120.8, 21.945, Sun), + L("安平古堡", 120.16, 23.001, Castle), + L("龜山島", 121.953, 24.843, Mountain), + L("桃園國際機場", 121.2328, 25.0777, Plane), + L("跨海大橋", 119.53, 23.655, Waves), + ], + "68000": [ + L("桃園國際機場", 121.2328, 25.0777, Plane), + L("竹圍漁港", 121.244, 25.118, Anchor), + L("高鐵桃園站", 121.215, 25.0129, TrainFront), + L("觀音蓮花", 121.14, 25.032, Flower2), + L("永安漁港", 121.0147, 24.9869, Anchor), + L("市政府", 121.301, 24.9936, Landmark), + L("虎頭山", 121.329, 25.0, Mountain), + L("龍潭大池", 121.216, 24.864, Waves), + L("大溪老街", 121.2862, 24.8836, Store), + L("慈湖", 121.2933, 24.8448, TreePine), + L("石門水庫", 121.245, 24.813, Droplets), + L("拉拉山", 121.442, 24.718, Mountain), + ], + "63000": [ + L("台北 101", 121.5645, 25.034, Building2), + L("故宮博物院", 121.5485, 25.1024, Landmark), + L("中正紀念堂", 121.5219, 25.0346, Landmark), + L("陽明山", 121.55, 25.17, Mountain), + L("士林夜市", 121.524, 25.088, Store), + ], + "65000": [ + L("九份", 121.844, 25.109, Store), + L("淡水老街", 121.439, 25.17, Store), + L("野柳", 121.69, 25.206, Waves), + L("烏來", 121.55, 24.865, Droplets), + L("板橋車站", 121.463, 25.014, TrainFront), + ], + "66000": [ + L("高美濕地", 120.553, 24.312, Waves), + L("台中國家歌劇院", 120.64, 24.163, Landmark), + L("逢甲夜市", 120.646, 24.179, Store), + L("梨山", 121.251, 24.255, Mountain), + ], + "67000": [ + L("安平古堡", 120.16, 23.001, Castle), + L("赤崁樓", 120.2027, 22.9975, Landmark), + L("奇美博物館", 120.2265, 22.9346, Landmark), + L("七股鹽山", 120.088, 23.153, Sun), + ], + "64000": [ + L("85 大樓", 120.3005, 22.6115, Building2), + L("駁二藝術特區", 120.281, 22.62, Store), + L("佛光山", 120.443, 22.755, Landmark), + L("旗津", 120.27, 22.6, Anchor), + L("美濃", 120.542, 22.898, TreePine), + ], + "10017": [L("基隆廟口", 121.743, 25.128, Store), L("和平島", 121.765, 25.161, Waves), L("基隆港", 121.74, 25.134, Anchor)], + "10018": [L("新竹城隍廟", 120.966, 24.804, Landmark), L("科學園區", 121.004, 24.78, Building2), L("南寮漁港", 120.927, 24.847, Anchor)], + "10004": [L("內灣老街", 121.182, 24.705, Store), L("司馬庫斯", 121.333, 24.58, TreePine), L("高鐵新竹站", 121.04, 24.808, TrainFront)], + "10005": [L("勝興車站", 120.785, 24.387, TrainFront), L("南庄老街", 121.001, 24.596, Store), L("三義木雕", 120.766, 24.414, Landmark)], + "10007": [L("鹿港老街", 120.436, 24.056, Store), L("八卦山大佛", 120.547, 24.08, Landmark)], + "10008": [L("日月潭", 120.916, 23.856, Waves), L("清境農場", 121.161, 24.057, TreePine), L("溪頭", 120.797, 23.672, TreePine), L("合歡山", 121.273, 24.138, Mountain)], + "10009": [L("北港朝天宮", 120.304, 23.568, Landmark), L("西螺大橋", 120.464, 23.804, Landmark)], + "10010": [L("阿里山", 120.805, 23.51, Mountain), L("故宮南院", 120.293, 23.473, Landmark), L("東石漁港", 120.15, 23.459, Anchor)], + "10020": [L("文化路夜市", 120.448, 23.481, Store), L("檜意森活村", 120.458, 23.488, TreePine)], + "10013": [L("墾丁", 120.8, 21.945, Sun), L("鵝鑾鼻燈塔", 120.853, 21.902, Landmark), L("大鵬灣", 120.472, 22.443, Waves), L("小琉球", 120.371, 22.342, Anchor)], + "10002": [L("龜山島", 121.953, 24.843, Mountain), L("礁溪溫泉", 121.768, 24.827, Droplets), L("羅東夜市", 121.77, 24.677, Store), L("太平山", 121.531, 24.496, TreePine)], + "10015": [L("太魯閣", 121.62, 24.158, Mountain), L("七星潭", 121.621, 24.03, Waves), L("東大門夜市", 121.609, 23.975, Store)], + "10014": [L("伯朗大道", 121.213, 23.105, Sun), L("三仙台", 121.413, 23.124, Waves), L("綠島", 121.491, 22.66, Anchor), L("蘭嶼", 121.545, 22.045, Anchor)], + "10016": [L("跨海大橋", 119.53, 23.655, Waves), L("雙心石滬", 119.516, 23.252, Anchor), L("馬公天后宮", 119.565, 23.564, Landmark)], + "09020": [L("莒光樓", 118.32, 24.422, Castle), L("翟山坑道", 118.306, 24.404, Anchor), L("模範街", 118.317, 24.433, Store)], + "09007": [L("北海坑道", 119.93, 26.158, Anchor), L("芹壁聚落", 119.984, 26.224, Store), L("東引燈塔", 120.51, 26.368, Landmark)], +}; + +/** 地圖上的海名;內陸縣市沒有 */ +export const SEA_NAME: Readonly> = { + "10002": "太平洋", + "10015": "太平洋", + "10014": "太平洋", + "10008": "", + "65000": "", + "63000": "", +}; + +export function seaNames(county: string): string[] { + const name = SEA_NAME[county] ?? "臺灣海峽"; + return name ? [name] : []; +} + +/** + * 區名標籤的位置(經度、緯度)。預設放在形狀的重心;被別的縣市包住、重心會落到別人身上的,在這裡指定。 + * 鍵是區代碼:鄉鎮市區 8 碼,全國地圖的縣市是「縣市代碼+000」。 + */ +export const LABEL_AT: Readonly> = { + "65000000": [121.66, 24.93], + "63000000": [121.56, 25.08], + "10017000": [121.73, 25.14], + "10018000": [120.95, 24.8], + "10004000": [121.2, 24.7], + "10020000": [120.45, 23.49], + "10010000": [120.66, 23.42], +}; diff --git a/web/src/game/stage/loadMap.ts b/web/src/game/stage/loadMap.ts new file mode 100644 index 0000000..e712435 --- /dev/null +++ b/web/src/game/stage/loadMap.ts @@ -0,0 +1,11 @@ +import type { FeatureCollection, Geometry } from "geojson"; + +/** 周邊縣市底圖(只是裝飾):讀不到就只畫這個縣市 */ +export async function loadContext(): Promise | null> { + try { + const res = await fetch("/maps/taiwan-counties.json"); + return res.ok ? await res.json() : null; + } catch { + return null; + } +} diff --git a/web/src/game/start/CampaignHero.tsx b/web/src/game/start/CampaignHero.tsx new file mode 100644 index 0000000..42ac9ca --- /dev/null +++ b/web/src/game/start/CampaignHero.tsx @@ -0,0 +1,34 @@ +import type { ReactNode } from "react"; +import { BallotStamp } from "../art/BallotStamp.tsx"; + +/** 主視覺上像傳單一樣貼著的三張插圖(卡牌插圖,一般場景、不畫真人) */ +const FLYERS = [ + { src: "/cards/rally.webp", alt: "夜晚的造勢晚會", tilt: -6 }, + { src: "/cards/temple_visit.webp", alt: "宮廟參拜", tilt: 4 }, + { src: "/cards/street_canvass.webp", alt: "騎樓下掃街拜票", tilt: -3 }, +] as const; + +/** + * 開始畫面的主視覺:競選文宣風的海報。 + * 深藍夜色加浪花條紋(造浪)、粗黑大字、螢光筆標語、像傳單一樣貼著的插圖、圈選章。 + */ +export function CampaignHero({ copy }: { copy: ReactNode }) { + return ( +

    +
    {copy}
    +
    + {FLYERS.map((f, i) => ( +
    + {f.alt} +
    + ))} + + + +
    + + 選戰開打 + +
    + ); +} diff --git a/web/src/game/start/HeroDiorama.tsx b/web/src/game/start/HeroDiorama.tsx new file mode 100644 index 0000000..39fd1ba --- /dev/null +++ b/web/src/game/start/HeroDiorama.tsx @@ -0,0 +1,145 @@ +import { Hand, Music, Music2 } from "lucide-react"; +import { useEffect, useRef, useState, type ReactNode } from "react"; +import { BallotStamp } from "../art/BallotStamp.tsx"; +import { updateSettings, useSettings } from "../audio/settings.ts"; +import { sfx } from "../audio/sfx.ts"; +import { CampaignHero } from "./CampaignHero.tsx"; +import { createHero, type HeroHandle, type HeroPop } from "./hero3d.ts"; +import "./hero.css"; + +export type HeroCheer = (kind: "rally" | "truck" | "crowd") => void; + +interface HeroProps { + /** 標題與按鈕 */ + copy: ReactNode; + /** 疊在小鎮上的東西(例如首頁的手牌);cheer 讓小鎮跟著動 */ + overlay?: (cheer: HeroCheer) => ReactNode; +} + +/** + * 首頁主視覺:會動的選戰小鎮(three.js),疊上標題、開始按鈕(copy)、手牌(overlay)與音樂開關。 + * WebGL 不能用時退回原本的文宣海報;減少動態時只畫一張靜止的畫面。 + */ +export function HeroDiorama({ copy, overlay }: HeroProps) { + const canvasRef = useRef(null); + const wrapRef = useRef(null); + const [state, setState] = useState<"loading" | "ready" | "failed">("loading"); + const settings = useSettings(); + const heroRef = useRef(null); + const [pops, setPops] = useState<(HeroPop & { id: number })[]>([]); + const [challenge, setChallenge] = useState<{ endAt: number; score: number; done: boolean } | null>(null); + const [now, setNow] = useState(() => Date.now()); + const popId = useRef(0); + useEffect(() => { + if (!challenge || challenge.done) return; + const t = setInterval(() => setNow(Date.now()), 200); + return () => clearInterval(t); + }, [challenge]); + + useEffect(() => { + const canvas = canvasRef.current; + const wrap = wrapRef.current; + if (!canvas || !wrap) return; + const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; + const lowPower = matchMedia("(max-width: 720px)").matches || (navigator.hardwareConcurrency ?? 8) <= 4; + let hero: HeroHandle | null = createHero(canvas, { + reduceMotion, + lowPower, + onReady: () => setState("ready"), + onError: () => setState("failed"), + onPop: (pop) => { + const id = ++popId.current; + setPops((list) => [...list.slice(-5), { ...pop, id }]); + setTimeout(() => setPops((list) => list.filter((x) => x.id !== id)), 1100); + if (pop.kind === "vote") sfx.coin(); + else if (pop.kind === "truck") sfx.cheer(); + else if (pop.kind === "stage") sfx.firecracker(); + else sfx.hop(); + }, + onChallenge: ({ left, score, done }) => { + setChallenge({ endAt: Date.now() + left * 1000, score, done }); + if (done) sfx.applause(); + }, + }); + heroRef.current = hero; + const size = () => { + const r = wrap.getBoundingClientRect(); + hero?.resize(Math.round(r.width), Math.round(r.height)); + }; + size(); + const ro = new ResizeObserver(size); + ro.observe(wrap); + // 捲到看不見或切到別的分頁時暫停,省電 + const io = new IntersectionObserver(([e]) => hero?.setActive(Boolean(e?.isIntersecting) && !document.hidden)); + io.observe(wrap); + const onVis = () => hero?.setActive(!document.hidden); + document.addEventListener("visibilitychange", onVis); + return () => { + ro.disconnect(); + io.disconnect(); + document.removeEventListener("visibilitychange", onVis); + hero?.dispose(); + hero = null; + heroRef.current = null; + }; + }, []); + + if (state === "failed") return ; + + return ( +
    +
    + + {state === "loading" && 選戰小鎮搭建中…} + {pops.map((p) => ( + + {p.text} + + ))} +
    + {state === "ready" && ( +
    + {challenge && !challenge.done ? ( + + 拜票中:點有黃色光圈的鄉親! 剩 {Math.max(0, Math.ceil((challenge.endAt - now) / 1000))} 秒・{challenge.score} 票 + + ) : ( + <> + {challenge?.done && ( + + 15 秒拜到 {challenge.score} 票!{challenge.score >= 12 ? "掃街達人,凍蒜!" : challenge.score >= 7 ? "很拚喔!" : "再接再厲"} + + )} + + {!challenge && 點小人、宣傳車、舞台試試看} + + )} +
    + )} + {copy} + {state === "ready" && overlay?.((kind) => heroRef.current?.cheer(kind))} + + + + +
    + ); +} diff --git a/web/src/game/start/hero.css b/web/src/game/start/hero.css new file mode 100644 index 0000000..cf70c02 --- /dev/null +++ b/web/src/game/start/hero.css @@ -0,0 +1,192 @@ +/* 首頁主視覺:全寬的 3D 選戰小鎮,左邊疊標題 */ +.hero3d { + position: relative; + width: min(1240px, 100%); + margin: 0 auto; + min-height: clamp(420px, 62vh, 620px); + border: 3px solid var(--ink); + border-radius: 22px; + overflow: hidden; + background: + radial-gradient(ellipse at 70% 0%, rgb(255 210 63 / 0.35), transparent 55%), + linear-gradient(180deg, #24365e 0%, #3a4f7c 45%, #c98a52 100%); + box-shadow: 8px 8px 0 var(--shadow-ink); + isolation: isolate; +} +.hero3d-stage { position: absolute; inset: 0; } +.hero3d-canvas { display: block; width: 100%; height: 100%; opacity: 0; transition: opacity 600ms ease-out; } +.hero3d.is-ready .hero3d-canvas { opacity: 1; } +.hero3d-loading { + position: absolute; + right: 24px; + bottom: 20px; + color: #fff; + font-weight: 700; + opacity: 0.8; +} +/* 標題底下加一層漸層,讓字在 3D 畫面上也讀得清楚 */ +.hero3d::before { + content: ""; + position: absolute; + inset: 0; + z-index: 1; + pointer-events: none; + background: linear-gradient(90deg, rgb(17 20 25 / 0.72) 0%, rgb(17 20 25 / 0.35) 34%, transparent 58%); +} +.hero3d-copy { + position: relative; + z-index: 2; + display: grid; + gap: 14px; + align-content: center; + width: min(520px, 100%); + min-height: inherit; + padding: 36px 40px; + color: #fff; + pointer-events: none; +} +.hero3d-copy a, .hero3d-copy button { pointer-events: auto; } +.hero3d-kicker { font-family: var(--font-num); font-weight: 700; font-size: 13px; letter-spacing: 0.18em; color: var(--signal); } +.hero3d-title { + display: flex; + align-items: flex-end; + gap: 4px; + margin: 0; + font-family: var(--font-serif); + font-size: clamp(76px, 11vw, 150px); + line-height: 0.9; + letter-spacing: -0.02em; + text-shadow: 6px 6px 0 #111419; +} +.hero3d-word { display: inline-block; animation: hero-drop 520ms cubic-bezier(0.23, 1, 0.32, 1) both; } +.hero3d-word:nth-child(2) { animation-delay: 90ms; } +@keyframes hero-drop { + from { opacity: 0; transform: translateY(-28px) rotate(-6deg) scale(0.92); } +} +.hero3d-title em { + align-self: center; + margin-left: 10px; + padding: 4px 12px; + border: 3px solid #111419; + border-radius: 8px; + background: var(--signal); + color: #111419; + font-family: var(--font-num); + font-size: 0.32em; + font-style: normal; + text-shadow: none; + transform: rotate(-4deg); + box-shadow: 4px 4px 0 #111419; + animation: hero-pop 420ms cubic-bezier(0.23, 1, 0.32, 1) 260ms both; +} +@keyframes hero-pop { + from { opacity: 0; transform: rotate(-4deg) scale(0.9); } +} +.hero3d-slogan { margin: 0; font-size: clamp(22px, 3vw, 32px); font-weight: 900; letter-spacing: 0.08em; text-shadow: 3px 3px 0 #111419; } +.hero3d-slogan mark { color: #fff; background: linear-gradient(transparent 58%, color-mix(in srgb, var(--signal) 85%, transparent) 58%); } +/* 新玩法入口:文宣黃,試玩期間放在開始選戰旁邊 */ +.hero3d-stamp { + position: absolute; + z-index: 2; + right: 22px; + top: 18px; + padding: 6px; + border-radius: 50%; + background: #fff; + box-shadow: 0 8px 18px -8px rgb(0 0 0 / 0.6); + animation: hero-stamp 520ms cubic-bezier(0.23, 1, 0.32, 1) 700ms both; +} +@keyframes hero-stamp { + from { opacity: 0; transform: scale(1.35) rotate(-24deg); } + to { transform: rotate(-12deg); } +} +.hero3d-stamp { transform: rotate(-12deg); } +.hero3d-music { + position: absolute; + z-index: 3; + right: 18px; + bottom: 16px; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 7px 14px; + border: 2px solid #111419; + border-radius: 999px; + background: #fff; + color: #111419; + font: inherit; + font-weight: 800; + cursor: pointer; + box-shadow: 3px 3px 0 #111419; + transition: transform 140ms cubic-bezier(0.23, 1, 0.32, 1); +} +.hero3d-music.is-on { background: var(--signal); } +.hero3d-music:active { transform: scale(0.96); } + +@media (max-width: 720px) { + .hero3d { min-height: 560px; border-radius: 16px; } + .hero3d::before { background: linear-gradient(180deg, rgb(17 20 25 / 0.75) 0%, rgb(17 20 25 / 0.25) 45%, transparent 65%); } + .hero3d-copy { align-content: start; min-height: 0; padding: 22px 18px; gap: 10px; } + .hero3d-stamp { display: none; } +} + +@media (prefers-reduced-motion: reduce) { + .hero3d-word, .hero3d-title em, .hero3d-stamp { animation: hero-fade 300ms ease both; } +} +@keyframes hero-fade { from { opacity: 0; } } + +/* 點小鎮跳出的字、拜票挑戰 */ +.hero3d-pop { + position: absolute; + z-index: 4; + translate: -50% -100%; + padding: 3px 10px; + border: 2px solid #111419; + border-radius: 999px; + background: #fff; + color: #111419; + font-weight: 900; + font-size: 15px; + white-space: nowrap; + pointer-events: none; + animation: hero-pop-up 1100ms cubic-bezier(0.23, 1, 0.32, 1) both; +} +.hero3d-pop.is-vote { background: var(--signal); font-size: 18px; } +.hero3d-pop.is-truck, .hero3d-pop.is-stage { background: var(--stamp); color: #fff; } +@keyframes hero-pop-up { + 0% { opacity: 0; transform: translateY(8px) scale(0.92); } + 15% { opacity: 1; transform: translateY(0) scale(1); } + 75% { opacity: 1; transform: translateY(-18px); } + 100% { opacity: 0; transform: translateY(-26px); } +} +.hero3d-game { + position: absolute; + z-index: 3; + left: 50%; + bottom: 16px; + translate: -50% 0; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 8px; + max-width: calc(100% - 200px); +} +.hero3d-game-hud { + padding: 6px 14px; + border: 2px solid #111419; + border-radius: 999px; + background: #fff; + color: #111419; + font-weight: 800; + box-shadow: 3px 3px 0 #111419; +} +.hero3d-game-hud b { color: var(--stamp); } +.hero3d-game-hud.is-result { background: var(--signal); } +.hero3d-tip { color: #fff; font-size: 13px; font-weight: 700; text-shadow: 0 1px 3px rgb(0 0 0 / 0.6); } +@media (max-width: 720px) { + .hero3d-game { left: 12px; right: 12px; translate: none; max-width: none; bottom: 64px; } +} +@media (prefers-reduced-motion: reduce) { + .hero3d-pop { animation: tv-fade 1100ms ease both; } +} diff --git a/web/src/game/start/hero3d.ts b/web/src/game/start/hero3d.ts new file mode 100644 index 0000000..d00a6a5 --- /dev/null +++ b/web/src/game/start/hero3d.ts @@ -0,0 +1,735 @@ +import * as THREE from "three"; +import { GLTFLoader, type GLTF } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { clone as cloneSkinned } from "three/examples/jsm/utils/SkeletonUtils.js"; + +/** + * 首頁主視覺:桌上的選戰小鎮。木頭桌面上一塊桌遊板,後排是店面住家, + * 中間是造勢舞台和揮旗的群眾,宣傳車沿著馬路繞圈,不時有金幣、星星和彩帶飛起來。 + * 模型、貼圖都是 CC0(web/public/assets/LICENSES.md);人物是不具名的 Q 版小人,不代表任何真人。 + */ + +const A = "/assets/3d/"; +const T = "/assets/textures/"; +const PALETTE = ["#d61f2c", "#ffd23f", "#1d4fa3", "#ffffff", "#0f8a4a", "#ff8a3d"]; +const BOARD_W = 16; +const BOARD_D = 11; +const BOARD_H = 0.5; +/** 宣傳車繞的馬路:圓角矩形(lane 是路寬) */ +const ROAD = { w: 13, d: 6.6, r: 1.6, lane: 1.1 }; + +export interface HeroHandle { + resize: (w: number, h: number) => void; + setActive: (active: boolean) => void; + /** 拜票挑戰:15 秒內點亮起光圈的鄉親,點到一個算一票 */ + startChallenge: () => void; + /** 首頁的手牌打進小鎮:造勢放煙火、宣傳車加速、群眾跳起來 */ + cheer: (kind: "rally" | "truck" | "crowd") => void; + dispose: () => void; +} + +/** 點小鎮時要在畫面上跳出的字(螢幕座標) */ +export interface HeroPop { + x: number; + y: number; + text: string; + kind: "person" | "truck" | "stage" | "vote"; +} + +interface Options { + reduceMotion: boolean; + /** 手機:關陰影、降解析度 */ + lowPower: boolean; + onReady: () => void; + onError: () => void; + onPop: (pop: HeroPop) => void; + onChallenge: (state: { left: number; score: number; done: boolean }) => void; +} + +/** 讀入模型,縮放到指定的高度(或寬度),底部貼齊 y=0 */ +function fit(obj: THREE.Object3D, size: number, by: "height" | "width" = "height"): THREE.Object3D { + const box = new THREE.Box3().setFromObject(obj); + const dim = box.getSize(new THREE.Vector3()); + const s = size / (by === "height" ? dim.y : Math.max(dim.x, dim.z)); + obj.scale.multiplyScalar(s); + const after = new THREE.Box3().setFromObject(obj); + obj.position.y -= after.min.y; + const wrap = new THREE.Group(); + wrap.add(obj); + return wrap; +} + +function shadows(obj: THREE.Object3D, on: boolean) { + obj.traverse((o) => { + if ((o as THREE.Mesh).isMesh) { + o.castShadow = on; + o.receiveShadow = on; + } + }); +} + +/** 桌遊板的板面:米色紙板、繞一圈的馬路與虛線、草地 */ +function boardTexture(): THREE.CanvasTexture { + const c = document.createElement("canvas"); + c.width = 1024; + c.height = 640; + const g = c.getContext("2d")!; + g.fillStyle = "#efe6cf"; + g.fillRect(0, 0, c.width, c.height); + const sx = c.width / BOARD_W; + const sz = c.height / BOARD_D; + const road = (inset: number) => { + const w = (ROAD.w - inset * 2) * sx; + const h = (ROAD.d - inset * 2) * sz; + const x = (c.width - w) / 2; + const y = (c.height - h) / 2; + const r = Math.max(4, (ROAD.r - inset) * sx); + g.beginPath(); + g.roundRect(x, y, w, h, r); + }; + // 草地與廣場 + g.fillStyle = "#b9d39a"; + g.fillRect(0, 0, c.width, 70); + g.fillRect(0, c.height - 70, c.width, 70); + // 馬路 + g.lineWidth = ROAD.lane * sx; + g.strokeStyle = "#5d6675"; + road(0); + g.stroke(); + g.lineWidth = 4; + g.setLineDash([22, 18]); + g.strokeStyle = "#ffd23f"; + road(0); + g.stroke(); + g.setLineDash([]); + // 廣場的磚 + g.fillStyle = "#e3d3ae"; + road(0.75); + g.fill(); + g.strokeStyle = "rgba(120,90,50,0.18)"; + g.lineWidth = 2; + for (let x = 0; x < c.width; x += 32) { + g.beginPath(); + g.moveTo(x, 0); + g.lineTo(x, c.height); + g.stroke(); + } + const t = new THREE.CanvasTexture(c); + t.colorSpace = THREE.SRGBColorSpace; + t.anisotropy = 4; + return t; +} + +/** 文宣布條(舞台背板、宣傳車看板):紙白底、紅框、粗黑字 */ +function bannerTexture(text: string, sub: string, w = 1024, h = 384): THREE.CanvasTexture { + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + const g = c.getContext("2d")!; + g.fillStyle = "#d61f2c"; + g.fillRect(0, 0, w, h); + g.fillStyle = "#fffaf0"; + g.fillRect(18, 18, w - 36, h - 36); + g.fillStyle = "#111419"; + g.textAlign = "center"; + g.textBaseline = "middle"; + g.font = `900 ${Math.round(h * 0.46)}px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(text, w / 2, h * 0.44, w - 80); + g.fillStyle = "#d61f2c"; + g.font = `900 ${Math.round(h * 0.13)}px "Tongsuan Rounded", "Noto Sans TC", sans-serif`; + g.fillText(sub, w / 2, h * 0.8); + const t = new THREE.CanvasTexture(c); + t.colorSpace = THREE.SRGBColorSpace; + return t; +} + +/** 宣傳車繞的路線:沿著馬路的圓角矩形 */ +const ROUTE = (() => { + const hw = ROAD.w / 2; + const hd = ROAD.d / 2; + const r = ROAD.r; + const pts: THREE.Vector3[] = []; + const corner = (cx: number, cz: number, from: number) => { + for (let k = 0; k <= 4; k++) { + const a = from + (k / 4) * (Math.PI / 2); + pts.push(new THREE.Vector3(cx + Math.cos(a) * r, 0, cz + Math.sin(a) * r)); + } + }; + corner(hw - r, hd - r, 0); + corner(-hw + r, hd - r, Math.PI / 2); + corner(-hw + r, -hd + r, Math.PI); + corner(hw - r, -hd + r, (3 * Math.PI) / 2); + return new THREE.CatmullRomCurve3(pts, true, "centripetal"); +})(); + +/** 路線上的位置(0–1 繞一圈)與車頭方向 */ +function roadPoint(u: number): { x: number; z: number; angle: number } { + const t = ((u % 1) + 1) % 1; + const p = ROUTE.getPointAt(t); + const d = ROUTE.getTangentAt(t); + return { x: p.x, z: p.z, angle: Math.atan2(d.x, d.z) }; +} + +export function createHero(canvas: HTMLCanvasElement, opts: Options): HeroHandle { + let renderer: THREE.WebGLRenderer; + try { + renderer = new THREE.WebGLRenderer({ + canvas, + antialias: !opts.lowPower, + alpha: true, + powerPreference: "low-power", + }); + } catch { + opts.onError(); + return { + resize: () => {}, + setActive: () => {}, + startChallenge: () => {}, + cheer: () => {}, + dispose: () => {}, + }; + } + renderer.setPixelRatio(Math.min(devicePixelRatio, opts.lowPower ? 1.25 : 1.75)); + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = !opts.lowPower; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + + const scene = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(32, 2, 0.1, 200); + const target = new THREE.Vector3(0.6, 0.6, 0); + + // 燈光:黃昏的暖光加天空光 + scene.add(new THREE.HemisphereLight("#fff4df", "#6b4a2b", 1.1)); + const sun = new THREE.DirectionalLight("#ffe0b0", 2.2); + sun.position.set(-8, 14, 9); + sun.castShadow = !opts.lowPower; + sun.shadow.mapSize.set(1024, 1024); + Object.assign(sun.shadow.camera, { + left: -12, + right: 12, + top: 10, + bottom: -10, + near: 1, + far: 40, + }); + sun.shadow.bias = -0.0008; + scene.add(sun); + const rim = new THREE.DirectionalLight("#9fb8ff", 0.6); + rim.position.set(9, 6, -10); + scene.add(rim); + + const textures: THREE.Texture[] = []; + const texLoader = new THREE.TextureLoader(); + const tex = (url: string, repeat = 1, color = true) => { + const t = texLoader.load(url); + if (color) t.colorSpace = THREE.SRGBColorSpace; + t.wrapS = t.wrapT = THREE.RepeatWrapping; + t.repeat.set(repeat, repeat); + textures.push(t); + return t; + }; + + // 木頭桌面 + const table = new THREE.Mesh( + new THREE.PlaneGeometry(70, 70), + new THREE.MeshStandardMaterial({ + map: tex(`${T}wood-table-diff.jpg`, 7), + normalMap: tex(`${T}wood-table-normal.jpg`, 7, false), + roughness: 0.75, + }), + ); + table.rotation.x = -Math.PI / 2; + table.position.y = -BOARD_H; + table.receiveShadow = true; + scene.add(table); + + // 桌遊板:紙板側面、印著馬路的板面 + const top = boardTexture(); + textures.push(top); + const side = new THREE.MeshStandardMaterial({ + map: tex(`${T}cardboard-diff.jpg`, 1), + roughness: 0.95, + }); + const board = new THREE.Mesh(new THREE.BoxGeometry(BOARD_W, BOARD_H, BOARD_D), [side, side, new THREE.MeshStandardMaterial({ map: top, roughness: 0.9 }), side, side, side]); + board.position.y = -BOARD_H / 2; + board.receiveShadow = true; + scene.add(board); + + // 舞台與背板 + const stage = new THREE.Group(); + const deck = new THREE.Mesh(new THREE.BoxGeometry(3.4, 0.45, 1.5), new THREE.MeshStandardMaterial({ color: "#d61f2c", roughness: 0.6 })); + deck.position.y = 0.225; + const trim = new THREE.Mesh(new THREE.BoxGeometry(3.5, 0.08, 1.6), new THREE.MeshStandardMaterial({ color: "#ffd23f", roughness: 0.5 })); + trim.position.y = 0.47; + const bannerTex = bannerTexture("選舉小鎮", "選戰開打・全民開講"); + textures.push(bannerTex); + const backdrop = new THREE.Mesh(new THREE.BoxGeometry(3.6, 1.5, 0.1), [ + new THREE.MeshStandardMaterial({ color: "#111419" }), + new THREE.MeshStandardMaterial({ color: "#111419" }), + new THREE.MeshStandardMaterial({ color: "#111419" }), + new THREE.MeshStandardMaterial({ color: "#111419" }), + new THREE.MeshStandardMaterial({ map: bannerTex, roughness: 0.7 }), + new THREE.MeshStandardMaterial({ color: "#111419" }), + ]); + backdrop.position.set(0, 1.35, -0.7); + const poles = [-1.75, 1.75].map((x) => { + const p = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.05, 2.2), new THREE.MeshStandardMaterial({ color: "#2b2f36" })); + p.position.set(x, 1.1, -0.72); + return p; + }); + stage.add(deck, trim, backdrop, ...poles); + stage.position.set(0.4, 0, -1.4); + shadows(stage, !opts.lowPower); + scene.add(stage); + + const mixers: THREE.AnimationMixer[] = []; + /** 可以點的小人:平常的動作、點了之後跳一下 */ + interface Person { + root: THREE.Object3D; + base: THREE.AnimationAction | null; + jump: THREE.AnimationAction | null; + } + const people: Person[] = []; + let stageGroup: THREE.Object3D | null = null; + let truckBoost = 0; + let truckU = 0; + const floaters: { + obj: THREE.Object3D; + born: number; + x: number; + z: number; + spin: number; + }[] = []; + let floaterSources: THREE.Object3D[] = []; + let truck: THREE.Object3D | null = null; + + // 彩帶:一次畫 260 片小紙片 + const CONFETTI = opts.reduceMotion ? 0 : opts.lowPower ? 120 : 260; + const confetti = new THREE.InstancedMesh(new THREE.PlaneGeometry(0.12, 0.07), new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, toneMapped: false }), Math.max(1, CONFETTI)); + const bits = Array.from({ length: CONFETTI }, () => ({ + p: new THREE.Vector3(0, -10, 0), + v: new THREE.Vector3(), + r: new THREE.Euler(), + w: new THREE.Vector3(Math.random() * 6, Math.random() * 6, Math.random() * 6), + })); + const color = new THREE.Color(); + for (let i = 0; i < CONFETTI; i++) confetti.setColorAt(i, color.set(PALETTE[i % PALETTE.length]!)); + confetti.count = CONFETTI; + scene.add(confetti); + const burst = (x: number, z: number) => { + let n = 0; + for (const b of bits) { + if (b.p.y > -1 || n > 90) continue; + b.p.set(x + (Math.random() - 0.5) * 2, 2 + Math.random(), z + (Math.random() - 0.5) * 1.5); + b.v.set((Math.random() - 0.5) * 3, 3 + Math.random() * 3, (Math.random() - 0.5) * 2); + n++; + } + }; + + const loader = new GLTFLoader(); + const load = (path: string) => new Promise((resolve, reject) => loader.load(A + path, resolve, undefined, reject)); + + const build = async () => { + const [chars, buildings, trees, flag, truckGltf, lights, coin, star, heart, pineapple] = await Promise.all([ + Promise.all( + ["character-male-a", "character-female-a", "character-male-b", "character-female-b", "character-male-c", "character-female-c", "character-male-d", "character-female-d"].map((n) => + load(`characters/${n}.glb`), + ), + ), + Promise.all( + ["town-shops/building-a", "town-shops/building-c", "town-houses/building-type-b", "town-shops/building-e", "town-shops/building-h", "town-houses/building-type-f", "town-shops/building-k"].map( + (n) => load(`${n}.glb`), + ), + ), + Promise.all(["nature/tree-default", "nature/tree-palm-short", "nature/tree-oak"].map((n) => load(`${n}.glb`))), + load("props/flag.glb"), + load("vehicles/truck.glb"), + load("festive/lights-colored.glb"), + load("props/coin-gold.glb"), + load("props/star.glb"), + load("props/heart.glb"), + load("food/pineapple.glb"), + ]); + + // 住宅原本是綠屋頂,容易聯想成政黨色,換成磚紅色的貼圖版本 + const brick = texLoader.load(`${A}town-houses/Textures/variation-b.png`); + brick.flipY = false; + brick.colorSpace = THREE.SRGBColorSpace; + brick.magFilter = THREE.NearestFilter; + textures.push(brick); + // 後排的店面與住家:整排站在馬路外側,不壓到宣傳車的路 + const front = -ROAD.d / 2 - ROAD.lane / 2 - 0.1; + const room = BOARD_D / 2 + front - 0.05; + const row = buildings.map((g, i) => { + if (i === 2 || i === 5) { + g.scene.traverse((o) => { + const m = o as THREE.Mesh; + if (m.isMesh) m.material = Object.assign((m.material as THREE.MeshStandardMaterial).clone(), { map: brick }); + }); + } + const dim = new THREE.Box3().setFromObject(g.scene).getSize(new THREE.Vector3()); + const b = fit(g.scene, dim.y * Math.min(1.95 / dim.x, room / dim.z)); + return { b, w: dim.x * Math.min(1.95 / dim.x, room / dim.z) }; + }); + const GAP = 0.15; + let x = -(row.reduce((a, r) => a + r.w, 0) + GAP * (row.length - 1)) / 2; + for (const { b, w } of row) { + const box = new THREE.Box3().setFromObject(b); + b.position.set(x + w / 2, 0, front - box.max.z); + x += w + GAP; + shadows(b, !opts.lowPower); + scene.add(b); + } + // 樹:種在板子四周的草地上,離馬路有距離,不擋宣傳車 + ( + [ + [-7.25, 4.6, 1, 1.6], + [7.25, 4.6, 0, 1.8], + [-7.5, -0.8, 2, 1.4], + [7.5, 0.6, 0, 1.4], + [7.3, -4.8, 1, 1.4], + ] as const + ).forEach(([tx, tz, kind, size]) => { + const t = fit(trees[kind]!.scene.clone(), size); + t.position.set(tx, 0, tz); + shadows(t, !opts.lowPower); + scene.add(t); + }); + // 舞台上方的燈串 + const l = fit(lights.scene, 4.2, "width"); + l.position.set(0.4, 2.2, -0.3); + scene.add(l); + + // 舞台上的候選人(不具名的 Q 版小人)與台下群眾 + const anim = (gltf: GLTF, name: string, obj: THREE.Object3D, offset: number, root: THREE.Object3D) => { + const mixer = new THREE.AnimationMixer(obj); + const clip = THREE.AnimationClip.findByName(gltf.animations, name) ?? gltf.animations[0]; + let base: THREE.AnimationAction | null = null; + if (clip) { + base = mixer.clipAction(clip); + base.time = offset * clip.duration; + base.play(); + } + const jumpClip = THREE.AnimationClip.findByName(gltf.animations, "jump"); + const jump = jumpClip ? mixer.clipAction(jumpClip) : null; + if (jump) { + jump.setLoop(THREE.LoopOnce, 1); + jump.clampWhenFinished = false; + } + mixer.addEventListener("finished", () => { + if (base) base.reset().fadeIn(0.2).play(); + }); + mixers.push(mixer); + people.push({ root, base, jump }); + }; + const speaker = fit(cloneSkinned(chars[0]!.scene), 1.25); + speaker.position.set(0.4, 0.5, -1.2); + speaker.rotation.y = 0; + shadows(speaker, !opts.lowPower); + scene.add(speaker); + anim(chars[0]!, "emote-yes", speaker.children[0]!, 0, speaker); + stageGroup = stage; + + const crowd: [number, number][] = [ + [-1.6, 0.9], + [-0.6, 1.2], + [0.5, 0.95], + [1.5, 1.25], + [2.5, 0.9], + [-1.1, 2.1], + [0.0, 2.25], + [1.1, 2.0], + [2.1, 2.3], + [-2.4, 1.8], + ]; + crowd.forEach(([x, z], i) => { + const src = chars[(i + 1) % chars.length]!; + const person = fit(cloneSkinned(src.scene), 0.95 + (i % 3) * 0.06); + person.position.set(x, 0, z); + // 面向舞台,帶一點角度讓鏡頭看得到臉 + person.rotation.y = Math.PI + Math.atan2(x - 0.4, z + 1.2) * 0.6; + shadows(person, !opts.lowPower); + scene.add(person); + anim(src, i % 3 === 1 ? "emote-yes" : "idle", person.children[0]!, (i * 0.37) % 1, person); + // 一半的人旁邊插一支旗子 + if (i % 2 === 0) { + const f = fit(flag.scene.clone(), 1.5); + f.position.set(x + 0.28, 0, z - 0.1); + f.rotation.y = -0.4 + (i % 4) * 0.2; + shadows(f, !opts.lowPower); + scene.add(f); + } + }); + + // 宣傳車:車頂加一塊「請支持!」看板 + truck = fit(truckGltf.scene, 1.6, "width"); + const signTex = bannerTexture("請支持!", "拜託 拜託", 512, 256); + textures.push(signTex); + const sign = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.55, 1.1), new THREE.MeshStandardMaterial({ map: signTex })); + const box = new THREE.Box3().setFromObject(truck); + sign.position.set(0, box.max.y + 0.3, 0); + const sign2 = sign.clone(); + sign.position.x = 0.12; + sign2.position.x = -0.12; + sign2.rotation.y = Math.PI; + truck.add(sign, sign2); + shadows(truck, !opts.lowPower); + scene.add(truck); + + floaterSources = [fit(coin.scene, 0.45), fit(star.scene, 0.5), fit(heart.scene, 0.45), fit(pineapple.scene, 0.55)]; + }; + + let active = true; + let raf = 0; + const clock = new THREE.Clock(); + let lastBurst = 0; + let lastFloat = 0; + let pointerX = 0; + const onPointer = (e: PointerEvent) => { + const r = canvas.getBoundingClientRect(); + pointerX = ((e.clientX - r.left) / r.width - 0.5) * 2; + }; + canvas.addEventListener("pointermove", onPointer); + + // ── 點小鎮:小人跳起來、宣傳車加速喊凍蒜、舞台放彩帶;拜票挑戰 ── + const ray = new THREE.Raycaster(); + const ndc = new THREE.Vector2(); + const ring = new THREE.Mesh(new THREE.TorusGeometry(0.42, 0.06, 8, 32), new THREE.MeshBasicMaterial({ color: "#ffd23f", toneMapped: false })); + ring.rotation.x = -Math.PI / 2; + ring.visible = false; + scene.add(ring); + // 目標鄉親頭上的箭頭 + const arrow = new THREE.Mesh(new THREE.ConeGeometry(0.16, 0.34, 4), new THREE.MeshBasicMaterial({ color: "#ffd23f", toneMapped: false })); + arrow.rotation.x = Math.PI; + arrow.visible = false; + scene.add(arrow); + let challenge: { end: number; score: number; target: number } | null = null; + const pickTarget = (not: number) => { + const crowdIdx = people.map((_, i) => i).filter((i) => i > 0 && i !== not); + return crowdIdx[Math.floor(Math.random() * crowdIdx.length)] ?? 1; + }; + const owner = (o: THREE.Object3D | null): { kind: "person"; index: number } | { kind: "truck" | "stage" } | null => { + for (let x = o; x; x = x.parent) { + const i = people.findIndex((p) => p.root === x); + if (i >= 0) return { kind: "person", index: i }; + if (x === truck) return { kind: "truck" }; + if (x === stageGroup) return { kind: "stage" }; + } + return null; + }; + const hit = (e: PointerEvent) => { + const r = canvas.getBoundingClientRect(); + ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + ray.setFromCamera(ndc, camera); + const roots = [...people.map((p) => p.root), ...(truck ? [truck] : []), ...(stageGroup ? [stageGroup] : [])]; + const first = ray.intersectObjects(roots, true)[0]; + return { + target: first ? owner(first.object) : null, + x: e.clientX - r.left, + y: e.clientY - r.top, + }; + }; + const jump = (i: number) => { + const p = people[i]; + if (!p?.jump) return; + p.base?.fadeOut(0.1); + p.jump.reset().fadeIn(0.1).play(); + }; + const onDown = (e: PointerEvent) => { + const { target, x, y } = hit(e); + if (!target) return; + if (target.kind === "person") { + jump(target.index); + if (challenge && target.index === challenge.target) { + challenge.score += 1; + challenge.target = pickTarget(target.index); + opts.onPop({ x, y, text: "+1 票", kind: "vote" }); + opts.onChallenge({ + left: Math.max(0, challenge.end - clock.elapsedTime), + score: challenge.score, + done: false, + }); + } else + opts.onPop({ + x, + y, + text: target.index === 0 ? "請支持!" : ["凍蒜!", "加油!", "讚啦!", "支持!"][Math.floor(Math.random() * 4)]!, + kind: "person", + }); + } else if (target.kind === "truck") { + truckBoost = 2.5; + opts.onPop({ x, y, text: "凍蒜!凍蒜!", kind: "truck" }); + } else { + burst(0.4, 0.2); + people.forEach((_, i) => setTimeout(() => jump(i), i * 60)); + opts.onPop({ x, y, text: "選戰開打!", kind: "stage" }); + } + }; + const onHover = (e: PointerEvent) => { + canvas.style.cursor = hit(e).target ? "pointer" : ""; + }; + canvas.addEventListener("pointerdown", onDown); + canvas.addEventListener("pointermove", onHover); + + // 鏡頭距離依畫面比例調整:直式(手機)拉遠拉高,讓整塊板子落在畫面下半部 + let view = { radius: 17, height: 9.5, lift: 0 }; + const place = (t: number) => { + // 鏡頭慢慢左右擺動,跟著滑鼠偏一點 + const sway = opts.reduceMotion ? 0 : Math.sin(t * 0.12) * 0.22 + pointerX * 0.08; + camera.position.set(Math.sin(sway) * view.radius + 1, view.height, Math.cos(sway) * view.radius); + camera.lookAt(target.x, target.y + view.lift, target.z); + }; + + const dummy = new THREE.Object3D(); + const frame = () => { + if (disposed) return; + raf = requestAnimationFrame(frame); + if (!active) return; + const dt = Math.min(clock.getDelta(), 0.05); + const t = clock.elapsedTime; + place(t); + for (const m of mixers) m.update(dt); + if (truck) { + // 點宣傳車會加速幾秒 + truckBoost = Math.max(0, truckBoost - dt); + truckU += dt * 0.035 * (1 + truckBoost * 1.6); + const p = roadPoint(truckU); + truck.position.set(p.x, truckBoost > 0 ? Math.abs(Math.sin(t * 30)) * 0.05 : 0, p.z); + truck.rotation.y = p.angle; + } + if (challenge) { + const left = challenge.end - t; + const who = people[challenge.target]; + if (who) { + ring.visible = true; + ring.position.set(who.root.position.x, 0.05 + Math.abs(Math.sin(t * 6)) * 0.05, who.root.position.z); + ring.scale.setScalar(1 + Math.sin(t * 8) * 0.08); + arrow.visible = true; + arrow.position.set(who.root.position.x, 1.55 + Math.abs(Math.sin(t * 5)) * 0.25, who.root.position.z); + arrow.rotation.y = t * 3; + } + if (left <= 0) { + opts.onChallenge({ left: 0, score: challenge.score, done: true }); + challenge = null; + ring.visible = false; + arrow.visible = false; + burst(0.4, 0.6); + } + } + if (!opts.reduceMotion) { + if (t - lastBurst > 6) { + lastBurst = t; + burst(0.4, 0.6); + } + if (floaterSources.length && t - lastFloat > 1.1) { + lastFloat = t; + const src = floaterSources[Math.floor(Math.random() * floaterSources.length)]!; + const obj = src.clone(); + const x = -2.4 + Math.random() * 5; + const z = 0.6 + Math.random() * 1.8; + obj.position.set(x, 1, z); + scene.add(obj); + floaters.push({ obj, born: t, x, z, spin: 2 + Math.random() * 2 }); + } + } + for (let i = floaters.length - 1; i >= 0; i--) { + const f = floaters[i]!; + const age = t - f.born; + f.obj.position.y = 1 + age * 1.3 + Math.sin(age * 3) * 0.1; + f.obj.rotation.y = age * f.spin; + const s = Math.max(0.001, age < 0.3 ? age / 0.3 : 1 - Math.max(0, age - 1.6) / 0.6); + f.obj.scale.setScalar(s); + if (age > 2.2) { + scene.remove(f.obj); + floaters.splice(i, 1); + } + } + for (let i = 0; i < CONFETTI; i++) { + const b = bits[i]!; + if (b.p.y > -1) { + b.v.y -= 4.5 * dt; + b.v.multiplyScalar(0.985); + b.p.addScaledVector(b.v, dt); + b.r.x += b.w.x * dt; + b.r.y += b.w.y * dt; + if (b.p.y < 0.02) b.p.y = -10; + } + dummy.position.copy(b.p); + dummy.rotation.copy(b.r); + dummy.updateMatrix(); + confetti.setMatrixAt(i, dummy.matrix); + } + if (CONFETTI) confetti.instanceMatrix.needsUpdate = true; + renderer.render(scene, camera); + }; + + // 模型還沒讀完玩家就離開首頁(已經 dispose):不要再啟動繪圖迴圈,否則它會在背景一直跑 + let disposed = false; + build() + .then(() => { + if (disposed) return; + place(0); + renderer.render(scene, camera); + opts.onReady(); + if (!opts.reduceMotion) raf = requestAnimationFrame(frame); + else { + // 減少動態:停在一張好看的畫面,只畫一次 + for (const m of mixers) m.update(0.4); + if (truck) { + const p = roadPoint(0.04); + truck.position.set(p.x, 0, p.z); + truck.rotation.y = p.angle; + } + renderer.render(scene, camera); + } + }) + .catch(() => !disposed && opts.onError()); + + return { + resize(w, h) { + renderer.setSize(w, h, false); + camera.aspect = w / Math.max(1, h); + // 窄螢幕拉遠一點,整塊板子都看得到 + camera.fov = camera.aspect < 1 ? 40 : camera.aspect < 1.5 ? 36 : 32; + view = camera.aspect < 1 ? { radius: 30, height: 22, lift: 4.5 } : camera.aspect < 1.5 ? { radius: 21, height: 12, lift: 1 } : { radius: 17, height: 9.5, lift: 0 }; + camera.updateProjectionMatrix(); + if (opts.reduceMotion) { + place(0); + renderer.render(scene, camera); + } + }, + cheer(kind) { + if (kind === "truck") truckBoost = 2.5; + if (kind === "rally") burst(0.4, 0.2); + people.forEach((_, i) => setTimeout(() => jump(i), i * (kind === "crowd" ? 40 : 70))); + }, + startChallenge() { + challenge = { + end: clock.elapsedTime + 15, + score: 0, + target: pickTarget(-1), + }; + opts.onChallenge({ left: 15, score: 0, done: false }); + }, + setActive(on) { + active = on; + if (on) clock.getDelta(); + }, + dispose() { + disposed = true; + cancelAnimationFrame(raf); + canvas.removeEventListener("pointermove", onPointer); + canvas.removeEventListener("pointermove", onHover); + canvas.removeEventListener("pointerdown", onDown); + textures.forEach((t) => t.dispose()); + scene.traverse((o) => { + const m = o as THREE.Mesh; + m.geometry?.dispose(); + const mat = m.material as THREE.Material | THREE.Material[] | undefined; + (Array.isArray(mat) ? mat : mat ? [mat] : []).forEach((x) => x.dispose()); + }); + renderer.dispose(); + }, + }; +} diff --git a/web/src/game/ui/ConfirmDialog.tsx b/web/src/game/ui/ConfirmDialog.tsx new file mode 100644 index 0000000..8b1675a --- /dev/null +++ b/web/src/game/ui/ConfirmDialog.tsx @@ -0,0 +1,62 @@ +import { AlertTriangle } from "lucide-react"; +import { useEffect, useRef, type ReactNode } from "react"; +import { sfx } from "../audio/sfx.ts"; +import "./scene.css"; + +/** + * 遊戲裡的確認視窗(取代瀏覽器的 confirm(),有些內嵌瀏覽器會擋掉、也不像遊戲)。 + * 預設焦點在「取消」,Esc 或點外面也是取消。 + */ +export function ConfirmDialog({ + title, + children, + confirmLabel, + cancelLabel = "取消", + danger = false, + onConfirm, + onCancel, +}: { + title: string; + children?: ReactNode; + confirmLabel: string; + cancelLabel?: string; + danger?: boolean; + onConfirm: () => void; + onCancel: () => void; +}) { + const cancelRef = useRef(null); + useEffect(() => { + cancelRef.current?.focus(); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCancel(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onCancel]); + return ( +
    e.target === e.currentTarget && onCancel()}> +
    + + + +

    {title}

    + {children &&
    {children}
    } +
    + + +
    +
    +
    + ); +} diff --git a/web/src/game/ui/GameScene.tsx b/web/src/game/ui/GameScene.tsx new file mode 100644 index 0000000..2ba7e00 --- /dev/null +++ b/web/src/game/ui/GameScene.tsx @@ -0,0 +1,62 @@ +import { ArrowLeft } from "lucide-react"; +import type { ReactNode } from "react"; +import { sfx } from "../audio/sfx.ts"; +import "./scene.css"; + +/** + * 全螢幕的遊戲場景(docs/23「沉浸式畫面」,18 第 43 項):每個畫面是一個場景,不像網頁往下捲。 + * - 左上角一顆圓形返回鍵+遊戲名牌(標題),右上角放這個畫面的狀態(點數、進度…)。 + * - 下面是場景本體:整頁不捲動;清單太長時,用 .gs-scroll 包起來,只有那一塊自己捲。 + * - 背景分三種:night(深藍夜色,和標題畫面一樣)、day(白天藍天)、paper(紙張,檔案室、卡冊)。 + * 顏色、字型都用 theme/tokens.css,和選戰畫面同一套。 + */ +export function GameScene({ + title, + kicker, + back = "#/", + backLabel = "回標題畫面", + tone = "night", + hud, + className, + children, +}: { + title: string; + kicker?: string; + back?: string; + backLabel?: string; + tone?: "night" | "day" | "paper"; + /** 右上角的狀態 */ + hud?: ReactNode; + className?: string; + children: ReactNode; +}) { + return ( +
    +
    +
    + sfx.click()}> + + +
    + {kicker && {kicker}} +

    {title}

    +
    + {hud &&
    {hud}
    } +
    +
    {children}
    +
    + ); +} + +/** 場景右上角的一個狀態徽章:圖示+數字+說明 */ +export function SceneStat({ icon, value, label }: { icon: ReactNode; value: ReactNode; label: string }) { + return ( + + + {icon} + + {value} + {label} + + ); +} diff --git a/web/src/game/ui/scene.css b/web/src/game/ui/scene.css new file mode 100644 index 0000000..c809236 --- /dev/null +++ b/web/src/game/ui/scene.css @@ -0,0 +1,75 @@ +/* 全螢幕的遊戲場景:整頁不捲動,左上返回鍵+名牌,右上狀態,下面是場景本體(GameScene.tsx) */ +.gs { position: fixed; inset: 0; z-index: 1; display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100dvh; overflow: hidden; color: var(--ink); padding-left: env(safe-area-inset-left, 0px); padding-right: env(safe-area-inset-right, 0px); } +.gs-bg { position: absolute; inset: 0; z-index: -1; } +.gs-night .gs-bg { background: radial-gradient(ellipse at 75% -10%, rgb(255 210 63 / 0.28), transparent 55%), radial-gradient(ellipse at 0% 110%, rgb(214 31 44 / 0.22), transparent 50%), linear-gradient(180deg, #1a2a4a 0%, #24365e 45%, #3a2a33 100%); } +.gs-day .gs-bg { background: radial-gradient(ellipse at 80% 0%, rgb(255 255 255 / 0.55), transparent 50%), linear-gradient(180deg, #8fd3ff 0%, #c9ecff 55%, #e9f6ff 100%); } +.gs-paper .gs-bg { background: repeating-linear-gradient(135deg, rgb(0 0 0 / 0.025) 0 2px, transparent 2px 14px), radial-gradient(ellipse at 50% 0%, rgb(255 210 63 / 0.25), transparent 60%), var(--newsprint); } +.gs-night { color: #fff; } + +/* 上面:返回鍵、名牌、狀態 */ +.gs-top { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: max(12px, env(safe-area-inset-top, 0px)) 16px 10px; } +.gs-back { width: 52px; height: 52px; display: grid; place-items: center; border-radius: 50%; background: #fffaf0; color: #111419; border: 3px solid #111419; box-shadow: 3px 3px 0 #111419; transition: transform 140ms var(--ease-out); } +.gs-back:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #111419; } +.gs-back:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +@media (hover: hover) and (pointer: fine) { + .gs-back:hover { background: var(--signal); } +} +.gs-plate { justify-self: start; display: grid; padding: 4px 22px 6px 16px; max-width: 100%; background: var(--signal); color: #111419; border: 3px solid #111419; box-shadow: 4px 4px 0 #111419; clip-path: polygon(0 0, 100% 0, calc(100% - 12px) 100%, 0 100%); animation: gs-plate 360ms var(--ease-out) both; } +.gs-plate small { font-size: 12px; font-weight: 800; letter-spacing: 0.12em; opacity: 0.75; } +.gs-plate h1 { margin: 0; font-family: var(--font-serif); font-size: clamp(22px, 3.2vw, 32px); line-height: 1.1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.gs-hud { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; } +.gs-stat { display: inline-grid; grid-template-columns: auto auto; grid-template-rows: auto auto; column-gap: 8px; align-items: center; padding: 4px 14px 4px 4px; border-radius: 999px; background: #fffaf0; color: #111419; border: 3px solid #111419; box-shadow: 3px 3px 0 #111419; } +.gs-stat-ic { grid-row: span 2; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 50%; background: var(--stamp); color: #fff; } +.gs-stat b { font-family: var(--font-num); font-size: 22px; line-height: 1; font-variant-numeric: tabular-nums; } +.gs-stat small { font-size: 11px; font-weight: 800; color: #5d646e; } + +/* 場景本體:整頁不捲;要捲的清單包 .gs-scroll */ +.gs-body { position: relative; min-height: 0; padding: 4px 16px max(14px, env(safe-area-inset-bottom, 0px)); animation: gs-in 360ms var(--ease-out) both; } +.gs-scroll { min-height: 0; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; } + +/* 場景裡的面板:厚框、偏移陰影(和選戰畫面同一套) */ +.gs-panel { background: var(--surface); color: var(--ink); border: 3px solid var(--ink); border-radius: 18px; box-shadow: 5px 5px 0 var(--shadow-ink); } + +/* 場景裡的厚框按鈕:一般是紙白、主要是黃、危險是紅 */ +.gs-btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 48px; padding: 8px 20px; border: 3px solid #111419; border-radius: 14px; background: #fffaf0; color: #111419; box-shadow: 3px 3px 0 #111419; font: inherit; font-weight: 900; font-size: 16px; text-decoration: none; cursor: pointer; transition: transform 140ms var(--ease-out), box-shadow 140ms var(--ease-out), background-color 150ms ease; } +.gs-btn.is-primary { background: var(--signal); } +.gs-btn.is-danger { background: var(--stamp); color: #fff; } +.gs-btn:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #111419; } +.gs-btn:disabled { opacity: 0.5; cursor: default; box-shadow: none; } +.gs-btn:focus-visible { outline: 4px solid var(--signal); outline-offset: 3px; } +.gs-btn.is-primary:focus-visible { outline-color: var(--stamp); } +@media (hover: hover) and (pointer: fine) { + .gs-btn:hover:not(:disabled) { background: var(--signal); } + .gs-btn.is-primary:hover:not(:disabled) { background: #ffe174; } + .gs-btn.is-danger:hover:not(:disabled) { background: #e8333f; } +} + +/* 確認視窗(ConfirmDialog.tsx) */ +.gs-confirm-wrap { position: fixed; inset: 0; z-index: 80; display: grid; place-items: center; padding: 16px; background: rgb(17 20 25 / 0.55); animation: gs-fade 180ms ease both; } +.gs-confirm { width: min(440px, 100%); display: grid; justify-items: center; gap: 10px; padding: 22px 20px 18px; text-align: center; animation: gs-pop 220ms var(--ease-out) both; } +.gs-confirm-ic { width: 52px; height: 52px; display: grid; place-items: center; border-radius: 50%; border: 3px solid var(--ink); background: var(--signal); color: #111419; } +.gs-confirm.is-danger .gs-confirm-ic { background: var(--stamp); color: #fff; } +.gs-confirm h2 { margin: 0; font-family: var(--font-serif); font-size: 24px; } +.gs-confirm-body { color: var(--muted); font-size: 15px; line-height: 1.5; } +.gs-confirm-body p { margin: 0; } +.gs-confirm-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 10px; margin-top: 6px; } +@keyframes gs-pop { from { opacity: 0; transform: scale(0.95); } } + +@keyframes gs-in { from { opacity: 0; transform: translateY(14px); } } +@keyframes gs-plate { from { opacity: 0; transform: translateX(-18px); } } +@media (max-width: 720px) { + .gs-top { gap: 8px; padding-inline: 10px; } + .gs-back { width: 44px; height: 44px; } + .gs-plate { padding: 3px 16px 4px 12px; } + .gs-stat { padding-right: 10px; } + .gs-stat-ic { width: 30px; height: 30px; } + .gs-stat b { font-size: 18px; } + .gs-body { padding-inline: 10px; } +} +@media (prefers-reduced-motion: reduce) { + .gs-body, + .gs-plate, + .gs-confirm { animation: gs-fade 200ms ease both; } + .gs-btn { transition: background-color 150ms ease; } +} +@keyframes gs-fade { from { opacity: 0; } } diff --git a/web/src/main.tsx b/web/src/main.tsx new file mode 100644 index 0000000..5bc9c06 --- /dev/null +++ b/web/src/main.tsx @@ -0,0 +1,12 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App.tsx"; +import "./theme/tokens.css"; + +const root = document.getElementById("root"); +if (!root) throw new Error("找不到 #root"); +createRoot(root).render( + + + , +); diff --git a/web/src/map/VillageMap.tsx b/web/src/map/VillageMap.tsx new file mode 100644 index 0000000..5b44c7e --- /dev/null +++ b/web/src/map/VillageMap.tsx @@ -0,0 +1,49 @@ +import type { VillageRecord } from "@election2026/protocol"; +import { geoMercator, geoPath } from "d3-geo"; +import { useMemo } from "react"; +import { feature } from "topojson-client"; +import type { GeometryCollection, Topology } from "topojson-specification"; +import type { Metric } from "./metrics.ts"; + +interface Props { + topology: Topology; + villages: Map; + metric: Metric; + selected: string | null; + onSelect: (code: string) => void; +} + +const WIDTH = 640; +const HEIGHT = 640; + +export function VillageMap({ topology, villages, metric, selected, onSelect }: Props) { + const shapes = useMemo(() => { + const object = topology.objects.villages as GeometryCollection<{ code: string; name: string }>; + const collection = feature(topology, object); + const projection = geoMercator().fitSize([WIDTH, HEIGHT], collection); + const path = geoPath(projection); + return collection.features.map((f) => ({ code: f.properties.code, d: path(f) ?? "" })); + }, [topology]); + + return ( + + {shapes.map(({ code, d }) => { + const village = villages.get(code); + const fill = village ? metric.color(metric.value(village)) : "var(--neutral)"; + return ( + onSelect(code)} + style={{ cursor: "pointer" }} + > + {village ? `${village.townName}${village.name}:${metric.format(metric.value(village))}` : code} + + ); + })} + + ); +} diff --git a/web/src/map/metrics.ts b/web/src/map/metrics.ts new file mode 100644 index 0000000..fe24ce1 --- /dev/null +++ b/web/src/map/metrics.ts @@ -0,0 +1,65 @@ +import type { VillageRecord } from "@election2026/protocol"; + +export type MetricId = "balance" | "third" | "turnout" | "elderly" | "flags"; + +export interface Metric { + id: MetricId; + label: string; + value: (v: VillageRecord) => number; + color: (x: number) => string; + format: (x: number) => string; +} + +const pct = (x: number) => `${(x * 100).toFixed(1)}%`; + +/** 兩色之間線性內插(#rrggbb)。 */ +export function mix(from: string, to: string, t: number): string { + const clamp = Math.min(1, Math.max(0, t)); + const parse = (hex: string) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)); + const [a, b] = [parse(from), parse(to)]; + return `#${a.map((c, i) => Math.round(c + ((b[i] ?? c) - c) * clamp).toString(16).padStart(2, "0")).join("")}`; +} + +/** 甲 − 乙 的傾向差:負值偏乙(赭)、正值偏甲(紫),±0.3 以上視為飽和。 */ +export function balanceColor(balance: number): string { + const neutral = "#d8dad6"; + return balance >= 0 ? mix(neutral, "#6d4a9e", balance / 0.3) : mix(neutral, "#b5762a", -balance / 0.3); +} + +export const METRICS: Metric[] = [ + { + id: "balance", + label: "政黨傾向(甲 − 乙)", + value: (v) => (v.lean ? v.lean.a_core + v.lean.a_lean - v.lean.b_core - v.lean.b_lean : 0), + color: balanceColor, + format: (x) => `${x >= 0 ? "甲" : "乙"} +${(Math.abs(x) * 100).toFixed(1)}`, + }, + { + id: "third", + label: "第三勢力傾向", + value: (v) => v.lean?.c_lean ?? 0, + color: (x) => mix("#d8dad6", "#3f8f8a", (x - 0.05) / 0.2), + format: pct, + }, + { + id: "turnout", + label: "基本投票率", + value: (v) => v.baseTurnout ?? 0, + color: (x) => mix("#d8dad6", "#1c2024", (x - 0.55) / 0.25), + format: pct, + }, + { + id: "elderly", + label: "65 歲以上比例(成年人口)", + value: (v) => (v.population.adults ? v.population.byAgeBand["65+"] / v.population.adults : 0), + color: (x) => mix("#d8dad6", "#c0352d", (x - 0.1) / 0.3), + format: pct, + }, + { + id: "flags", + label: "補值旗標", + value: (v) => (v.flags.some((f) => f.includes("imputed")) ? 1 : v.flags.length ? 0.5 : 0), + color: (x) => (x === 1 ? "#c0352d" : x > 0 ? "#e2b857" : "#d8dad6"), + format: (x) => (x === 1 ? "有補值" : x > 0 ? "有其他旗標" : "無"), + }, +]; diff --git a/web/src/theme/campaign.css b/web/src/theme/campaign.css new file mode 100644 index 0000000..58b08ec --- /dev/null +++ b/web/src/theme/campaign.css @@ -0,0 +1,114 @@ +/* + * 選戰文宣風(2026-10-25 改版):學台灣近年競選文宣與《人選之人—造浪者》的視覺語言, + * 但不套用任何政黨的識別色(政黨色只用在各候選人自己身上)。 + * - 粗黑體大字、窄體數字與小英文標籤 + * - 貼紙感:黑色粗框+錯位陰影的按鈕、標籤與卡牌 + * - 螢光筆黃標重點、圈選章紅是唯一的強調色 + * - 深藍夜色加浪花條紋:主視覺、狀態列、地圖桌面 + * 這個檔案最後載入,蓋過 game.css、screens.css 裡同名的樣式;顏色一律來自 tokens.css。 + */ + +body { -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } +.paper { --font-serif: var(--font-news); } +mark, .hl { background: linear-gradient(transparent 55%, var(--signal) 55%); color: inherit; padding: 0 0.1em; } + +/* ── 按鈕:貼紙 ── */ +.btn { + border: 2px solid var(--ink); + border-radius: 10px; + font-weight: 800; + box-shadow: 3px 3px 0 var(--shadow-ink); + transition: transform 120ms var(--ease-out), box-shadow 120ms var(--ease-out), background-color 150ms ease; +} +.btn:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--shadow-ink); } +.btn:disabled { box-shadow: none; } +.btn-primary { background: var(--ink); color: var(--surface); } +.btn-soft, .btn-ghost { background: var(--surface); color: var(--ink); } +.btn-ghost { box-shadow: none; border-width: 1.5px; } +.btn-ghost:active:not(:disabled) { transform: scale(0.97); box-shadow: none; } +@media (hover: hover) and (pointer: fine) { + .btn-soft:hover:not(:disabled) { background: var(--signal); color: var(--signal-ink); } + .btn-ghost:hover:not(:disabled) { background: var(--surface-2); } + .btn-primary:hover:not(:disabled) { background: color-mix(in srgb, var(--ink) 88%, var(--stamp)); } +} + +/* ── 面板:白紙黑框 ── */ +.side-body, .pick, .creator-preview { + border: 2px solid var(--ink); + border-radius: 16px; + background: var(--surface); +} +.notice { border: 2px solid var(--stamp); border-radius: 10px; background: color-mix(in srgb, var(--stamp) 8%, var(--surface)); font-weight: 600; } + +/* 跑馬燈:螢光黃新聞條 */ +.ticker { background: var(--signal); color: var(--signal-ink); border: 2px solid var(--ink); font-weight: 700; } +.ticker .tone-negative { color: color-mix(in srgb, var(--stamp) 85%, var(--signal-ink)); } + +/* ── 卡牌:印刷傳單 ── */ +.played li { background: var(--surface); border: 1.5px solid var(--ink); } + +/* ── 開始畫面 ── */ +.start { gap: 28px; } +.pick { box-shadow: 6px 6px 0 var(--shadow-ink); } +.creator-cta { border: 2px dashed var(--ink); background: color-mix(in srgb, var(--signal) 18%, var(--surface)); } + +/* 主視覺海報 */ +.ch { + position: relative; + display: grid; + grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); + align-items: center; + gap: 16px; + min-height: 360px; + padding: clamp(24px, 5vw, 56px); + border-radius: 22px; + overflow: hidden; + isolation: isolate; + color: var(--navy-ink); + background: + var(--wave-light), + radial-gradient(90% 120% at 85% 10%, color-mix(in srgb, var(--stamp) 35%, var(--navy-2)) 0%, transparent 55%), + linear-gradient(160deg, var(--navy-2) 0%, var(--navy) 70%); + border: 3px solid var(--ink); + box-shadow: 8px 8px 0 var(--shadow-ink); +} +.ch::after { + /* 網點:右下角像印刷品的網點 */ + content: ""; + position: absolute; + inset: auto 0 0 auto; + width: 60%; + height: 70%; + background: radial-gradient(circle, rgb(255 255 255 / 0.12) 1.6px, transparent 1.8px) 0 0 / 11px 11px; + -webkit-mask-image: radial-gradient(120% 120% at 100% 100%, #000 20%, transparent 70%); + mask-image: radial-gradient(120% 120% at 100% 100%, #000 20%, transparent 70%); + z-index: -1; +} +.ch-copy { display: grid; gap: 12px; align-content: center; min-width: 0; } +.ch-collage { position: relative; min-height: 300px; } +.ch-flyer { position: absolute; margin: 0; width: min(58%, 250px); background: #fff; padding: 8px 8px 22px; border-radius: 4px; box-shadow: 0 16px 30px -12px rgb(0 0 0 / 0.6); transform: rotate(var(--tilt)); } +.ch-flyer img { display: block; width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 2px; } +.ch-flyer::before { content: ""; position: absolute; top: -10px; left: 50%; width: 64px; height: 20px; translate: -50% 0; rotate: 3deg; background: color-mix(in srgb, var(--signal) 75%, #fff); opacity: 0.9; } +.ch-flyer-0 { left: 0; top: 4%; z-index: 1; } +.ch-flyer-1 { right: 0; top: 0; z-index: 2; } +.ch-flyer-2 { left: 22%; bottom: 0; z-index: 3; } +.ch-stamp { position: absolute; right: 4%; bottom: 2%; z-index: 4; rotate: -12deg; background: #fff; border-radius: 50%; padding: 6px; box-shadow: 0 8px 20px -8px rgb(0 0 0 / 0.6); } +.ch-vertical { position: absolute; right: 14px; top: 18px; writing-mode: vertical-rl; font-weight: 900; font-size: 15px; letter-spacing: 0.4em; color: color-mix(in srgb, var(--navy-ink) 45%, transparent); } +@media (max-width: 760px) { + .ch { grid-template-columns: minmax(0, 1fr); min-height: 0; padding-bottom: 20px; } + .ch-collage { min-height: 220px; } + .ch-flyer { width: 44%; } + .ch-vertical { display: none; } +} +@media (prefers-reduced-motion: no-preference) { + .ch-flyer { animation: flyer-in 520ms var(--ease-out) both; } + .ch-flyer-1 { animation-delay: 80ms; } + .ch-flyer-2 { animation-delay: 160ms; } + .ch-stamp { animation: stamp-drop 420ms 420ms var(--ease-out) both; } +} +@keyframes flyer-in { from { opacity: 0; transform: translateY(18px) rotate(var(--tilt)); } } +@keyframes stamp-drop { from { opacity: 0; scale: 1.6; } } + +/* 晨報:報紙本身也是一張貼在桌上的紙,頭條配插圖 */ +.paper { border: 3px solid var(--ink); border-radius: 6px; box-shadow: 10px 10px 0 var(--shadow-ink); } +.card-art.is-paper { aspect-ratio: 21 / 8; border-radius: 4px; filter: saturate(0.9) contrast(1.05); } diff --git a/web/src/theme/tokens.css b/web/src/theme/tokens.css new file mode 100644 index 0000000..121ff5c --- /dev/null +++ b/web/src/theme/tokens.css @@ -0,0 +1,154 @@ +/* 字型(web/public/assets/LICENSES.md):一般粗細用 jf open 粉圓(OFL,未修改), + 粗體與標題用 Tongsuan Rounded(源泉圓體 Heavy 的子集,OFL 規定改過的版本要改名) */ +@font-face { + font-family: "Tongsuan UI"; + src: url("/assets/fonts/jf-openhuninn-2.1.woff2") format("woff2"); + font-weight: 100 600; + font-display: swap; +} +@font-face { + font-family: "Tongsuan UI"; + src: url("/assets/fonts/tongsuan-rounded-heavy.woff2") format("woff2"); + font-weight: 700 950; + font-display: swap; +} +@font-face { + font-family: "Tongsuan Rounded"; + src: url("/assets/fonts/tongsuan-rounded-heavy.woff2") format("woff2"); + font-weight: 100 950; + font-display: swap; +} + +/* 設計 token:換風格只改這裡(docs/16)。 + 政黨槽位用真實政黨色:a=民主進步黨(綠)、b=中國國民黨(藍)、c=台灣民眾黨(青)。 + 色階經 dataviz validate_palette 驗證:淺色、深色各自通過色盲分辨與對比檢查(任兩色都比較過); + 民眾黨青和民進黨綠在藍黃色盲(tritan)下較接近,所以候選人一律附名字標示,不只靠顏色。 + 「其他」(無黨籍)用灰色。黨旗本身用官方色,見 game/PartyFlag.tsx。 */ +:root { + color-scheme: light; + /* 選戰文宣風:海報紙、黑墨、圈選章紅、螢光筆黃;深色模式是夜裡的競選辦公室(深藍) */ + --paper: #ecebe6; + --surface: #ffffff; + --surface-2: #f3f2ee; + --ink: #111419; + --muted: #5d646e; + --line: #d6d4cd; + --stamp: #d61f2c; + --signal: #ffd23f; + --signal-ink: #111419; + --navy: #0f1e33; + --navy-2: #1a2e4a; + --navy-ink: #eef2f7; + --shadow-ink: #111419; + --good: #2f7d4f; + --newsprint: #f8f4ea; + --sea: #cfe1e6; + --sea-line: #b4cfd7; + --land-neighbor: #e8e2d3; + --land-neighbor-line: #d2c9b5; + --district-line: rgb(255 255 255 / 0.9); + --county-line: #5c554a; + --terrain-line: rgb(60 50 30 / 0.16); + --landmark-line: #9a8f78; + --landmark-ink: #5c554a; + --tv-bg: #0f1d33; + --tv-ink: #f4f1ea; + --slot-a: #1b9431; + --slot-b: #2349b8; + --slot-c: #16a3a6; + --slot-other: #858a8f; + --neutral: #c9cdca; + /* 地圖底色:領先幅度小的區往這個顏色混,淺色、深色模式都是「越濃=領先越多」 */ + --map-base: #efebe1; + /* 立體桌遊盤的木框 */ + --board-wood: #b98a5a; + --board-wood-grain: #6e4a2a; + --font-body: "Tongsuan UI", "Noto Sans TC", "PingFang TC", "Microsoft JhengHei", system-ui, sans-serif; + /* 標題一律用粗黑體(競選文宣的大字);報紙版面另外用明體(.paper 裡重新定義) */ + --font-serif: "Tongsuan Rounded", "Noto Sans TC", "PingFang TC", "Microsoft JhengHei", system-ui, sans-serif; + --font-news: "Noto Serif TC", "Songti TC", "PMingLiU", serif; + /* 數字與小英文標籤:窄體,像看板上的號次與日期 */ + --font-num: "Barlow Condensed", "Tongsuan UI", "Noto Sans TC", ui-sans-serif, system-ui, sans-serif; + /* 浪花條紋(造浪):用在主視覺、狀態列、桌面 */ + --wave-light: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='96' height='20' viewBox='0 0 96 20'%3E%3Cpath d='M0 10 Q12 2 24 10 T48 10 T72 10 T96 10' fill='none' stroke='white' stroke-opacity='.10' stroke-width='2'/%3E%3C/svg%3E"); + --ease-out: cubic-bezier(0.23, 1, 0.32, 1); + --ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + color-scheme: dark; + --paper: #0b1420; + --surface: #111d2d; + --surface-2: #17273b; + --ink: #eef1f5; + --muted: #93a1b3; + --line: #253852; + --stamp: #ff4d5a; + --signal: #ffd23f; + --signal-ink: #111419; + --navy: #060d17; + --navy-2: #0f1d30; + --navy-ink: #eef2f7; + --shadow-ink: #000000; + --good: #5bb37f; + --newsprint: #24231f; + --sea: #17262d; + --sea-line: #213a44; + --land-neighbor: #26272a; + --land-neighbor-line: #33353a; + --district-line: rgb(20 21 23 / 0.85); + --county-line: #b3aa97; + --terrain-line: rgb(255 255 255 / 0.1); + --landmark-line: #6f6a60; + --landmark-ink: #cfc8b9; + --tv-bg: #0a1526; + --tv-ink: #f4f1ea; + --slot-a: #2ea84a; + --slot-b: #4a63e0; + --slot-c: #16a4b8; + --slot-other: #8a9096; + --neutral: #3a3f44; + --map-base: #5a6066; + --board-wood: #5e4630; + --board-wood-grain: #2a1d12; + } +} +:root[data-theme="dark"] { + color-scheme: dark; + --paper: #0b1420; + --surface: #111d2d; + --surface-2: #17273b; + --ink: #eef1f5; + --muted: #93a1b3; + --line: #253852; + --stamp: #ff4d5a; + --signal: #ffd23f; + --signal-ink: #111419; + --navy: #060d17; + --navy-2: #0f1d30; + --navy-ink: #eef2f7; + --shadow-ink: #000000; + --good: #5bb37f; + --newsprint: #24231f; + --sea: #17262d; + --sea-line: #213a44; + --land-neighbor: #26272a; + --land-neighbor-line: #33353a; + --district-line: rgb(20 21 23 / 0.85); + --county-line: #b3aa97; + --terrain-line: rgb(255 255 255 / 0.1); + --landmark-line: #6f6a60; + --landmark-ink: #cfc8b9; + --tv-bg: #0a1526; + --tv-ink: #f4f1ea; + --slot-a: #2ea84a; + --slot-b: #4a63e0; + --slot-c: #16a4b8; + --slot-other: #8a9096; + --neutral: #3a3f44; + --map-base: #5a6066; + --board-wood: #5e4630; + --board-wood-grain: #2a1d12; +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--paper); color: var(--ink); font-family: var(--font-body); } diff --git a/web/src/viewer/DataViewer.tsx b/web/src/viewer/DataViewer.tsx new file mode 100644 index 0000000..feb5da6 --- /dev/null +++ b/web/src/viewer/DataViewer.tsx @@ -0,0 +1,94 @@ +import { LEANS, type VillageRecord } from "@election2026/protocol"; +import { useEffect, useMemo, useState } from "react"; +import { type DataPack, loadPack } from "../data/loadPack.ts"; +import { METRICS, type MetricId } from "../map/metrics.ts"; +import { VillageMap } from "../map/VillageMap.tsx"; + +const PACK = "/fixtures/packs/68000"; +const LEAN_LABELS: Record = { + a_core: "甲核心", + a_lean: "甲傾向", + middle: "中間", + b_lean: "乙傾向", + b_core: "乙核心", + c_lean: "第三勢力", +}; + +export function DataViewer() { + const [pack, setPack] = useState(null); + const [error, setError] = useState(null); + const [metricId, setMetricId] = useState("balance"); + const [selected, setSelected] = useState(null); + + useEffect(() => { + loadPack(PACK).then(setPack, (e: unknown) => setError(e instanceof Error ? e.message : String(e))); + }, []); + + const villages = useMemo(() => new Map(pack?.villages.map((v) => [v.code, v]) ?? []), [pack]); + const metric = METRICS.find((m) => m.id === metricId) ?? METRICS[0]!; + + if (error) return
    資料讀取失敗:{error}
    ; + if (!pack) return
    讀取資料包中…
    ; + + const village = selected ? villages.get(selected) : undefined; + const slots = pack.manifest.partySlots; + return ( +
    +
    +

    資料檢視器:{pack.manifest.scope.countyName}

    +

    + {pack.manifest.packId}・{pack.villages.length} 個里・甲={slots.a}、乙={slots.b}、第三勢力={slots.c}・ + 有旗標 {pack.manifest.counts.villagesWithFlags} 個里 +

    +
    + +
    + + +
    +
    + ); +} + +function VillageDetail({ village, cells }: { village: VillageRecord; cells: number[] | undefined }) { + const pct = (x: number | null | undefined) => (x == null ? "—" : `${(x * 100).toFixed(1)}%`); + return ( +
    +

    + {village.townName}{village.name} +

    +
    人口 {village.population.total.toLocaleString()}・成年 {village.population.adults.toLocaleString()}
    +
    選舉人數 {village.electors?.toLocaleString() ?? "—"}・基本投票率 {pct(village.baseTurnout)}
    +
    所得中位數 {village.attributes.incomeMedian ?? "—"} 千元・寺廟 {village.attributes.templeCount} 間
    + + + {LEANS.map((l) => ( + + + + + ))} + +
    {LEAN_LABELS[l]}{pct(village.lean?.[l])}
    +
    選民群:{cells ? `${cells.length} 格` : "—"}
    + {village.flags.length > 0 && ( +
      + {village.flags.map((f) => ( +
    • {f}
    • + ))} +
    + )} +
    + ); +} diff --git a/web/test/career-rules.test.ts b/web/test/career-rules.test.ts new file mode 100644 index 0000000..7c19272 --- /dev/null +++ b/web/test/career-rules.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { emptyTiers, gainExp, highestOpen, noCarry, runExp, startAbilities, toNext, unlockOf, withOriginRules, type CareerState } from "../src/game/rogue/careerRules.ts"; + +const base = { eloquence: 1, organization: 1, media: 1, finance: 1, integrity: 1 }; +const fresh = (over: Partial = {}): CareerState => ({ + id: "c", + character: { id: "x", name: "林小美", party: "民主進步黨", background: "基層里長", stats: { fame: 5, eloquence: 5, strategy: 5, wealth: 5, network: 5 }, avatar: {} as never }, + county: { code: "64000", name: "高雄市" }, + village: null, + villageTown: null, + district: null, + level: 1, + exp: 0, + skillPoints: 0, + abilities: base, + base, + tiers: emptyTiers(), + skipped: [], + carry: noCarry(), + history: [], + pending: null, + ...over, +}); + +describe("政治生涯的練等規則", () => { + it("一開始只能選里長;議員要先選上里長、而且 Lv 3", () => { + const c = fresh(); + expect(highestOpen(c)).toBe(1); + expect(unlockOf(c, 2)).toEqual({ open: false, why: "先選上里長・要 Lv 3" }); + const won = fresh({ tiers: { ...emptyTiers(), 1: { runs: 1, wins: 1, best: "B", topExtra: 0 } } }); + expect(unlockOf(won, 2).why).toBe("要 Lv 3"); + expect(unlockOf({ ...won, level: 3 }, 2).open).toBe(true); + }); + + it("經驗:當選全額、落選四成、逆風越高越多、回去選低的關打六折", () => { + const c = fresh(); + expect(runExp(c, 1, true, "B", 0).exp).toBe(40); + expect(runExp(c, 1, false, "C", 0).exp).toBe(16); + expect(runExp(c, 1, true, "S", 2).exp).toBe(Math.round(40 * 1.3 * 1.5)); + const higher = fresh({ level: 3, tiers: { ...emptyTiers(), 1: { runs: 1, wins: 1, best: "B", topExtra: 0 } } }); + expect(runExp(higher, 1, true, "B", 0).exp).toBe(24); + }); + + it("升級:經驗滿了升級,每級 +1 技能點,一次可以連升", () => { + expect(toNext(1)).toBe(40); + expect(toNext(2)).toBe(70); + const { next, levels } = gainExp(fresh({ exp: 30 }), 90); + expect(levels).toBe(2); + expect(next.level).toBe(3); + expect(next.exp).toBe(30 + 90 - 40 - 70); + expect(next.skillPoints).toBe(2); + }); + + it("選上總統要很多場:大約十幾到二十場才到 Lv 12", () => { + let total = 0; + for (let lv = 1; lv < 12; lv++) total += toNext(lv); + expect(total).toBeGreaterThan(2000); + }); +}); + +describe("出身與黨的資源(18 第 53 項)", () => { + it("小黨、無黨籍經驗 ×1.2", () => { + const c = fresh(); + const minor = { ...c, character: { ...c.character, party: null } }; + expect(runExp(minor, 1, true, "B", 0).exp).toBe(Math.round(runExp(c, 1, true, "B", 0).exp * 1.2)); + expect(runExp(minor, 1, true, "B", 0).why).toContain("無黨籍 ×1.2"); + }); + + it("開局能力:點數+出身 +1+黨的資源 +1;舊存檔換新規則時保留自己加的點", () => { + const c = fresh(); + // 基層里長:組織 +1;民進黨(大黨):組織 +1;點數 5 → 每項 1 級 + expect(startAbilities(c.character)).toEqual({ eloquence: 1, organization: 3, media: 1, finance: 1, integrity: 0 }); + const old = { ...c, base: { eloquence: 1, organization: 1, media: 1, finance: 1, integrity: 1 }, abilities: { eloquence: 3, organization: 1, media: 1, finance: 1, integrity: 1 } }; + const next = withOriginRules(old); + expect(next.base).toEqual(startAbilities(c.character)); + expect(next.abilities.eloquence).toBe(3); + expect(next.abilities.organization).toBe(3); + expect(next.abilities.integrity).toBe(0); + expect(withOriginRules(next)).toBe(next); + }); +}); diff --git a/web/test/game.test.ts b/web/test/game.test.ts new file mode 100644 index 0000000..2251e5a --- /dev/null +++ b/web/test/game.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from "vitest"; +import { pct } from "../src/game/format.ts"; + +describe("顯示用的小工具", () => { + it("百分比", () => { + expect(pct(0.4567)).toBe("45.7%"); + expect(pct(0.4567, 2)).toBe("45.67%"); + }); +}); diff --git a/web/test/geometry-rings.test.ts b/web/test/geometry-rings.test.ts new file mode 100644 index 0000000..b051131 --- /dev/null +++ b/web/test/geometry-rings.test.ts @@ -0,0 +1,30 @@ +/// +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { FeatureCollection, Geometry } from "geojson"; +import type { Topology } from "topojson-specification"; +import { describe, expect, it } from "vitest"; +import { STAGE_HEIGHT, STAGE_WIDTH, buildGeometry, type StagePolygons } from "../src/game/stage/geometry.ts"; + +const packs = join(import.meta.dirname, "..", "..", "backend", "data", "build", "packs"); +const read = (path: string): T => JSON.parse(readFileSync(path, "utf-8")) as T; +const context = read>(join(import.meta.dirname, "..", "public", "maps", "taiwan-counties.json")); +const has = (pack: string) => existsSync(join(packs, pack, "topology.json")); +const topo = (pack: string) => read(join(packs, pack, "topology.json")); + +const points = (polys: StagePolygons) => polys.flat(2); +const inside = (polys: StagePolygons, pad = 1) => points(polys).every(([x, y]) => x >= -pad && x <= STAGE_WIDTH + pad && y >= -pad && y <= STAGE_HEIGHT + pad); + +describe("立體盤面用的多邊形", () => { + it.skipIf(!has("68000-before-2022-11-26"))("桃園:每區都有外圈,鄰近縣市裁在盤面內", () => { + const g = buildGeometry(topo("68000-before-2022-11-26"), context, { county: "68000", level: "town", villages: null, names: new Map() }); + expect(g.towns.length).toBe(13); + for (const t of g.towns) { + expect(t.rings.length).toBeGreaterThan(0); + expect(t.rings[0]![0]!.length).toBeGreaterThanOrEqual(3); + expect(inside(t.rings)).toBe(true); + } + expect(g.context.length).toBeGreaterThan(0); + for (const c of g.context) expect(inside(c.rings, 0.01)).toBe(true); + }); +}); diff --git a/web/test/geometry.test.ts b/web/test/geometry.test.ts new file mode 100644 index 0000000..ec6c7ff --- /dev/null +++ b/web/test/geometry.test.ts @@ -0,0 +1,55 @@ +/// +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { FeatureCollection, Geometry } from "geojson"; +import type { Topology } from "topojson-specification"; +import { describe, expect, it } from "vitest"; +import { STAGE_HEIGHT, STAGE_WIDTH, buildGeometry } from "../src/game/stage/geometry.ts"; + +const packs = join(import.meta.dirname, "..", "..", "backend", "data", "build", "packs"); +const read = (path: string): T => JSON.parse(readFileSync(path, "utf-8")) as T; +const context = read>(join(import.meta.dirname, "..", "public", "maps", "taiwan-counties.json")); +const has = (pack: string) => existsSync(join(packs, pack, "topology.json")); +const topo = (pack: string) => read(join(packs, pack, "topology.json")); + +/** path 字串裡所有座標都在舞台內(允許一點邊界誤差) */ +function inStage(d: string): boolean { + const nums = d.match(/-?\d+(\.\d+)?/g)?.map(Number) ?? []; + for (let i = 0; i + 1 < nums.length; i += 2) if (nums[i]! < -1 || nums[i]! > STAGE_WIDTH + 1 || nums[i + 1]! < -1 || nums[i + 1]! > STAGE_HEIGHT + 1) return false; + return true; +} + +describe("地圖舞台", () => { + it.skipIf(!has("63000-before-2024-01-13"))("立委選區:只上色選區內的里,選區外的同市各區當底圖", () => { + const t = topo("63000-before-2024-01-13"); + const all = (t.objects.villages as unknown as { geometries: { properties: { code: string } }[] }).geometries.map((g) => g.properties.code); + const villages = new Set(all.filter((c) => c.startsWith("63000120") || c === "63000110001")); + const g = buildGeometry(t, context, { county: "63000", level: "town", villages, names: new Map([["63000120", "北投區"], ["63000110", "士林區"]]) }); + expect(g.villages.length).toBe(villages.size); + expect(g.towns.map((x) => x.name).sort()).toEqual(["北投區", "士林區"]); + // 士林區其餘的里、以及大安區等,都畫成底圖 + expect(g.context.some((c) => c.name === "士林區")).toBe(true); + expect(g.context.some((c) => c.name === "大安區")).toBe(true); + expect(g.villages.every((v) => inStage(v.d))).toBe(true); + }); + + it.skipIf(!has("10002-before-2022-11-26"))("宜蘭縣:遠方的釣魚台不算進縮放範圍,本島填滿畫面", () => { + const g = buildGeometry(topo("10002-before-2022-11-26"), context, { county: "10002", level: "town", villages: null, names: new Map() }); + const yilan = g.towns.find((x) => x.name === "宜蘭市")!; + expect(yilan.cx).toBeGreaterThan(0); + expect(yilan.cx).toBeLessThan(STAGE_WIDTH); + // 宜蘭市在縣的中段:沒被釣魚台擠到畫面左邊 + expect(yilan.cx).toBeGreaterThan(STAGE_WIDTH * 0.3); + }); + + it.skipIf(!has("00000-before-2024-01-13"))("全國:22 縣市各是一區,金門、馬祖放進小框", () => { + const g = buildGeometry(topo("00000-before-2024-01-13"), context, { county: "00000", level: "county", villages: null, names: new Map() }); + expect(g.towns.length).toBe(22); + expect(g.insets.map((i) => i.name)).toEqual(["連江縣", "金門縣"]); + const matsu = g.towns.find((x) => x.code === "09007000")!; + const box = g.insets[0]!; + expect(matsu.cx).toBeGreaterThan(box.x); + expect(matsu.cx).toBeLessThan(box.x + box.w); + expect(g.context).toEqual([]); + }); +}); diff --git a/web/test/island-bonus.test.ts b/web/test/island-bonus.test.ts new file mode 100644 index 0000000..863f5c3 --- /dev/null +++ b/web/test/island-bonus.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { POLICY_HOME, policyBonuses, policyBoost, targetsOf } from "../src/game/island/data.ts"; + +describe("政策落地:政策和小島的關係", () => { + it("每種政策對象都有一棟家;長照中心是長輩政策的家", () => { + expect(POLICY_HOME.old).toBe("care"); + expect(targetsOf("plaza")).toEqual(["客家鄉親", "信眾"]); + }); + + it("長輩補助:落地+長照中心的長輩區加成合成一列;政策研究院 3 級才算生效", () => { + const rows = policyBonuses({ target: "old", method: "subsidy" }, { care: 2, library: 1 }); + const care = rows.find((r) => r.building === "care")!; + expect(care.home).toBe(true); + expect(care.text).toBe("政策落地 +20%;打在長輩多的區 +16%"); + expect(care.active).toBe(true); + expect(rows.find((r) => r.building === "library")!.active).toBe(false); + // 一定吃得到的只有落地 +20% + expect(policyBoost({ target: "old", method: "subsidy" }, { care: 2, library: 1 })).toBe(20); + }); + + it("修法、減稅算媒體牌:媒體中心也會加;還沒蓋的寫「蓋了每級 +N%」", () => { + const rows = policyBonuses({ target: "young", method: "tax_cut" }, { media: 1 }); + expect(rows.map((r) => r.building)).toEqual(["techpark", "media", "library"]); + expect(rows[0]!.text).toBe("政策落地:蓋了每級 +10%"); + expect(rows[1]!.text).toBe("算媒體牌 +6%"); + expect(policyBoost({ target: "young", method: "tax_cut" }, { media: 1, techpark: 1, library: 3 })).toBe(Math.round((1.1 * 1.06 * 1.15 - 1) * 100)); + }); +}); diff --git a/web/test/metrics.test.ts b/web/test/metrics.test.ts new file mode 100644 index 0000000..5335cca --- /dev/null +++ b/web/test/metrics.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { balanceColor, METRICS, mix } from "../src/map/metrics.ts"; + +describe("mix", () => { + it("兩端與中點", () => { + expect(mix("#000000", "#ffffff", 0)).toBe("#000000"); + expect(mix("#000000", "#ffffff", 1)).toBe("#ffffff"); + expect(mix("#000000", "#ffffff", 0.5)).toBe("#808080"); + }); + it("超出範圍會被夾住", () => { + expect(mix("#000000", "#ffffff", 2)).toBe("#ffffff"); + expect(mix("#000000", "#ffffff", -1)).toBe("#000000"); + }); +}); + +describe("balanceColor", () => { + it("正值偏紫、負值偏赭、零為中性", () => { + expect(balanceColor(0.3)).toBe("#6d4a9e"); + expect(balanceColor(-0.3)).toBe("#b5762a"); + expect(balanceColor(0)).toBe("#d8dad6"); + }); +}); + +describe("METRICS", () => { + it("每個指標都有唯一 id", () => { + expect(new Set(METRICS.map((m) => m.id)).size).toBe(METRICS.length); + }); +}); diff --git a/web/test/minigames.test.ts b/web/test/minigames.test.ts new file mode 100644 index 0000000..a4348b2 --- /dev/null +++ b/web/test/minigames.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it } from "vitest"; +import { BILLBOARD_MS, billboardScore, makeBillboard, walkway } from "../src/game/minigames/billboard-logic.ts"; +import { HANDSHAKE_MS, handshakeScore, makeHandshake, portraitSpots } from "../src/game/minigames/handshake-logic.ts"; +import { GOOD_MS, PERFECT_MS, judgeOffset, makeChart, rallyScore } from "../src/game/minigames/rally-logic.ts"; +import { + MAX_STARS, + RECORDS_KEY, + defaultTier, + emptyRecords, + isUnlocked, + loadRecords, + lockReason, + parseTier, + recordResult, + sanitizeRecords, + saveRecords, + totalStars, +} from "../src/game/minigames/records.ts"; +import { clampScore, starsFor } from "../src/game/minigames/types.ts"; + +/** 測試用的 localStorage(vitest 跑在 Node,沒有瀏覽器的儲存空間) */ +function fakeStorage(): Storage { + const m = new Map(); + return { + get length() { + return m.size; + }, + clear: () => m.clear(), + getItem: (k) => m.get(k) ?? null, + key: (i) => [...m.keys()][i] ?? null, + removeItem: (k) => void m.delete(k), + setItem: (k, v) => void m.set(k, String(v)), + }; +} + +describe("星等換算", () => { + it("40/70/90 分是 1/2/3 星的門檻", () => { + expect(starsFor(0)).toBe(0); + expect(starsFor(39)).toBe(0); + expect(starsFor(40)).toBe(1); + expect(starsFor(69)).toBe(1); + expect(starsFor(70)).toBe(2); + expect(starsFor(89)).toBe(2); + expect(starsFor(90)).toBe(3); + expect(starsFor(100)).toBe(3); + }); + it("超出範圍、小數、NaN 先夾到 0–100 的整數", () => { + expect(starsFor(150)).toBe(3); + expect(starsFor(-5)).toBe(0); + expect(starsFor(39.6)).toBe(1); + expect(starsFor(Number.NaN)).toBe(0); + expect(clampScore(Number.POSITIVE_INFINITY)).toBe(0); + }); +}); + +describe("最佳紀錄清洗", () => { + it("壞掉、不認得的東西一律清成空紀錄", () => { + for (const raw of [null, undefined, 42, "x", [], { handshake: "nope" }]) expect(sanitizeRecords(raw)).toEqual(emptyRecords()); + }); + it("分數夾到 0–100、次數至少 1、型別不對的那一級丟掉、不認得的遊戲丟掉", () => { + const r = sanitizeRecords({ + handshake: [{ best: 250, plays: 3 }, { best: "90" }, { best: 55.4, plays: -2 }], + rally: [{ best: -10, plays: 1e12 }], + hacked: [{ best: 100 }], + }); + expect(r.handshake).toEqual([{ best: 100, plays: 3 }, null, { best: 55, plays: 1 }]); + expect(r.rally).toEqual([{ best: 0, plays: 1_000_000 }, null, null]); + expect(r.billboard).toEqual([null, null, null]); + expect("hacked" in r).toBe(false); + }); + it("存進去再讀出來一樣;讀到壞 JSON 不會出錯", () => { + const s = fakeStorage(); + const { records } = recordResult(emptyRecords(), "rally", 0, 82); + saveRecords(records, s); + expect(loadRecords(s)).toEqual(records); + s.setItem(RECORDS_KEY, "{not json"); + expect(loadRecords(s)).toEqual(emptyRecords()); + expect(loadRecords(null)).toEqual(emptyRecords()); + }); + it("儲存空間丟錯(私密模式)時不會讓遊戲壞掉", () => { + const broken = { + getItem: () => { + throw new Error("blocked"); + }, + setItem: () => { + throw new Error("blocked"); + }, + }; + expect(loadRecords(broken)).toEqual(emptyRecords()); + expect(() => saveRecords(emptyRecords(), broken)).not.toThrow(); + }); +}); + +describe("記分與新紀錄", () => { + it("第一次玩、分數大於 0 算新紀錄;比較低不會蓋掉最高分,但次數會加", () => { + let r = emptyRecords(); + let res = recordResult(r, "handshake", 0, 61); + expect(res.newBest).toBe(true); + r = res.records; + res = recordResult(r, "handshake", 0, 48); + expect(res.newBest).toBe(false); + expect(res.records.handshake[0]).toEqual({ best: 61, plays: 2 }); + res = recordResult(res.records, "handshake", 0, 61); + expect(res.newBest).toBe(false); + res = recordResult(res.records, "handshake", 0, 77); + expect(res.newBest).toBe(true); + expect(res.records.handshake[0]).toEqual({ best: 77, plays: 4 }); + expect(recordResult(emptyRecords(), "rally", 1, 0).newBest).toBe(false); + }); + it("不改原本的物件", () => { + const r = emptyRecords(); + recordResult(r, "billboard", 2, 90); + expect(r).toEqual(emptyRecords()); + }); + it("總星數:每個遊戲每級最多 3 顆,總共 27", () => { + let r = emptyRecords(); + expect(totalStars(r)).toBe(0); + r = recordResult(r, "handshake", 0, 95).records; + r = recordResult(r, "rally", 0, 72).records; + r = recordResult(r, "rally", 1, 41).records; + expect(totalStars(r)).toBe(6); + expect(MAX_STARS).toBe(27); + }); +}); + +describe("難度解鎖", () => { + it("新手一開始就能玩,老手、選戰老將要前一級拿到 2 星", () => { + let r = emptyRecords(); + expect(isUnlocked(r, "rally", 0)).toBe(true); + expect(isUnlocked(r, "rally", 1)).toBe(false); + expect(lockReason(r, "rally", 1)).toBe("新手拿到 2 星解鎖"); + r = recordResult(r, "rally", 0, 69).records; + expect(isUnlocked(r, "rally", 1)).toBe(false); + r = recordResult(r, "rally", 0, 70).records; + expect(isUnlocked(r, "rally", 1)).toBe(true); + expect(isUnlocked(r, "rally", 2)).toBe(false); + expect(lockReason(r, "rally", 2)).toBe("老手拿到 2 星解鎖"); + // 各遊戲分開算 + expect(isUnlocked(r, "handshake", 1)).toBe(false); + }); + it("預設難度是解鎖的最高一級;網址指定鎖住的難度會退回預設", () => { + let r = emptyRecords(); + expect(defaultTier(r, "billboard")).toBe(0); + r = recordResult(r, "billboard", 0, 88).records; + expect(defaultTier(r, "billboard")).toBe(1); + expect(parseTier("0", r, "billboard")).toBe(0); + expect(parseTier("2", r, "billboard")).toBe(1); + expect(parseTier("abc", r, "billboard")).toBe(1); + expect(parseTier(null, r, "billboard")).toBe(1); + }); +}); + +describe("三個遊戲的關卡與分數", () => { + it("同一個種子、難度產生一樣的關卡", () => { + expect(makeHandshake(7, 0.5)).toEqual(makeHandshake(7, 0.5)); + expect(makeChart(7, 0.5)).toEqual(makeChart(7, 0.5)); + expect(makeBillboard(7, 0.5)).toEqual(makeBillboard(7, 0.5)); + }); + + it("掃街握手:同一個人不會同時舉兩次手、時間內結束、難度越高舉手越多", () => { + for (const seed of [1, 2, 3, 99, 2026]) { + const easy = makeHandshake(seed, 0.2); + const hard = makeHandshake(seed, 0.9); + for (const lv of [easy, hard]) { + expect(lv.spawns[0]!.kind).toBe("fan"); + const busy = new Map(); + for (const s of lv.spawns) { + expect(s.t).toBeLessThan(HANDSHAKE_MS); + expect(s.t).toBeGreaterThanOrEqual(busy.get(s.person) ?? 0); + busy.set(s.person, s.t + s.dur); + } + } + expect(hard.spawns.length).toBeGreaterThan(easy.spawns.length); + } + }); + + it("掃街握手:直式手機四排 5-4-5-4,18 個位置都在畫面裡、不重疊", () => { + const spots = portraitSpots(18); + expect(spots.map((s) => s.row)).toEqual([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3]); + for (const s of spots) { + expect(s.x).toBeGreaterThan(5); + expect(s.x).toBeLessThan(95); + expect(s.y).toBeLessThanOrEqual(98); + } + for (let i = 1; i < spots.length; i++) if (spots[i]!.row === spots[i - 1]!.row) expect(spots[i]!.x - spots[i - 1]!.x).toBeGreaterThan(15); + }); + + it("掃街握手的分數:全部握到 100、握一半約 50、被拍與揮空扣分", () => { + expect(handshakeScore({ points: 30, totalPoints: 30, reporters: 0, misses: 0 })).toBe(100); + expect(handshakeScore({ points: 15, totalPoints: 30, reporters: 0, misses: 0 })).toBe(53); + expect(handshakeScore({ points: 25, totalPoints: 30, reporters: 1, misses: 2 })).toBe(77); + expect(handshakeScore({ points: 0, totalPoints: 30, reporters: 3, misses: 9 })).toBe(0); + }); + + it("造勢喊凍蒜:判定窗、譜面在曲子裡、分數一致", () => { + expect(judgeOffset(0)).toBe("perfect"); + expect(judgeOffset(-PERFECT_MS)).toBe("perfect"); + expect(judgeOffset(PERFECT_MS + 1)).toBe("good"); + expect(judgeOffset(-GOOD_MS)).toBe("good"); + expect(judgeOffset(GOOD_MS + 1)).toBeNull(); + for (const lv of [0.2, 0.55, 0.9]) { + const c = makeChart(5, lv); + expect(c.notes.length).toBeGreaterThan(18); + expect(Math.max(...c.notes)).toBeLessThan(c.endMs); + expect([...c.notes].sort((a, b) => a - b)).toEqual(c.notes); + } + expect(rallyScore({ perfect: 30, good: 0, early: 0, maxCombo: 30, total: 30 })).toBe(100); + // 隨手:一半 Perfect、三分之一 Good、幾次亂按 → 40–60 + const casual = rallyScore({ perfect: 15, good: 10, early: 3, maxCombo: 6, total: 30 }); + expect(casual).toBeGreaterThanOrEqual(40); + expect(casual).toBeLessThanOrEqual(60); + // 玩得好:大多 Perfect → 80–95 + const good = rallyScore({ perfect: 25, good: 4, early: 1, maxCombo: 18, total: 30 }); + expect(good).toBeGreaterThanOrEqual(80); + expect(good).toBeLessThanOrEqual(95); + }); + + it("看板卡位:一開始路是通的、最佳擺法夠大、分數曲線", () => { + for (const seed of [1, 42, 777, 20261128]) { + for (const level of [0.2, 0.9]) { + const lv = makeBillboard(seed, level); + expect(walkway((i) => lv.tiles[i] !== "free")).not.toBeNull(); + expect(lv.best).toBeGreaterThanOrEqual(18); + expect(lv.pieces.length).toBe(level > 0.5 ? 4 : 3); + } + } + expect(BILLBOARD_MS).toBe(40_000); + expect(billboardScore(40, 40)).toBe(100); + expect(billboardScore(50, 40)).toBe(100); + expect(billboardScore(0, 40)).toBe(0); + const casual = billboardScore(30, 40); + expect(casual).toBeGreaterThanOrEqual(40); + expect(casual).toBeLessThanOrEqual(60); + expect(billboardScore(37, 40)).toBeGreaterThanOrEqual(80); + }); +}); diff --git a/web/test/people-shared.test.ts b/web/test/people-shared.test.ts new file mode 100644 index 0000000..3402929 --- /dev/null +++ b/web/test/people-shared.test.ts @@ -0,0 +1,39 @@ +import type { ElectionRun } from "@election2026/protocol"; +import { describe, expect, it } from "vitest"; +import { isPartyList, kind, mateLabel, place } from "../src/game/people/shared.ts"; + +const run = (over: Partial = {}): ElectionRun => ({ + year: 2024, + date: "2024-01-13", + election: "總統", + office: "president", + indigenous: null, + county: "全國", + countyCode: null, + district: null, + number: 2, + party: "甲黨", + votes: 5_000_000, + share: 0.4, + elected: true, + incumbent: false, + ...over, +}); + +describe("檔案室參選證的文字", () => { + it("總統副總統:選區寫全國,搭檔標明是總統還是副總統候選人", () => { + const top = run({ runningMate: "乙" }); + const vice = run({ election: "副總統", runningMate: "甲" }); + expect([place(top), kind(top), mateLabel(top)]).toEqual(["全國", "總統", "乙(副總統)"]); + expect([kind(vice), mateLabel(vice)]).toEqual(["副總統", "甲(總統)"]); + expect(mateLabel(run({ election: "直轄市長", office: "mayor" }))).toBeNull(); + }); + + it("立委:區域寫縣市+選區,原住民附類別,不分區看名單排名", () => { + const district = run({ election: "立法委員", office: "legislator", county: "臺北市", countyCode: "63000", district: "第1選區" }); + expect([place(district), kind(district), isPartyList(district)]).toEqual(["臺北市第1選區", "立法委員", false]); + expect(kind(run({ election: "立法委員", office: "legislator", indigenous: "山地原住民" }))).toBe("立法委員(山地原住民)"); + const listed = run({ election: "不分區立法委員", office: "legislator", votes: null, share: null, listRank: 3, partyVotes: 4_000_000, partyShare: 0.3 }); + expect([place(listed), isPartyList(listed)]).toEqual(["全國", true]); + }); +}); diff --git a/web/test/rogue-progress.test.ts b/web/test/rogue-progress.test.ts new file mode 100644 index 0000000..3f8e167 --- /dev/null +++ b/web/test/rogue-progress.test.ts @@ -0,0 +1,89 @@ +import type { RogueView } from "@election2026/protocol"; +import { beforeEach, describe, expect, it } from "vitest"; +import { dailyPick, loadProgress, recordRun, todayKey } from "../src/game/rogue/progress.ts"; + +/** 測試用的 localStorage(vitest 跑在 Node,沒有瀏覽器的儲存空間) */ +function fakeStorage(): Storage { + const m = new Map(); + return { + get length() { + return m.size; + }, + clear: () => m.clear(), + getItem: (k) => m.get(k) ?? null, + key: (i) => [...m.keys()][i] ?? null, + removeItem: (k) => void m.delete(k), + setItem: (k, v) => void m.set(k, String(v)), + }; +} + +const finished = (runId: string, won: boolean, ascension = 0, feats: string[] = ["win"], you = { id: "chang-san-cheng", name: "張善政" }): RogueView => + ({ + runId, + scenarioId: "taoyuan-2022-mayor-even", + you, + options: { + ascension, + tutorial: false, + daily: null, + even: true, + career: null, + }, + result: { + won, + you: 1, + rival: 0, + others: 0, + youShare: won ? 0.5 : 0.4, + rivalShare: 0.45, + grade: won ? "B" : "C", + byTown: [], + feats: won ? feats : [], + }, + }) as unknown as RogueView; + +describe("選戰卡牌的進度", () => { + beforeEach(() => { + Object.defineProperty(globalThis, "localStorage", { + value: fakeStorage(), + configurable: true, + }); + }); + + it("贏了解鎖下一級逆風、記成就;同一局重新整理不會重複算", () => { + expect(loadProgress().ascension).toBe(0); + const first = recordRun(finished("r1", true)); + expect(first.unlocked).toBe(1); + expect(first.newFeats).toEqual(["win"]); + expect(loadProgress().wins).toBe(1); + const again = recordRun(finished("r1", true)); + expect(again.unlocked).toBeNull(); + expect(loadProgress().runs).toBe(1); + // 打比已解鎖還低的等級贏了,不會再解鎖 + expect(recordRun(finished("r2", true, 0)).unlocked).toBeNull(); + // 輸了不解鎖、不算勝場 + const lost = recordRun(finished("r3", false, 1)); + expect(lost.unlocked).toBeNull(); + expect(loadProgress()).toMatchObject({ runs: 3, wins: 2, ascension: 1 }); + }); + + it("記下玩過的真實參選人(參選人卡冊上色用);自創角色不記", () => { + recordRun(finished("r1", true)); + recordRun(finished("r2", false, 0)); + recordRun(finished("r3", true, 0, ["win"], { id: "custom", name: "林小美" })); + expect(loadProgress().played).toEqual({ + 張善政: { + runs: 2, + wins: 1, + grade: "B", + scenarios: ["taoyuan-2022-mayor-even"], + }, + }); + }); + + it("每日一戰:同一天挑到同一個題目", () => { + const items = ["a", "b", "c", "d", "e"]; + expect(dailyPick(items, "2026-10-26")).toBe(dailyPick(items, "2026-10-26")); + expect(todayKey(new Date(2026, 9, 26))).toBe("2026-10-26"); + }); +}); diff --git a/web/test/wardrobe.test.ts b/web/test/wardrobe.test.ts new file mode 100644 index 0000000..1901f07 --- /dev/null +++ b/web/test/wardrobe.test.ts @@ -0,0 +1,150 @@ +import { shopShelf, wearItem, type AvatarSpecData } from "@election2026/protocol"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { itemState, setTint, wear } from "../src/game/shop/unlocks.ts"; +import { WARDROBE_KEY, buyItem, coinsForRun, earnCoins, loadWardrobe, sanitizeWardrobe, totalCoins } from "../src/game/shop/wardrobe.ts"; + +/** 測試用的 localStorage(vitest 跑在 Node,沒有瀏覽器的儲存空間) */ +function fakeStorage(): Storage { + const m = new Map(); + return { + get length() { + return m.size; + }, + clear: () => m.clear(), + getItem: (k) => m.get(k) ?? null, + key: (i) => [...m.keys()][i] ?? null, + removeItem: (k) => void m.delete(k), + setItem: (k, v) => void m.set(k, String(v)), + }; +} + +const legacyAvatar: AvatarSpecData = { skin: "#f6d3b7", hair: "bobSide", hairColor: "#2f2520", outfit: "blouse", suit: "#5a2d34", shirt: "#f3e6d8", tie: "#2c5aa0", glasses: true, beard: false, bg: "#efe0e6", face: "heart", eyes: "narrow", glassesStyle: "halfRim", part: "right" }; + +beforeEach(() => { + vi.stubGlobal("localStorage", fakeStorage()); +}); + +describe("小鎮幣怎麼發", () => { + it("當選 3、落選 2、S 評價 +2、新成就每個 +1、每日一戰 +2、政治生涯過關 +2", () => { + expect(coinsForRun({ won: true, grade: "A" }).coins).toBe(3); + expect(coinsForRun({ won: false, grade: "C" }).coins).toBe(2); + expect(coinsForRun({ won: true, grade: "S", newFeats: 2, daily: true, career: true })).toEqual({ coins: 11, reason: "當選 +3、S 評價 +2、新成就 +2、每日一戰 +2、政治生涯過關 +2" }); + // 政治生涯落選不算過關 + expect(coinsForRun({ won: false, career: true }).coins).toBe(2); + }); +}); + +describe("小鎮幣記帳", () => { + it("發的記在「免費取得」那本;同一局只發一次;每筆都留紀錄", () => { + expect(earnCoins(5, "當選 +3、S 評價 +2", "run-1")).toBe(true); + expect(earnCoins(5, "重新整理又算一次", "run-1")).toBe(false); + expect(earnCoins(2, "落選也打完 +2", "run-2")).toBe(true); + const s = loadWardrobe(); + expect(s.coins).toEqual({ free: 7, paid: 0 }); + expect(s.log.map((e) => [e.free, e.paid, e.runId])).toEqual([ + [5, 0, "run-1"], + [2, 0, "run-2"], + ]); + expect(earnCoins(0, "沒有")).toBe(false); + expect(earnCoins(-3, "負的")).toBe(false); + }); + + it("買東西先扣免費的、不夠再扣付費的;買過不能再買;錢不夠不能買", () => { + const now = new Date("2026-10-28T12:00:00+08:00"); + localStorage.setItem(WARDROBE_KEY, JSON.stringify({ coins: { free: 5, paid: 10 }, owned: {}, log: [] })); + // 漁夫帽是基本款,一直都買得到(8 枚) + expect(buyItem("hat-bucket", now)).toEqual({ ok: true }); + const s = loadWardrobe(); + expect(s.coins).toEqual({ free: 0, paid: 7 }); + expect(s.owned["hat-bucket"]).toBeDefined(); + expect(s.log.at(-1)).toMatchObject({ free: -5, paid: -3, itemId: "hat-bucket", reason: "買「漁夫帽」" }); + expect(buyItem("hat-bucket", now)).toEqual({ ok: false, reason: "owned" }); + expect(buyItem("outer-volunteer-vest", now)).toEqual({ ok: false, reason: "poor" }); + expect(totalCoins(loadWardrobe())).toBe(7); + }); + + it("這週沒上架的、免費的、解鎖的、不存在的都不能用小鎮幣買", () => { + const now = new Date("2026-10-28T12:00:00+08:00"); + localStorage.setItem(WARDROBE_KEY, JSON.stringify({ coins: { free: 999, paid: 0 }, owned: {}, log: [] })); + const shelf = shopShelf(now); + const offShelf = ["hat-victory-band", "hat-bamboo", "hat-helmet", "outer-hivis", "held-fan", "held-thermos", "frame-billboard", "frame-newspaper"].find((id) => !shelf.weekly.some((i) => i.id === id))!; + expect(buyItem(offShelf, now)).toEqual({ ok: false, reason: "notForSale" }); + // 限定品只在 11、12 月 + expect(buyItem("frame-neon", now)).toEqual({ ok: false, reason: "notForSale" }); + expect(buyItem("frame-neon", new Date("2026-11-20T12:00:00+08:00"))).toEqual({ ok: true }); + expect(buyItem("sash-red", now)).toEqual({ ok: false, reason: "unknown" }); + expect(buyItem("chest-corsage", now)).toEqual({ ok: false, reason: "unknown" }); + expect(buyItem("hat-from-the-future", now)).toEqual({ ok: false, reason: "unknown" }); + }); + + it("清洗:壞掉的存檔不會當機;負數、小數、怪代號、壞紀錄都丟掉;看不懂但格式對的部件代號照留", () => { + expect(sanitizeWardrobe("garbage")).toEqual({ coins: { free: 0, paid: 0 }, owned: {}, log: [] }); + const s = sanitizeWardrobe({ + coins: { free: -4, paid: 3.7 }, + owned: { "hat-bucket": { at: "2026-10-01" }, "hat-from-next-version": {}, "