Merge current engine into 3D viewer and prepare main delivery

This commit is contained in:
coyotte508 2026-10-04 11:55:47 +02:00
commit 2b90d8d5ef
398 changed files with 17273 additions and 5956 deletions

View file

@ -1,7 +1,11 @@
{ {
$schema: "https://docs.renovatebot.com/renovate-schema.json", $schema: "https://docs.renovatebot.com/renovate-schema.json",
extends: [ extends: [
"config:best-practices",
"config:recommended" "config:recommended"
], ],
automerge: true, automerge: true,
labels: [
"dependencies"
],
} }

View file

@ -1,15 +1,13 @@
name: Performance Benchmark name: Performance Benchmark
on: [pull_request] on: [ pull_request ]
jobs: jobs:
check: check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: jdx/mise-action@v3 - uses: jdx/mise-action@94c60b39bc2d90ab2f9bab27f38d3cc4812c1834 # v5.1.0
with: - name: Random actions test
version: 2025.7.3 run: mise run random-actions
- name: Random actions test
run: mise run random-actions

View file

@ -1,15 +1,16 @@
name: Check name: Check
on: [pull_request] on:
pull_request:
push:
branches: [main]
jobs: jobs:
check: check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: jdx/mise-action@v3 - uses: jdx/mise-action@94c60b39bc2d90ab2f9bab27f38d3cc4812c1834 # v5.1.0
with: - name: Check all
version: 2025.7.3 run: mise run ci
- name: Check all
run: mise run ci

View file

@ -11,12 +11,10 @@ jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: jdx/mise-action@v3 - uses: jdx/mise-action@94c60b39bc2d90ab2f9bab27f38d3cc4812c1834 # v5.1.0
with:
version: 2025.7.3
- name: Use Node.js ${{ env.node_version }} - name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v4 uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with: with:
node-version: ${{ env.node_version }} node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED # setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED

View file

@ -1,17 +1,15 @@
name: Test Release name: Test Release
on: [pull_request] on: [ pull_request ]
jobs: jobs:
check: check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: jdx/mise-action@v3 - uses: jdx/mise-action@94c60b39bc2d90ab2f9bab27f38d3cc4812c1834 # v5.1.0
with: - name: Test server release
version: 2025.7.3 run: mise run build-remote-server
- name: Test server release - name: Test client release
run: mise run build-remote-server run: mise run build-remote-client
- name: Test client release
run: mise run build-remote-client

View file

@ -3,7 +3,7 @@ on:
pull_request: pull_request:
paths: ['web-client/**', 'server/**', 'Cargo.*', '.github/workflows/web-viewer.yml'] paths: ['web-client/**', 'server/**', 'Cargo.*', '.github/workflows/web-viewer.yml']
push: push:
branches: [feat/3d-web-viewer] branches: [main, feat/3d-web-viewer]
jobs: jobs:
verify: verify:
runs-on: ubuntu-latest runs-on: ubuntu-latest

15
AGENTS.md Normal file
View file

@ -0,0 +1,15 @@
# Agent instructions
## BGS publication and Git delivery
Whenever changes are published to BGS, commit the corresponding source, tests,
dependency/lockfile changes and version bumps, then push them to this repository's
`main` or `master` release branch in the same task. A BGS upload or a push only to
a feature branch does not complete delivery. This is standing authorization to
commit and push published changes without asking for separate confirmation.
Fetch and integrate the latest release-branch changes, run the relevant repository
checks, and push without force. Update any public mirrors required by this repo's
existing workflow too. Keep credentials, generated artifacts excluded by the repo,
and unrelated unfinished work out of the commit. Verify the remote branch contains
the delivered commit and report any blocker instead of claiming delivery.

975
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,10 @@
![Lines of code](https://img.shields.io/tokei/lines/github/boardgamers/clash) ![Lines of code](https://img.shields.io/tokei/lines/github/boardgamers/clash)
## Play online at
[boardgamers.space](https://boardgamers.space)
## Client ## Client
### Run native client ### Run native client

View file

@ -18,7 +18,7 @@ wasm-bindgen = "0.2.100"
wasm-bindgen-futures = "0.4.50" wasm-bindgen-futures = "0.4.50"
console_error_panic_hook = "0.1.7" console_error_panic_hook = "0.1.7"
web-sys = { version = "0.3.77", features = ["Window"] } web-sys = { version = "0.3.77", features = ["Window"] }
pyroscope = { version = "0.5.8", optional = true } pyroscope = { version = "2.0.0", optional = true }
pyroscope_pprofrs = { version = "0.2.10", optional = true } pyroscope_pprofrs = { version = "0.2.10", optional = true }
serde = { version = "1.0.219", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

View file

@ -5,9 +5,9 @@
"requires": true, "requires": true,
"dependencies": { "dependencies": {
"@discoveryjs/json-ext": { "@discoveryjs/json-ext": {
"version": "0.6.3", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.6.3.tgz", "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-1.1.0.tgz",
"integrity": "sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ==", "integrity": "sha512-Xc3VhU02wqZ1HvHRJUwL09HkZSTvidqY5Ya0NXBSYOxAp+Ln9dcJr9fySI+CkONzP3PekQo9WdzCv0PGER/mOA==",
"dev": true "dev": true
}, },
"@jridgewell/gen-mapping": { "@jridgewell/gen-mapping": {
@ -37,45 +37,25 @@
} }
}, },
"@jridgewell/sourcemap-codec": { "@jridgewell/sourcemap-codec": {
"version": "1.5.5", "version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true "dev": true
}, },
"@jridgewell/trace-mapping": { "@jridgewell/trace-mapping": {
"version": "0.3.30", "version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.30.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true, "dev": true,
"requires": { "requires": {
"@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"@types/eslint": {
"version": "9.6.1",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",
"integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",
"dev": true,
"requires": {
"@types/estree": "*",
"@types/json-schema": "*"
}
},
"@types/eslint-scope": {
"version": "3.7.7",
"resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz",
"integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==",
"dev": true,
"requires": {
"@types/eslint": "*",
"@types/estree": "*"
}
},
"@types/estree": { "@types/estree": {
"version": "1.0.8", "version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"dev": true "dev": true
}, },
"@types/json-schema": { "@types/json-schema": {
@ -85,12 +65,12 @@
"dev": true "dev": true
}, },
"@types/node": { "@types/node": {
"version": "24.3.0", "version": "26.6.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.1.tgz",
"integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==", "integrity": "sha512-VqGJBMCtdhqkBUCcBLvywI0NJ+KLuVzgNnlBUNFOQjqVxzo2lxLUNg1DSey8+u2u6ktswSAxg+s68QLzWHNOuA==",
"dev": true, "dev": true,
"requires": { "requires": {
"undici-types": "~7.10.0" "undici-types": "~8.9.0"
} }
}, },
"@webassemblyjs/ast": { "@webassemblyjs/ast": {
@ -239,24 +219,6 @@
"@xtuc/long": "4.2.2" "@xtuc/long": "4.2.2"
} }
}, },
"@webpack-cli/configtest": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-3.0.1.tgz",
"integrity": "sha512-u8d0pJ5YFgneF/GuvEiDA61Tf1VDomHHYMjv/wc9XzYj7nopltpG96nXN5dJRstxZhcNpV1g+nT6CydO7pHbjA==",
"dev": true
},
"@webpack-cli/info": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-3.0.1.tgz",
"integrity": "sha512-coEmDzc2u/ffMvuW9aCjoRzNSPDl/XLuhPdlFRpT9tZHmJ/039az33CE7uH+8s0uL1j5ZNtfdv0HkfaKRBGJsQ==",
"dev": true
},
"@webpack-cli/serve": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-3.0.1.tgz",
"integrity": "sha512-sbgw03xQaCLiT6gcY/6u3qBDn01CWw/nbaXl3gTdTFuJJ75Gffv3E3DBpgvY2fkkrdS1fpjaXNOmJlnbtKauKg==",
"dev": true
},
"@xtuc/ieee754": { "@xtuc/ieee754": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
@ -270,21 +232,15 @@
"dev": true "dev": true
}, },
"acorn": { "acorn": {
"version": "8.15.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true
},
"acorn-import-phases": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz",
"integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==",
"dev": true "dev": true
}, },
"ajv": { "ajv": {
"version": "8.17.1", "version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"dev": true, "dev": true,
"requires": { "requires": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
@ -294,9 +250,9 @@
} }
}, },
"ajv-formats": { "ajv-formats": {
"version": "2.1.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
"integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
"dev": true, "dev": true,
"requires": { "requires": {
"ajv": "^8.0.0" "ajv": "^8.0.0"
@ -311,16 +267,23 @@
"fast-deep-equal": "^3.1.3" "fast-deep-equal": "^3.1.3"
} }
}, },
"baseline-browser-mapping": {
"version": "2.11.25",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz",
"integrity": "sha512-gMmEShwwq7FJqMwvfRwvCl00v4kN+KOfJqXn+f4nrufak5gNHJOksd/60Dvjuz7sI8Y5WiSFBa8FEYr+zoyqCw==",
"dev": true
},
"browserslist": { "browserslist": {
"version": "4.25.2", "version": "4.29.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.25.2.tgz", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz",
"integrity": "sha512-0si2SJK3ooGzIawRu61ZdPCO1IncZwS8IzuX73sPZsXW6EQ/w/DAfPyKI8l1ETTCr2MnvqWitmlCUxgdul45jA==", "integrity": "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==",
"dev": true, "dev": true,
"requires": { "requires": {
"caniuse-lite": "^1.0.30001733", "baseline-browser-mapping": "^2.11.23",
"electron-to-chromium": "^1.5.199", "caniuse-lite": "^1.0.30001810",
"node-releases": "^2.0.19", "electron-to-chromium": "^1.5.427",
"update-browserslist-db": "^1.1.3" "node-releases": "^2.0.55",
"update-browserslist-db": "^1.3.3"
} }
}, },
"buffer-from": { "buffer-from": {
@ -330,9 +293,9 @@
"dev": true "dev": true
}, },
"caniuse-lite": { "caniuse-lite": {
"version": "1.0.30001735", "version": "1.0.30001810",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001735.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz",
"integrity": "sha512-EV/laoX7Wq2J9TQlyIXRxTJqIw4sxfXS4OYgudGxBYRuTv0q7AM6yMEpU/Vo1I94thg9U6EZ2NfZx9GJq83u7w==", "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==",
"dev": true "dev": true
}, },
"chrome-trace-event": { "chrome-trace-event": {
@ -352,12 +315,6 @@
"shallow-clone": "^3.0.0" "shallow-clone": "^3.0.0"
} }
}, },
"colorette": {
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
"dev": true
},
"commander": { "commander": {
"version": "2.20.3", "version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
@ -376,31 +333,37 @@
} }
}, },
"electron-to-chromium": { "electron-to-chromium": {
"version": "1.5.203", "version": "1.5.433",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.203.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.433.tgz",
"integrity": "sha512-uz4i0vLhfm6dLZWbz/iH88KNDV+ivj5+2SA+utpgjKaj9Q0iDLuwk6Idhe9BTxciHudyx6IvTvijhkPvFGUQ0g==", "integrity": "sha512-5lCAbyZBjtmUt/RAGHRqrL2q0oEFRThDAsZHHDn9XHa89Qw7gMYOeSicBTy+AHfvo0r6vwsZvqNJTQIQy1BLzA==",
"dev": true "dev": true
}, },
"enhanced-resolve": { "enhanced-resolve": {
"version": "5.18.3", "version": "5.25.1",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.3.tgz", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.25.1.tgz",
"integrity": "sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==", "integrity": "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==",
"dev": true, "dev": true,
"requires": { "requires": {
"graceful-fs": "^4.2.4", "graceful-fs": "^4.2.4",
"tapable": "^2.2.0" "tapable": "^2.3.3"
} }
}, },
"envinfo": { "envinfo": {
"version": "7.14.0", "version": "7.21.0",
"resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.14.0.tgz", "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.21.0.tgz",
"integrity": "sha512-CO40UI41xDQzhLB1hWyqUKgFhs250pNcGbyGKe1l/e4FSaI/+YE4IMG76GDt0In67WLPACIITC+sOi08x4wIvg==", "integrity": "sha512-Lw7I8Zp5YKHFCXL7+Dz95g4CcbMEpgvqZNNq3AmlT5XAV6CgAAk6gyAMqn2zjw08K9BHfcNuKrMiCPLByGafow==",
"dev": true
},
"es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"dev": true "dev": true
}, },
"es-module-lexer": { "es-module-lexer": {
"version": "1.7.0", "version": "2.3.2",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
"integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true "dev": true
}, },
"escalade": { "escalade": {
@ -409,39 +372,6 @@
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true "dev": true
}, },
"eslint-scope": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",
"integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",
"dev": true,
"requires": {
"esrecurse": "^4.3.0",
"estraverse": "^4.1.1"
}
},
"esrecurse": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
"integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
"dev": true,
"requires": {
"estraverse": "^5.2.0"
},
"dependencies": {
"estraverse": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
"integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
"dev": true
}
}
},
"estraverse": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",
"integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
"dev": true
},
"events": { "events": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
@ -454,15 +384,9 @@
"dev": true "dev": true
}, },
"fast-uri": { "fast-uri": {
"version": "3.0.6", "version": "3.1.8",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
"integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==", "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
"dev": true
},
"fastest-levenshtein": {
"version": "1.0.16",
"resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz",
"integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==",
"dev": true "dev": true
}, },
"find-up": { "find-up": {
@ -487,12 +411,6 @@
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true "dev": true
}, },
"glob-to-regexp": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
"integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
"dev": true
},
"graceful-fs": { "graceful-fs": {
"version": "4.2.11", "version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
@ -506,9 +424,9 @@
"dev": true "dev": true
}, },
"hasown": { "hasown": {
"version": "2.0.2", "version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"dev": true, "dev": true,
"requires": { "requires": {
"function-bind": "^1.1.2" "function-bind": "^1.1.2"
@ -531,12 +449,12 @@
"dev": true "dev": true
}, },
"is-core-module": { "is-core-module": {
"version": "2.16.1", "version": "2.16.2",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz",
"integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==",
"dev": true, "dev": true,
"requires": { "requires": {
"hasown": "^2.0.2" "hasown": "^2.0.3"
} }
}, },
"is-plain-object": { "is-plain-object": {
@ -571,12 +489,6 @@
"supports-color": "^8.0.0" "supports-color": "^8.0.0"
} }
}, },
"json-parse-even-better-errors": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
"integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
"dev": true
},
"json-schema-traverse": { "json-schema-traverse": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@ -589,12 +501,6 @@
"integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
"dev": true "dev": true
}, },
"loader-runner": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz",
"integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==",
"dev": true
},
"locate-path": { "locate-path": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
@ -611,30 +517,27 @@
"dev": true "dev": true
}, },
"mime-db": { "mime-db": {
"version": "1.52.0", "version": "1.54.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
"dev": true "dev": true
}, },
"mime-types": { "minimizer-webpack-plugin": {
"version": "2.1.35", "version": "5.10.1",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.10.1.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "integrity": "sha512-+dsZEyTcy1lkq41lxdiOqvb26gXbYGgwY+30w37f9PqUVkuEBejBLDotsHOTjuga9xJyGLW2DqzKDUyJ4W/PMQ==",
"dev": true, "dev": true,
"requires": { "requires": {
"mime-db": "1.52.0" "@jridgewell/trace-mapping": "^0.3.31",
"jest-worker": "^27.4.5",
"schema-utils": "^4.3.3",
"terser": "^5.51.0"
} }
}, },
"neo-async": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"dev": true
},
"node-releases": { "node-releases": {
"version": "2.0.19", "version": "2.0.56",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.56.tgz",
"integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", "integrity": "sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A==",
"dev": true "dev": true
}, },
"p-limit": { "p-limit": {
@ -694,15 +597,6 @@
"find-up": "^4.0.0" "find-up": "^4.0.0"
} }
}, },
"randombytes": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
"integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
"dev": true,
"requires": {
"safe-buffer": "^5.1.0"
}
},
"rechoir": { "rechoir": {
"version": "0.8.0", "version": "0.8.0",
"resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz",
@ -719,12 +613,13 @@
"dev": true "dev": true
}, },
"resolve": { "resolve": {
"version": "1.22.10", "version": "1.22.12",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz",
"integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==",
"dev": true, "dev": true,
"requires": { "requires": {
"is-core-module": "^2.16.0", "es-errors": "^1.3.0",
"is-core-module": "^2.16.1",
"path-parse": "^1.0.7", "path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0" "supports-preserve-symlinks-flag": "^1.0.0"
} }
@ -744,33 +639,18 @@
"integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
"dev": true "dev": true
}, },
"safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"dev": true
},
"schema-utils": { "schema-utils": {
"version": "4.3.2", "version": "4.5.0",
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.2.tgz", "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz",
"integrity": "sha512-Gn/JaSk/Mt9gYubxTtSn/QCV4em9mpAPiR1rqy/Ocu19u/G9J5WWdNoUT4SiV6mFC3y6cxyFcFwdzPM3FgxGAQ==", "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==",
"dev": true, "dev": true,
"requires": { "requires": {
"@types/json-schema": "^7.0.9", "@types/json-schema": "^7.0.15",
"ajv": "^8.9.0", "ajv": "^8.20.0",
"ajv-formats": "^2.1.1", "ajv-formats": "^3.0.1",
"ajv-keywords": "^5.1.0" "ajv-keywords": "^5.1.0"
} }
}, },
"serialize-javascript": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
"integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
"dev": true,
"requires": {
"randombytes": "^2.1.0"
}
},
"shallow-clone": { "shallow-clone": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz",
@ -827,46 +707,33 @@
"dev": true "dev": true
}, },
"tapable": { "tapable": {
"version": "2.2.2", "version": "2.3.3",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.2.tgz", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz",
"integrity": "sha512-Re10+NauLTMCudc7T5WLFLAwDhQ0JWdrMK+9B2M8zR5hRExKmsRDCBA7/aV/pNJFltmBFO5BAMlQFi/vq3nKOg==", "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",
"dev": true "dev": true
}, },
"terser": { "terser": {
"version": "5.43.1", "version": "5.51.2",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.43.1.tgz", "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",
"integrity": "sha512-+6erLbBm0+LROX2sPXlUYx/ux5PyE9K/a92Wrt6oA+WDAoFTdpHE5tCYCI5PNzq2y8df4rA+QgHLJuR4jNymsg==", "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",
"dev": true, "dev": true,
"requires": { "requires": {
"@jridgewell/source-map": "^0.3.3", "@jridgewell/source-map": "^0.3.3",
"acorn": "^8.14.0", "acorn": "^8.15.0",
"commander": "^2.20.0", "commander": "^2.20.0",
"source-map-support": "~0.5.20" "source-map-support": "~0.5.20"
} }
}, },
"terser-webpack-plugin": {
"version": "5.3.14",
"resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.14.tgz",
"integrity": "sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==",
"dev": true,
"requires": {
"@jridgewell/trace-mapping": "^0.3.25",
"jest-worker": "^27.4.5",
"schema-utils": "^4.3.0",
"serialize-javascript": "^6.0.2",
"terser": "^5.31.1"
}
},
"undici-types": { "undici-types": {
"version": "7.10.0", "version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==", "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true "dev": true
}, },
"update-browserslist-db": { "update-browserslist-db": {
"version": "1.1.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
"integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
"dev": true, "dev": true,
"requires": { "requires": {
"escalade": "^3.2.0", "escalade": "^3.2.0",
@ -874,73 +741,59 @@
} }
}, },
"watchpack": { "watchpack": {
"version": "2.4.4", "version": "2.5.2",
"resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.4.tgz", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz",
"integrity": "sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA==", "integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==",
"dev": true, "dev": true,
"requires": { "requires": {
"glob-to-regexp": "^0.4.1",
"graceful-fs": "^4.1.2" "graceful-fs": "^4.1.2"
} }
}, },
"webpack": { "webpack": {
"version": "5.101.3", "version": "5.111.1",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.101.3.tgz", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.111.1.tgz",
"integrity": "sha512-7b0dTKR3Ed//AD/6kkx/o7duS8H3f1a4w3BYpIriX4BzIhjkn4teo05cptsxvLesHFKK5KObnadmCHBwGc+51A==", "integrity": "sha512-cNypaz0RP+S4cvQVi1M/3bRUkvNP0xZpL0TjFx+c6jg64VbxD+2weWDgY9UnjRI6dhZgtaj8DU76GGFcJ79xPQ==",
"dev": true, "dev": true,
"requires": { "requires": {
"@types/eslint-scope": "^3.7.7",
"@types/estree": "^1.0.8", "@types/estree": "^1.0.8",
"@types/json-schema": "^7.0.15", "@types/json-schema": "^7.0.15",
"@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/ast": "^1.14.1",
"@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1",
"@webassemblyjs/wasm-parser": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1",
"acorn": "^8.15.0", "browserslist": "^4.28.1",
"acorn-import-phases": "^1.0.3",
"browserslist": "^4.24.0",
"chrome-trace-event": "^1.0.2", "chrome-trace-event": "^1.0.2",
"enhanced-resolve": "^5.17.3", "enhanced-resolve": "^5.25.0",
"es-module-lexer": "^1.2.1", "es-module-lexer": "^2.1.0",
"eslint-scope": "5.1.1",
"events": "^3.2.0", "events": "^3.2.0",
"glob-to-regexp": "^0.4.1",
"graceful-fs": "^4.2.11", "graceful-fs": "^4.2.11",
"json-parse-even-better-errors": "^2.3.1", "mime-db": "^1.54.0",
"loader-runner": "^4.2.0", "minimizer-webpack-plugin": "^5.7.0",
"mime-types": "^2.1.27", "schema-utils": "^4.5.0",
"neo-async": "^2.6.2", "tapable": "^2.3.0",
"schema-utils": "^4.3.2", "watchpack": "^2.5.2",
"tapable": "^2.1.1", "webpack-sources": "^3.5.1"
"terser-webpack-plugin": "^5.3.11",
"watchpack": "^2.4.1",
"webpack-sources": "^3.3.3"
} }
}, },
"webpack-cli": { "webpack-cli": {
"version": "6.0.1", "version": "7.2.3",
"resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-6.0.1.tgz", "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-7.2.3.tgz",
"integrity": "sha512-MfwFQ6SfwinsUVi0rNJm7rHZ31GyTcpVE5pgVA3hwFRb7COD4TzjUUwhGWKfO50+xdc2MQPuEBBJoqIMGt3JDw==", "integrity": "sha512-vDFU7jrfCctnN7jJQWPl+V26B51GLp11prVZXg50oeonsgeBzSTJEWmXkjHsOjTgMjlPOQM8GWLh33X9RN/0ow==",
"dev": true, "dev": true,
"requires": { "requires": {
"@discoveryjs/json-ext": "^0.6.1", "@discoveryjs/json-ext": "^1.1.0",
"@webpack-cli/configtest": "^3.0.1", "commander": "^14.0.3",
"@webpack-cli/info": "^3.0.1", "cross-spawn": "^7.0.6",
"@webpack-cli/serve": "^3.0.1", "envinfo": "^7.21.0",
"colorette": "^2.0.14", "import-local": "^3.2.0",
"commander": "^12.1.0",
"cross-spawn": "^7.0.3",
"envinfo": "^7.14.0",
"fastest-levenshtein": "^1.0.12",
"import-local": "^3.0.2",
"interpret": "^3.1.1", "interpret": "^3.1.1",
"rechoir": "^0.8.0", "rechoir": "^0.8.0",
"webpack-merge": "^6.0.1" "webpack-merge": "^6.0.1"
}, },
"dependencies": { "dependencies": {
"commander": { "commander": {
"version": "12.1.0", "version": "14.0.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz",
"integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==",
"dev": true "dev": true
} }
} }
@ -957,9 +810,9 @@
} }
}, },
"webpack-sources": { "webpack-sources": {
"version": "3.3.3", "version": "3.5.1",
"resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.3.3.tgz", "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz",
"integrity": "sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg==", "integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==",
"dev": true "dev": true
}, },
"which": { "which": {

View file

@ -18,8 +18,8 @@
"build": "webpack" "build": "webpack"
}, },
"devDependencies": { "devDependencies": {
"webpack": "^5.94.0", "webpack": "5.111.1",
"webpack-cli": "^6.0.0" "webpack-cli": "7.2.3"
}, },
"dependencies": { "dependencies": {
"events": "^3.3.0" "events": "^3.3.0"

View file

@ -5,13 +5,13 @@ use crate::event_ui::event_help_tooltip;
use crate::happiness_ui::open_increase_happiness_dialog; use crate::happiness_ui::open_increase_happiness_dialog;
use crate::influence_ui::new_cultural_influence_dialog; use crate::influence_ui::new_cultural_influence_dialog;
use crate::layout_ui::{bottom_left_texture, icon_pos}; use crate::layout_ui::{bottom_left_texture, icon_pos};
use crate::log_ui::MultilineText;
use crate::move_ui::MoveIntent; use crate::move_ui::MoveIntent;
use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use itertools::Itertools; use itertools::Itertools;
use server::action::Action; use server::action::Action;
use server::city::City; use server::city::City;
use server::content::custom_actions::{CustomAction, CustomActionInfo}; use server::content::custom_actions::{CustomAction, SpecialActionInfo};
use server::cultural_influence::available_influence_actions; use server::cultural_influence::available_influence_actions;
use server::happiness::available_happiness_actions; use server::happiness::available_happiness_actions;
use server::playing_actions::{PlayingAction, PlayingActionType}; use server::playing_actions::{PlayingAction, PlayingActionType};
@ -65,7 +65,7 @@ pub(crate) fn action_buttons(rc: &RenderContext) -> RenderResult {
&MultilineText::of(rc, "Cultural Influence"), &MultilineText::of(rc, "Cultural Influence"),
) )
{ {
return base_or_custom_action(rc, &influence, "Influence culture", |d| { return base_or_modified_action(rc, &influence, "Influence culture", |d| {
new_cultural_influence_dialog(rc.game, rc.shown_player.index, d) new_cultural_influence_dialog(rc.game, rc.shown_player.index, d)
}); });
} }
@ -74,7 +74,7 @@ pub(crate) fn action_buttons(rc: &RenderContext) -> RenderResult {
if let Some(action) = generic_custom_action(rc, &c, None) { if let Some(action) = generic_custom_action(rc, &c, None) {
if bottom_left_texture( if bottom_left_texture(
rc, rc,
&assets.custom_actions[&c.action], &assets.custom_actions[&c.custom_action_type()],
icon_pos(i as i8, -1), icon_pos(i as i8, -1),
&event_help_tooltip(rc, &c.event_origin), &event_help_tooltip(rc, &c.event_origin),
) { ) {
@ -103,7 +103,7 @@ pub(crate) fn custom_action_buttons<'a>(
.filter_map(|c| { .filter_map(|c| {
generic_custom_action(rc, &c, city).map(|action| { generic_custom_action(rc, &c, city).map(|action| {
IconAction::new( IconAction::new(
&rc.assets().custom_actions[&c.action], &rc.assets().custom_actions[&c.custom_action_type()],
false, false,
event_help_tooltip(rc, &c.event_origin), event_help_tooltip(rc, &c.event_origin),
Box::new(move || action.clone()), Box::new(move || action.clone()),
@ -128,10 +128,10 @@ fn global_move(rc: &RenderContext) -> RenderResult {
fn generic_custom_action( fn generic_custom_action(
rc: &RenderContext, rc: &RenderContext,
c: &CustomActionInfo, c: &SpecialActionInfo,
city: Option<&City>, city: Option<&City>,
) -> Option<RenderResult> { ) -> Option<RenderResult> {
let custom_action_type = c.action; let custom_action_type = c.custom_action_type();
if let Some(city) = city { if let Some(city) = city {
c.is_city_available(rc.game, city) c.is_city_available(rc.game, city)
@ -147,7 +147,7 @@ fn generic_custom_action(
} }
} }
pub(crate) fn base_or_custom_action( pub(crate) fn base_or_modified_action(
rc: &RenderContext, rc: &RenderContext,
action_types: &[PlayingActionType], action_types: &[PlayingActionType],
title: &str, title: &str,
@ -158,8 +158,8 @@ pub(crate) fn base_or_custom_action(
action_types action_types
.iter() .iter()
.map(|action_type| match action_type { .map(|action_type| match action_type {
PlayingActionType::Custom(c) => { PlayingActionType::Special(s) => {
let origin = &rc.shown_player.custom_action_info(*c).event_origin; let origin = &rc.shown_player.special_action_info(s).event_origin;
( (
Some(origin.clone()), Some(origin.clone()),
execute(BaseOrCustomDialog { execute(BaseOrCustomDialog {

View file

@ -1,7 +1,7 @@
use crate::city_ui::add_building_description; use crate::city_ui::add_building_description;
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::layout_ui::{button_pressed, top_centered_text}; use crate::layout_ui::{button_pressed, top_centered_text};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::payment_ui::{Payment, payment_dialog}; use crate::payment_ui::{Payment, payment_dialog};
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::unit_ui::add_unit_description; use crate::unit_ui::add_unit_description;

View file

@ -60,6 +60,10 @@ pub(crate) struct Assets {
pub custom_actions: HashMap<CustomActionType, Texture2D>, pub custom_actions: HashMap<CustomActionType, Texture2D>,
pub civ: HashMap<String, CivAssets>, pub civ: HashMap<String, CivAssets>,
pub default_civ: CivAssets, pub default_civ: CivAssets,
// Log
pub hex: Texture2D,
pub fast: Texture2D,
} }
impl Assets { impl Assets {
@ -116,6 +120,10 @@ impl Assets {
export: load_png(include_bytes!("../assets/export-2-svgrepo-com.png")), export: load_png(include_bytes!("../assets/export-2-svgrepo-com.png")),
play: load_png(include_bytes!("../assets/play-1003-svgrepo-com.png")), play: load_png(include_bytes!("../assets/play-1003-svgrepo-com.png")),
pause: load_png(include_bytes!("../assets/pause-1006-svgrepo-com.png")), pause: load_png(include_bytes!("../assets/pause-1006-svgrepo-com.png")),
// Log
hex: load_png(include_bytes!("../assets/hex-svgrepo-com.png")),
fast: load_png(include_bytes!("../assets/lightning-svgrepo-com.png")),
} }
} }

View file

@ -3,7 +3,7 @@ use crate::custom_phase_ui;
use crate::custom_phase_ui::MultiSelection; use crate::custom_phase_ui::MultiSelection;
use crate::dialog_ui::ok_button; use crate::dialog_ui::ok_button;
use crate::layout_ui::{bottom_centered_text, button_pressed, rect_from}; use crate::layout_ui::{bottom_centered_text, button_pressed, rect_from};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::player_ui::get_combat; use crate::player_ui::get_combat;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::select_ui::HighlightType; use crate::select_ui::HighlightType;
@ -58,7 +58,7 @@ impl SelectionInfo {
pub(crate) fn show_cards(rc: &RenderContext) -> RenderResult { pub(crate) fn show_cards(rc: &RenderContext) -> RenderResult {
let p = rc.shown_player; let p = rc.shown_player;
let cards = hand_cards(p, &HandCardType::get_all()); let cards = hand_cards(p, &HandCardType::get_all_and_public(), rc.game);
let size = vec2(180., 30.); let size = vec2(180., 30.);
let selection = match &rc.state.active_dialog { let selection = match &rc.state.active_dialog {

View file

@ -1,4 +1,4 @@
use crate::action_buttons::{base_or_custom_action, custom_action_buttons}; use crate::action_buttons::{base_or_modified_action, custom_action_buttons};
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::collect_ui::CollectResources; use crate::collect_ui::CollectResources;
use crate::construct_ui::{ConstructionPayment, ConstructionProject}; use crate::construct_ui::{ConstructionPayment, ConstructionProject};
@ -11,8 +11,8 @@ use crate::hex_ui;
use crate::layout_ui::{ use crate::layout_ui::{
draw_scaled_icon, draw_scaled_icon_with_tooltip, is_in_circle, is_mouse_pressed, draw_scaled_icon, draw_scaled_icon_with_tooltip, is_in_circle, is_mouse_pressed,
}; };
use crate::log_ui::MultilineText;
use crate::map_ui::{move_units_buttons, show_map_action_buttons}; use crate::map_ui::{move_units_buttons, show_map_action_buttons};
use crate::multiline::MultilineText;
use crate::recruit_unit_ui::RecruitAmount; use crate::recruit_unit_ui::RecruitAmount;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::select_ui::HighlightType; use crate::select_ui::HighlightType;
@ -241,7 +241,7 @@ fn collect_resources_button<'a>(rc: &'a RenderContext, city: &'a City) -> Option
false, false,
MultilineText::of(rc, "Collect Resources"), MultilineText::of(rc, "Collect Resources"),
Box::new(move || { Box::new(move || {
base_or_custom_action(rc, &actions, "Collect resources", |custom| { base_or_modified_action(rc, &actions, "Collect resources", |custom| {
let i = possible_resource_collections( let i = possible_resource_collections(
rc.game, rc.game,
city.position, city.position,
@ -345,27 +345,27 @@ pub(crate) fn draw_city(rc: &RenderContext, city: &City) -> RenderResult {
{ {
draw_selected_state(rc, c, 15., h)?; draw_selected_state(rc, c, 15., h)?;
} else { } else {
draw_mood_state(rc, city, c); let mood = match &rc.state.active_dialog {
ActiveDialog::IncreaseHappiness(increase) => {
let steps = increase
.steps
.iter()
.find(|(p, _)| p == &city.position)
.map_or(&0, |(_, s)| s);
&city.mood_state.clone().add(*steps)
}
_ => &city.mood_state,
};
draw_mood_state(rc, c, mood);
} }
let i = draw_wonders(rc, city, c, owner, highlighted)?; let i = draw_wonders(rc, city, c, owner, highlighted)?;
draw_buildings(rc, city, c, highlighted, i) draw_buildings(rc, city, c, highlighted, i)
} }
fn draw_mood_state(rc: &RenderContext, city: &City, c: Vec2) { pub(crate) fn draw_mood_state(rc: &RenderContext, c: Vec2, mood_state: &MoodState) {
let state = &rc.state; let t = match mood_state {
let mood = match &state.active_dialog {
ActiveDialog::IncreaseHappiness(increase) => {
let steps = increase
.steps
.iter()
.find(|(p, _)| p == &city.position)
.map_or(&0, |(_, s)| s);
&city.mood_state.clone().add(*steps)
}
_ => &city.mood_state,
};
let t = match mood {
MoodState::Happy => Some(&rc.assets().resources[&ResourceType::MoodTokens]), MoodState::Happy => Some(&rc.assets().resources[&ResourceType::MoodTokens]),
MoodState::Neutral => None, MoodState::Neutral => None,
MoodState::Angry => Some(&rc.assets().angry), MoodState::Angry => Some(&rc.assets().angry),
@ -375,7 +375,7 @@ fn draw_mood_state(rc: &RenderContext, city: &City, c: Vec2) {
draw_scaled_icon( draw_scaled_icon(
rc, rc,
t, t,
&format!("Happiness: {}", city.mood_state), &format!("Happiness: {mood_state}"),
c + vec2(-size / 2., -size / 2.), c + vec2(-size / 2., -size / 2.),
size, size,
); );

View file

@ -21,8 +21,9 @@ use crate::layout_ui::{
ICON_SIZE, bottom_center_anchor, bottom_centered_text_with_offset, ICON_SIZE, bottom_center_anchor, bottom_centered_text_with_offset,
draw_scaled_icon_with_tooltip, icon_pos, is_mouse_pressed, top_right_texture, draw_scaled_icon_with_tooltip, icon_pos, is_mouse_pressed, top_right_texture,
}; };
use crate::log_ui::{LogDialog, MultilineText, show_log}; use crate::log_ui::{LogDialog, show_log};
use crate::map_ui::{draw_map, explore_dialog, show_tile_menu}; use crate::map_ui::{draw_map, explore_dialog, show_tile_menu};
use crate::multiline::MultilineText;
use crate::player_ui::{ use crate::player_ui::{
ColumnLabelPainter, player_select, show_global_controls, show_top_center, show_top_left, ColumnLabelPainter, player_select, show_global_controls, show_top_center, show_top_left,
}; };
@ -52,10 +53,12 @@ fn set_zoom(state: &mut State) {
let w = state.raw_screen_size.x; let w = state.raw_screen_size.x;
let h = state.raw_screen_size.y; let h = state.raw_screen_size.y;
state.world_camera.viewport = Some((0, 0, w as i32, h as i32)); state.world_camera.viewport = Some((0, 0, w as i32, h as i32));
state.world_camera.zoom.x = state.world_zoom * state.world_zoom_factor;
state.world_camera.zoom.y = state.world_camera.zoom.x * w / h; state.world_camera.zoom.y = state.world_camera.zoom.x * w / h;
let scale = state.ui_scale; let scale = state.ui_scale;
state.screen_size = vec2(w / scale, h / scale); let adjust = (1.0 - scale) * 250.0; // not sure why this is needed on mobile
state.screen_size = vec2((w / scale) - adjust, h / scale - adjust);
state.ui_camera = Camera2D { state.ui_camera = Camera2D {
zoom: vec2(2.0 / w * scale, 2.0 / h * scale), zoom: vec2(2.0 / w * scale, 2.0 / h * scale),

View file

@ -17,6 +17,7 @@ use crate::recruit_unit_ui::{RecruitAmount, RecruitSelection};
use crate::render_context::{RenderContext, RenderStage}; use crate::render_context::{RenderContext, RenderStage};
use crate::status_phase_ui::ChooseAdditionalAdvances; use crate::status_phase_ui::ChooseAdditionalAdvances;
use macroquad::prelude::*; use macroquad::prelude::*;
use serde::{Deserialize, Serialize};
use server::action::Action; use server::action::Action;
use server::advance::Advance; use server::advance::Advance;
use server::card::HandCard; use server::card::HandCard;
@ -112,11 +113,11 @@ impl ActiveDialog {
ActiveDialog::StructuresRequest(d, r) => { ActiveDialog::StructuresRequest(d, r) => {
if let Some(b) = d { if let Some(b) = d {
let v = vec!["Click on a building to influence its culture".to_string()]; let v = vec!["Click on a building to influence its culture".to_string()];
if let PlayingActionType::Custom(c) = &b.action_type { if let PlayingActionType::Special(c) = &b.action_type {
let mut r = v.clone(); let mut r = v.clone();
r.extend(event_help( r.extend(event_help(
rc, rc,
&rc.shown_player.custom_action_info(*c).event_origin, &rc.shown_player.special_action_info(c).event_origin,
)); ));
} }
v v
@ -338,6 +339,12 @@ pub(crate) enum CameraMode {
World, World,
} }
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub enum ColorProfile {
Standard,
HighContrast,
}
use crate::info_ui::InfoDialog; use crate::info_ui::InfoDialog;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use server::ai::AI; use server::ai::AI;
@ -349,18 +356,21 @@ pub struct State {
pub show_player: usize, pub show_player: usize,
pub(crate) active_dialog: ActiveDialog, pub(crate) active_dialog: ActiveDialog,
pub(crate) pending_update: Option<PendingUpdate>, pub(crate) pending_update: Option<PendingUpdate>,
pub world_camera: Camera2D, pub(crate) world_camera: Camera2D,
pub ui_camera: Camera2D, pub(crate) world_zoom: f32,
pub world_zoom_factor: f32,
pub(crate) ui_camera: Camera2D,
pub ui_scale: f32, pub ui_scale: f32,
pub raw_screen_size: Vec2, pub raw_screen_size: Vec2,
pub screen_size: Vec2, // scaled by ui_scale pub(crate) screen_size: Vec2, // scaled by ui_scale
pub(crate) mouse_positions: Vec<MousePosition>, pub(crate) mouse_positions: Vec<MousePosition>,
pub focused_tile: Option<Position>, pub(crate) focused_tile: Option<Position>,
pub show_permanent_effects: bool, pub(crate) show_permanent_effects: bool,
pub ai_autoplay: bool, pub ai_autoplay: bool,
pub pan_map: bool, pub(crate) pan_map: bool,
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub ai_players: Vec<AI>, pub ai_players: Vec<AI>,
pub color_profile: ColorProfile,
} }
pub const ZOOM: f32 = 0.001; pub const ZOOM: f32 = 0.001;
@ -377,12 +387,13 @@ impl State {
control_player: None, control_player: None,
show_player: 0, show_player: 0,
world_camera: Camera2D { world_camera: Camera2D {
zoom: vec2(ZOOM, ZOOM),
offset: OFFSET, offset: OFFSET,
..Default::default() ..Default::default()
}, },
ui_camera: Camera2D::default(), ui_camera: Camera2D::default(),
ui_scale: 1.0, ui_scale: 1.0,
world_zoom_factor: 1.0,
world_zoom: ZOOM,
raw_screen_size: vec2(0., 0.), raw_screen_size: vec2(0., 0.),
screen_size: vec2(0., 0.), screen_size: vec2(0., 0.),
mouse_positions: vec![], mouse_positions: vec![],
@ -392,6 +403,7 @@ impl State {
ai_autoplay: false, ai_autoplay: false,
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
ai_players: vec![], ai_players: vec![],
color_profile: ColorProfile::Standard,
} }
} }
@ -589,11 +601,11 @@ impl State {
} }
pub(crate) fn draw_text(&self, text: &str, x: f32, y: f32) { pub(crate) fn draw_text(&self, text: &str, x: f32, y: f32) {
self.draw_text_with_color(text, x, y, BLACK); self.draw_text_ex(text, x, y, BLACK, FONT_SIZE);
} }
pub(crate) fn draw_text_with_color(&self, text: &str, x: f32, y: f32, color: Color) { pub(crate) fn draw_text_ex(&self, text: &str, x: f32, y: f32, color: Color, font_size: u16) {
if crate::localization::draw(text, FONT_SIZE, x, y, color) { if crate::localization::draw(text, font_size, x, y, color) {
return; return;
} }
draw_text_ex( draw_text_ex(
@ -602,7 +614,7 @@ impl State {
y, y,
TextParams { TextParams {
font: Some(&self.assets.font), font: Some(&self.assets.font),
font_size: FONT_SIZE, font_size,
color, color,
..Default::default() ..Default::default()
}, },

View file

@ -2,7 +2,7 @@ use crate::advance_ui::{AdvanceState, show_advance_menu};
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::dialog_ui::{BaseOrCustomDialog, OkTooltip, cancel_button_with_tooltip, ok_button}; use crate::dialog_ui::{BaseOrCustomDialog, OkTooltip, cancel_button_with_tooltip, ok_button};
use crate::layout_ui::{bottom_center_anchor, bottom_centered_text, icon_pos}; use crate::layout_ui::{bottom_center_anchor, bottom_centered_text, icon_pos};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::payment_ui::{Payment, multi_payment_dialog, payment_dialog}; use crate::payment_ui::{Payment, multi_payment_dialog, payment_dialog};
use crate::player_ui::choose_player_dialog; use crate::player_ui::choose_player_dialog;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;

View file

@ -1,6 +1,6 @@
use crate::client_state::{NO_UPDATE, PendingUpdate, RenderResult, StateUpdate}; use crate::client_state::{NO_UPDATE, PendingUpdate, RenderResult, StateUpdate};
use crate::layout_ui::{bottom_centered_text_with_offset, bottom_right_texture, icon_pos}; use crate::layout_ui::{bottom_centered_text_with_offset, bottom_right_texture, icon_pos};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use macroquad::math::{Vec2, vec2}; use macroquad::math::{Vec2, vec2};
use server::playing_actions::PlayingActionType; use server::playing_actions::PlayingActionType;

View file

@ -1,4 +1,4 @@
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::payment_ui::Payment; use crate::payment_ui::Payment;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use server::content::effects; use server::content::effects;

View file

@ -1,4 +1,4 @@
use crate::action_buttons::base_or_custom_action; use crate::action_buttons::base_or_modified_action;
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::dialog_ui::BaseOrCustomDialog; use crate::dialog_ui::BaseOrCustomDialog;
use crate::payment_ui::{Payment, payment_dialog}; use crate::payment_ui::{Payment, payment_dialog};
@ -66,7 +66,7 @@ pub(crate) fn open_increase_happiness_dialog(
actions: &[PlayingActionType], actions: &[PlayingActionType],
init: impl Fn(IncreaseHappinessConfig) -> IncreaseHappinessConfig, init: impl Fn(IncreaseHappinessConfig) -> IncreaseHappinessConfig,
) -> RenderResult { ) -> RenderResult {
base_or_custom_action(rc, actions, "Increase happiness", |custom| { base_or_modified_action(rc, actions, "Increase happiness", |custom| {
ActiveDialog::IncreaseHappiness(init(IncreaseHappinessConfig::new(rc, custom))) ActiveDialog::IncreaseHappiness(init(IncreaseHappinessConfig::new(rc, custom)))
}) })
} }

View file

@ -1,6 +1,6 @@
use std::f32::consts::PI; use std::f32::consts::PI;
use crate::layout_ui::draw_scaled_icon; use crate::layout_ui::{FONT_SIZE, draw_scaled_icon};
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use hex2d::{Coordinate, Spacing}; use hex2d::{Coordinate, Spacing};
use macroquad::color::Color; use macroquad::color::Color;
@ -58,12 +58,13 @@ pub(crate) fn draw_hex(
} }
draw_hexagon(c.x, c.y, SIZE, 2.0, false, DARKGRAY, overlay); draw_hexagon(c.x, c.y, SIZE, 2.0, false, DARKGRAY, overlay);
let text_y = c.y - 35.0; let text_y = c.y - 35.0;
rc.draw_text_with_color(&p.to_string(), c.x - 30.0, text_y, text_color); rc.draw_text_ex(&p.to_string(), c.x - 30.0, text_y, text_color, FONT_SIZE);
rc.draw_text_with_color( rc.draw_text_ex(
&block_for_position(rc.game, p).0.to_string(), &block_for_position(rc.game, p).0.to_string(),
c.x + 10.0, c.x + 10.0,
text_y, text_y,
text_color, text_color,
FONT_SIZE,
); );
} }

View file

@ -4,7 +4,7 @@ use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::dialog_ui::{OkTooltip, ok_button}; use crate::dialog_ui::{OkTooltip, ok_button};
use crate::event_ui::event_help_tooltip; use crate::event_ui::event_help_tooltip;
use crate::layout_ui::button_pressed; use crate::layout_ui::button_pressed;
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use itertools::Itertools; use itertools::Itertools;
use macroquad::color::Color; use macroquad::color::Color;

View file

@ -1,4 +1,4 @@
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::tooltip::show_tooltip_for_rect; use crate::tooltip::show_tooltip_for_rect;
use macroquad::color::WHITE; use macroquad::color::WHITE;

View file

@ -27,14 +27,17 @@ mod influence_ui;
mod info_ui; mod info_ui;
mod layout_ui; mod layout_ui;
mod localization; mod localization;
mod log_collector;
mod log_ui; mod log_ui;
mod map_ui; mod map_ui;
mod move_ui; mod move_ui;
mod multiline;
mod payment_ui; mod payment_ui;
mod player_ui; mod player_ui;
mod recruit_unit_ui; mod recruit_unit_ui;
mod render_context; mod render_context;
mod resource_ui; mod resource_ui;
mod richtext;
mod select_ui; mod select_ui;
mod status_phase_ui; mod status_phase_ui;
mod tooltip; mod tooltip;

View file

@ -26,7 +26,7 @@ enum Mode {
async fn main() { async fn main() {
start_profiling(); start_profiling();
set_window_size(1200, 600); set_window_size(1800, 1600);
let mut args: Vec<String> = env::args().collect(); let mut args: Vec<String> = env::args().collect();
args.remove(0); // program name args.remove(0); // program name
@ -57,7 +57,8 @@ async fn main() {
} else { } else {
CivSetupOption::Random CivSetupOption::Random
}, },
patch: PatchOption::BalancePatch, patch: PatchOption::Standard,
..GameOptions::default()
}) })
.build(), .build(),
); );

450
client/src/log_collector.rs Normal file
View file

@ -0,0 +1,450 @@
use crate::log_ui::multiline_label;
use crate::render_context::RenderContext;
use server::action::Action;
use server::card::HandCardLocation;
use server::combat_roll::UnitCombatRoll;
use server::content::ability::combat_event_origin;
use server::cultural_influence::InfluenceCultureAttemptInfo;
use server::events::EventOrigin;
use server::game_setup::setup_event_origin;
use server::log::{
ActionLogAction, ActionLogAge, ActionLogBalance, ActionLogEntry, ActionLogItem, ActionLogRound,
ActionLogTurn, SetupTurnType, TurnType,
};
use server::playing_actions::PlayingAction;
use server::status_phase::StatusPhaseStateType;
use server::unit::Units;
use server::utils::remove_element_by;
#[derive(Clone, Debug)]
pub(crate) struct ActionLogInfluence {
pub(crate) player: usize,
pub(crate) info: InfluenceCultureAttemptInfo,
}
#[derive(Clone, Debug)]
pub(crate) struct ActionLogBody {
pub(crate) action: ActionLogAction,
pub(crate) action_cost: bool,
pub(crate) argument: Option<ActionLogEntry>,
pub(crate) payment: Option<ActionLogEntry>,
}
impl ActionLogBody {
pub(crate) fn new(action: ActionLogAction) -> Self {
ActionLogBody {
action,
action_cost: false,
argument: None,
payment: None,
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum LogBody {
Message(String),
Item(ActionLogItem),
PlayerSetup(SetupTurnType),
PlayerTurn {
age: u32,
round: u32,
player: usize,
},
Action(Box<ActionLogBody>),
CombatUnits {
role: String,
player: usize,
units: Units,
},
DieRoll(UnitCombatRoll),
InfluenceStartCity(ActionLogInfluence),
InfluenceRangeBoost(ActionLogInfluence),
}
#[derive(Clone, Debug)]
pub(crate) struct LogEntry {
pub(crate) body: LogBody,
pub(crate) active_origin: Option<EventOrigin>,
pub(crate) indent: usize,
pub(crate) age: u32,
pub(crate) round: u32,
}
impl LogEntry {
pub(crate) fn new(
body: LogBody,
active_origin: Option<EventOrigin>,
indent: usize,
age: u32,
round: u32,
) -> Self {
LogEntry {
body,
active_origin,
indent,
age,
round,
}
}
}
struct LogCollector {
age: u32,
round: u32,
log_entries: Vec<LogEntry>,
active_origin: Option<EventOrigin>,
}
impl LogCollector {
fn new() -> Self {
Self {
log_entries: Vec::new(),
active_origin: None,
age: 0,
round: 0,
}
}
fn add_entry(&mut self, body: LogBody, indent: usize) {
self.log_entries.push(LogEntry::new(
body,
self.active_origin.clone(),
indent,
self.age,
self.round,
));
}
fn add_message(&mut self, message: &str, indent: usize) {
self.add_entry(LogBody::Message(message.to_string()), indent);
}
}
pub(crate) fn collect_log_entries(rc: &RenderContext) -> Vec<LogEntry> {
let mut c = LogCollector::new();
for age in &rc.game.log {
c.age = age.age;
if age.age == 0 {
c.add_message("Game Start", 0);
}
for round in &age.rounds {
c.round = round.round;
if round.round > 0 {
c.add_message(&format!("Age {}, Round {}", age.age, round.round), 0);
}
for turn in &round.turns {
c.active_origin = None;
let indent = add_title_items(&mut c, age, round, turn);
for action in &turn.actions {
collect_action(rc, &mut c, action, indent + action.active_events);
}
}
}
}
c.log_entries
}
fn collect_action(
rc: &RenderContext,
c: &mut LogCollector,
action: &ActionLogAction,
indent: usize,
) {
let origin = &action.origin;
if origin.is_some() {
c.active_origin.clone_from(origin);
}
let mut items = action.items.clone();
let indent = if matches!(action.action, Action::StartTurn) {
indent
} else {
let mut body = ActionLogBody::new(action.clone());
inline_action_items(&mut items, &mut body);
c.add_entry(LogBody::Action(Box::new(body.clone())), indent);
add_additional_action_items(c, &mut body, action, indent + 1);
indent + 1
};
for item in &items {
match &item.entry {
ActionLogEntry::Text(m) => {
add_text_item(rc, c, indent, item, m);
continue;
}
ActionLogEntry::HandCard {
to: HandCardLocation::PlayToKeep,
..
} => {
// redundant
continue;
}
_ => {}
}
set_item_origin(c, item);
c.add_entry(LogBody::Item(item.clone()), indent);
add_additional_items(c, item, indent);
}
}
fn add_additional_action_items(
c: &mut LogCollector,
body: &mut ActionLogBody,
action: &ActionLogAction,
indent: usize,
) {
if let Some(ActionLogEntry::InfluenceCultureAttempt(i)) = &body.argument {
c.add_entry(
LogBody::InfluenceStartCity(ActionLogInfluence {
player: action.player,
info: i.clone(),
}),
indent,
);
if !i.range_boost_cost.is_free() {
c.add_entry(
LogBody::InfluenceRangeBoost(ActionLogInfluence {
player: action.player,
info: i.clone(),
}),
indent,
);
}
}
}
fn add_text_item(
rc: &RenderContext,
c: &mut LogCollector,
indent: usize,
item: &ActionLogItem,
m: &str,
) {
// Simulate multiline labels to get accurate line count
multiline_label(rc.state, m, max_width(rc), |i, label: &str| {
if i == 0 {
c.add_entry(LogBody::Item(item.clone()), indent);
} else {
c.add_message(label, indent);
}
});
}
fn set_item_origin(c: &mut LogCollector, item: &ActionLogItem) {
if matches!(
item.entry,
ActionLogEntry::CombatRound(_) | ActionLogEntry::CombatRoll(_)
) {
c.active_origin = Some(combat_event_origin());
}
}
fn add_title_items(
c: &mut LogCollector,
age: &ActionLogAge,
round: &ActionLogRound,
turn: &ActionLogTurn,
) -> usize {
match &turn.turn_type {
TurnType::Player(p) => {
c.add_entry(
LogBody::PlayerTurn {
age: age.age,
round: round.round,
player: *p,
},
1,
);
2
}
TurnType::Setup(t) => {
c.active_origin = Some(setup_event_origin());
c.add_entry(LogBody::PlayerSetup(t.clone()), 1);
2
}
TurnType::StatusPhase(t) => status_phase_title(age, *t, c),
}
}
fn add_additional_items(c: &mut LogCollector, item: &ActionLogItem, indent: usize) {
match &item.entry {
ActionLogEntry::CombatRound(r) => {
c.add_entry(
LogBody::CombatUnits {
role: "Attacking:".to_string(),
player: item.player,
units: r.attackers.clone(),
},
indent + 1,
);
c.add_entry(
LogBody::CombatUnits {
role: "Defending:".to_string(),
player: r.defending_player,
units: r.defenders.clone(),
},
indent + 1,
);
}
ActionLogEntry::CombatRoll(r) => {
for m in &r.combat_modifiers {
c.add_message(m, indent + 1);
}
for r in &r.rolls {
c.add_entry(LogBody::DieRoll(r.clone()), indent + 1);
}
}
_ => {}
}
}
fn inline_action_items(items: &mut Vec<ActionLogItem>, action: &mut ActionLogBody) {
if remove_element_by(items, |item| {
matches!(
item,
ActionLogItem {
player,
entry: ActionLogEntry::Action {
balance: ActionLogBalance::Pay,
..
},
..
} if *player == action.action.player
)
})
.is_some()
{
action.action_cost = true;
}
action.argument = pull_action_arg(items, action);
action.payment = remove_element_by(items, |item| {
matches!(
item,
ActionLogItem {
player,
entry: ActionLogEntry::Resources {
balance: ActionLogBalance::Pay,
..
},
..
} if *player == action.action.player
)
})
.map(|i| i.entry);
}
pub fn find_action_arg(
list: &mut Vec<ActionLogItem>,
body: &ActionLogBody,
f: impl Fn(&ActionLogItem) -> bool,
) -> Option<ActionLogEntry> {
let arg = remove_element_by(list, |i| f(i) && i.player == body.action.player).map(|i| i.entry);
assert!(arg.is_some(), "Could not find action argument in log items");
arg
}
fn pull_action_arg(items: &mut Vec<ActionLogItem>, body: &ActionLogBody) -> Option<ActionLogEntry> {
match &body.action.action {
Action::Playing(a) => match a {
PlayingAction::Advance(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::Advance(_),
..
}
)
}),
PlayingAction::Collect(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::Resources {
balance: ActionLogBalance::Gain,
..
},
..
}
)
}),
PlayingAction::FoundCity { .. } | PlayingAction::Construct(_) => {
find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::Structure(_),
..
}
)
})
}
PlayingAction::Recruit(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::Units { .. },
..
}
)
}),
PlayingAction::InfluenceCultureAttempt(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::InfluenceCultureAttempt(_),
..
}
)
}),
PlayingAction::ActionCard(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::HandCard { .. },
..
}
)
}),
_ => None,
},
Action::Movement(_) => find_action_arg(items, body, |item| {
matches!(
item,
ActionLogItem {
entry: ActionLogEntry::Move(_),
..
}
)
}),
_ => None,
}
}
fn status_phase_title(age: &ActionLogAge, t: StatusPhaseStateType, c: &mut LogCollector) -> usize {
if matches!(t, StatusPhaseStateType::CompleteObjectives) {
c.add_message(&format!("Status Phase (Age {})", age.age), 2);
}
c.add_message(
match t {
StatusPhaseStateType::CompleteObjectives => "Complete Objectives",
StatusPhaseStateType::FreeAdvance => "Free Advance",
StatusPhaseStateType::DrawCards => "Draw Cards",
StatusPhaseStateType::RazeSize1City => "Raze Size 1 City",
StatusPhaseStateType::ChangeGovernmentType => "Change Government Type",
StatusPhaseStateType::DetermineFirstPlayer => "Determine First Player",
},
3,
);
if matches!(t, StatusPhaseStateType::DrawCards) {
4
} else {
3 // response adds another indent
}
}
fn max_width(rc: &RenderContext) -> f32 {
rc.state.screen_size.x - 300.
}

View file

@ -1,27 +1,22 @@
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, State, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, State, StateUpdate};
use crate::layout_ui::bottom_center_texture; use crate::layout_ui::bottom_center_texture;
use crate::log_collector::{ActionLogBody, LogBody, LogEntry, collect_log_entries};
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::richtext::RichTextDrawer;
use macroquad::math::vec2; use macroquad::math::vec2;
use server::log::TurnType; use server::action::Action;
use server::card::hand_card_message;
#[derive(Clone, Debug)] use server::combat_roll::UnitCombatRoll;
pub(crate) struct LogEntry { use server::content::custom_actions::SpecialAction;
pub age: Option<String>, use server::content::persistent_events::EventResponse;
pub round: Option<String>, use server::events::EventOrigin;
pub name: String, use server::log::{
pub message: String, ActionLogBalance, ActionLogEntry, ActionLogEntryAdvance, ActionLogEntryMove,
} ActionLogIncidentToken, ActionLogItem,
};
impl LogEntry { use server::movement::MovementAction;
pub(crate) fn new(age: Option<u32>, round: Option<u32>, name: &str, message: String) -> Self { use server::playing_actions::{PlayingAction, PlayingActionType};
LogEntry { use server::unit::UnitType;
age: age.map(|a| a.to_string()),
round: round.map(|r| r.to_string()),
name: name.to_string(),
message,
}
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub(crate) struct LogDialog { pub(crate) struct LogDialog {
@ -35,47 +30,7 @@ impl LogDialog {
pub(crate) fn new(rc: &RenderContext) -> Self { pub(crate) fn new(rc: &RenderContext) -> Self {
let lines_per_page = (rc.state.screen_size.y - 150.) as usize / 25; let lines_per_page = (rc.state.screen_size.y - 150.) as usize / 25;
// Build structured log entries with age, round, player, and message let log_entries = collect_log_entries(rc);
let mut log_entries = Vec::new();
for age in &rc.game.log {
for round in &age.rounds {
for turn in &round.turns {
for action in &turn.actions {
for message in &action.log {
// Simulate multiline labels to get accurate line count
multiline_label(
rc.state,
message,
Self::max_width(rc),
|label: &str| {
log_entries.push(match turn.turn_type {
TurnType::Player(p) => LogEntry::new(
Some(age.age),
Some(round.round),
&rc.game.player_name(p),
label.to_string(),
),
TurnType::Setup => LogEntry::new(
None,
None,
"Game Started",
label.to_string(),
),
TurnType::StatusPhase => LogEntry::new(
None,
Some(round.round),
"Status Phase",
label.to_string(),
),
});
},
);
}
}
}
}
}
let total_lines = log_entries.len(); let total_lines = log_entries.len();
let pages = if total_lines == 0 { let pages = if total_lines == 0 {
@ -91,68 +46,28 @@ impl LogDialog {
log_entries, log_entries,
} }
} }
fn max_width(rc: &RenderContext) -> f32 {
rc.state.screen_size.x - 300.
}
} }
pub(crate) fn show_log(rc: &RenderContext, d: &LogDialog) -> RenderResult { pub(crate) fn show_log(rc: &RenderContext, d: &LogDialog) -> RenderResult {
let state = &rc.state; let state = rc.state;
// Use the pre-calculated log entries // Use the pre-calculated log entries
let start = d.current_page * d.lines_per_page; let start = d.current_page * d.lines_per_page;
let end = usize::min(start + d.lines_per_page, d.log_entries.len()); let end = usize::min(start + d.lines_per_page, d.log_entries.len());
let mut y = 0.;
// Draw column headers // Header: turn and round, unless age is 0
let age_pos = vec2(30., 20.); if let Some(first_entry) = d.log_entries.get(start)
let round_pos = vec2(80., 20.); && first_entry.age > 0
let player_pos = vec2(140., 20.); {
let message_pos = vec2(280., 20.); let header = format!("Age {}, Round {}", first_entry.age, first_entry.round);
let header_width = state.measure_text(&header).width;
rc.draw_text(&header, state.screen_size.x / 2. - header_width / 2., 30.);
}
rc.draw_text("Age", age_pos.x, age_pos.y); let mut y = 1.5;
rc.draw_text("Round", round_pos.x, round_pos.y);
rc.draw_text("Player", player_pos.x, player_pos.y);
rc.draw_text("Message", message_pos.x, message_pos.y);
y += 1.5; // Add some space after headers
// Track previous values to only show when they change
let mut prev_age: Option<String> = None;
let mut prev_round: Option<String> = None;
let mut prev_name: Option<String> = None;
for entry in &d.log_entries[start..end] { for entry in &d.log_entries[start..end] {
let message_text = &entry.message; draw_line(rc, y, entry);
// Calculate positions for each column
let age_pos = vec2(30., y * 25. + 20.);
let round_pos = vec2(80., y * 25. + 20.);
let player_pos = vec2(140., y * 25. + 20.);
let message_pos = vec2(280., y * 25. + 20.);
// Draw each column
if let Some(age) = &entry.age
&& entry.age != prev_age
{
rc.draw_text(age, age_pos.x, age_pos.y);
}
if let Some(round) = &entry.round
&& entry.round != prev_round
{
rc.draw_text(round, round_pos.x, round_pos.y);
}
if Some(&entry.name) != prev_name.as_ref() {
rc.draw_text(&entry.name, player_pos.x, player_pos.y);
}
rc.draw_text(message_text, message_pos.x, message_pos.y);
// Update previous values
prev_age.clone_from(&entry.age);
prev_round.clone_from(&entry.round);
prev_name = Some(entry.name.clone());
y += 1.; y += 1.;
} }
// Bottom center navigation // Bottom center navigation
@ -199,20 +114,235 @@ pub(crate) fn show_log(rc: &RenderContext, d: &LogDialog) -> RenderResult {
NO_UPDATE NO_UPDATE
} }
pub(crate) fn multiline_label(state: &State, label: &str, len: f32, mut print: impl FnMut(&str)) { fn draw_line(rc: &RenderContext, y: f32, entry: &LogEntry) {
let message_pos = vec2(20. + entry.indent as f32 * 45.0, y * 25. + 20.);
let mut drawer = RichTextDrawer::new(rc, message_pos);
match &entry.body {
LogBody::Message(m) => rc.draw_text(m, message_pos.x, message_pos.y),
LogBody::Item(item) => {
draw_item(entry, &mut drawer, item);
}
LogBody::PlayerSetup(t) => {
drawer.player(t.player);
if let Some(civilization) = &t.civilization {
drawer.text("plays as");
drawer.text(civilization);
} else {
drawer.text("starts without a civilization");
}
}
LogBody::PlayerTurn { age, round, player } => {
drawer.player(*player);
drawer.text(&format!("starts their turn (Age {age}, Round {round})"));
}
LogBody::Action(a) => {
draw_action(&mut drawer, a);
}
LogBody::CombatUnits {
role,
player,
units,
} => {
drawer.text(role);
drawer.player(*player);
drawer.text("with");
drawer.units(units, None);
}
LogBody::DieRoll(r) => {
draw_die_roll(&mut drawer, r);
}
LogBody::InfluenceStartCity(i) => {
drawer.player(i.player);
drawer.text("uses start city");
drawer.at_location(i.info.starting_city_position);
}
LogBody::InfluenceRangeBoost(i) => {
drawer.player(i.player);
drawer.text("may pay");
drawer.resources(&i.info.range_boost_cost.default, &ActionLogBalance::Pay);
drawer.text("to boost the range");
}
}
}
fn draw_item(entry: &LogEntry, drawer: &mut RichTextDrawer, item: &ActionLogItem) {
drawer.player(item.player);
let balance = item.entry.balance();
if let Some(b) = &balance {
drawer.text(match b {
ActionLogBalance::Gain => "gains",
ActionLogBalance::Loss => "loses",
ActionLogBalance::Pay => "pays",
});
}
draw_entry(drawer, &item.entry, item.player);
if entry
.active_origin
.as_ref()
.is_none_or(|o| o != &item.origin)
{
drawer.modifier(&item.origin.name(drawer.rc.game), balance);
}
item.modifiers.iter().for_each(|m| {
drawer.modifier(&m.name(drawer.rc.game), balance);
});
}
fn draw_die_roll(drawer: &mut RichTextDrawer, r: &UnitCombatRoll) {
let (bonus_str, add_value) = if r.bonus {
match r.unit_type {
UnitType::Settler | UnitType::Ship => panic!("unit does not have bonus"),
UnitType::Infantry => (Some("+1 combat value"), true),
UnitType::Cavalry if r.combat_bonus == Some(3) => {
(Some("+3 combat value (Horsemanship)"), true)
}
UnitType::Cavalry => (Some("+2 combat value"), true),
UnitType::Elephant => (Some("-1 hits, no combat value"), false),
UnitType::Leader(_) => (Some("re-roll"), false),
}
} else {
(None, true)
};
if add_value {
drawer.text(&format!("rolls a {}", r.value));
} else {
drawer.text(&format!("rolls a ({})", r.value));
}
drawer.unit_icon(r.unit_type);
if let Some(bonus_str) = bonus_str {
drawer.text(bonus_str);
}
}
fn draw_entry(drawer: &mut RichTextDrawer, entry: &ActionLogEntry, player: usize) {
match entry {
ActionLogEntry::Action { balance, amount } => {
if let Some(a) = amount {
drawer.amount(*a, balance);
}
drawer.action_icon();
}
ActionLogEntry::Resources { resources, balance } => {
drawer.resources(resources, balance);
}
ActionLogEntry::Advance(a) => {
draw_advance(drawer, a);
}
ActionLogEntry::Units {
units,
balance,
position,
} => {
drawer.units(units, Some(balance));
drawer.at_location(*position);
}
ActionLogEntry::Structure(s) => {
drawer.structure(&s.structure, s.position, s.port_position, player);
}
ActionLogEntry::HandCard { card, from, to } => {
let (_, message) = hand_card_message(drawer.rc.game, card, from, to);
drawer.text(&message);
}
ActionLogEntry::MoodChange { city, mood } => {
drawer.text("'s city");
drawer.at_location(*city);
drawer.text(&format!("becomes {mood}"));
drawer.mood(player, mood);
}
ActionLogEntry::Move(m) => draw_move(drawer, m),
ActionLogEntry::Explore { tiles } => {
drawer.text("explores:");
for (p, t) in tiles {
drawer.location(*p);
drawer.text(&format!("is {t}"));
}
}
ActionLogEntry::CombatRound(r) => {
drawer.text(&format!("Combat Round {}", r.round));
}
ActionLogEntry::CombatRoll(r) => {
drawer.text(&format!(
"rolls for combined combat value of {} and gets {} hits",
r.combat_value, r.hits,
));
}
ActionLogEntry::Text(m) => {
drawer.text(m);
}
ActionLogEntry::InfluenceCultureAttempt(i) => {
drawer.structure(&i.structure, i.position, None, i.target_player);
}
}
}
fn draw_advance(drawer: &mut RichTextDrawer, advance: &ActionLogEntryAdvance) {
drawer.icon(&drawer.rc.assets().advances);
drawer.text(advance.advance.name(drawer.rc.game));
if let ActionLogIncidentToken::Take(t) = advance.incident_token {
if t > 0 {
drawer.text(&format!("and takes an event token ({t} left)"));
} else {
drawer.text("and takes the last event token - triggering an event!");
}
}
}
fn draw_move(drawer: &mut RichTextDrawer, m: &ActionLogEntryMove) {
let game = drawer.rc.game;
let t = game
.map
.get(m.destination)
.expect("the destination position should be on the map");
let (verb, suffix) = if game.map.is_sea(m.start) {
if t.is_unexplored() || t.is_water() {
("sails", "")
} else {
("disembarks", "")
}
} else if m.embark_carrier_id.is_some() {
("embarks", "")
} else if m.start.is_neighbor(m.destination) {
("marches", "")
} else {
("marches", " on roads")
};
drawer.text(verb);
drawer.units(&m.units, None);
drawer.text("from");
drawer.location(m.start);
drawer.text("to");
drawer.location(m.destination);
if !suffix.is_empty() {
drawer.text(suffix);
}
}
pub(crate) fn multiline_label(
state: &State,
label: &str,
len: f32,
mut print: impl FnMut(usize, &str),
) {
if let Some(lines) = crate::localization::wrap(label, len, crate::layout_ui::FONT_SIZE) { if let Some(lines) = crate::localization::wrap(label, len, crate::layout_ui::FONT_SIZE) {
for line in lines { for (i, line) in lines.iter().enumerate() {
print(&line); print(i, line);
} }
return; return;
} }
let label = crate::localization::translate(label); let label = crate::localization::translate(label);
let mut line = String::new(); let mut line = String::new();
let mut i = 0;
label.split(' ').for_each(|s| { label.split(' ').for_each(|s| {
let next = format!("{line} {s}"); let next = format!("{line} {s}");
let dimensions = state.measure_text(&next); let dimensions = state.measure_text(&next);
if dimensions.width > len { if dimensions.width > len {
print(&line); print(i, &line);
i += 1;
line = " ".to_string(); line = " ".to_string();
} }
if !line.is_empty() { if !line.is_empty() {
@ -221,40 +351,160 @@ pub(crate) fn multiline_label(state: &State, label: &str, len: f32, mut print: i
line.push_str(s); line.push_str(s);
}); });
if !line.is_empty() { if !line.is_empty() {
print(&line); print(i, &line);
} }
} }
pub(crate) struct MultilineText { fn draw_action(drawer: &mut RichTextDrawer, body: &ActionLogBody) {
pub width: f32, if body.action_cost {
pub text: Vec<String>, drawer.action_icon();
} } else {
drawer.icon(&drawer.rc.assets().fast);
}
let a = &body.action;
drawer.player(a.player);
impl MultilineText { match &a.action {
pub(crate) fn default() -> Self { Action::Playing(p) => draw_playing_action(drawer, p, body),
MultilineText { Action::Movement(m) => match m {
width: 500., MovementAction::Move(_) => {
text: vec![], draw_argument(drawer, body);
}
MovementAction::Stop => {
drawer.text("stops movement");
}
},
Action::Response(r) => draw_response_action(drawer, r),
Action::Undo => panic!("Unexpected undo in log"),
Action::Redo => panic!("Unexpected redo in log"),
Action::StartTurn => panic!("Unexpected start turn in log"),
Action::ChooseCivilization(c) => {
drawer.text(&format!("Choose Civilization: {c}"));
} }
} }
pub(crate) fn of(rc: &RenderContext, text: &str) -> Self { if let Some(payment) = &body.payment {
let mut t = Self::default(); drawer.text("paying");
t.add(rc, text); draw_entry(drawer, payment, body.action.player);
t }
} }
pub(crate) fn from(rc: &RenderContext, text: &[String]) -> Self { fn draw_response_action(drawer: &mut RichTextDrawer, r: &EventResponse) {
let mut t = Self::default(); match r {
for label in text { EventResponse::SelectAdvance(_) => drawer.text("selects advance"),
t.add(rc, label); EventResponse::Payment(_) => drawer.text("selects payment"),
} EventResponse::ResourceReward(_) => drawer.text("receives"),
t EventResponse::SelectPlayer(_p) => drawer.text("selects a player"),
} EventResponse::SelectPositions(p) => {
drawer.text("selects positions");
pub(crate) fn add(&mut self, rc: &RenderContext, label: &str) { for pos in p {
multiline_label(rc.state, label, self.width, |line: &str| { drawer.location(*pos);
self.text.push(line.to_string()); }
}); }
EventResponse::SelectUnitType(u) => {
drawer.text(&format!("select unit type: {}", u.name(drawer.rc.game)));
}
EventResponse::SelectUnits(_u) => drawer.text("selects units"),
EventResponse::SelectCaptives(_) => drawer.text("selects captives"),
EventResponse::SelectHandCards(_h) => drawer.text("selects hand cards"),
EventResponse::SelectStructures(_s) => drawer.text("select structures"),
EventResponse::Bool(b) => {
if *b {
drawer.text("accepts");
} else {
drawer.text("declines");
}
}
EventResponse::ChangeGovernmentType(c) => {
drawer.text(&format!("changes government to {}", c.new_government));
}
EventResponse::ExploreResolution(_) => drawer.text("chooses rotation"),
}
}
fn draw_playing_action(drawer: &mut RichTextDrawer, p: &PlayingAction, body: &ActionLogBody) {
let a = &body.action;
let origin = body.action.origin.as_ref();
match p {
PlayingAction::Advance(_) => {
drawer.text("advances");
draw_argument(drawer, body);
}
PlayingAction::FoundCity { .. } => {
drawer.text("founds a");
draw_argument(drawer, body);
}
PlayingAction::Construct(_) => {
drawer.text("builds a");
draw_argument(drawer, body);
}
PlayingAction::Collect(c) => {
drawer.text("collects");
draw_argument(drawer, body);
drawer.at_location(c.city_position);
draw_modifier_suffix(drawer, &c.action_type, origin);
}
PlayingAction::Recruit(_) => {
drawer.text("recruits");
draw_argument(drawer, body);
}
PlayingAction::IncreaseHappiness(i) => {
drawer.text("increases happiness");
draw_modifier_suffix(drawer, &i.action_type, origin);
}
PlayingAction::InfluenceCultureAttempt(a) => {
drawer.text("attempts to influence");
draw_argument(drawer, body);
draw_modifier_suffix(drawer, &a.action_type, origin);
}
PlayingAction::Custom(c) => {
drawer.text(&format!(
"starts {}",
a.origin
.as_ref()
.expect("origin should be set for custom actions")
.name(drawer.rc.game)
));
if let Some(pos) = c.city {
drawer.at_location(pos);
}
}
PlayingAction::ActionCard(a) => {
drawer.text(&format!(
"plays action card: {}",
drawer.rc.game.cache.get_action_card(*a).name()
));
}
PlayingAction::WonderCard(w) => {
drawer.text("plays wonder card");
drawer.wonder(*w);
}
PlayingAction::EndTurn => {
drawer.text("ends their turn");
}
}
}
fn draw_modifier_suffix(
drawer: &mut RichTextDrawer,
action_type: &PlayingActionType,
origin: Option<&EventOrigin>,
) {
if let PlayingActionType::Special(SpecialAction::Modifier(_)) = action_type {
drawer.text(&format!(
"using {}",
origin
.as_ref()
.expect("origin not found")
.name(drawer.rc.game)
));
}
}
fn draw_argument(drawer: &mut RichTextDrawer, body: &ActionLogBody) {
if let Some(a) = &body.argument {
draw_entry(drawer, a, body.action.player);
} else {
panic!("subject missing argument");
} }
} }

View file

@ -8,8 +8,8 @@ use crate::hex_ui::HexFeature;
use crate::layout_ui::{ use crate::layout_ui::{
bottom_center_anchor, bottom_center_texture, bottom_right_texture, icon_pos, bottom_center_anchor, bottom_center_texture, bottom_right_texture, icon_pos,
}; };
use crate::log_ui::MultilineText;
use crate::move_ui::{MoveIntent, movable_units}; use crate::move_ui::{MoveIntent, movable_units};
use crate::multiline::MultilineText;
use crate::player_ui::get_combat; use crate::player_ui::get_combat;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::select_ui::HighlightType; use crate::select_ui::HighlightType;
@ -120,12 +120,12 @@ fn get_overlay(rc: &RenderContext) -> HashMap<Position, Terrain> {
} }
pub(crate) fn pan_and_zoom(state: &mut State) { pub(crate) fn pan_and_zoom(state: &mut State) {
let new_zoom = state.world_camera.zoom + mouse_wheel_speed() * 0.0006; let new_zoom = state.world_zoom + mouse_wheel_speed() * 0.0006;
let max = 0.005; let max = 0.005;
let min = 0.0005; let min = 0.0005;
let x = new_zoom.x.min(max).max(min); let zoom = new_zoom.min(max).max(min);
if x < max && x > min { if zoom < max && zoom > min {
state.world_camera.zoom = new_zoom; state.world_zoom = new_zoom;
} }
let pan_map = is_mouse_button_down(MouseButton::Left); let pan_map = is_mouse_button_down(MouseButton::Left);

36
client/src/multiline.rs Normal file
View file

@ -0,0 +1,36 @@
use crate::log_ui;
use crate::render_context::RenderContext;
pub(crate) struct MultilineText {
pub width: f32,
pub text: Vec<String>,
}
impl MultilineText {
pub(crate) fn default() -> Self {
MultilineText {
width: 500.,
text: vec![],
}
}
pub(crate) fn of(rc: &RenderContext, text: &str) -> Self {
let mut t = Self::default();
t.add(rc, text);
t
}
pub(crate) fn from(rc: &RenderContext, text: &[String]) -> Self {
let mut t = Self::default();
for label in text {
t.add(rc, label);
}
t
}
pub(crate) fn add(&mut self, rc: &RenderContext, label: &str) {
log_ui::multiline_label(rc.state, label, self.width, |_, line: &str| {
self.text.push(line.to_string());
});
}
}

View file

@ -4,7 +4,7 @@ use crate::event_ui::event_help;
use crate::layout_ui::{ use crate::layout_ui::{
ICON_SIZE, bottom_centered_text_with_offset, draw_scaled_icon_with_tooltip, ICON_SIZE, bottom_centered_text_with_offset, draw_scaled_icon_with_tooltip,
}; };
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::resource_ui::{new_resource_map, resource_name}; use crate::resource_ui::{new_resource_map, resource_name};
use crate::select_ui; use crate::select_ui;

View file

@ -7,8 +7,9 @@ use crate::layout_ui::{
bottom_centered_text_with_offset, bottom_right_texture, button_pressed, bottom_centered_text_with_offset, bottom_right_texture, button_pressed,
draw_scaled_icon_with_tooltip, icon_pos, top_center_anchor, top_center_texture, draw_scaled_icon_with_tooltip, icon_pos, top_center_anchor, top_center_texture,
}; };
use crate::log_ui::{MultilineText, multiline_label}; use crate::log_ui::multiline_label;
use crate::map_ui::terrain_name; use crate::map_ui::terrain_name;
use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::resource_ui::{new_resource_map, resource_name}; use crate::resource_ui::{new_resource_map, resource_name};
use crate::tooltip::show_tooltip_for_circle; use crate::tooltip::show_tooltip_for_circle;
@ -27,7 +28,7 @@ use server::player::Player;
use server::playing_actions::PlayingAction; use server::playing_actions::PlayingAction;
use server::position::Position; use server::position::Position;
use server::resource::ResourceType; use server::resource::ResourceType;
use server::status_phase::get_status_phase; use server::status_phase::{get_status_phase, status_phase_type};
use server::victory_points::victory_points_parts; use server::victory_points::victory_points_parts;
pub(crate) fn player_select(rc: &RenderContext) -> RenderResult { pub(crate) fn player_select(rc: &RenderContext) -> RenderResult {
@ -68,7 +69,7 @@ pub(crate) fn player_select(rc: &RenderContext) -> RenderResult {
} }
let tooltip = if rc.state.control_player.is_some_and(|p| p == pl.index) { let tooltip = if rc.state.control_player.is_some_and(|p| p == pl.index) {
format!("{pl} (You)") format!("{} (You)", pl.get_name())
} else { } else {
pl.get_name() pl.get_name()
}; };
@ -185,7 +186,7 @@ pub(crate) fn show_top_left(rc: &RenderContext, painter: &mut ColumnLabelPainter
_ => painter.label(&format!("Age {}", game.age)), _ => painter.label(&format!("Age {}", game.age)),
} }
if let Some(s) = get_status_phase(game) { if let Some(s) = get_status_phase(game) {
painter.label(&format!("Status Phase: {s}")); painter.label(&format!("Status Phase: {}", status_phase_type(s)));
} else { } else {
painter.label(&format!("Round {}", game.round)); painter.label(&format!("Round {}", game.round));
} }
@ -281,7 +282,7 @@ impl<'a> ColumnLabelPainter<'a> {
pub fn label(&mut self, text: &str) { pub fn label(&mut self, text: &str) {
let rc = self.rc; let rc = self.rc;
multiline_label(rc.state, text, self.max_column_width, |label| { multiline_label(rc.state, text, self.max_column_width, |_, label| {
self.used_column_width = self self.used_column_width = self
.used_column_width .used_column_width
.max(rc.state.measure_text(label).width); .max(rc.state.measure_text(label).width);

View file

@ -1,7 +1,7 @@
use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{ActiveDialog, NO_UPDATE, RenderResult, StateUpdate};
use crate::construct_ui::{ConstructionPayment, ConstructionProject}; use crate::construct_ui::{ConstructionPayment, ConstructionProject};
use crate::dialog_ui::{OkTooltip, cancel_button, ok_button}; use crate::dialog_ui::{OkTooltip, cancel_button, ok_button};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::select_ui; use crate::select_ui;
use crate::select_ui::{CountSelector, HasCountSelectableObject, HighlightType, SELECT_RADIUS}; use crate::select_ui::{CountSelector, HasCountSelectableObject, HighlightType, SELECT_RADIUS};

View file

@ -4,7 +4,7 @@ use macroquad::prelude::next_frame;
extern crate console_error_panic_hook; extern crate console_error_panic_hook;
use client::client::{Features, GameSyncRequest, GameSyncResult, init, render_and_update}; use client::client::{Features, GameSyncRequest, GameSyncResult, init, render_and_update};
use client::client_state::State; use client::client_state::{ColorProfile, State};
use macroquad::math::vec2; use macroquad::math::vec2;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use server::action::Action; use server::action::Action;
@ -74,7 +74,9 @@ struct RemoteClient {
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
struct Preferences { struct Preferences {
ui_scale: Option<String>, ui_scale: String,
world_zoom_factor: String,
color_profile: ColorProfile,
} }
#[macroquad::main("Clash")] #[macroquad::main("Clash")]
@ -120,15 +122,7 @@ impl RemoteClient {
let prefs = self.control.receive_preferences(); let prefs = self.control.receive_preferences();
if !prefs.is_empty() { if !prefs.is_empty() {
log("received preferences: {prefs}"); self.apply_preferences(&prefs);
let p: Preferences =
serde_json::from_str(&prefs).expect("preferences can't be deserialized");
if let Some(scale) = p.ui_scale {
self.state.ui_scale =
f32::from_str(&scale).expect("ui scale should be a float");
log(&format!("set ui scale to {scale}"));
}
} }
let s = self.control.canvas_size(); let s = self.control.canvas_size();
@ -150,6 +144,25 @@ impl RemoteClient {
} }
} }
fn apply_preferences(&mut self, prefs: &String) {
log(&format!("received preferences: {prefs}"));
let p: Preferences =
serde_json::from_str(prefs).expect("preferences can't be deserialized");
let scale = p.ui_scale;
self.state.ui_scale = f32::from_str(&scale).expect("ui scale should be a float");
log(&format!("set ui scale to {scale}"));
let zoom = p.world_zoom_factor;
self.state.world_zoom_factor =
f32::from_str(&zoom).expect("world zoom factor should be a float");
log(&format!("set world zoom factor to {zoom}"));
let profile = p.color_profile;
log(&format!("set color profile to {profile:?}",));
self.state.color_profile = profile;
}
fn update_state(&mut self) -> GameSyncResult { fn update_state(&mut self) -> GameSyncResult {
let s = self.control.receive_state(); let s = self.control.receive_state();
if !s.is_null() { if !s.is_null() {

View file

@ -2,10 +2,10 @@ use crate::assets::Assets;
use crate::client_state::{CameraMode, RenderResult, State}; use crate::client_state::{CameraMode, RenderResult, State};
use crate::layout_ui::{IconBackground, limit_str}; use crate::layout_ui::{IconBackground, limit_str};
use crate::payment_ui::Payment; use crate::payment_ui::Payment;
use macroquad::color::{Color, PINK, YELLOW}; use macroquad::color::{Color, PINK};
use macroquad::input::mouse_position; use macroquad::input::mouse_position;
use macroquad::math::{Vec2, bool}; use macroquad::math::{Vec2, bool};
use macroquad::prelude::{BLACK, LIME, Rect, SKYBLUE, WHITE, set_camera}; use macroquad::prelude::{BLACK, LIME, ORANGE, Rect, SKYBLUE, WHITE, set_camera};
use server::game::Game; use server::game::Game;
use server::payment::PaymentOptions; use server::payment::PaymentOptions;
use server::player::Player; use server::player::Player;
@ -159,7 +159,7 @@ impl RenderContext<'_> {
return BLACK; return BLACK;
} }
match player_index { match player_index {
0 => YELLOW, 0 => ORANGE,
1 => PINK, 1 => PINK,
2 => SKYBLUE, 2 => SKYBLUE,
3 => LIME, 3 => LIME,
@ -187,9 +187,9 @@ impl RenderContext<'_> {
} }
} }
pub(crate) fn draw_text_with_color(&self, text: &str, x: f32, y: f32, color: Color) { pub(crate) fn draw_text_ex(&self, text: &str, x: f32, y: f32, color: Color, font_size: u16) {
if self.stage.is_main() { if self.stage.is_main() {
self.state.draw_text_with_color(text, x, y, color); self.state.draw_text_ex(text, x, y, color, font_size);
} }
} }

214
client/src/richtext.rs Normal file
View file

@ -0,0 +1,214 @@
use crate::city_ui::draw_mood_state;
use crate::client_state::ColorProfile;
use crate::layout_ui::{FONT_SIZE, draw_scaled_icon};
use crate::render_context::RenderContext;
use macroquad::color::{BLACK, BLUE, Color, RED};
use macroquad::math::{Vec2, vec2};
use macroquad::prelude::{GREEN, Texture2D};
use server::city::MoodState;
use server::log::ActionLogBalance;
use server::position::Position;
use server::resource_pile::ResourcePile;
use server::structure::Structure;
use server::unit::{UnitPrintArg, UnitType, Units};
use server::wonder::Wonder;
pub struct RichTextDrawer<'a> {
pub(crate) rc: &'a RenderContext<'a>,
pub(crate) current_pos: Vec2,
space: f32,
}
impl RichTextDrawer<'_> {
pub(crate) fn new<'a>(rc: &'a RenderContext<'_>, start_pos: Vec2) -> RichTextDrawer<'a> {
RichTextDrawer {
rc,
current_pos: start_pos,
space: rc.state.measure_text(" ").width,
}
}
pub(crate) fn text(&mut self, text: &str) {
self.text_ex(text, BLACK, FONT_SIZE);
}
fn text_ex(&mut self, text: &str, color: Color, font_size: u16) {
self.rc.draw_text_ex(
text,
self.current_pos.x,
self.current_pos.y,
color,
font_size,
);
self.current_pos.x += self.rc.state.measure_text(text).width + self.space;
}
pub(crate) fn modifier(&mut self, modifier: &str, balance: Option<&ActionLogBalance>) {
let verb = match balance {
None | Some(ActionLogBalance::Gain) => "using",
Some(ActionLogBalance::Loss) => "to",
Some(ActionLogBalance::Pay) => "for",
};
self.text(&format!("{verb} {modifier}"));
}
pub(crate) fn icon(&mut self, texture: &Texture2D) {
self.icon_with_size(texture, 20.0);
}
fn icon_with_size(&mut self, texture: &Texture2D, size: f32) {
draw_scaled_icon(
&self.rc.no_icon_background(),
texture,
"",
vec2(self.current_pos.x, self.current_pos.y - size / 2.0 - 5.0),
size,
);
self.current_pos.x += size + self.space;
}
pub(crate) fn player(&mut self, player: usize) {
self.text_ex(
&self.rc.game.player_name(player),
self.rc.player_color(player),
FONT_SIZE,
);
self.current_pos.x += self.space;
}
pub(crate) fn at_location(&mut self, position: Position) {
self.text("at");
self.location(position);
}
pub(crate) fn location(&mut self, position: Position) {
self.icon_with_size(&self.rc.assets().hex, 35.0);
self.current_pos.x -= 31.0;
self.text_ex(&format!("{position}"), BLACK, 17);
}
pub(crate) fn resources(&mut self, resources: &ResourcePile, balance: &ActionLogBalance) {
for (resource, amount) in resources.clone() {
if amount > 0 {
self.icon(&self.rc.assets().resources[&resource]);
self.amount(u32::from(amount), balance);
}
}
}
pub(crate) fn amount(&mut self, amount: u32, balance: &ActionLogBalance) {
self.text_ex(
&amount.to_string(),
if *balance == ActionLogBalance::Gain {
if self.rc.state.color_profile == ColorProfile::HighContrast {
BLUE
} else {
GREEN
}
} else {
RED
},
FONT_SIZE,
);
}
pub(crate) fn unit_icon(&mut self, unit_type: UnitType) {
self.icon(self.rc.assets().unit(unit_type, self.rc.shown_player));
}
pub(crate) fn units(&mut self, units: &Units, balance: Option<&ActionLogBalance>) {
for (unit, amount) in units.clone() {
if amount > 0 {
self.unit_icon(unit);
let mut u = Units::empty();
for _ in 0..amount {
u += &unit;
}
u.print(Some(self.rc.game), &mut |a| match a {
UnitPrintArg::Text(t) => self.text(t),
UnitPrintArg::Amount(a) => {
if let Some(b) = balance {
self.amount(u32::from(*a), b);
} else {
self.text(&a.to_string());
}
}
});
}
}
}
pub(crate) fn action_icon(&mut self) {
self.icon(&self.rc.assets().end_turn);
}
pub(crate) fn structure(
&mut self,
structure: &Structure,
position: Position,
port_position: Option<Position>,
player: usize,
) {
// Draw structure icon or circle
match structure {
Structure::CityCenter => {
self.rc.draw_circle(
center(self.current_pos),
RADIUS,
self.rc.player_color(player),
);
self.current_pos.x += 35.0;
self.text("City");
}
Structure::Building(b) => {
draw_scaled_icon(
self.rc,
&self.rc.assets().buildings[b],
"",
self.building_pos(),
ICON_SIZE,
);
self.current_pos.x += 35.0;
self.text(b.name());
}
Structure::Wonder(w) => {
self.wonder(*w);
}
}
self.at_location(position);
if let Some(port_pos) = port_position {
self.text(" at the water tile");
self.at_location(port_pos);
}
}
fn building_pos(&mut self) -> Vec2 {
self.current_pos + vec2(0.0, -20.0)
}
pub(crate) fn wonder(&mut self, w: Wonder) {
draw_scaled_icon(
self.rc,
&self.rc.assets().wonders[&w],
"",
self.building_pos(),
ICON_SIZE,
);
self.current_pos.x += 35.0;
self.text(&w.name());
}
pub(crate) fn mood(&mut self, player: usize, mood: &MoodState) {
let c = center(self.current_pos);
self.rc.draw_circle(c, RADIUS, self.rc.player_color(player));
draw_mood_state(self.rc, c, mood);
self.current_pos.x += 35.0;
}
}
const RADIUS: f32 = 15.0;
const ICON_SIZE: f32 = 15.0 * 2.0;
fn center(message_pos: Vec2) -> Vec2 {
vec2(message_pos.x + 15.0, message_pos.y - RADIUS / 2.0)
}

View file

@ -1,6 +1,8 @@
use crate::client_state::{NO_UPDATE, RenderResult, StateUpdate}; use crate::client_state::{NO_UPDATE, RenderResult, StateUpdate};
use crate::dialog_ui::{OkTooltip, cancel_button, ok_button}; use crate::dialog_ui::{OkTooltip, cancel_button, ok_button};
use crate::layout_ui::{ICON_SIZE, UI_BACKGROUND, bottom_center_anchor, bottom_center_texture}; use crate::layout_ui::{
FONT_SIZE, ICON_SIZE, UI_BACKGROUND, bottom_center_anchor, bottom_center_texture,
};
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use macroquad::color::{BLACK, BLUE, Color, WHITE}; use macroquad::color::{BLACK, BLUE, Color, WHITE};
use macroquad::math::{Vec2, bool, vec2}; use macroquad::math::{Vec2, bool, vec2};
@ -48,11 +50,12 @@ pub(crate) fn count_dialog<C, O: HasCountSelectableObject>(
rc.draw_circle(point, SELECT_RADIUS, UI_BACKGROUND); rc.draw_circle(point, SELECT_RADIUS, UI_BACKGROUND);
draw(&rc.no_icon_background(), o, point); draw(&rc.no_icon_background(), o, point);
let current_pos = vec2(x + 13., -40.) + anchor + offset; let current_pos = vec2(x + 13., -40.) + anchor + offset;
rc.draw_text_with_color( rc.draw_text_ex(
&format!("{}", c.current), &format!("{}", c.current),
current_pos.x, current_pos.x,
current_pos.y, current_pos.y,
BLACK, BLACK,
FONT_SIZE,
); );
let small = &rc.small_background(); let small = &rc.small_background();
if c.current > c.min if c.current > c.min

View file

@ -1,6 +1,6 @@
use crate::client_state::{CameraMode, MousePosition, NO_UPDATE, State}; use crate::client_state::{CameraMode, MousePosition, NO_UPDATE, State};
use crate::layout_ui::rect_from; use crate::layout_ui::rect_from;
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use macroquad::color::Color; use macroquad::color::Color;
use macroquad::input::mouse_position; use macroquad::input::mouse_position;

View file

@ -9,7 +9,7 @@ use crate::hex_ui;
use crate::select_ui::HighlightType; use crate::select_ui::HighlightType;
use crate::layout_ui::{draw_scaled_icon_with_tooltip, is_in_circle}; use crate::layout_ui::{draw_scaled_icon_with_tooltip, is_in_circle};
use crate::log_ui::MultilineText; use crate::multiline::MultilineText;
use crate::render_context::RenderContext; use crate::render_context::RenderContext;
use crate::tooltip::show_tooltip_for_circle; use crate::tooltip::show_tooltip_for_circle;
use itertools::Itertools; use itertools::Itertools;

View file

@ -21,7 +21,7 @@ dir = "server"
[tasks.update-tests] [tasks.update-tests]
description = "Run server tests and update JSON files" description = "Run server tests and update JSON files"
run = 'cargo test --jobs 2 {{arg(name="test", default="")}}' run = 'cargo nextest run {{arg(name="test", default="")}}'
env = { UPDATE_EXPECTED = "true", RUSTFLAGS = '' } env = { UPDATE_EXPECTED = "true", RUSTFLAGS = '' }
dir = "server" dir = "server"
@ -67,8 +67,8 @@ description = "Test publish client (the real one is done in GitHub Actions)"
run = "./scripts/publish-client.sh test" run = "./scripts/publish-client.sh test"
[tools] [tools]
"cargo:cargo-nextest" = "0.9.98" "cargo:cargo-nextest" = "0.9.146"
"cargo:wasm-bindgen-cli" = "0.2.100" "cargo:wasm-bindgen-cli" = "0.2.105"
"cargo:wasm-pack" = "0.13.1" "cargo:wasm-pack" = "0.15.0"
rust = { version = "1.89.0", targets = "wasm32-unknown-unknown", components = "clippy,rustfmt" } rust = { version = "1.94.1", targets = "wasm32-unknown-unknown", components = "clippy,rustfmt" }

View file

@ -32,9 +32,10 @@ pathfinding = "4.14.0"
num_cpus = "1.16.0" num_cpus = "1.16.0"
enumset = { version = "1.1.6" } enumset = { version = "1.1.6" }
rustc-hash = "2.1.1" rustc-hash = "2.1.1"
pyroscope = { version = "0.5.8", optional = true } pyroscope = { version = "2.0.0", optional = true }
pyroscope_pprofrs = { version = "0.2.10", optional = true } pyroscope_pprofrs = { version = "0.2.10", optional = true }
chrono = "0.4.41" chrono = "0.4.41"
string-builder = "0.2.0"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1.45.0", features = ["full"]} tokio = { version = "1.45.0", features = ["full"]}

View file

@ -6,7 +6,8 @@ use crate::combat::{Combat, update_combat_strength};
use crate::combat_listeners::CombatStrength; use crate::combat_listeners::CombatStrength;
use crate::content::ability::{Ability, AbilityBuilder}; use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::custom_actions::{ use crate::content::custom_actions::{
CustomActionActionExecution, CustomActionExecution, CustomActionInfo, CustomActionActionExecution, PlayingActionModifier, SpecialAction, SpecialActionExecution,
SpecialActionInfo,
}; };
use crate::content::persistent_events::{ use crate::content::persistent_events::{
AdvanceRequest, EventResponse, HandCardsRequest, MultiRequest, PaymentRequest, AdvanceRequest, EventResponse, HandCardsRequest, MultiRequest, PaymentRequest,
@ -35,7 +36,6 @@ pub(crate) type AbilityInitializerWithPrioDelta = Arc<dyn Fn(&mut Game, usize, i
pub(crate) struct SelectedChoice<A, C> { pub(crate) struct SelectedChoice<A, C> {
pub player_index: usize, pub player_index: usize,
pub player_name: String,
pub origin: EventOrigin, pub origin: EventOrigin,
pub actively_selected: bool, pub actively_selected: bool,
pub choices: A, pub choices: A,
@ -46,7 +46,6 @@ impl<A, C> SelectedChoice<A, C> {
pub fn new(p: &EventPlayer, actively_selected: bool, choices: A, choice: C) -> Self { pub fn new(p: &EventPlayer, actively_selected: bool, choices: A, choice: C) -> Self {
Self { Self {
player_index: p.index, player_index: p.index,
player_name: p.name.clone(),
origin: p.origin.clone(), origin: p.origin.clone(),
actively_selected, actively_selected,
choices, choices,
@ -55,15 +54,11 @@ impl<A, C> SelectedChoice<A, C> {
} }
pub fn player(&self) -> EventPlayer { pub fn player(&self) -> EventPlayer {
EventPlayer::new( EventPlayer::new(self.player_index, self.origin.clone())
self.player_index,
self.player_name.clone(),
self.origin.clone(),
)
} }
pub fn other_player(&self, player_index: usize, game: &Game) -> EventPlayer { pub fn other_player(&self, player_index: usize) -> EventPlayer {
EventPlayer::from_player(player_index, game, self.origin.clone()) EventPlayer::new(player_index, self.origin.clone())
} }
pub fn log(&self, game: &mut Game, message: &str) { pub fn log(&self, game: &mut Game, message: &str) {
@ -181,7 +176,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
.add_initializer(move |game, player_index, prio_delta| { .add_initializer(move |game, player_index, prio_delta| {
initializer( initializer(
game, game,
&EventPlayer::from_player(player_index, game, key.clone()), &EventPlayer::new(player_index, key.clone()),
prio_delta, prio_delta,
); );
}); });
@ -194,10 +189,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
{ {
let key = self.get_key().clone(); let key = self.get_key().clone();
self.builder().add_deinitializer(move |game, player_index| { self.builder().add_deinitializer(move |game, player_index| {
deinitializer( deinitializer(game, &EventPlayer::new(player_index, key.clone()));
game,
&EventPlayer::from_player(player_index, game, key.clone()),
);
}); });
self self
} }
@ -209,10 +201,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
let key = self.get_key().clone(); let key = self.get_key().clone();
self.builder() self.builder()
.add_once_initializer(move |game, player_index| { .add_once_initializer(move |game, player_index| {
initializer( initializer(game, &EventPlayer::new(player_index, key.clone()));
game,
&EventPlayer::from_player(player_index, game, key.clone()),
);
}); });
self self
} }
@ -224,10 +213,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
let key = self.get_key().clone(); let key = self.get_key().clone();
self.builder() self.builder()
.add_once_deinitializer(move |game, player_index| { .add_once_deinitializer(move |game, player_index| {
deinitializer( deinitializer(game, &EventPlayer::new(player_index, key.clone()));
game,
&EventPlayer::from_player(player_index, game, key.clone()),
);
}); });
self self
} }
@ -972,10 +958,10 @@ pub(crate) trait AbilityInitializerSetup: Sized {
) -> Self { ) -> Self {
let name = self.name(); let name = self.name();
let desc = self.description(); let desc = self.description();
self.add_custom_action_execution( self.add_special_action_execution(
action, SpecialAction::Custom(action),
cost, cost,
CustomActionExecution::Action(CustomActionActionExecution::new( SpecialActionExecution::Action(CustomActionActionExecution::new(
ability(Ability::builder(&name, &desc)).build(), ability(Ability::builder(&name, &desc)).build(),
Arc::new(can_play), Arc::new(can_play),
None, None,
@ -993,10 +979,10 @@ pub(crate) trait AbilityInitializerSetup: Sized {
) -> Self { ) -> Self {
let name = self.name(); let name = self.name();
let desc = self.description(); let desc = self.description();
self.add_custom_action_execution( self.add_special_action_execution(
action, SpecialAction::Custom(action),
cost, cost,
CustomActionExecution::Action(CustomActionActionExecution::new( SpecialActionExecution::Action(CustomActionActionExecution::new(
ability(Ability::builder(&name, &desc)).build(), ability(Ability::builder(&name, &desc)).build(),
Arc::new(can_play), Arc::new(can_play),
Some(Arc::new(city_checker)), Some(Arc::new(city_checker)),
@ -1006,25 +992,29 @@ pub(crate) trait AbilityInitializerSetup: Sized {
fn add_action_modifier( fn add_action_modifier(
self, self,
action: CustomActionType, modifier: PlayingActionModifier,
info: impl Fn(ActionCostOncePerTurnBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static, info: impl Fn(ActionCostOncePerTurnBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static,
base_action: PlayingActionType, base_action: PlayingActionType,
) -> Self { ) -> Self {
self.add_custom_action_execution(action, info, CustomActionExecution::Modifier(base_action)) self.add_special_action_execution(
SpecialAction::Modifier(modifier),
info,
SpecialActionExecution::Modifier(base_action),
)
} }
fn add_custom_action_execution( fn add_special_action_execution(
self, self,
action: CustomActionType, action: SpecialAction,
cost: impl Fn(ActionCostOncePerTurnBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static, cost: impl Fn(ActionCostOncePerTurnBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static,
execution: CustomActionExecution, execution: SpecialActionExecution,
) -> Self { ) -> Self {
let deinitializer_action = action; let deinitializer_action = action;
let exec = execution.clone(); let exec = execution.clone();
self.add_initializer(move |game, player, _prio_delta| { self.add_initializer(move |game, player, _prio_delta| {
player.get_mut(game).custom_actions.insert( player.get_mut(game).special_actions.insert(
action, action,
CustomActionInfo::new( SpecialActionInfo::new(
action, action,
exec.clone(), exec.clone(),
player.origin.clone(), player.origin.clone(),
@ -1035,7 +1025,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
.add_deinitializer(move |game, player| { .add_deinitializer(move |game, player| {
player player
.get_mut(game) .get_mut(game)
.custom_actions .special_actions
.remove(&deinitializer_action); .remove(&deinitializer_action);
}) })
} }
@ -1077,18 +1067,11 @@ where
let deinitialize_event = event.clone(); let deinitialize_event = event.clone();
let initializer = move |game: &mut Game, p: &EventPlayer, prio_delta: i32| { let initializer = move |game: &mut Game, p: &EventPlayer, prio_delta: i32| {
let e = event(&mut p.get_mut(game).events); let e = event(&mut p.get_mut(game).events);
e.inner e.add_listener_mut(listener.clone(), priority + prio_delta, p.clone());
.as_mut()
.unwrap_or_else(|| panic!("event {} should be set: {:?}", e.name, p.origin))
.add_listener_mut(listener.clone(), priority + prio_delta, p.clone());
}; };
let deinitializer = move |game: &mut Game, p: &EventPlayer| { let deinitializer = move |game: &mut Game, p: &EventPlayer| {
let e = deinitialize_event(&mut p.get_mut(game).events); let e = deinitialize_event(&mut p.get_mut(game).events);
if let Some(inner) = &mut e.inner { e.remove_listener_mut_by_key(&p.origin);
inner.remove_listener_mut_by_key(&p.origin);
} else {
e.deleted = Some(p.origin.clone());
}
}; };
setup setup
.add_initializer(initializer) .add_initializer(initializer)

View file

@ -9,22 +9,23 @@ use crate::construct::on_construct;
use crate::content::custom_actions::on_custom_action; use crate::content::custom_actions::on_custom_action;
use crate::content::persistent_events::{EventResponse, PersistentEventType}; use crate::content::persistent_events::{EventResponse, PersistentEventType};
use crate::cultural_influence::on_cultural_influence; use crate::cultural_influence::on_cultural_influence;
use crate::events::EventPlayer; use crate::events::{EventOrigin, EventPlayer};
use crate::explore::ask_explore_resolution; use crate::explore::ask_explore_resolution;
use crate::game::GameState; use crate::game::GameState;
use crate::game::{Game, GameContext}; use crate::game::{Game, GameContext};
use crate::game_setup::execute_choose_civ; use crate::game_setup::execute_choose_civ;
use crate::incident::{on_choose_incident, on_trigger_incident}; use crate::incident::{on_choose_incident, on_trigger_incident};
use crate::log::{ use crate::log::{
ActionLogBalance, ActionLogEntry, add_action_log_item, add_log_action, current_turn_log_mut, ActionLogBalance, ActionLogEntry, ActionLogItem, add_action_log_item, add_log_action,
current_turn_log_mut,
}; };
use crate::movement::{MovementAction, execute_movement_action, on_ship_construction_conversion}; use crate::movement::{MovementAction, execute_movement_action, on_ship_construction_conversion};
use crate::objective_card::{complete_objective_card, gain_objective_card, on_objective_cards}; use crate::objective_card::{complete_objective_card, on_objective_cards};
use crate::playing_actions::{PlayingAction, PlayingActionType}; use crate::playing_actions::{PlayingAction, PlayingActionType};
use crate::position::Position; use crate::position::Position;
use crate::recruit::on_recruit; use crate::recruit::on_recruit;
use crate::resource::check_for_waste; use crate::resource::check_for_waste;
use crate::status_phase::play_status_phase; use crate::status_phase::status_phase_response;
use crate::undo::{clean_patch, redo, to_serde_value, undo}; use crate::undo::{clean_patch, redo, to_serde_value, undo};
use crate::unit::units_killed; use crate::unit::units_killed;
use crate::victory_points::add_dynamic_victory_points; use crate::victory_points::add_dynamic_victory_points;
@ -38,8 +39,7 @@ pub enum Action {
Response(EventResponse), Response(EventResponse),
Undo, Undo,
Redo, Redo,
StartTurn, // created for trade routes StartTurn, // created for trade routes and status phase
Setup, // Game setup
ChooseCivilization(String), ChooseCivilization(String),
} }
@ -131,9 +131,14 @@ pub fn execute_without_undo(
&& !matches!(action, Action::Response(_)) && !matches!(action, Action::Response(_))
{ {
// ignore missing response in replay // ignore missing response in replay
game.add_info_log_item(&format!( game.add_log_item(ActionLogItem::new(
"interrupted {} events in replay due to a missing response", player_index,
game.events.len() ActionLogEntry::message(format!(
"interrupted {} events in replay due to a missing response",
game.events.len()
)),
EventOrigin::Ability("replay".to_string()),
vec![],
)); ));
game.events.clear(); game.events.clear();
} }
@ -160,10 +165,6 @@ pub fn execute_without_undo(
pub(crate) fn after_action(game: &mut Game, player_index: usize) { pub(crate) fn after_action(game: &mut Game, player_index: usize) {
check_for_waste(game); check_for_waste(game);
if let Some(o) = game.player_mut(player_index).gained_objective.take() {
gain_objective_card(game, player_index, o);
}
if game if game
.player(player_index) .player(player_index)
.cities .cities
@ -249,7 +250,7 @@ pub(crate) fn execute_custom_phase_action(
ExploreResolution(r) => { ExploreResolution(r) => {
ask_explore_resolution(game, player, r); ask_explore_resolution(game, player, r);
} }
InfluenceCulture(r) => { InfluenceCultureBoost(r) => {
on_cultural_influence(game, player, r); on_cultural_influence(game, player, r);
} }
UnitsKilled(k) => units_killed(game, player, k), UnitsKilled(k) => units_killed(game, player, k),
@ -269,7 +270,7 @@ pub(crate) fn execute_custom_phase_action(
CombatEnd(s) => { CombatEnd(s) => {
on_end_combat(game, s); on_end_combat(game, s);
} }
StatusPhase(s) => play_status_phase(game, s), StatusPhase(s) => status_phase_response(game, s),
TurnStart => game.on_start_turn(), TurnStart => game.on_start_turn(),
PayAction(a) => { PayAction(a) => {
a.on_pay_action(game, player, game.current_event().origin_override.clone())?; a.on_pay_action(game, player, game.current_event().origin_override.clone())?;
@ -360,24 +361,21 @@ pub(crate) fn gain_action(game: &mut Game, player: &EventPlayer) {
add_action_log_item( add_action_log_item(
game, game,
player.index, player.index,
ActionLogEntry::action(ActionLogBalance::Gain), ActionLogEntry::action(ActionLogBalance::Gain, 1),
player.origin.clone(), player.origin.clone(),
vec![], vec![],
); );
player.log(game, "Gain 1 action");
} }
pub(crate) fn lose_action(game: &mut Game, player: &EventPlayer) { pub(crate) fn lose_action(game: &mut Game, player: &EventPlayer) {
subtract_action(game, player); subtract_action(game, player, ActionLogBalance::Loss);
player.log(game, "Lose 1 action");
} }
pub(crate) fn pay_action(game: &mut Game, player: &EventPlayer) { pub(crate) fn pay_action(game: &mut Game, player: &EventPlayer) {
subtract_action(game, player); subtract_action(game, player, ActionLogBalance::Pay);
player.log(game, "Pay 1 action");
} }
fn subtract_action(game: &mut Game, player: &EventPlayer) { fn subtract_action(game: &mut Game, player: &EventPlayer, balance: ActionLogBalance) {
if game.actions_left == 0 && game.context == GameContext::Replay { if game.actions_left == 0 && game.context == GameContext::Replay {
return; return;
} }
@ -386,7 +384,7 @@ fn subtract_action(game: &mut Game, player: &EventPlayer) {
add_action_log_item( add_action_log_item(
game, game,
player.index, player.index,
ActionLogEntry::action(ActionLogBalance::Loss), ActionLogEntry::action(balance, 1),
player.origin.clone(), player.origin.clone(),
vec![], vec![],
); );

View file

@ -54,15 +54,17 @@ pub struct ActionCard {
pub id: u8, pub id: u8,
pub civil_card: CivilCard, pub civil_card: CivilCard,
pub tactics_card: Option<TacticsCard>, pub tactics_card: Option<TacticsCard>,
pub public: bool,
} }
impl ActionCard { impl ActionCard {
#[must_use] #[must_use]
fn new(id: u8, civil_card: CivilCard, tactics_card: Option<TacticsCard>) -> Self { fn new(id: u8, civil_card: CivilCard, tactics_card: Option<TacticsCard>, public: bool) -> Self {
Self { Self {
id, id,
civil_card, civil_card,
tactics_card, tactics_card,
public,
} }
} }
@ -88,6 +90,7 @@ impl ActionCard {
action_cost: cost(ActionCostBuilder::new(None)).cost, action_cost: cost(ActionCostBuilder::new(None)).cost,
target: CivilCardTarget::ActivePlayer, target: CivilCardTarget::ActivePlayer,
target_choices: None, target_choices: None,
public: false,
} }
} }
@ -108,6 +111,7 @@ pub struct ActionCardBuilder {
action_cost: ActionCost, action_cost: ActionCost,
can_play: CanPlayCard, can_play: CanPlayCard,
combat_requirement: Option<CombatRequirement>, combat_requirement: Option<CombatRequirement>,
public: bool,
tactics_card: Option<TacticsCard>, tactics_card: Option<TacticsCard>,
builder: AbilityInitializerBuilder, builder: AbilityInitializerBuilder,
target: CivilCardTarget, target: CivilCardTarget,
@ -148,7 +152,7 @@ impl ActionCardBuilder {
let target = self.target; let target = self.target;
self.target_choices = Some(Arc::new(move |game, player| { self.target_choices = Some(Arc::new(move |game, player| {
let mut game = game.clone(); let mut game = game.clone();
let p = EventPlayer::from_player(player, &game, EventOrigin::CivilCard(id)); let p = EventPlayer::new(player, EventOrigin::CivilCard(id));
let mut info = ActionCardInfo::new( let mut info = ActionCardInfo::new(
id, id,
None, None,
@ -173,6 +177,12 @@ impl ActionCardBuilder {
) )
} }
#[must_use]
pub fn public(mut self, public: bool) -> Self {
self.public = public;
self
}
#[must_use] #[must_use]
pub fn tactics_card(mut self, tactics_card: TacticsCardFactory) -> Self { pub fn tactics_card(mut self, tactics_card: TacticsCardFactory) -> Self {
self.tactics_card = Some(tactics_card(self.id)); self.tactics_card = Some(tactics_card(self.id));
@ -206,6 +216,7 @@ impl ActionCardBuilder {
target_choices: self.target_choices, target_choices: self.target_choices,
}, },
self.tactics_card, self.tactics_card,
self.public,
) )
} }
} }
@ -275,7 +286,7 @@ pub(crate) fn on_play_action_card(game: &mut Game, player_index: usize, i: Actio
pub(crate) fn gain_action_card_from_pile(game: &mut Game, player: &EventPlayer) { pub(crate) fn gain_action_card_from_pile(game: &mut Game, player: &EventPlayer) {
let controller = crate::content::civilizations::celts::delegated_player(game, player.index); let controller = crate::content::civilizations::celts::delegated_player(game, player.index);
if controller != player.index { if controller != player.index {
let p = EventPlayer::from_player(controller, game, player.origin.clone()); let p = EventPlayer::new(controller, player.origin.clone());
return gain_action_card_from_pile(game, &p); return gain_action_card_from_pile(game, &p);
} }
if player if player
@ -290,14 +301,15 @@ pub(crate) fn gain_action_card_from_pile(game: &mut Game, player: &EventPlayer)
} }
pub(crate) fn do_gain_action_card_from_pile(game: &mut Game, player: &EventPlayer) { pub(crate) fn do_gain_action_card_from_pile(game: &mut Game, player: &EventPlayer) {
if let Some(c) = draw_action_card_from_pile(game) { if let Some(c) = draw_action_card_from_pile(game, player) {
gain_action_card(game, player, c, HandCardLocation::DrawPile); gain_action_card(game, player, c, HandCardLocation::DrawPile);
} }
} }
fn draw_action_card_from_pile(game: &mut Game) -> Option<u8> { fn draw_action_card_from_pile(game: &mut Game, player: &EventPlayer) -> Option<u8> {
draw_card_from_pile( draw_card_from_pile(
game, game,
player,
"Action Card", "Action Card",
|g| &mut g.action_cards_left, |g| &mut g.action_cards_left,
|g| g.cache.get_action_cards().iter().map(|c| c.id).collect(), |g| g.cache.get_action_cards().iter().map(|c| c.id).collect(),
@ -313,7 +325,7 @@ pub(crate) fn gain_action_card(
) { ) {
let controller = crate::content::civilizations::celts::delegated_player(game, player.index); let controller = crate::content::civilizations::celts::delegated_player(game, player.index);
if controller != player.index { if controller != player.index {
let p = EventPlayer::from_player(controller, game, player.origin.clone()); let p = EventPlayer::new(controller, player.origin.clone());
return gain_action_card(game, &p, action_card, from); return gain_action_card(game, &p, action_card, from);
} }
player.get_mut(game).action_cards.push(action_card); player.get_mut(game).action_cards.push(action_card);
@ -394,7 +406,7 @@ pub fn combat_requirement_met(
action_card_id: u8, action_card_id: u8,
requirement: &CombatRequirement, requirement: &CombatRequirement,
) -> Option<usize> { ) -> Option<usize> {
let sister_card = if action_card_id % 2 == 0 { let sister_card = if action_card_id.is_multiple_of(2) {
action_card_id - 1 action_card_id - 1
} else { } else {
action_card_id + 1 action_card_id + 1

View file

@ -1,5 +1,5 @@
use crate::advance::base_advance_cost; use crate::advance::base_advance_cost;
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::SpecialAction;
use crate::events::{EventOrigin, check_event_origin}; use crate::events::{EventOrigin, check_event_origin};
use crate::game::{Game, GameContext}; use crate::game::{Game, GameContext};
use crate::payment::PaymentOptions; use crate::payment::PaymentOptions;
@ -81,12 +81,12 @@ impl ActionCost {
} }
pub(crate) struct ActionCostOncePerTurnBuilder { pub(crate) struct ActionCostOncePerTurnBuilder {
action: CustomActionType, action: SpecialAction,
} }
impl ActionCostOncePerTurnBuilder { impl ActionCostOncePerTurnBuilder {
#[must_use] #[must_use]
pub fn new(action: CustomActionType) -> Self { pub fn new(action: SpecialAction) -> Self {
Self { action } Self { action }
} }
@ -105,19 +105,19 @@ impl ActionCostOncePerTurnBuilder {
#[must_use] #[must_use]
pub fn once_per_turn_mutually_exclusive( pub fn once_per_turn_mutually_exclusive(
self, self,
mutually_exclusive: CustomActionType, mutually_exclusive: SpecialAction,
) -> ActionCostBuilder { ) -> ActionCostBuilder {
ActionCostBuilder::new(Some(mutually_exclusive)) ActionCostBuilder::new(Some(mutually_exclusive))
} }
} }
pub(crate) struct ActionCostBuilder { pub(crate) struct ActionCostBuilder {
once_per_turn: Option<CustomActionType>, once_per_turn: Option<SpecialAction>,
} }
impl ActionCostBuilder { impl ActionCostBuilder {
#[must_use] #[must_use]
pub(crate) fn new(once_per_turn: Option<CustomActionType>) -> Self { pub(crate) fn new(once_per_turn: Option<SpecialAction>) -> Self {
Self { once_per_turn } Self { once_per_turn }
} }
@ -133,13 +133,13 @@ impl ActionCostBuilder {
} }
pub(crate) struct ActionResourceCostBuilder { pub(crate) struct ActionResourceCostBuilder {
once_per_turn: Option<CustomActionType>, once_per_turn: Option<SpecialAction>,
free: bool, free: bool,
} }
impl ActionResourceCostBuilder { impl ActionResourceCostBuilder {
#[must_use] #[must_use]
fn new(once_per_turn: Option<CustomActionType>, free: bool) -> ActionResourceCostBuilder { fn new(once_per_turn: Option<SpecialAction>, free: bool) -> ActionResourceCostBuilder {
ActionResourceCostBuilder { ActionResourceCostBuilder {
once_per_turn, once_per_turn,
free, free,
@ -187,14 +187,14 @@ impl ActionResourceCostBuilder {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ActionCostOncePerTurn { pub struct ActionCostOncePerTurn {
pub cost: ActionCost, pub cost: ActionCost,
pub once_per_turn: Option<CustomActionType>, pub once_per_turn: Option<SpecialAction>,
} }
impl ActionCostOncePerTurn { impl ActionCostOncePerTurn {
#[must_use] #[must_use]
pub(crate) fn new( pub(crate) fn new(
free: bool, free: bool,
once_per_turn: Option<CustomActionType>, once_per_turn: Option<SpecialAction>,
cost: ActionResourceCost, cost: ActionResourceCost,
) -> ActionCostOncePerTurn { ) -> ActionCostOncePerTurn {
ActionCostOncePerTurn { ActionCostOncePerTurn {

View file

@ -6,7 +6,7 @@ use crate::content::persistent_events::PersistentEventType;
use crate::events::{EventOrigin, EventPlayer}; use crate::events::{EventOrigin, EventPlayer};
use crate::game::Game; use crate::game::Game;
use crate::incident::trigger_incident; use crate::incident::trigger_incident;
use crate::log::{ActionLogBalance, ActionLogEntry, add_action_log_item}; use crate::log::{ActionLogBalance, ActionLogEntry, ActionLogIncidentToken, add_action_log_item};
use crate::payment::PaymentOptions; use crate::payment::PaymentOptions;
use crate::player::Player; use crate::player::Player;
use crate::player_events::OnAdvanceInfo; use crate::player_events::OnAdvanceInfo;
@ -291,27 +291,18 @@ pub(crate) fn do_advance(
true, true,
); );
player.log(
game,
&format!(
"Gain {} {}",
advance.name(game),
if take_incident_token {
(if t > 1 {
format!("and take an event token ({} left)", t - 1)
} else {
"and take an event token (triggering an incident)".to_string()
})
.to_string()
} else {
"without taking an event token".to_string()
}
),
);
add_action_log_item( add_action_log_item(
game, game,
player_index, player_index,
ActionLogEntry::advance(advance, ActionLogBalance::Gain, take_incident_token), ActionLogEntry::advance(
advance,
ActionLogBalance::Gain,
if take_incident_token {
ActionLogIncidentToken::Take(t - 1)
} else {
ActionLogIncidentToken::NoChange
},
),
player.origin.clone(), player.origin.clone(),
vec![], vec![],
); );
@ -398,7 +389,7 @@ pub(crate) fn execute_advance_action(
gain_advance_without_payment( gain_advance_without_payment(
game, game,
advance, advance,
&EventPlayer::from_player(player_index, game, advance_event_origin()), &EventPlayer::new(player_index, advance_event_origin()),
a.payment.clone(), a.payment.clone(),
true, true,
); );
@ -439,7 +430,7 @@ pub(crate) fn on_advance(game: &mut Game, player_index: usize, info: OnAdvanceIn
player.incident_tokens -= 1; player.incident_tokens -= 1;
if player.incident_tokens == 0 { if player.incident_tokens == 0 {
player.incident_tokens = 3; player.incident_tokens = 3;
trigger_incident(game, player_index); trigger_incident(game, player_index, EventOrigin::Advance(info.advance));
} }
} }
} }
@ -470,20 +461,28 @@ pub(crate) fn remove_advance(game: &mut Game, advance: Advance, player: &EventPl
advance_bonus.resources(), advance_bonus.resources(),
EventOrigin::Advance(advance), EventOrigin::Advance(advance),
vec![], vec![],
ActionLogBalance::Loss,
); );
} }
game.player_mut(player_index).advances.remove(advance); game.player_mut(player_index).advances.remove(advance);
add_action_log_item( add_action_log_item(
game, game,
player_index, player_index,
ActionLogEntry::advance(advance, ActionLogBalance::Loss, false), ActionLogEntry::advance(
advance,
ActionLogBalance::Loss,
ActionLogIncidentToken::NoChange,
),
player.origin.clone(), player.origin.clone(),
vec![], vec![],
); );
} }
fn unlock_special_advance(game: &mut Game, special_advance: SpecialAdvance, player: &EventPlayer) { fn unlock_special_advance(game: &mut Game, special_advance: SpecialAdvance, player: &EventPlayer) {
player.log(game, &format!("Unlock {}", special_advance.info(game).name)); player.log(
game,
&format!("unlocks {}", special_advance.info(game).name),
);
special_advance special_advance
.info(game) .info(game)
.listeners .listeners

View file

@ -5,7 +5,7 @@ use crate::card::validate_card_selection;
use crate::city::{City, MoodState}; use crate::city::{City, MoodState};
use crate::collect::{Collect, available_collect_actions, possible_resource_collections}; use crate::collect::{Collect, available_collect_actions, possible_resource_collections};
use crate::construct::{Construct, available_buildings, new_building_positions}; use crate::construct::{Construct, available_buildings, new_building_positions};
use crate::content::custom_actions::{CustomAction, CustomActionType}; use crate::content::custom_actions::{CustomAction, CustomActionType, SpecialAction};
use crate::content::persistent_events::{ use crate::content::persistent_events::{
EventResponse, HandCardsRequest, MultiRequest, PersistentEventRequest, PersistentEventState, EventResponse, HandCardsRequest, MultiRequest, PersistentEventRequest, PersistentEventState,
PositionRequest, SelectedStructure, is_selected_structures_valid, PositionRequest, SelectedStructure, is_selected_structures_valid,
@ -195,7 +195,13 @@ fn base_actions(ai: &mut AiActions, game: &Game) -> Vec<(ActionType, Vec<Action>
} }
for info in game.available_custom_actions(p.index) { for info in game.available_custom_actions(p.index) {
if info.action == CustomActionType::ImperialArmy { let t = info.custom_action_type();
// Calendar only reveals information. Until the AI has a policy for using
// that knowledge, repeatedly peeking for free would block EndTurn.
if t == CustomActionType::Calendar {
continue;
}
if t == CustomActionType::ImperialArmy {
// buggy // buggy
continue; continue;
} }
@ -212,12 +218,11 @@ fn base_actions(ai: &mut AiActions, game: &Game) -> Vec<(ActionType, Vec<Action>
vec![None] vec![None]
}; };
let a = info.action;
for c in cities { for c in cities {
actions.push(( actions.push((
ActionType::Playing(PlayingActionType::Custom(a)), ActionType::Playing(PlayingActionType::Special(info.action)),
vec![Action::Playing(PlayingAction::Custom(CustomAction::new( vec![Action::Playing(PlayingAction::Custom(CustomAction::new(
a, c, t, c,
)))], )))],
)); ));
} }
@ -497,11 +502,11 @@ fn calculate_increase_happiness(
fn prefer_custom_action(actions: &[PlayingActionType]) -> PlayingActionType { fn prefer_custom_action(actions: &[PlayingActionType]) -> PlayingActionType {
actions actions
.iter() .iter()
.find(|a| matches!(a, PlayingActionType::Custom(_))) .find(|a| matches!(a, PlayingActionType::Special(SpecialAction::Modifier(_))))
.or_else(|| { .or_else(|| {
actions actions
.iter() .iter()
.find(|a| !matches!(a, PlayingActionType::Custom(_))) .find(|a| !matches!(a, PlayingActionType::Special(SpecialAction::Modifier(_))))
}) })
.cloned() .cloned()
.expect("expected at least one action type, either custom or base") .expect("expected at least one action type, either custom or base")

View file

@ -8,7 +8,7 @@ use std::mem;
pub(crate) fn possible_collections(info: &CollectInfo) -> Vec<Vec<PositionCollection>> { pub(crate) fn possible_collections(info: &CollectInfo) -> Vec<Vec<PositionCollection>> {
let choices = info.choices.clone(); let choices = info.choices.clone();
let mut list = choices.iter().collect_vec(); let mut list = choices.iter().filter(|(_, v)| !v.is_empty()).collect_vec();
let tiles = list.len(); // production focus is not considered let tiles = list.len(); // production focus is not considered
let mut max_tiles = tiles; let mut max_tiles = tiles;
@ -69,7 +69,12 @@ fn add_combination(
} }
} }
} else { } else {
let n = pile.iter().next().expect("pile empty"); let n = pile.iter().next().unwrap_or_else(|| {
panic!(
"Pile should have at least one element for position {pos:?}, \
got choices {choices:?} and combo {combo:?}"
)
});
for r in &mut *result { for r in &mut *result {
r.push(PositionCollection::new(*pos, n.clone())); r.push(PositionCollection::new(*pos, n.clone()));
} }

View file

@ -21,8 +21,8 @@ pub fn can_create(game: &Game) -> bool {
// These discard arrays are lifetime archives, not current-cycle piles. // These discard arrays are lifetime archives, not current-cycle piles.
// Once a pile has refilled, their exclusions are no longer sufficient. // Once a pile has refilled, their exclusions are no longer sufficient.
&& !game.log.iter().flat_map(|a| &a.rounds).flat_map(|r| &r.turns) && !game.log.iter().flat_map(|a| &a.rounds).flat_map(|r| &r.turns)
.flat_map(|t| &t.actions).flat_map(|a| &a.log).any(|text| { .flat_map(|t| &t.actions).flat_map(|a| &a.items).any(|item| {
text == "Reshuffling Action Card pile" || text == "Reshuffling Events pile" matches!(&item.entry, crate::log::ActionLogEntry::Text(text) if text == "Reshuffling Action Card pile" || text == "Reshuffling Events pile")
}) })
} }
@ -42,7 +42,7 @@ fn public_continuation(event: &crate::content::persistent_events::PersistentEven
| E::ShipConstructionConversion(_) | E::ShipConstructionConversion(_)
| E::StopBarbarianMovement(_) | E::StopBarbarianMovement(_)
| E::UnitsKilled(_) | E::UnitsKilled(_)
| E::InfluenceCulture(_) | E::InfluenceCultureBoost(_)
| E::StatusPhase(_) => true, | E::StatusPhase(_) => true,
E::PayAction(payment) => !matches!( E::PayAction(payment) => !matches!(
payment.action, payment.action,
@ -330,7 +330,7 @@ fn retain_rule_facts(game: &mut Game) {
source_turn.actions.len() source_turn.actions.len()
}; };
for a in source_turn.actions.iter().take(limit) { for a in source_turn.actions.iter().take(limit) {
let mut fact = ActionLogAction::new(Action::StartTurn); let mut fact = ActionLogAction::new(Action::StartTurn, a.player, None, 0);
fact.combat_stats = a.combat_stats.clone().map(|mut s| { fact.combat_stats = a.combat_stats.clone().map(|mut s| {
s.claimed_action_cards.clear(); s.claimed_action_cards.clear();
s.selected_card = None; s.selected_card = None;
@ -426,7 +426,12 @@ mod tests {
vec![HandCard::ActionCard(37)], vec![HandCard::ActionCard(37)],
), ),
); );
a.log.push("source secret".into()); a.items.push(ActionLogItem::new(
a.player,
crate::log::ActionLogEntry::Text("source secret".into()),
EventOrigin::Ability("test".into()),
vec![],
));
a.undo = serde_json::from_value(serde_json::json!([{"op":"replace","path":"/seed","value":"undo secret"}])).unwrap(); a.undo = serde_json::from_value(serde_json::json!([{"op":"replace","path":"/seed","value":"undo secret"}])).unwrap();
} }
} }
@ -459,9 +464,9 @@ mod tests {
game = game_api::execute(game, Action::Playing(PlayingAction::EndTurn), p); game = game_api::execute(game, Action::Playing(PlayingAction::EndTurn), p);
} }
let p = game.active_player(); let p = game.active_player();
crate::log::add_start_turn_action_if_needed(&mut game); let active = game.active_player();
let player = crate::log::add_start_turn_action_if_needed(&mut game, active);
crate::events::EventPlayer::from_player(p, &game, EventOrigin::Ability("test".into())); let player = crate::events::EventPlayer::new(p, EventOrigin::Ability("test".into()));
let before = game.players[p].action_cards.len(); let before = game.players[p].action_cards.len();
crate::action_card::gain_action_card_from_pile(&mut game, &player); crate::action_card::gain_action_card_from_pile(&mut game, &player);
assert_eq!(game.players[p].action_cards.len(), before + 1); assert_eq!(game.players[p].action_cards.len(), before + 1);
@ -522,7 +527,8 @@ mod tests {
fn publicly_revealed_opponent_card_stays_in_their_hand() { fn publicly_revealed_opponent_card_stays_in_their_hand() {
let mut source = game_api::init(2, "source".into(), GameOptions::default()); let mut source = game_api::init(2, "source".into(), GameOptions::default());
let id = source.players[1].action_cards[0]; let id = source.players[1].action_cards[0];
crate::log::add_start_turn_action_if_needed(&mut source); let active = source.active_player();
crate::log::add_start_turn_action_if_needed(&mut source, active);
crate::log::add_action_log_item( crate::log::add_action_log_item(
&mut source, &mut source,
1, 1,
@ -575,12 +581,12 @@ mod tests {
#[test] #[test]
fn fails_closed_after_action_pile_refill() { fn fails_closed_after_action_pile_refill() {
let mut game = game_api::init(2, "source".into(), GameOptions::default()); let mut game = game_api::init(2, "source".into(), GameOptions::default());
crate::log::add_start_turn_action_if_needed(&mut game); let active = game.active_player();
crate::log::add_start_turn_action_if_needed(&mut game, active);
game.action_cards_left.clear(); game.action_cards_left.clear();
game.action_cards_discarded = game.cache.get_action_cards().iter().map(|c| c.id).collect(); game.action_cards_discarded = game.cache.get_action_cards().iter().map(|c| c.id).collect();
let p = game.active_player(); let p = game.active_player();
let player = let player = crate::events::EventPlayer::new(p, EventOrigin::Ability("test".into()));
crate::events::EventPlayer::from_player(p, &game, EventOrigin::Ability("test".into()));
crate::action_card::gain_action_card_from_pile(&mut game, &player); crate::action_card::gain_action_card_from_pile(&mut game, &player);
assert!(!game.action_cards_left.is_empty()); assert!(!game.action_cards_left.is_empty());
assert!(!can_create(&game)); assert!(!can_create(&game));

View file

@ -599,7 +599,7 @@ fn cities_in_land_range(
#[must_use] #[must_use]
pub(crate) fn get_barbarians_event_player(game: &Game, origin: &EventOrigin) -> EventPlayer { pub(crate) fn get_barbarians_event_player(game: &Game, origin: &EventOrigin) -> EventPlayer {
let player = get_barbarians_player(game); let player = get_barbarians_player(game);
EventPlayer::new(player.index, player.get_name(), origin.clone()) EventPlayer::new(player.index, origin.clone())
} }
/// ///

View file

@ -137,8 +137,10 @@ pub fn execute(mut game: Game, action: Action, player: usize) -> Result<Game, St
let ended_turn = matches!(action, Action::Playing(PlayingAction::EndTurn)); let ended_turn = matches!(action, Action::Playing(PlayingAction::EndTurn));
let label = if let Action::Playing(PlayingAction::Custom(custom)) = &action { let label = if let Action::Playing(PlayingAction::Custom(custom)) = &action {
game.player(player) game.player(player)
.custom_actions .special_actions
.get(&custom.action) .get(&crate::content::custom_actions::SpecialAction::Custom(
custom.action,
))
.map(|info| info.event_origin.name(&game)) .map(|info| info.event_origin.name(&game))
.unwrap_or_else(|| title(&action)) .unwrap_or_else(|| title(&action))
} else if matches!(action, Action::Response(_)) { } else if matches!(action, Action::Response(_)) {
@ -232,7 +234,7 @@ fn effects(game: &Game, from: usize) -> Vec<BoardEffect> {
return None; return None;
}; };
let kind = match card.card_type() { let kind = match card.card_type() {
HandCardType::Action => "action", HandCardType::Action | HandCardType::Public => "action",
HandCardType::Objective => "objective", HandCardType::Objective => "objective",
HandCardType::Wonder => "wonder", HandCardType::Wonder => "wonder",
}; };

View file

@ -4,7 +4,7 @@ use crate::city_pieces::Building;
use crate::civilization::Civilization; use crate::civilization::Civilization;
use crate::content::ability::Ability; use crate::content::ability::Ability;
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo};
use crate::content::custom_actions::CustomActionExecution; use crate::content::custom_actions::SpecialActionExecution;
use crate::content::{ use crate::content::{
ability, action_cards, advances, civilizations, incidents, objective_cards, objectives, wonders, ability, action_cards, advances, civilizations, incidents, objective_cards, objectives, wonders,
}; };
@ -13,10 +13,9 @@ use crate::incident::Incident;
use crate::leader::{Leader, LeaderInfo}; use crate::leader::{Leader, LeaderInfo};
use crate::objective_card::{Objective, ObjectiveCard}; use crate::objective_card::{Objective, ObjectiveCard};
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo}; use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo};
use crate::status_phase::StatusPhaseState::{ChangeGovernmentType, DetermineFirstPlayer};
use crate::status_phase::{ use crate::status_phase::{
StatusPhaseState, complete_objectives, determine_first_player, draw_cards, free_advance, StatusPhaseStateType, complete_objectives, determine_first_player, draw_cards, free_advance,
get_status_phase, may_change_government, use_raze_city, get_status_phase, may_change_government, status_phase_type, use_raze_city,
}; };
use crate::tactics_card::TacticsCard; use crate::tactics_card::TacticsCard;
use crate::wonder::{Wonder, WonderInfo}; use crate::wonder::{Wonder, WonderInfo};
@ -27,7 +26,7 @@ use std::collections::HashMap;
pub struct Cache { pub struct Cache {
all_abilities: Vec<Ability>, all_abilities: Vec<Ability>,
abilities_by_name: HashMap<String, Ability>, abilities_by_name: HashMap<String, Ability>,
status_phase_handlers: HashMap<StatusPhaseState, Ability>, status_phase_handlers: HashMap<StatusPhaseStateType, Ability>,
all_advance_groups: Vec<AdvanceGroupInfo>, all_advance_groups: Vec<AdvanceGroupInfo>,
advance_groups_by_name: HashMap<AdvanceGroup, AdvanceGroupInfo>, advance_groups_by_name: HashMap<AdvanceGroup, AdvanceGroupInfo>,
@ -129,7 +128,7 @@ impl Cache {
all_civilizations: civilizations::get_all_uncached() all_civilizations: civilizations::get_all_uncached()
.into_iter() .into_iter()
.filter(super::civilization::Civilization::can_choose) .filter(Civilization::can_choose)
.sorted_by_key(|c| c.name.clone()) .sorted_by_key(|c| c.name.clone())
.collect_vec(), .collect_vec(),
civilizations_by_name: civilizations::get_all_uncached() civilizations_by_name: civilizations::get_all_uncached()
@ -220,8 +219,8 @@ impl Cache {
.get(name) .get(name)
.map_or_else( .map_or_else(
|| { || {
for c in game.player(game.active_player()).custom_actions.values() { for c in game.player(game.active_player()).special_actions.values() {
if let CustomActionExecution::Action(e) = &c.execution if let SpecialActionExecution::Action(e) = &c.execution
&& e.ability.name == name && e.ability.name == name
{ {
return Some(t(&e.ability)); return Some(t(&e.ability));
@ -229,7 +228,7 @@ impl Cache {
} }
if let Some(p) = get_status_phase(game) { if let Some(p) = get_status_phase(game) {
return Some(t(self.status_phase_handler(p))); return Some(t(self.status_phase_handler(&status_phase_type(p))));
} }
None None
}, },
@ -244,12 +243,8 @@ impl Cache {
} }
#[must_use] #[must_use]
pub fn status_phase_handler(&self, p: &StatusPhaseState) -> &Ability { pub fn status_phase_handler(&self, p: &StatusPhaseStateType) -> &Ability {
match p { &self.status_phase_handlers[p]
DetermineFirstPlayer(_) => &self.status_phase_handlers[&DetermineFirstPlayer(0)],
ChangeGovernmentType(_) => &self.status_phase_handlers[&ChangeGovernmentType(false)],
_ => &self.status_phase_handlers[p],
}
} }
#[must_use] #[must_use]
@ -371,15 +366,15 @@ impl Cache {
} }
} }
fn status_phase_handlers() -> HashMap<StatusPhaseState, Ability> { fn status_phase_handlers() -> HashMap<StatusPhaseStateType, Ability> {
use StatusPhaseState::*; use StatusPhaseStateType::*;
HashMap::from([ HashMap::from([
(CompleteObjectives, complete_objectives()), (CompleteObjectives, complete_objectives()),
(FreeAdvance, free_advance()), (FreeAdvance, free_advance()),
(DrawCards, draw_cards()), (DrawCards, draw_cards()),
(RazeSize1City, use_raze_city()), (RazeSize1City, use_raze_city()),
(ChangeGovernmentType(false), may_change_government()), (ChangeGovernmentType, may_change_government()),
(DetermineFirstPlayer(0), determine_first_player()), (DetermineFirstPlayer, determine_first_player()),
]) ])
} }

View file

@ -1,7 +1,7 @@
use crate::content::action_cards::spy::validate_spy_cards; use crate::content::action_cards::spy::validate_spy_cards;
use crate::content::action_cards::synergies::validate_new_plans; use crate::content::action_cards::synergies::validate_new_plans;
use crate::content::civilizations::rome::validate_princeps_cards; use crate::content::civilizations::rome::validate_princeps_cards;
use crate::events::EventOrigin; use crate::events::{EventOrigin, EventPlayer};
use crate::game::Game; use crate::game::Game;
use crate::log::{ActionLogEntry, add_action_log_item}; use crate::log::{ActionLogEntry, add_action_log_item};
use crate::player::Player; use crate::player::Player;
@ -14,6 +14,7 @@ use std::fmt::Display;
#[derive(Clone, Copy, Eq, PartialEq)] #[derive(Clone, Copy, Eq, PartialEq)]
pub enum HandCardType { pub enum HandCardType {
Action, Action,
Public, // is modeled as an action card with public=true
Objective, Objective,
Wonder, Wonder,
} }
@ -21,10 +22,19 @@ pub enum HandCardType {
impl HandCardType { impl HandCardType {
#[must_use] #[must_use]
pub fn get_all() -> Vec<HandCardType> { pub fn get_all() -> Vec<HandCardType> {
vec![
HandCardType::Action, // Public is not a real type of card
HandCardType::Objective,
HandCardType::Wonder,
]
}
#[must_use]
pub fn get_all_and_public() -> Vec<HandCardType> {
vec![ vec![
HandCardType::Action, HandCardType::Action,
HandCardType::Objective, HandCardType::Objective,
HandCardType::Wonder, HandCardType::Wonder,
HandCardType::Public,
] ]
} }
} }
@ -35,6 +45,7 @@ impl Display for HandCardType {
HandCardType::Action => write!(f, "an action card"), HandCardType::Action => write!(f, "an action card"),
HandCardType::Objective => write!(f, "an objective card"), HandCardType::Objective => write!(f, "an objective card"),
HandCardType::Wonder => write!(f, "a wonder card"), HandCardType::Wonder => write!(f, "a wonder card"),
HandCardType::Public => write!(f, "a public action card"),
} }
} }
} }
@ -59,9 +70,27 @@ impl HandCard {
#[must_use] #[must_use]
pub fn name(&self, game: &Game) -> String { pub fn name(&self, game: &Game) -> String {
match self { match self {
HandCard::ActionCard(id) => game.cache.get_action_card(*id).name(), HandCard::ActionCard(id) => {
HandCard::ObjectiveCard(id) => game.cache.get_objective_card(*id).name(), if *id == 0 {
HandCard::Wonder(wonder) => wonder.name(), "an action card".to_string()
} else {
game.cache.get_action_card(*id).name()
}
}
HandCard::ObjectiveCard(id) => {
if *id == 0 {
"an objective card".to_string()
} else {
game.cache.get_objective_card(*id).name()
}
}
HandCard::Wonder(wonder) => {
if wonder == &Wonder::Hidden {
"a wonder card".to_string()
} else {
wonder.name()
}
}
} }
} }
} }
@ -108,6 +137,7 @@ impl HandCardLocation {
pub(crate) fn draw_card_from_pile<T>( pub(crate) fn draw_card_from_pile<T>(
game: &mut Game, game: &mut Game,
player: &EventPlayer,
name: &str, name: &str,
get_pile: impl Fn(&mut Game) -> &mut Vec<T>, get_pile: impl Fn(&mut Game) -> &mut Vec<T>,
reshuffle_pile: impl Fn(&Game) -> Vec<T>, reshuffle_pile: impl Fn(&Game) -> Vec<T>,
@ -124,13 +154,13 @@ where
} }
if !new_pile.is_empty() { if !new_pile.is_empty() {
game.add_info_log_item(&format!("Reshuffling {name} pile")); player.log(game, &format!("Reshuffling {name} pile"));
*get_pile(game) = new_pile.shuffled(&mut game.rng); *get_pile(game) = new_pile.shuffled(&mut game.rng);
} }
} }
if get_pile(game).is_empty() { if get_pile(game).is_empty() {
game.add_info_log_item(&format!("No {name} left to draw")); player.log(game, &format!("No {name} left to draw"));
return None; return None;
} }
@ -159,13 +189,20 @@ pub(crate) fn discard_card(
} }
#[must_use] #[must_use]
pub fn hand_cards(player: &Player, types: &[HandCardType]) -> Vec<HandCard> { pub fn hand_cards(player: &Player, types: &[HandCardType], game: &Game) -> Vec<HandCard> {
types types
.iter() .iter()
.flat_map(|t| match t { .flat_map(|t| match t {
HandCardType::Action => player HandCardType::Action => player
.action_cards .action_cards
.iter() .iter()
.filter(|id| **id == 0 || !game.cache.get_action_card(**id).public)
.map(|&id| HandCard::ActionCard(id))
.collect_vec(),
HandCardType::Public => player
.action_cards
.iter()
.filter(|id| **id != 0 && game.cache.get_action_card(**id).public)
.map(|&id| HandCard::ActionCard(id)) .map(|&id| HandCard::ActionCard(id))
.collect_vec(), .collect_vec(),
HandCardType::Objective => player HandCardType::Objective => player
@ -243,58 +280,7 @@ pub(crate) fn log_card_transfer(
to: HandCardLocation, to: HandCardLocation,
origin: &EventOrigin, origin: &EventOrigin,
) { ) {
let (player_index, message): (usize, &str) = if let HandCardLocation::Hand(p) = to { let (player_index, _message) = hand_card_message(game, card, &from, &to);
let name = card_name(card, &from, game);
(
p,
match from {
HandCardLocation::DrawPile => &format!("Draw {name}"),
HandCardLocation::Hand(from) | HandCardLocation::RevealedHand(from) => {
&format!("Gain {name} from {}", game.player_name(from))
}
HandCardLocation::DiscardPile => &format!("Gain {name} from discard pile"),
HandCardLocation::Public => &format!("Gain {name} from the public area"),
HandCardLocation::GreatSeer(_) => &format!("Gain {name} from Great Seer"),
HandCardLocation::Incident => &format!("Gain {name} from the current event"),
_ => {
panic!(
"Cannot transfer card from played to hand: {card:?} from {from:?} to {to:?}"
)
}
},
)
} else if let HandCardLocation::Hand(p) = from {
let name = card_name(card, &to, game);
(
p,
match to {
HandCardLocation::DiscardPile => &format!("Discard {name}"),
HandCardLocation::DrawPile => &format!("Shuffle {name} back into the draw pile"),
HandCardLocation::PlayToDiscard | HandCardLocation::PlayToKeep => {
&format!("Play {name}")
}
HandCardLocation::CompleteObjective(ref o) => &format!("Complete {o} using {name}"),
HandCardLocation::PlayToDiscardFaceDown => &format!("Play {name} face down"),
HandCardLocation::Public => &format!("Place {name} in public area"),
_ => panic!(
"Cannot transfer card from hand to draw pile: {card:?} from {from:?} to {to:?}"
),
},
)
} else if let HandCardLocation::GreatSeer(p) = to {
assert_eq!(from, HandCardLocation::DrawPile);
(p, "Placed a card from the draw pile in the Great Seer")
} else if let HandCardLocation::DrawPilePeeked(p) = from {
assert_eq!(to, HandCardLocation::DrawPile);
(
p,
"Reshuffled a card from the draw pile back into the draw pile",
)
} else {
panic!("Invalid card transfer from {from:?} to {to:?}");
};
game.log(player_index, origin, message);
add_action_log_item( add_action_log_item(
game, game,
player_index, player_index,
@ -304,10 +290,65 @@ pub(crate) fn log_card_transfer(
); );
} }
fn card_name(card: &HandCard, l: &HandCardLocation, game: &mut Game) -> String { ///
if l.is_public() { /// # Panics
card.name(game) /// Panics if the transfer is invalid
#[must_use]
pub fn hand_card_message(
game: &Game,
card: &HandCard,
from: &HandCardLocation,
to: &HandCardLocation,
) -> (usize, String) {
let (player_index, message): (usize, &str) = if let HandCardLocation::Hand(p) = to {
let name = card.name(game);
(
*p,
match from {
HandCardLocation::DrawPile => &format!("draws {name}"),
HandCardLocation::Hand(from) | HandCardLocation::RevealedHand(from) => {
&format!("gains {name} from {}", game.player_name(*from))
}
HandCardLocation::DiscardPile => &format!("gains {name} from discard pile"),
HandCardLocation::Public => &format!("gains {name} from the public area"),
HandCardLocation::GreatSeer(_) => &format!("gains {name} from Great Seer"),
HandCardLocation::Incident => &format!("gains {name} from the current event"),
_ => {
panic!(
"Cannot transfer card from played to hand: {card:?} from {from:?} to {to:?}"
)
}
},
)
} else if let HandCardLocation::Hand(p) = from {
let name = card.name(game);
(
*p,
match to {
HandCardLocation::DiscardPile => &format!("Discard {name}"),
HandCardLocation::DrawPile => &format!("Shuffle {name} back into the draw pile"),
HandCardLocation::PlayToDiscard | HandCardLocation::PlayToKeep => {
&format!("Play {name}")
}
HandCardLocation::CompleteObjective(o) => &format!("Complete {o} using {name}"),
HandCardLocation::PlayToDiscardFaceDown => &format!("Play {name} face down"),
HandCardLocation::Public => &format!("Place {name} in public area"),
_ => panic!(
"Cannot transfer card from hand to draw pile: {card:?} from {from:?} to {to:?}"
),
},
)
} else if let HandCardLocation::GreatSeer(p) = to {
assert_eq!(*from, HandCardLocation::DrawPile);
(*p, "Placed a card from the draw pile in the Great Seer")
} else if let HandCardLocation::DrawPilePeeked(p) = from {
assert_eq!(*to, HandCardLocation::DrawPile);
(
*p,
"Reshuffled a card from the draw pile back into the draw pile",
)
} else { } else {
card.card_type().to_string() panic!("Invalid card transfer from {from:?} to {to:?}");
} };
(player_index, message.to_string())
} }

View file

@ -4,6 +4,7 @@ use std::ops::{Add, Sub};
use crate::city_pieces::lose_building; use crate::city_pieces::lose_building;
use crate::content::custom_actions::CustomActionType::ForcedLabor; use crate::content::custom_actions::CustomActionType::ForcedLabor;
use crate::content::custom_actions::SpecialAction;
use crate::content::persistent_events::PersistentEventType; use crate::content::persistent_events::PersistentEventType;
use crate::events::{EventOrigin, EventPlayer}; use crate::events::{EventOrigin, EventPlayer};
use crate::log::{ActionLogBalance, ActionLogEntry, add_action_log_item}; use crate::log::{ActionLogBalance, ActionLogEntry, add_action_log_item};
@ -149,7 +150,10 @@ impl City {
Happy => size + 1, Happy => size + 1,
Neutral => size, Neutral => size,
Angry => { Angry => {
if player.played_once_per_turn_actions.contains(&ForcedLabor) { if player
.played_once_per_turn_actions
.contains(&SpecialAction::Custom(ForcedLabor))
{
self.size() self.size()
} else { } else {
1 1
@ -280,7 +284,7 @@ pub(crate) fn execute_found_city_action(
add_action_log_item( add_action_log_item(
game, game,
player_index, player_index,
ActionLogEntry::units(u, ActionLogBalance::Loss), ActionLogEntry::units(u, ActionLogBalance::Pay, settler.position),
origin.clone(), origin.clone(),
vec![], vec![],
); );
@ -289,7 +293,7 @@ pub(crate) fn execute_found_city_action(
} }
found_city( found_city(
game, game,
&EventPlayer::from_player(player_index, game, origin), &EventPlayer::new(player_index, origin),
settler.position, settler.position,
); );
Ok(()) Ok(())
@ -386,12 +390,6 @@ pub(crate) fn set_city_mood(
return; return;
} }
city.mood_state = new_state.clone(); city.mood_state = new_state.clone();
game.log(
player,
origin,
&format!("City {position} became {new_state}"),
);
add_action_log_item( add_action_log_item(
game, game,
player, player,

View file

@ -357,7 +357,7 @@ pub(crate) fn gain_building(
position: Position, position: Position,
) { ) {
if let Some(old) = game.get_any_city(position).pieces.building_owner(building) { if let Some(old) = game.get_any_city(position).pieces.building_owner(building) {
let old = EventPlayer::from_player(old, game, player.origin.clone()); let old = EventPlayer::new(old, player.origin.clone());
lose_building(game, &old, building, position); lose_building(game, &old, building, position);
} }
game.get_any_city_mut(position) game.get_any_city_mut(position)
@ -372,27 +372,13 @@ pub(crate) fn log_gain_building(
building: Building, building: Building,
position: Position, position: Position,
) { ) {
let port_pos = if building == Port {
format!(
" at the water tile {}",
game.get_any_city(position)
.port_position
.expect("Port must have a port position",)
)
} else {
String::new()
};
player.log(
game,
&format!("Gain {} at {position}{port_pos}", building.name()),
);
log_structure( log_structure(
game, game,
player, player,
Structure::Building(building), Structure::Building(building),
ActionLogBalance::Gain, ActionLogBalance::Gain,
position, position,
log_port_position(game, building, position),
); );
} }
@ -402,12 +388,18 @@ pub(crate) fn log_lose_building(
building: Building, building: Building,
position: Position, position: Position,
) { ) {
player.log(game, &format!("Lose {} at {}", building.name(), position));
log_structure( log_structure(
game, game,
player, player,
Structure::Building(building), Structure::Building(building),
ActionLogBalance::Loss, ActionLogBalance::Loss,
position, position,
log_port_position(game, building, position),
); );
} }
fn log_port_position(game: &Game, building: Building, position: Position) -> Option<Position> {
(building == Port)
.then_some(game.get_any_city(position).port_position)
.flatten()
}

View file

@ -8,7 +8,7 @@ use crate::map::Terrain;
use crate::map::Terrain::{Fertile, Forest, Mountain}; use crate::map::Terrain::{Fertile, Forest, Mountain};
use crate::player::{CostTrigger, Player}; use crate::player::{CostTrigger, Player};
use crate::player_events::ActionInfo; use crate::player_events::ActionInfo;
use crate::playing_actions::{PlayingActionType, base_or_custom_available}; use crate::playing_actions::{PlayingActionType, base_or_modified_available};
use crate::position::Position; use crate::position::Position;
use crate::resource::gain_resources_with_modifiers; use crate::resource::gain_resources_with_modifiers;
use crate::resource_pile::ResourcePile; use crate::resource_pile::ResourcePile;
@ -216,11 +216,6 @@ pub(crate) fn execute_collect(
c: &Collect, c: &Collect,
) -> Result<(), String> { ) -> Result<(), String> {
let origin = collect_event_origin(&c.action_type, game.player(player_index)); let origin = collect_event_origin(&c.action_type, game.player(player_index));
game.log(
player_index,
&origin,
&format!("Use city {}", c.city_position),
);
let mut i = get_total_collection_with_ballcourts( let mut i = get_total_collection_with_ballcourts(
game, game,
@ -238,6 +233,7 @@ pub(crate) fn execute_collect(
ResourcePile::mood_tokens(1), ResourcePile::mood_tokens(1),
EventOrigin::SpecialAdvance(crate::special_advance::SpecialAdvance::Ballcourts), EventOrigin::SpecialAdvance(crate::special_advance::SpecialAdvance::Ballcourts),
vec![], vec![],
crate::log::ActionLogBalance::Pay,
); );
} }
let city = game.players[player_index].get_city_mut(c.city_position); let city = game.players[player_index].get_city_mut(c.city_position);
@ -354,10 +350,7 @@ pub fn possible_resource_collections(
.events .events
.transient .transient
.terrain_collect_options; .terrain_collect_options;
let modifiers = let modifiers = event.trigger_with_modifiers(&mut terrain_options, &(), &(), &mut (), trigger);
event
.get()
.trigger_with_modifiers(&mut terrain_options, &(), &(), &mut (), trigger);
let collect_options = city_pos let collect_options = city_pos
.neighbors() .neighbors()
@ -444,9 +437,8 @@ pub fn available_collect_actions_for_city(
.into_iter() .into_iter()
.filter(|action| { .filter(|action| {
*action *action
!= PlayingActionType::Custom( != crate::content::custom_actions::PlayingActionModifier::Tributes
crate::content::custom_actions::CustomActionType::Tributes, .playing_action_type()
)
|| crate::content::civilizations::aztecs::tributes_city( || crate::content::civilizations::aztecs::tributes_city(
game.player(player), game.player(player),
position, position,
@ -460,7 +452,7 @@ pub fn available_collect_actions_for_city(
#[must_use] #[must_use]
pub fn available_collect_actions(game: &Game, player: usize) -> Vec<PlayingActionType> { pub fn available_collect_actions(game: &Game, player: usize) -> Vec<PlayingActionType> {
base_or_custom_available(game, player, &PlayingActionType::Collect) base_or_modified_available(game, player, &PlayingActionType::Collect)
} }
pub(crate) fn collect_event_origin( pub(crate) fn collect_event_origin(

View file

@ -13,6 +13,7 @@ use crate::content::ability::combat_event_origin;
use crate::content::persistent_events::PersistentEventType; use crate::content::persistent_events::PersistentEventType;
use crate::events::{EventOrigin, EventPlayer}; use crate::events::{EventOrigin, EventPlayer};
use crate::game::Game; use crate::game::Game;
use crate::log::{ActionLogEntry, ActionLogEntryCombatRound};
use crate::movement::{MoveUnits, MovementRestriction, move_units, stop_current_move}; use crate::movement::{MoveUnits, MovementRestriction, move_units, stop_current_move};
use crate::position::Position; use crate::position::Position;
use crate::resource_pile::ResourcePile; use crate::resource_pile::ResourcePile;
@ -223,43 +224,37 @@ pub fn initiate_combat(
} }
pub(crate) fn log_round(game: &mut Game, c: &Combat) { pub(crate) fn log_round(game: &mut Game, c: &Combat) {
game.add_info_log_item(&format!("Combat round {}", c.stats.round)); let attackers = c
let origin = &combat_event_origin(); .attackers
game.log( .iter()
c.attacker(), .flat_map(|u| {
origin, let p = game.player(c.attacker());
&format!( let u = p.get_unit(*u);
"Attacking with {}", vec![u.unit_type]
c.attackers .into_iter()
.iter() .chain(
.flat_map(|u| { carried_units(u.id, p)
let p = game.player(c.attacker()); .iter()
let u = p.get_unit(*u); .map(|u| p.get_unit(*u).unit_type),
vec![u.unit_type] )
.into_iter() .collect_vec()
.chain( })
carried_units(u.id, p) .collect::<Units>();
.iter() let defending_player = c.defender();
.map(|u| p.get_unit(*u).unit_type), let defenders = game
) .player(defending_player)
.collect_vec() .get_units(c.defender_position())
}) .iter()
.collect::<Units>() .map(|u| u.unit_type)
.to_string(Some(game)) .collect::<Units>();
), EventPlayer::new(c.attacker(), combat_event_origin()).add_log_entry(
); game,
game.log( ActionLogEntry::CombatRound(ActionLogEntryCombatRound {
c.defender(), round: c.stats.round,
origin, attackers,
&format!( defending_player,
"Defending with {}", defenders,
game.player(c.defender()) }),
.get_units(c.defender_position())
.iter()
.map(|u| u.unit_type)
.collect::<Units>()
.to_string(Some(game))
),
); );
} }
@ -448,7 +443,7 @@ fn take_over_city(
} }
pub(crate) fn capture_position(game: &mut Game, stats: &mut CombatStats) { pub(crate) fn capture_position(game: &mut Game, stats: &mut CombatStats) {
let p = &EventPlayer::from_player(stats.attacker.player, game, combat_event_origin()); let p = &EventPlayer::new(stats.attacker.player, combat_event_origin());
let old_player = stats.defender.player; let old_player = stats.defender.player;
let position = stats.defender.position; let position = stats.defender.position;
let captured_settlers = game.players[old_player] let captured_settlers = game.players[old_player]
@ -468,7 +463,7 @@ pub(crate) fn capture_position(game: &mut Game, stats: &mut CombatStats) {
} }
kill_units_with_stats(stats, game, old_player, &captured_settlers); kill_units_with_stats(stats, game, old_player, &captured_settlers);
if game.player(old_player).try_get_city(position).is_some() { if game.player(old_player).try_get_city(position).is_some() {
let d = &EventPlayer::from_player(old_player, game, combat_event_origin()); let d = &EventPlayer::new(old_player, combat_event_origin());
conquer_city(game, position, p, d); conquer_city(game, position, p, d);
} }
} }
@ -563,9 +558,8 @@ fn apply_battle_movement_restriction(game: &mut Game, player_index: usize, unit_
} }
if used_longships { if used_longships {
EventPlayer::from_player( EventPlayer::new(
player_index, player_index,
game,
EventOrigin::SpecialAdvance(SpecialAdvance::Longships), EventOrigin::SpecialAdvance(SpecialAdvance::Longships),
) )
.log(game, "Ignore battle movement restrictions"); .log(game, "Ignore battle movement restrictions");

View file

@ -5,7 +5,7 @@ use crate::combat_roll::CombatHits;
use crate::combat_stats::CombatStats; use crate::combat_stats::CombatStats;
use crate::content::ability::{Ability, combat_event_origin}; use crate::content::ability::{Ability, combat_event_origin};
use crate::content::persistent_events::{PersistentEventType, PositionRequest, UnitsRequest}; use crate::content::persistent_events::{PersistentEventType, PositionRequest, UnitsRequest};
use crate::events::EventOrigin; use crate::events::{EventOrigin, EventPlayer};
use crate::game::Game; use crate::game::Game;
use crate::log::current_action_log_mut; use crate::log::current_action_log_mut;
use crate::movement::move_units; use crate::movement::move_units;
@ -334,7 +334,7 @@ pub(crate) fn combat_round_end(game: &mut Game, r: CombatRoundEnd) -> Option<Com
} }
fn attacker_wins(game: &mut Game, mut c: Combat) { fn attacker_wins(game: &mut Game, mut c: Combat) {
game.add_info_log_item("Attacker wins"); log_winner(game, c.attacker(), None);
move_units( move_units(
game, game,
c.attacker(), c.attacker(),
@ -346,20 +346,26 @@ fn attacker_wins(game: &mut Game, mut c: Combat) {
end_combat_and_store_stats(game, CombatEnd::new(CombatResult::AttackerWins, c)); end_combat_and_store_stats(game, CombatEnd::new(CombatResult::AttackerWins, c));
} }
fn log_winner(game: &mut Game, player_index: usize, origin: Option<EventOrigin>) {
EventPlayer::new(player_index, origin.unwrap_or(combat_event_origin()))
.log(game, "wins the battle");
}
fn defender_wins(game: &mut Game, c: Combat) { fn defender_wins(game: &mut Game, c: Combat) {
game.add_info_log_item("Defender wins"); log_winner(game, c.defender(), None);
end_combat_and_store_stats(game, CombatEnd::new(CombatResult::DefenderWins, c)); end_combat_and_store_stats(game, CombatEnd::new(CombatResult::DefenderWins, c));
} }
pub(crate) fn draw(game: &mut Game, c: Combat) { pub(crate) fn draw(game: &mut Game, c: Combat) {
if c.defender_fortress(game) && c.first_round() { if c.defender_fortress(game) && c.first_round() {
game.add_info_log_item(&format!( log_winner(
"{} wins the battle because he has a defending fortress", game,
game.player_name(c.defender()) c.defender(),
)); Some(EventOrigin::Ability("fortress".to_string())),
);
return end_combat_and_store_stats(game, CombatEnd::new(CombatResult::DefenderWins, c)); return end_combat_and_store_stats(game, CombatEnd::new(CombatResult::DefenderWins, c));
} }
game.add_info_log_item("Battle ends in a draw"); EventPlayer::new(c.attacker(), combat_event_origin()).log(game, "ends the battle in a draw");
end_combat_and_store_stats(game, CombatEnd::new(CombatResult::Draw, c)); end_combat_and_store_stats(game, CombatEnd::new(CombatResult::Draw, c));
} }

View file

@ -3,6 +3,7 @@ use crate::combat_listeners::CombatStrength;
use crate::content::ability::combat_event_origin; use crate::content::ability::combat_event_origin;
use crate::events::EventPlayer; use crate::events::EventPlayer;
use crate::game::Game; use crate::game::Game;
use crate::log::{ActionLogEntry, ActionLogEntryCombatRoll};
use crate::unit::UnitType::{Cavalry, Elephant, Infantry}; use crate::unit::UnitType::{Cavalry, Elephant, Infantry};
use crate::unit::{LEADER_UNIT, UnitType, Units}; use crate::unit::{LEADER_UNIT, UnitType, Units};
use num::Zero; use num::Zero;
@ -59,12 +60,20 @@ impl CombatHits {
} }
} }
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct UnitCombatRoll {
pub value: u8,
pub unit_type: UnitType,
pub bonus: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub combat_bonus: Option<u8>,
}
pub(crate) struct CombatRoundStats { pub(crate) struct CombatRoundStats {
horse_master_value: Option<u8>, horse_master_value: Option<u8>,
player: usize, player: usize,
opponent_str: String,
pub(crate) fighters: u8, pub(crate) fighters: u8,
log_str: String, rolls: Vec<UnitCombatRoll>,
combat_value: u8, combat_value: u8,
hit_cancels: u8, hit_cancels: u8,
strength: CombatStrength, strength: CombatStrength,
@ -78,7 +87,7 @@ impl CombatRoundStats {
strength: CombatStrength, strength: CombatStrength,
) -> CombatRoundStats { ) -> CombatRoundStats {
let fighting = c.fighting_units(game, player); let fighting = c.fighting_units(game, player);
let mut log = vec![]; let mut unit_rolls = vec![];
let rolls = roll( let rolls = roll(
game, game,
player, player,
@ -93,29 +102,20 @@ impl CombatRoundStats {
&& game && game
.player(player) .player(player)
.has_special_advance(crate::special_advance::SpecialAdvance::Horsemanship), .has_special_advance(crate::special_advance::SpecialAdvance::Horsemanship),
&mut log, &mut unit_rolls,
); );
let log_str = roll_log_str(&log);
let combat_value = rolls.combat_value as u8; let combat_value = rolls.combat_value as u8;
let hit_cancels = rolls.hit_cancels + strength.hit_cancels; let hit_cancels = rolls.hit_cancels + strength.hit_cancels;
let opponent_str = if c.defender() == player {
"attacking"
} else {
"defending"
}
.to_string();
CombatRoundStats { CombatRoundStats {
horse_master_value: (c.first_round() horse_master_value: (c.first_round()
&& game.player(player).active_leader() == Some(crate::leader::Leader::Attila) && game.player(player).active_leader() == Some(crate::leader::Leader::Attila)
&& c.has_leader(c.role(player), game)) && c.has_leader(c.role(player), game))
.then_some(rolls.horse_master_value) .then_some(rolls.horse_master_value)
.flatten(), .flatten(),
opponent_str,
strength, strength,
player, player,
log_str, rolls: unit_rolls,
combat_value, combat_value,
hit_cancels, hit_cancels,
fighters: fighting.len() as u8, fighters: fighting.len() as u8,
@ -135,37 +135,20 @@ impl CombatRoundStats {
self.combat_value, self.combat_value,
); );
combat_hits.horse_master_value = self.horse_master_value; combat_hits.horse_master_value = self.horse_master_value;
let hits = combat_hits.hits();
let p = EventPlayer::from_player(self.player, game, combat_event_origin()); EventPlayer::new(self.player, combat_event_origin()).add_log_entry(
p.log(
game, game,
&format!( ActionLogEntry::CombatRoll(ActionLogEntryCombatRoll {
"Roll {} for combined combat value of {} and gets {} hits against {} units", rolls: self.rolls.clone(),
self.log_str, self.combat_value, hits, self.opponent_str, combat_value: self.combat_value,
), hits: combat_hits.hits(),
combat_modifiers: self.strength.roll_log.clone(),
}),
); );
if !self.strength.roll_log.is_empty() {
p.log(
game,
&format!(
"Combat modifiers: {}",
roll_log_str(&self.strength.roll_log)
),
);
}
combat_hits combat_hits
} }
} }
fn roll_log_str(log: &[String]) -> String {
if log.is_empty() {
return String::from("no dice");
}
log.join(", ")
}
struct CombatRolls { struct CombatRolls {
horse_master_value: Option<u8>, horse_master_value: Option<u8>,
pub combat_value: i8, pub combat_value: i8,
@ -209,7 +192,7 @@ fn roll(
deny_combat_abilities: bool, deny_combat_abilities: bool,
cap_bonus: bool, cap_bonus: bool,
mut horsemanship: bool, mut horsemanship: bool,
roll_log: &mut Vec<String>, roll_log: &mut Vec<UnitCombatRoll>,
) -> CombatRolls { ) -> CombatRolls {
let mut dice_rolls = extra_dies; let mut dice_rolls = extra_dies;
let mut unit_types = Units::empty(); let mut unit_types = Units::empty();
@ -237,20 +220,16 @@ fn roll(
Infantry => { Infantry => {
rolls.combat_value += 1; rolls.combat_value += 1;
bonus += 1; bonus += 1;
add_roll_log_effect(roll_log, "+1 combat value"); add_bonus(roll_log);
} }
Cavalry => { Cavalry => {
let extra = if horsemanship { 3 } else { 2 }; let extra = if horsemanship { 3 } else { 2 };
rolls.combat_value += extra; rolls.combat_value += extra;
bonus += extra; bonus += extra;
add_roll_log_effect( add_bonus(roll_log);
roll_log, if horsemanship {
if horsemanship { roll_log.last_mut().expect("cavalry roll").combat_bonus = Some(3);
"+3 combat value (Horsemanship)" }
} else {
"+2 combat value"
},
);
horsemanship = false; horsemanship = false;
if rolls.horse_master_value.is_none() { if rolls.horse_master_value.is_none() {
rolls.horse_master_value = Some(value); rolls.horse_master_value = Some(value);
@ -259,12 +238,10 @@ fn roll(
Elephant => { Elephant => {
rolls.hit_cancels += 1; rolls.hit_cancels += 1;
rolls.combat_value -= value as i8; rolls.combat_value -= value as i8;
add_roll_log_effect(roll_log, "-1 hits, no combat value"); add_bonus(roll_log);
} }
_ => (), _ => (),
} }
} else {
add_roll_log_effect(roll_log, "no bonus");
} }
} }
rolls.horse_master_value = rolls.horse_master_value.map(|v| { rolls.horse_master_value = rolls.horse_master_value.map(|v| {
@ -276,7 +253,11 @@ fn roll(
}); });
if cap_bonus && bonus > 2 { if cap_bonus && bonus > 2 {
rolls.combat_value -= bonus - 2; rolls.combat_value -= bonus - 2;
roll_log.push(format!("opponent limits combat bonus from +{bonus} to +2")); game.log(
player_index,
&combat_event_origin(),
&format!("opponent limits combat bonus from +{bonus} to +2"),
);
} }
if rolls.combat_value < 0 { if rolls.combat_value < 0 {
rolls.combat_value = 0; rolls.combat_value = 0;
@ -288,7 +269,7 @@ fn dice_roll_with_leader_reroll(
game: &mut Game, game: &mut Game,
unit_types: &mut Units, unit_types: &mut Units,
deny_combat_abilities: bool, deny_combat_abilities: bool,
roll_log: &mut Vec<String>, roll_log: &mut Vec<UnitCombatRoll>,
) -> CombatDieRoll { ) -> CombatDieRoll {
let side = roll_die(game, roll_log); let side = roll_die(game, roll_log);
@ -303,7 +284,7 @@ fn dice_roll_with_leader_reroll(
// if used, the leader grants unlimited rerolls of 1s // if used, the leader grants unlimited rerolls of 1s
loop { loop {
add_roll_log_effect(roll_log, "re-roll"); add_bonus(roll_log);
let side = roll_die(game, roll_log); let side = roll_die(game, roll_log);
if side.bonus != LEADER_UNIT { if side.bonus != LEADER_UNIT {
@ -312,13 +293,17 @@ fn dice_roll_with_leader_reroll(
} }
} }
fn add_roll_log_effect(roll_log: &mut [String], effect: &str) { fn add_bonus(roll_log: &mut [UnitCombatRoll]) {
use std::fmt::Write as _; roll_log.last_mut().expect("entry not found").bonus = true;
let _ = write!(roll_log[roll_log.len() - 1], "{effect})");
} }
fn roll_die(game: &mut Game, roll_log: &mut Vec<String>) -> CombatDieRoll { fn roll_die(game: &mut Game, roll_log: &mut Vec<UnitCombatRoll>) -> CombatDieRoll {
let roll = game.next_dice_roll(); let roll = game.next_dice_roll();
roll_log.push(format!("{} ({}, ", roll.value, roll.bonus.generic_name())); roll_log.push(UnitCombatRoll {
roll.clone() value: roll.value,
unit_type: roll.bonus,
bonus: false,
combat_bonus: None,
});
roll
} }

View file

@ -181,7 +181,7 @@ pub(crate) fn construct(
} }
gain_building( gain_building(
game, game,
&EventPlayer::from_player(player, game, origin.clone()), &EventPlayer::new(player, origin.clone()),
building, building,
city_position, city_position,
); );
@ -232,7 +232,7 @@ pub(crate) fn on_construct(game: &mut Game, player_index: usize, info: Construct
gain_advance_without_payment( gain_advance_without_payment(
game, game,
b.advance, b.advance,
&EventPlayer::from_player(player_index, game, b.origin), &EventPlayer::new(player_index, b.origin),
ResourcePile::empty(), ResourcePile::empty(),
true, true,
); );

View file

@ -154,7 +154,8 @@ pub(crate) fn recruit_event_origin() -> EventOrigin {
EventOrigin::Ability("Recruit".to_string()) EventOrigin::Ability("Recruit".to_string())
} }
pub(crate) fn combat_event_origin() -> EventOrigin { #[must_use]
pub fn combat_event_origin() -> EventOrigin {
EventOrigin::Ability("Combat".to_string()) EventOrigin::Ability("Combat".to_string())
} }

View file

@ -7,7 +7,7 @@ use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{SelectedStructure, UnitTypeRequest}; use crate::content::persistent_events::{SelectedStructure, UnitTypeRequest};
use crate::content::tactics_cards::TacticsCardFactory; use crate::content::tactics_cards::TacticsCardFactory;
use crate::cultural_influence::{ use crate::cultural_influence::{
InfluenceCultureInfo, available_influence_actions, influence_culture_boost_cost, InfluenceCultureAttemptInfo, available_influence_actions, influence_culture_boost_cost,
}; };
use crate::game::Game; use crate::game::Game;
use crate::player::{Player, gain_unit, remove_unit}; use crate::player::{Player, gain_unit, remove_unit};
@ -104,6 +104,7 @@ fn any_barbarian_city_can_be_influenced(game: &Game, p: &Player) -> bool {
i, i,
true, true,
true, true,
c.player_index,
) )
.is_ok() .is_ok()
}) })
@ -138,7 +139,7 @@ pub(crate) fn use_cultural_takeover() -> Ability {
&& i.target_unit.is_none() && i.target_unit.is_none()
&& matches!(i.structure, Structure::CityCenter) && matches!(i.structure, Structure::CityCenter)
&& !(is_barbarian_takeover(game, i) && !(is_barbarian_takeover(game, i)
|| i.barbarian_takeover_check || i.barbarian_takeover
|| crate::content::civilizations::celts::can_mark_city( || crate::content::civilizations::celts::can_mark_city(
game, game,
i.info.player, i.info.player,
@ -168,7 +169,7 @@ pub(crate) fn use_cultural_takeover() -> Ability {
.build() .build()
} }
fn is_barbarian_takeover(game: &Game, c: &InfluenceCultureInfo) -> bool { fn is_barbarian_takeover(game: &Game, c: &InfluenceCultureAttemptInfo) -> bool {
let city = game.get_any_city(c.position); let city = game.get_any_city(c.position);
city.player_index == get_barbarians_player(game).index city.player_index == get_barbarians_player(game).index
&& city.size() == 1 && city.size() == 1

View file

@ -8,7 +8,8 @@ use crate::content::civilizations::rome::owner_of_sulla_in_range;
use crate::content::persistent_events::{PaymentRequest, PositionRequest}; use crate::content::persistent_events::{PaymentRequest, PositionRequest};
use crate::content::tactics_cards::TacticsCardFactory; use crate::content::tactics_cards::TacticsCardFactory;
use crate::game::Game; use crate::game::Game;
use crate::movement::{MoveUnits, move_action_log}; use crate::log::ActionLogEntry;
use crate::movement::MoveUnits;
use crate::player::Player; use crate::player::Player;
use crate::position::Position; use crate::position::Position;
use crate::resource::ResourceType; use crate::resource::ResourceType;
@ -153,7 +154,8 @@ fn move_army(b: ActionCardBuilder, i: i32) -> ActionCardBuilder {
let units = b.get_units(from).iter().map(|u| u.id).collect_vec(); let units = b.get_units(from).iter().map(|u| u.id).collect_vec();
let m = MoveUnits::new(units, to, None, ResourcePile::empty()); let m = MoveUnits::new(units, to, None, ResourcePile::empty());
s.log(game, &move_action_log(game, b, &m)); s.player()
.add_log_entry(game, ActionLogEntry::move_units(b, &m));
move_with_possible_combat(game, barbarian, &m); move_with_possible_combat(game, barbarian, &m);
}, },
@ -192,7 +194,8 @@ fn barbarian_army_positions_in_range2(
.is_some_and(|sulla_owner| player.index != sulla_owner) .is_some_and(|sulla_owner| player.index != sulla_owner)
{ {
log.push(format!( log.push(format!(
"{player} cannot move Barbarian army at {p} because Sulla is in range", "{} cannot move Barbarian army at {p} because Sulla is in range",
player.get_name()
)); ));
return false; return false;
} }

View file

@ -94,7 +94,7 @@ pub(crate) fn use_negotiations() -> Ability {
} }
} }
} }
add_start_turn_action_if_needed(game); add_start_turn_action_if_needed(game, p.index);
// must be in reverse order to not mess up the indices during deletion // must be in reverse order to not mess up the indices during deletion
for i in delete.iter().rev() { for i in delete.iter().rev() {
p.log(game, &format!("May attack {partner_name} again.",)); p.log(game, &format!("May attack {partner_name} again.",));
@ -193,7 +193,7 @@ pub(crate) fn use_assassination() -> Ability {
if remove_element_by(&mut game.permanent_effects, |e| is_assassinated(e, p.index)) if remove_element_by(&mut game.permanent_effects, |e| is_assassinated(e, p.index))
.is_some() .is_some()
{ {
add_start_turn_action_if_needed(game); add_start_turn_action_if_needed(game, p.index);
lose_action(game, p); lose_action(game, p);
} }
}, },

View file

@ -51,10 +51,10 @@ pub(crate) fn spy(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
let other = game.player(a.selected_player.expect("player not found")); let other = game.player(a.selected_player.expect("player not found"));
let all = HandCardType::get_all(); let all = HandCardType::get_all();
let mut cards = hand_cards(other, &all); let mut cards = hand_cards(other, &all, game);
for t in all { for t in all {
if !hand_cards(other, &[t]).is_empty() { if !hand_cards(other, &[t], game).is_empty() {
cards.extend(hand_cards(p, &[t])); cards.extend(hand_cards(p, &[t], game));
} }
} }
@ -88,7 +88,7 @@ pub(crate) fn spy(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
fn players_with_cards(game: &Game, player: usize) -> Vec<usize> { fn players_with_cards(game: &Game, player: usize) -> Vec<usize> {
game.players game.players
.iter() .iter()
.filter(|p| p.index != player && has_any_card(p)) .filter(|p| p.index != player && has_any_card(p, game))
.map(|p| p.index) .map(|p| p.index)
.collect_vec() .collect_vec()
} }
@ -110,8 +110,8 @@ fn swap_spy_cards(
let p = player.get(game); let p = player.get(game);
let o = game.player(other); let o = game.player(other);
let our_card = get_swap_card(swap, p)?; let our_card = get_swap_card(swap, p, game)?;
let other_card = get_swap_card(swap, o)?; let other_card = get_swap_card(swap, o, game)?;
let t = match our_card { let t = match our_card {
HandCard::ActionCard(id) => { HandCard::ActionCard(id) => {
@ -221,22 +221,23 @@ fn swap_card<T: PartialEq + Ord + Debug + Copy>(
); );
} }
fn get_swap_card(swap: &[HandCard], p: &Player) -> Result<HandCard, String> { fn get_swap_card(swap: &[HandCard], p: &Player, game: &Game) -> Result<HandCard, String> {
hand_cards(p, &HandCardType::get_all()) hand_cards(p, &HandCardType::get_all(), game)
.iter() .iter()
.find(|c| swap.contains(c)) .find(|c| swap.contains(c))
.ok_or("card not found".to_string()) .ok_or("card not found".to_string())
.cloned() .cloned()
} }
fn has_any_card(p: &Player) -> bool { fn has_any_card(p: &Player, game: &Game) -> bool {
!hand_cards(p, &HandCardType::get_all()).is_empty() !hand_cards(p, &HandCardType::get_all(), game).is_empty()
} }
fn get_swap_secrets(other: &Player, game: &Game) -> Vec<String> { fn get_swap_secrets(other: &Player, game: &Game) -> Vec<String> {
vec![ vec![
format!( format!(
"{other} has the following action cards: {}", "{} has the following action cards: {}",
other.get_name(),
other other
.action_cards .action_cards
.iter() .iter()
@ -244,7 +245,8 @@ fn get_swap_secrets(other: &Player, game: &Game) -> Vec<String> {
.join(", ") .join(", ")
), ),
format!( format!(
"{other} has the following objective cards: {}", "{} has the following objective cards: {}",
other.get_name(),
other other
.objective_cards .objective_cards
.iter() .iter()
@ -252,7 +254,8 @@ fn get_swap_secrets(other: &Player, game: &Game) -> Vec<String> {
.join(", ") .join(", ")
), ),
format!( format!(
"{other} has the following wonder cards: {}", "{} has the following wonder cards: {}",
other.get_name(),
other.wonder_cards.iter().map(Wonder::name).join(", ") other.wonder_cards.iter().map(Wonder::name).join(", ")
), ),
] ]
@ -270,6 +273,7 @@ pub(crate) fn validate_spy_cards(cards: &[HandCard], game: &Game) -> Result<(),
let our = hand_cards( let our = hand_cards(
game.player(game.current_event().player.index), game.player(game.current_event().player.index),
&HandCardType::get_all(), &HandCardType::get_all(),
game,
) )
.into_iter() .into_iter()
.filter(|c| cards.contains(c)) .filter(|c| cards.contains(c))

View file

@ -56,9 +56,9 @@ fn totalitarianism() -> AdvanceBuilder {
.add_transient_event_listener( .add_transient_event_listener(
|event| &mut event.on_influence_culture_attempt, |event| &mut event.on_influence_culture_attempt,
0, 0,
|r, city, game, _| { |r, city, game, p| {
if let Ok(info) = r if let Ok(info) = r
&& info.is_defender && info.is_defender(p.index)
&& game && game
.player(city.player_index) .player(city.player_index)
.get_units(city.position) .get_units(city.position)

View file

@ -2,7 +2,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::advance::Bonus::{CultureToken, MoodToken}; use crate::advance::Bonus::{CultureToken, MoodToken};
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo}; use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder};
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::PlayingActionModifier;
use crate::game::GameOptions; use crate::game::GameOptions;
use crate::payment::PaymentConversion; use crate::payment::PaymentConversion;
use crate::playing_actions::PlayingActionType; use crate::playing_actions::PlayingActionType;
@ -87,5 +87,5 @@ fn city_planning() -> AdvanceBuilder {
"Once per turn, as a free action, you may pay 1 idea and 1 wood to get a free Construct action.", "Once per turn, as a free action, you may pay 1 idea and 1 wood to get a free Construct action.",
) )
.replaces(Advance::Sanitation) .replaces(Advance::Sanitation)
.add_action_modifier(CustomActionType::CityPlanning, |cost| cost.once_per_turn().free_action().resources(ResourcePile::ideas(1) + ResourcePile::wood(1)), PlayingActionType::Construct) .add_action_modifier(PlayingActionModifier::CityPlanning, |cost| cost.once_per_turn().free_action().resources(ResourcePile::ideas(1) + ResourcePile::wood(1)), PlayingActionType::Construct)
} }

View file

@ -5,7 +5,7 @@ use crate::city::{City, MoodState};
use crate::city_pieces::Building::Obelisk; use crate::city_pieces::Building::Obelisk;
use crate::content::ability::AbilityBuilder; use crate::content::ability::AbilityBuilder;
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder};
use crate::content::custom_actions::{CustomActionType, any_non_happy}; use crate::content::custom_actions::{CustomActionType, PlayingActionModifier, any_non_happy};
use crate::content::persistent_events::PaymentRequest; use crate::content::persistent_events::PaymentRequest;
use crate::events::{EventOrigin, check_event_origin}; use crate::events::{EventOrigin, check_event_origin};
use crate::game::GameOptions; use crate::game::GameOptions;
@ -37,7 +37,7 @@ fn arts() -> AdvanceBuilder {
.with_advance_bonus(CultureToken) .with_advance_bonus(CultureToken)
.with_unlocked_building(Obelisk) .with_unlocked_building(Obelisk)
.add_action_modifier( .add_action_modifier(
CustomActionType::ArtsInfluenceCultureAttempt, PlayingActionModifier::ArtsInfluenceCultureAttempt,
|c| { |c| {
c.once_per_turn() c.once_per_turn()
.free_action() .free_action()
@ -79,9 +79,9 @@ fn monuments() -> AdvanceBuilder {
.add_transient_event_listener( .add_transient_event_listener(
|event| &mut event.on_influence_culture_attempt, |event| &mut event.on_influence_culture_attempt,
1, 1,
|r, city, _, _| { |r, city, _, p| {
if let Ok(info) = r if let Ok(info) = r
&& info.is_defender && info.is_defender(p.index)
&& !city.pieces.wonders.is_empty() && !city.pieces.wonders.is_empty()
{ {
*r = Err( *r = Err(

View file

@ -3,9 +3,8 @@ use crate::action::Action;
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo}; use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::city::{self, MoodState}; use crate::city::{self, MoodState};
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder};
use crate::content::custom_actions::CustomActionType::{ use crate::content::custom_actions::CustomActionType::{self, CivilLiberties};
self, CivilLiberties, FreeEconomyCollect, VotingIncreaseHappiness, use crate::content::custom_actions::{PlayingActionModifier, SpecialAction};
};
use crate::content::persistent_events::PositionRequest; use crate::content::persistent_events::PositionRequest;
use crate::game::GameOptions; use crate::game::GameOptions;
use crate::log::current_turn_log_without_redo; use crate::log::current_turn_log_without_redo;
@ -34,7 +33,7 @@ fn voting() -> AdvanceBuilder {
"Take an Increase Happiness action without spending an action. Pay the normal mood cost plus 1 extra mood token in total, regardless of how many of your cities you improve.", "Take an Increase Happiness action without spending an action. Pay the normal mood cost plus 1 extra mood token in total, regardless of how many of your cities you improve.",
) )
.add_action_modifier( .add_action_modifier(
VotingIncreaseHappiness, PlayingActionModifier::VotingIncreaseHappiness,
|c| { |c| {
c.any_times() c.any_times()
.free_action() .free_action()
@ -92,7 +91,7 @@ fn free_economy() -> AdvanceBuilder {
"Pay 1 mood token to activate one of your cities and collect resources without spending an action. This must be your only Collect action that turn.", "Pay 1 mood token to activate one of your cities and collect resources without spending an action. This must be your only Collect action that turn.",
) )
.add_action_modifier( .add_action_modifier(
FreeEconomyCollect, PlayingActionModifier::FreeEconomyCollect,
|c| { |c| {
c.once_per_turn() c.once_per_turn()
.free_action() .free_action()
@ -107,12 +106,14 @@ fn free_economy() -> AdvanceBuilder {
PlayingActionType::Collect PlayingActionType::Collect
if p.get(game) if p.get(game)
.played_once_per_turn_actions .played_once_per_turn_actions
.contains(&FreeEconomyCollect) => .contains(&SpecialAction::Modifier(
PlayingActionModifier::FreeEconomyCollect,
)) =>
{ {
*available = Err("Cannot collect when Free Economy Collect was used".to_string()); *available = Err("Cannot collect when Free Economy Collect was used".to_string());
} }
PlayingActionType::Custom(i) PlayingActionType::Special(SpecialAction::Modifier(m))
if *i == FreeEconomyCollect if *m == PlayingActionModifier::FreeEconomyCollect
&& current_turn_log_without_redo(game) && current_turn_log_without_redo(game)
.actions .actions
.iter() .iter()

View file

@ -156,7 +156,7 @@ where
if !p.get(game).can_use_advance(Advance::TradeRoutes) { if !p.get(game).can_use_advance(Advance::TradeRoutes) {
return None; return None;
} }
add_start_turn_action_if_needed(game); add_start_turn_action_if_needed(game, p.index);
trade_route_reward(game, p).map(|(reward, routes)| { trade_route_reward(game, p).map(|(reward, routes)| {
gain_market_bonus(game, &routes); gain_market_bonus(game, &routes);
ResourceRewardRequest::new(reward, "Collect trade routes reward".to_string()) ResourceRewardRequest::new(reward, "Collect trade routes reward".to_string())

View file

@ -6,11 +6,11 @@ use crate::card::HandCardLocation;
use crate::city_pieces::Building; use crate::city_pieces::Building;
use crate::content::ability::Ability; use crate::content::ability::Ability;
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder};
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::PlayingActionModifier;
use crate::content::persistent_events::PaymentRequest; use crate::content::persistent_events::PaymentRequest;
use crate::game::GameOptions; use crate::game::GameOptions;
use crate::log::{self, ActionLogEntry}; use crate::log::{ActionLogEntry, current_turn_log_mut};
use crate::objective_card::draw_objective_card_from_pile; use crate::objective_card::gain_objective_card_from_pile;
use crate::playing_actions::PlayingActionType; use crate::playing_actions::PlayingActionType;
use crate::resource::gain_resources; use crate::resource::gain_resources;
use crate::resource_pile::ResourcePile; use crate::resource_pile::ResourcePile;
@ -42,16 +42,16 @@ fn writing() -> AdvanceBuilder {
if !game.is_update_patch() { if !game.is_update_patch() {
gain_action_card_from_pile(game, player); gain_action_card_from_pile(game, player);
} }
// can't gain objective card directly, because the "combat_end" listener might gain_objective_card_from_pile(game, player);
// currently being processed ("teach us now")
player.get_mut(game).gained_objective = draw_objective_card_from_pile(game, player);
}) })
.add_transient_event_listener( .add_transient_event_listener(
|event| &mut event.after_action, |event| &mut event.after_action,
1, 1,
|game, (), (), p| { |game, (), (), p| {
if game.is_update_patch() { if game.is_update_patch()
let count = log::current_action_log_mut(game) && let Some(a) = current_turn_log_mut(game).actions.last()
{
let count = a
.items .items
.iter() .iter()
.filter(|item| { .filter(|item| {
@ -64,7 +64,9 @@ fn writing() -> AdvanceBuilder {
) )
}) })
.count(); .count();
p.gain_resources(game, ResourcePile::ideas(count as u8)); if count > 0 {
p.gain_resources(game, ResourcePile::ideas(count as u8));
}
} }
}, },
) )
@ -189,7 +191,7 @@ fn philosophy_patched() -> AdvanceBuilder {
) )
.replaces(Advance::Philosophy) .replaces(Advance::Philosophy)
.add_action_modifier( .add_action_modifier(
CustomActionType::Philosophy, PlayingActionModifier::Philosophy,
|cost| { |cost| {
cost.any_times() cost.any_times()
.free_action() .free_action()

View file

@ -7,7 +7,9 @@ use crate::content::ability::Ability;
use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder}; use crate::content::advances::{AdvanceGroup, AdvanceGroupInfo, advance_group_builder};
use crate::content::persistent_events::ResourceRewardRequest; use crate::content::persistent_events::ResourceRewardRequest;
use crate::game::GameOptions; use crate::game::GameOptions;
use crate::log::ActionLogBalance;
use crate::resource::ResourceType; use crate::resource::ResourceType;
use crate::resource_pile::ResourcePile;
pub(crate) fn science(options: &GameOptions) -> AdvanceGroupInfo { pub(crate) fn science(options: &GameOptions) -> AdvanceGroupInfo {
advance_group_builder( advance_group_builder(
@ -104,17 +106,22 @@ fn metallurgy() -> AdvanceBuilder {
"Metallurgy", "Metallurgy",
"If you have the Steel Weapons Advance, \ "If you have the Steel Weapons Advance, \
you no longer have to pay 1 ore to activate it against enemies without Steel Weapons. \ you no longer have to pay 1 ore to activate it against enemies without Steel Weapons. \
If you collect at least 2 ore, replace 1 ore with 1 gold", If you collect at least 2 ore, you may replace 1 ore with 1 gold",
) )
.with_advance_bonus(CultureToken) .with_advance_bonus(CultureToken)
.add_transient_event_listener( .add_bool_request(
|event| &mut event.collect_total, |event| &mut event.collect,
0, 0,
|i, _, _, p| { |_game, _p, i| {
if i.total.ore >= 2 { (i.total.ore >= 2).then_some("Do you want to convert 1 ore to 1 gold?".to_string())
i.total.ore -= 1; },
i.total.gold += 1; move |game, s, _| {
i.info.add_log(p, "Convert 1 ore to 1 gold"); if s.choice {
s.player()
.lose_resources(game, ResourcePile::ore(1), ActionLogBalance::Pay);
s.player().gain_resources(game, ResourcePile::gold(1));
} else {
s.log(game, "Did not convert ore to gold");
} }
}, },
) )

View file

@ -83,9 +83,9 @@ fn devotion() -> AdvanceBuilder {
.add_transient_event_listener( .add_transient_event_listener(
|event| &mut event.on_influence_culture_attempt, |event| &mut event.on_influence_culture_attempt,
4, 4,
|r, city, _, _| { |r, city, _, p| {
if let Ok(info) = r if let Ok(info) = r
&& info.is_defender && info.is_defender(p.index)
&& city.pieces.temple.is_some() && city.pieces.temple.is_some()
{ {
info.set_no_boost(); info.set_no_boost();
@ -106,13 +106,10 @@ fn conversion() -> AdvanceBuilder {
3, 3,
|r, _, _, p| { |r, _, _, p| {
if let Ok(info) = r if let Ok(info) = r
&& !info.is_defender && !info.is_defender(p.index)
{ {
info.roll_boost += 1; info.roll_boost += 1;
info.info.add_log( info.info.add_log(p, "gains +1 to Influence Culture roll");
p,
"Gain +1 to Influence Culture roll for Conversion Advance",
);
} }
}, },
) )

View file

@ -225,9 +225,17 @@ fn use_steel_weapons(game: &Game, c: &Combat, s: &mut CombatStrength, role: Comb
let add_combat_value = |s: &mut CombatStrength, value: u8| { let add_combat_value = |s: &mut CombatStrength, value: u8| {
s.extra_combat_value += value as i8; s.extra_combat_value += value as i8;
let free = value == 2 && game.player(c.player(role)).can_use_advance(Advance::Metallurgy); let free = value == 2
let benefit = if free { " (Metallurgy: no ore cost)" } else { "" }; && game
s.roll_log.push(format!("steel weapons added {value} combat value{benefit}")); .player(c.player(role))
.can_use_advance(Advance::Metallurgy);
let benefit = if free {
" (Metallurgy: no ore cost)"
} else {
""
};
s.roll_log
.push(format!("steel weapons added {value} combat value{benefit}"));
}; };
if role.is_attacker() { if role.is_attacker() {

View file

@ -102,14 +102,14 @@ fn human_sacrifice() -> SpecialAdvanceInfo {
let p=s.player(); let p=s.player();
// Put the chosen pieces first so the shared payment path returns exactly these pieces. // Put the chosen pieces first so the shared payment path returns exactly these pieces.
let held=&mut p.get_mut(game).captives;held.sort_by_key(|c|!s.choice.contains(c)); let held=&mut p.get_mut(game).captives;held.sort_by_key(|c|!s.choice.contains(c));
let amount=s.choice.len() as u8;lose_resources(game,p.index,ResourcePile::captives(amount),s.origin.clone(),vec![]); let amount=s.choice.len() as u8;lose_resources(game,p.index,ResourcePile::captives(amount),s.origin.clone(),vec![],crate::log::ActionLogBalance::Pay);
a.payment=ResourcePile::captives(amount); a.payment=ResourcePile::captives(amount);
}) })
.add_resource_request(|e|&mut e.custom_action,1,|_,p,a|Some(crate::content::persistent_events::ResourceRewardRequest::new(p.reward_options().tokens(a.payment.captives),"Human Sacrifice · Gain mood or culture tokens".into()))), .add_resource_request(|e|&mut e.custom_action,1,|_,p,a|Some(crate::content::persistent_events::ResourceRewardRequest::new(p.reward_options().tokens(a.payment.captives),"Human Sacrifice · Gain mood or culture tokens".into()))),
|_,p|!p.captives.is_empty()) |_,p|!p.captives.is_empty())
.add_transient_event_listener(|e|&mut e.general_payment_conversions,15,|conversions,(),(),_|conversions.push(PaymentConversion::resource_options(vec![ResourcePile::mood_tokens(1),ResourcePile::culture_tokens(1)],ResourcePile::captives(1),PaymentConversionType::Unlimited))) .add_transient_event_listener(|e|&mut e.general_payment_conversions,15,|conversions,(),(),_|conversions.push(PaymentConversion::resource_options(vec![ResourcePile::mood_tokens(1),ResourcePile::culture_tokens(1)],ResourcePile::captives(1),PaymentConversionType::Unlimited)))
.add_bool_request(|e|&mut e.incident,10000,|game,p,i|(i.active_player==p.index&&!i.consumed&&i.passed.is_none()&&p.get(game).resources.captives>0).then(||format!("Human Sacrifice · Sacrifice 1 captive to cancel {} and draw another event?",game.cache.get_incident(i.incident_id).name)),|game,s,i|{ .add_bool_request(|e|&mut e.incident,10000,|game,p,i|(i.active_player==p.index&&!i.consumed&&i.passed.is_none()&&p.get(game).resources.captives>0).then(||format!("Human Sacrifice · Sacrifice 1 captive to cancel {} and draw another event?",game.cache.get_incident(i.incident_id).name)),|game,s,i|{
if s.choice {lose_resources(game,s.player_index,ResourcePile::captives(1),s.origin.clone(),vec![]);i.consumed=true;i.replaced_by_sacrifice=true;s.log(game,"Sacrificed a captive: the entire event and its icon are cancelled");} if s.choice {lose_resources(game,s.player_index,ResourcePile::captives(1),s.origin.clone(),vec![],crate::log::ActionLogBalance::Pay);i.consumed=true;i.replaced_by_sacrifice=true;s.log(game,"Sacrificed a captive: the entire event and its icon are cancelled");}
}).build() }).build()
} }
fn aztec_gold() -> SpecialAdvanceInfo { fn aztec_gold() -> SpecialAdvanceInfo {
@ -227,7 +227,7 @@ fn acamapichtli() -> LeaderInfo {
.add_transient_event_listener(|e|&mut e.building_cost,14,|i,_,game,p|growth(i,game,p)) .add_transient_event_listener(|e|&mut e.building_cost,14,|i,_,game,p|growth(i,game,p))
.add_transient_event_listener(|e|&mut e.wonder_cost,14,|i,_,game,p|growth(i,game,p)).build(), .add_transient_event_listener(|e|&mut e.wonder_cost,14,|i,_,game,p|growth(i,game,p)).build(),
LeaderAbility::builder("Tributes","Once per turn, pay 2 mood tokens to Collect from Acamapichtli's city as a free action, if its size is 3 or less.") LeaderAbility::builder("Tributes","Once per turn, pay 2 mood tokens to Collect from Acamapichtli's city as a free action, if its size is 3 or less.")
.add_action_modifier(CustomActionType::Tributes,|c|c.once_per_turn().free_action().resources(ResourcePile::mood_tokens(2)),crate::playing_actions::PlayingActionType::Collect).build()) .add_action_modifier(crate::content::custom_actions::PlayingActionModifier::Tributes,|c|c.once_per_turn().free_action().resources(ResourcePile::mood_tokens(2)),crate::playing_actions::PlayingActionType::Collect).build())
} }
fn ahuitzotl() -> LeaderInfo { fn ahuitzotl() -> LeaderInfo {
LeaderInfo::new(Leader::Ahuitzotl,"Ahuitzotl", LeaderInfo::new(Leader::Ahuitzotl,"Ahuitzotl",

View file

@ -216,12 +216,8 @@ pub(crate) fn innovator(game: &mut Game, position: Position) {
let player = game.get_any_city(position).player_index; let player = game.get_any_city(position).player_index;
let p = game.player(player); let p = game.player(player);
if p.active_leader() == Some(Leader::Imhotep) && leader_position(p) == position { if p.active_leader() == Some(Leader::Imhotep) && leader_position(p) == position {
EventPlayer::from_player( EventPlayer::new(player, EventOrigin::LeaderAbility("Innovator".to_string()))
player, .gain_resources(game, ResourcePile::ideas(1));
game,
EventOrigin::LeaderAbility("Innovator".to_string()),
)
.gain_resources(game, ResourcePile::ideas(1));
} }
} }

View file

@ -9,7 +9,7 @@ use crate::combat_listeners::CombatStrength;
use crate::content::ability::AbilityBuilder; use crate::content::ability::AbilityBuilder;
use crate::content::advances::AdvanceGroup; use crate::content::advances::AdvanceGroup;
use crate::content::advances::warfare::draft_cost; use crate::content::advances::warfare::draft_cost;
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::{CustomActionType, PlayingActionModifier, SpecialAction};
use crate::content::persistent_events::{HandCardsRequest, PositionRequest}; use crate::content::persistent_events::{HandCardsRequest, PositionRequest};
use crate::events::check_event_origin; use crate::events::check_event_origin;
use crate::game::Game; use crate::game::Game;
@ -108,11 +108,13 @@ fn hellenistic_culture() -> SpecialAdvanceInfo {
"You may start Influence Culture attempts from cities containing a building in your color, including cities owned by other players. You may pay 2 mood tokens instead of the 1 culture token for Arts.", "You may start Influence Culture attempts from cities containing a building in your color, including cities owned by other players. You may pay 2 mood tokens instead of the 1 culture token for Arts.",
) )
.add_action_modifier( .add_action_modifier(
CustomActionType::HellenisticInfluenceCultureAttempt, PlayingActionModifier::HellenisticInfluenceCultureAttempt,
|c| { |c| {
c.once_per_turn_mutually_exclusive(CustomActionType::ArtsInfluenceCultureAttempt) c.once_per_turn_mutually_exclusive(SpecialAction::Modifier(
.free_action() PlayingActionModifier::ArtsInfluenceCultureAttempt,
.resources(ResourcePile::mood_tokens(2)) ))
.free_action()
.resources(ResourcePile::mood_tokens(2))
}, },
PlayingActionType::InfluenceCultureAttempt, PlayingActionType::InfluenceCultureAttempt,
) )

View file

@ -184,7 +184,7 @@ pub(crate) fn finish_city_move(game: &mut Game, player: usize, from: Position, t
Some(Terrain::Mountain) => ResourcePile::ore(1), Some(Terrain::Mountain) => ResourcePile::ore(1),
_ => ResourcePile::empty(), _ => ResourcePile::empty(),
}; };
let p = EventPlayer::from_player(player, game, origin); let p = EventPlayer::new(player, origin);
p.log(game, &format!("Moved city {from} to {to}")); p.log(game, &format!("Moved city {from} to {to}"));
if !pile.is_empty() { if !pile.is_empty() {
p.gain_resources(game, pile); p.gain_resources(game, pile);

View file

@ -10,7 +10,7 @@ use crate::combat::CombatModifier;
use crate::content::ability::{Ability, AbilityBuilder}; use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::CustomActionType;
use crate::content::persistent_events::{AdvanceRequest, PaymentRequest}; use crate::content::persistent_events::{AdvanceRequest, PaymentRequest};
use crate::cultural_influence::{InfluenceCultureInfo, resolve_influence_roll}; use crate::cultural_influence::{InfluenceCultureAttemptInfo, resolve_influence_roll};
use crate::game::Game; use crate::game::Game;
use crate::leader::{Leader, LeaderInfo}; use crate::leader::{Leader, LeaderInfo};
use crate::leader_ability::{LeaderAbility, activate_leader_city, can_activate_leader_city}; use crate::leader_ability::{LeaderAbility, activate_leader_city, can_activate_leader_city};
@ -171,7 +171,11 @@ fn sri_gupta() -> LeaderInfo {
) )
} }
pub(crate) fn buddhism_available(game: &Game, player: usize, info: &InfluenceCultureInfo) -> bool { pub(crate) fn buddhism_available(
game: &Game,
player: usize,
info: &InfluenceCultureAttemptInfo,
) -> bool {
let p = game.player(player); let p = game.player(player);
!p.event_info.contains_key(BUDDHISM) !p.event_info.contains_key(BUDDHISM)
&& p.units.iter().any(|u| { && p.units.iter().any(|u| {
@ -190,15 +194,15 @@ fn ashoka() -> LeaderInfo {
LeaderAbility::builder(BUDDHISM, LeaderAbility::builder(BUDDHISM,
"Once per turn, reroll Cultural Influence from Ashoka's city if it has a Temple or the target is a Temple.") "Once per turn, reroll Cultural Influence from Ashoka's city if it has a Temple or the target is a Temple.")
.add_bool_request( .add_bool_request(
|e| &mut e.influence_culture, 1, |e| &mut e.influence_culture_boost, 1,
|game, p, info| (info.roll < crate::consts::INFLUENCE_MIN_ROLL |game, p, info| (info.roll < crate::consts::INFLUENCE_MIN_ROLL
&& buddhism_available(game, p.index, info)) && buddhism_available(game, p.index, &info.attempt))
.then(|| format!("Buddhism · Rolled {}. Reroll?", info.roll)), .then(|| format!("Buddhism · Rolled {}. Reroll?", info.roll)),
|game, s, info| { |game, s, info| {
if s.choice { if s.choice {
let previous = info.roll; let previous = info.roll;
info.roll = game.next_dice_roll().value + info.roll_boost; info.roll = game.next_dice_roll().value + info.attempt.roll_boost;
info.info.info.insert(BUDDHISM.into(), "used".into()); info.attempt.info.info.insert(BUDDHISM.into(), "used".into());
game.player_mut(s.player_index).event_info.insert(BUDDHISM.into(), "used".into()); game.player_mut(s.player_index).event_info.insert(BUDDHISM.into(), "used".into());
s.log(game, &format!("Rerolled Cultural Influence: {previous} → {}", info.roll)); s.log(game, &format!("Rerolled Cultural Influence: {previous} → {}", info.roll));
} }

View file

@ -82,7 +82,7 @@ pub(crate) fn on_declare_card(game: &mut Game, a: CardAnnouncement) -> Result<()
if !a.shogunate && !game.cache.get_civil_card(a.card).action_type.free { if !a.shogunate && !game.cache.get_civil_card(a.card).action_type.free {
pay_action( pay_action(
game, game,
&EventPlayer::from_player(a.player, game, EventOrigin::CivilCard(a.card)), &EventPlayer::new(a.player, EventOrigin::CivilCard(a.card)),
); );
} }
PlayingAction::ActionCard(a.card).execute_without_action_cost(game, a.player) PlayingAction::ActionCard(a.card).execute_without_action_cost(game, a.player)

View file

@ -84,7 +84,7 @@ fn calendar() -> SpecialAdvanceInfo {
"As a free action, look at the next event. You may pay 1 culture token to put it at the bottom of the deck, then use Calendar again.") "As a free action, look at the next event. You may pay 1 culture token to put it at the bottom of the deck, then use Calendar again.")
.add_custom_action(CustomActionType::Calendar, |c| c.any_times().free_action().no_resources(), |b| b .add_custom_action(CustomActionType::Calendar, |c| c.any_times().free_action().no_resources(), |b| b
.add_persistent_event_listener(|e| &mut e.custom_action, 0, |game, p, _| { .add_persistent_event_listener(|e| &mut e.custom_action, 0, |game, p, _| {
let id = crate::card::draw_card_from_pile(game, "Events", |g| &mut g.incidents_left, let id = crate::card::draw_card_from_pile(game, p, "Events", |g| &mut g.incidents_left,
|g| g.cache.get_incidents().iter().map(|i| i.id).collect(), |g| g.cache.get_incidents().iter().map(|i| i.id).collect(),
|p| p.action_cards.iter().filter_map(|id| id.checked_sub(crate::content::incidents::great_persons::GREAT_PERSON_OFFSET)).collect()).expect("event deck"); |p| p.action_cards.iter().filter_map(|id| id.checked_sub(crate::content::incidents::great_persons::GREAT_PERSON_OFFSET)).collect()).expect("event deck");
game.incidents_left.insert(0, id); game.incidents_left.insert(0, id);
@ -152,6 +152,7 @@ fn influence_targets(game: &Game, p: &Player) -> Vec<SelectedStructure> {
&crate::playing_actions::PlayingActionType::InfluenceCultureAttempt, &crate::playing_actions::PlayingActionType::InfluenceCultureAttempt,
false, false,
false, false,
game.get_any_city(target.position).player_index,
Some(pos), Some(pos),
) )
.is_ok() .is_ok()

View file

@ -5,7 +5,7 @@ use crate::card::{HandCard, HandCardLocation, all_action_hand_cards, all_objecti
use crate::city::{MoodState, set_city_mood}; use crate::city::{MoodState, set_city_mood};
use crate::civilization::Civilization; use crate::civilization::Civilization;
use crate::content::ability::AbilityBuilder; use crate::content::ability::AbilityBuilder;
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::{CustomActionType, PlayingActionModifier};
use crate::content::persistent_events::{HandCardsRequest, PaymentRequest, PositionRequest}; use crate::content::persistent_events::{HandCardsRequest, PaymentRequest, PositionRequest};
use crate::game::Game; use crate::game::Game;
use crate::leader::{Leader, LeaderInfo, leader_position}; use crate::leader::{Leader, LeaderInfo, leader_position};
@ -265,7 +265,7 @@ fn caesar() -> LeaderInfo {
to increase happiness in the leader city.", to increase happiness in the leader city.",
) )
.add_action_modifier( .add_action_modifier(
CustomActionType::StatesmanIncreaseHappiness, PlayingActionModifier::StatesmanIncreaseHappiness,
|c| c.any_times().free_action().no_resources(), |c| c.any_times().free_action().no_resources(),
PlayingActionType::IncreaseHappiness, PlayingActionType::IncreaseHappiness,
) )
@ -326,9 +326,9 @@ fn sulla() -> LeaderInfo {
.add_transient_event_listener( .add_transient_event_listener(
|event| &mut event.on_influence_culture_attempt, |event| &mut event.on_influence_culture_attempt,
6, 6,
|r, city, game, _| { |r, city, game, p| {
if let Ok(info) = r if let Ok(info) = r
&& info.is_defender && info.is_defender(p.index)
&& leader_position(game.player(city.player_index)) == city.position && leader_position(game.player(city.player_index)) == city.position
{ {
*r = *r =

View file

@ -8,15 +8,15 @@ use crate::consts::STACK_LIMIT;
use crate::content::ability::{Ability, AbilityBuilder}; use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::advances::economy::use_taxes; use crate::content::advances::economy::use_taxes;
use crate::content::advances::trade_routes::TradeRoute; use crate::content::advances::trade_routes::TradeRoute;
use crate::content::custom_actions::CustomActionType; use crate::content::custom_actions::{CustomActionType, SpecialAction};
use crate::content::persistent_events::{PaymentRequest, PositionRequest, UnitsRequest}; use crate::content::persistent_events::{PaymentRequest, PositionRequest, UnitsRequest};
use crate::events::EventOrigin; use crate::events::EventOrigin;
use crate::game::Game; use crate::game::Game;
use crate::leader::{Leader, LeaderInfo, leader_position}; use crate::leader::{Leader, LeaderInfo, leader_position};
use crate::leader_ability::{LeaderAbility, activate_leader_city, can_activate_leader_city}; use crate::leader_ability::{LeaderAbility, activate_leader_city, can_activate_leader_city};
use crate::log::add_start_turn_action_if_needed; use crate::log::{ActionLogEntry, add_start_turn_action_if_needed};
use crate::map::{Block, Terrain, block_for_position, capital_city_position}; use crate::map::{Block, Terrain, block_for_position, capital_city_position};
use crate::movement::{MoveUnits, move_action_log}; use crate::movement::MoveUnits;
use crate::player::{Data, Player}; use crate::player::{Data, Player};
use crate::position::Position; use crate::position::Position;
use crate::resource::ResourceType; use crate::resource::ResourceType;
@ -223,7 +223,7 @@ pub(crate) fn lose_raid_resource() -> Ability {
.then_some(vec![PaymentRequest::mandatory(c, "Pay 1 resource")]) .then_some(vec![PaymentRequest::mandatory(c, "Pay 1 resource")])
}, },
|game, s, ()| { |game, s, ()| {
add_start_turn_action_if_needed(game); add_start_turn_action_if_needed(game, s.player_index);
s.log(game, &format!("Lose {}", s.choice[0])); s.log(game, &format!("Lose {}", s.choice[0]));
}, },
) )
@ -306,7 +306,7 @@ fn danegeld() -> LeaderAbility {
.add_custom_action( .add_custom_action(
CustomActionType::Danegeld, CustomActionType::Danegeld,
|c| { |c| {
c.once_per_turn_mutually_exclusive(CustomActionType::Taxes) c.once_per_turn_mutually_exclusive(SpecialAction::Custom(CustomActionType::Taxes))
.action() .action()
.no_resources() .no_resources()
}, },
@ -384,7 +384,8 @@ fn new_colonies() -> LeaderAbility {
.collect_vec(); .collect_vec();
let m = MoveUnits::new(units, to, None, ResourcePile::empty()); let m = MoveUnits::new(units, to, None, ResourcePile::empty());
s.log(game, &move_action_log(game, p, &m)); s.player()
.add_log_entry(game, ActionLogEntry::move_units(p, &m));
move_with_possible_combat(game, s.player_index, &m); move_with_possible_combat(game, s.player_index, &m);
}, },

View file

@ -4,7 +4,7 @@ use crate::content::ability::Ability;
use crate::content::persistent_events::{ use crate::content::persistent_events::{
PersistentEventType, TriggerPersistentEventParams, trigger_persistent_event_with_listener, PersistentEventType, TriggerPersistentEventParams, trigger_persistent_event_with_listener,
}; };
use crate::events::{EventOrigin, EventPlayer}; use crate::events::EventOrigin;
use crate::player::Player; use crate::player::Player;
use crate::playing_actions::PlayingActionType; use crate::playing_actions::PlayingActionType;
use crate::position::Position; use crate::position::Position;
@ -60,22 +60,22 @@ impl CustomActionActivation {
} }
#[derive(Clone)] #[derive(Clone)]
pub struct CustomActionInfo { pub struct SpecialActionInfo {
pub action: CustomActionType, pub action: SpecialAction,
pub execution: CustomActionExecution, pub execution: SpecialActionExecution,
pub event_origin: EventOrigin, pub event_origin: EventOrigin,
pub cost: ActionCostOncePerTurn, pub cost: ActionCostOncePerTurn,
} }
impl CustomActionInfo { impl SpecialActionInfo {
#[must_use] #[must_use]
pub fn new( pub fn new(
action: CustomActionType, action: SpecialAction,
execution: CustomActionExecution, execution: SpecialActionExecution,
event_origin: EventOrigin, event_origin: EventOrigin,
cost: ActionCostOncePerTurn, cost: ActionCostOncePerTurn,
) -> CustomActionInfo { ) -> SpecialActionInfo {
CustomActionInfo { SpecialActionInfo {
action, action,
execution, execution,
event_origin, event_origin,
@ -90,12 +90,36 @@ impl CustomActionInfo {
#[must_use] #[must_use]
pub fn city_bound(&self) -> Option<&CustomActionCityChecker> { pub fn city_bound(&self) -> Option<&CustomActionCityChecker> {
if let CustomActionExecution::Action(a) = &self.execution { if let SpecialActionExecution::Action(a) = &self.execution {
a.city_checker.as_ref() a.city_checker.as_ref()
} else { } else {
None None
} }
} }
///
/// # Panics
/// Panics if not a modifier action
#[must_use]
pub fn custom_action_type(&self) -> CustomActionType {
if let SpecialAction::Custom(c) = self.action {
c
} else {
panic!("Not a custom action")
}
}
///
/// # Panics
/// Panics if not a modifier action
#[must_use]
pub fn modifier_action_type(&self) -> PlayingActionType {
if let SpecialAction::Modifier(m) = self.action {
m.playing_action_type()
} else {
panic!("Not a modifier action")
}
}
} }
type CustomActionChecker = Arc<dyn Fn(&Game, &Player) -> bool + Sync + Send>; type CustomActionChecker = Arc<dyn Fn(&Game, &Player) -> bool + Sync + Send>;
@ -124,11 +148,54 @@ impl CustomActionActionExecution {
} }
#[derive(Clone)] #[derive(Clone)]
pub enum CustomActionExecution { pub enum SpecialActionExecution {
Modifier(PlayingActionType), Modifier(PlayingActionType),
Action(CustomActionActionExecution), Action(CustomActionActionExecution),
} }
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum SpecialAction {
Modifier(PlayingActionModifier),
Custom(CustomActionType),
}
impl SpecialAction {
#[must_use]
pub fn playing_action_type(&self) -> PlayingActionType {
match self {
SpecialAction::Modifier(m) => m.playing_action_type(),
SpecialAction::Custom(c) => c.playing_action_type(),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum PlayingActionModifier {
Tributes,
// Advances
ArtsInfluenceCultureAttempt,
FreeEconomyCollect,
VotingIncreaseHappiness,
// Update patch Advances
CityPlanning,
Philosophy,
// Civilizations,
// Rome
StatesmanIncreaseHappiness,
// Greece
HellenisticInfluenceCultureAttempt,
}
impl PlayingActionModifier {
#[must_use]
pub fn playing_action_type(&self) -> PlayingActionType {
PlayingActionType::Special(SpecialAction::Modifier(*self))
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Hash, Debug)] #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum CustomActionType { pub enum CustomActionType {
// Advances // Advances
@ -136,16 +203,11 @@ pub enum CustomActionType {
ForcedLabor, ForcedLabor,
CivilLiberties, CivilLiberties,
Bartering, Bartering,
ArtsInfluenceCultureAttempt,
VotingIncreaseHappiness,
FreeEconomyCollect,
Sports, Sports,
Taxes, Taxes,
Theaters, Theaters,
// Update patch Advances // Update patch Advances
CityPlanning,
Philosophy,
WelfareState, WelfareState,
ForcedMarch, ForcedMarch,
MilitaryState, MilitaryState,
@ -160,10 +222,8 @@ pub enum CustomActionType {
// Rome // Rome
Aqueduct, Aqueduct,
Princeps, Princeps,
StatesmanIncreaseHappiness,
// Greece // Greece
HellenisticInfluenceCultureAttempt,
Idol, Idol,
Master, Master,
@ -198,7 +258,6 @@ pub enum CustomActionType {
TribalAllies, TribalAllies,
SpreadOfFear, SpreadOfFear,
MassSacrifice, MassSacrifice,
Tributes,
Hegemony, Hegemony,
HegemonyFounder, HegemonyFounder,
Founder, Founder,
@ -209,21 +268,7 @@ pub enum CustomActionType {
impl CustomActionType { impl CustomActionType {
#[must_use] #[must_use]
pub fn playing_action_type(&self) -> PlayingActionType { pub fn playing_action_type(&self) -> PlayingActionType {
PlayingActionType::Custom(*self) PlayingActionType::Special(SpecialAction::Custom(*self))
}
}
pub(crate) fn log_start_custom_action(game: &mut Game, player_index: usize, action: &CustomAction) {
let p = game.player(player_index);
let player = EventPlayer::from_player(
player_index,
game,
action.action.playing_action_type().origin(p),
);
if let Some(city) = action.city {
player.log(game, &format!("Start action in city {city}"));
} else {
player.log(game, "Start action");
} }
} }
@ -250,8 +295,11 @@ pub(crate) fn custom_action_execution(
player: &Player, player: &Player,
action_type: CustomActionType, action_type: CustomActionType,
) -> Option<CustomActionActionExecution> { ) -> Option<CustomActionActionExecution> {
if let CustomActionExecution::Action(e) = if let SpecialActionExecution::Action(e) = player
player.custom_actions.get(&action_type)?.execution.clone() .special_actions
.get(&SpecialAction::Custom(action_type))?
.execution
.clone()
{ {
Some(e) Some(e)
} else { } else {
@ -259,23 +307,23 @@ pub(crate) fn custom_action_execution(
} }
} }
pub(crate) fn can_play_custom_action( pub(crate) fn can_play_special_action(
game: &Game, game: &Game,
p: &Player, p: &Player,
c: CustomActionType, c: SpecialAction,
) -> Result<(), String> { ) -> Result<(), String> {
if !p.custom_actions.contains_key(&c) { if !p.special_actions.contains_key(&c) {
return Err("Custom action not available".to_string()); return Err("Custom action not available".to_string());
} }
let info = p.custom_action_info(c); let info = p.special_action_info(&c);
if let Some(key) = info.cost.once_per_turn if let Some(key) = info.cost.once_per_turn
&& p.played_once_per_turn_actions.contains(&key) && p.played_once_per_turn_actions.contains(&key)
{ {
return Err("Custom action already played this turn".to_string()); return Err("Custom action already played this turn".to_string());
} }
if let CustomActionExecution::Action(e) = &info.execution if let SpecialActionExecution::Action(e) = &info.execution
&& !(e.checker)(game, p) && !(e.checker)(game, p)
{ {
return Err("Custom action cannot be played".to_string()); return Err("Custom action cannot be played".to_string());
@ -296,8 +344,11 @@ pub(crate) fn is_base_or_modifier(
base_type: &PlayingActionType, base_type: &PlayingActionType,
) -> bool { ) -> bool {
match base_type { match base_type {
PlayingActionType::Custom(c) => { PlayingActionType::Special(SpecialAction::Modifier(c)) => {
if let CustomActionExecution::Modifier(t) = &p.custom_action_info(*c).execution { if let SpecialActionExecution::Modifier(t) = &p
.special_action_info(&SpecialAction::Modifier(*c))
.execution
{
t == action_type t == action_type
} else { } else {
false false
@ -312,7 +363,7 @@ pub(crate) fn custom_action_modifier_event_origin(
action_type: &PlayingActionType, action_type: &PlayingActionType,
player: &Player, player: &Player,
) -> EventOrigin { ) -> EventOrigin {
if let PlayingActionType::Custom(c) = action_type { if let PlayingActionType::Special(SpecialAction::Modifier(c)) = action_type {
c.playing_action_type().origin(player) c.playing_action_type().origin(player)
} else { } else {
base_action_origin base_action_origin

View file

@ -275,7 +275,7 @@ fn envoy() -> Incident {
|_p, _, _| true, |_p, _, _| true,
0, 0,
|game, s, _| { |game, s, _| {
s.other_player(s.choice, game) s.other_player(s.choice)
.gain_resources(game, ResourcePile::culture_tokens(1)); .gain_resources(game, ResourcePile::culture_tokens(1));
}, },
) )

View file

@ -204,7 +204,7 @@ fn destroy_building(game: &mut Game, b: Building, position: Position, origin: &E
let o = game.player_mut(owner); let o = game.player_mut(owner);
o.gain_event_victory_points(2.0, origin); o.gain_event_victory_points(2.0, origin);
o.destroyed_structures.add_building(b); o.destroyed_structures.add_building(b);
let player = EventPlayer::from_player(city_owner, game, origin.clone()); let player = EventPlayer::new(city_owner, origin.clone());
lose_building(game, &player, b, position); lose_building(game, &player, b, position);
game.log( game.log(
owner, owner,
@ -219,11 +219,7 @@ fn destroy_wonder_for_points(
wonder: Wonder, wonder: Wonder,
origin: &EventOrigin, origin: &EventOrigin,
) { ) {
let p = &EventPlayer::from_player( let p = &EventPlayer::new(game.get_any_city(position).player_index, origin.clone());
game.get_any_city(position).player_index,
game,
origin.clone(),
);
destroy_wonder(game, p, wonder, position); destroy_wonder(game, p, wonder, position);
let a = wonder.info(game).owned_victory_points; let a = wonder.info(game).owned_victory_points;

View file

@ -7,6 +7,7 @@ use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::UnitsRequest; use crate::content::persistent_events::UnitsRequest;
use crate::game::Game; use crate::game::Game;
use crate::incident::{DecreaseMood, Incident, IncidentBaseEffect, MoodModifier}; use crate::incident::{DecreaseMood, Incident, IncidentBaseEffect, MoodModifier};
use crate::log::ActionLogBalance;
use crate::player::Player; use crate::player::Player;
use crate::player_events::IncidentTarget; use crate::player_events::IncidentTarget;
use crate::playing_actions::PlayingActionType; use crate::playing_actions::PlayingActionType;
@ -219,7 +220,7 @@ pub(crate) fn famine(
// only avoid anger if full amount is paid // only avoid anger if full amount is paid
i.player.payment = ResourcePile::food(lost); i.player.payment = ResourcePile::food(lost);
} }
player.lose_resources(game, ResourcePile::food(lost)); player.lose_resources(game, ResourcePile::food(lost), ActionLogBalance::Loss);
player.log(game, &format!("Lost {lost} food",)); player.log(game, &format!("Lost {lost} food",));
}) })

View file

@ -147,7 +147,7 @@ fn good_year(mut builder: IncidentBuilder, amount: u8, good_year_type: &GoodYear
|p, _, _| p.resources.food < p.resource_limit.food, |p, _, _| p.resources.food < p.resource_limit.food,
i as i32, i as i32,
move |game, s, _| { move |game, s, _| {
s.other_player(s.choice, game) s.other_player(s.choice)
.gain_resources(game, ResourcePile::food(1)); .gain_resources(game, ResourcePile::food(1));
}, },
); );

View file

@ -7,9 +7,8 @@ use crate::content::ability::Ability;
use crate::content::advances::AdvanceGroup; use crate::content::advances::AdvanceGroup;
use crate::content::effects::ConstructEffect; use crate::content::effects::ConstructEffect;
use crate::content::effects::PermanentEffect::Construct; use crate::content::effects::PermanentEffect::Construct;
use crate::content::incidents::great_persons::{ use crate::content::incidents::great_persons::GreatPersonType;
GREAT_PERSON_DESCRIPTION, great_person_action_card, great_person_description, use crate::content::incidents::great_persons::{great_person_card, tech_great_person_description};
};
use crate::content::persistent_events::HandCardsRequest; use crate::content::persistent_events::HandCardsRequest;
use crate::game::Game; use crate::game::Game;
use crate::player::Player; use crate::player::Player;
@ -21,13 +20,14 @@ use crate::wonder::{Wonder, WonderCardInfo, cities_for_wonder, on_play_wonder_ca
pub(crate) fn great_engineer() -> ActionCard { pub(crate) fn great_engineer() -> ActionCard {
let groups = vec![AdvanceGroup::Construction]; let groups = vec![AdvanceGroup::Construction];
great_person_action_card( great_person_card(
26, 26,
GreatPersonType::ActionCard,
"Great Engineer", "Great Engineer",
&format!( &format!(
"{} Then, you may construct a building in one of your cities. \ "{} Then, you may construct a building in one of your cities. \
Pay its normal resource cost, without spending an additional action or activating the city.", Pay its normal resource cost, without spending an additional action or activating the city.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -118,14 +118,13 @@ pub(crate) fn construct_only() -> Ability {
} }
pub(crate) fn great_architect() -> ActionCard { pub(crate) fn great_architect() -> ActionCard {
great_person_action_card::<_>( great_person_card::<_>(
55, 55,
GreatPersonType::Public,
"Great Architect", "Great Architect",
&format!( "When constructing a wonder, you may ignore \
"{GREAT_PERSON_DESCRIPTION} When constructing a wonder, you may ignore \ the requirement advances (but not Engineering). \
the requirement advances (but not Engineering). \ In addition, the cost of constructing the wonder is reduced by 3 culture tokens.",
In addition, the cost of constructing the wonder is reduced by 3 culture tokens.",
),
|c| c.free_action().no_resources(), |c| c.free_action().no_resources(),
vec![], vec![],
|game, player| !playable_wonders(game, player).is_empty(), |game, player| !playable_wonders(game, player).is_empty(),

View file

@ -2,9 +2,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::ActionCard; use crate::action_card::ActionCard;
use crate::content::ability::Ability; use crate::content::ability::Ability;
use crate::content::effects::PermanentEffect; use crate::content::effects::PermanentEffect;
use crate::content::incidents::great_persons::{ use crate::content::incidents::great_persons::{GreatPersonType, great_person_card};
GREAT_PERSON_DESCRIPTION, great_person_action_card,
};
use crate::game::Game; use crate::game::Game;
use crate::incident::IncidentBuilder; use crate::incident::IncidentBuilder;
use crate::player_events::IncidentTarget; use crate::player_events::IncidentTarget;
@ -14,15 +12,14 @@ use serde::{Deserialize, Serialize};
pub(crate) const DIPLOMAT_ID: u8 = 57; pub(crate) const DIPLOMAT_ID: u8 = 57;
pub(crate) fn great_diplomat() -> ActionCard { pub(crate) fn great_diplomat() -> ActionCard {
great_person_action_card::<_>( great_person_card::<_>(
DIPLOMAT_ID, DIPLOMAT_ID,
GreatPersonType::Public,
"Great Diplomat", "Great Diplomat",
&format!( "Choose another player. \
"{GREAT_PERSON_DESCRIPTION} Choose another player. \ You cannot attack each other, unless you pay 2 culture tokens. \
You cannot attack each other, unless you pay 2 culture tokens. \ Discard this card if either player attacks the other. \
Discard this card if either player attacks the other. \ You may discard the card as a regular action.",
You may discard the card as a regular action.",
),
// action for ending diplomatic relations // action for ending diplomatic relations
|c| c.action().no_resources(), |c| c.action().no_resources(),
vec![], vec![],

View file

@ -3,7 +3,7 @@ use crate::action_card::{ActionCard, ActionCardBuilder};
use crate::city::{found_city, is_valid_city_terrain}; use crate::city::{found_city, is_valid_city_terrain};
use crate::content::advances::AdvanceGroup; use crate::content::advances::AdvanceGroup;
use crate::content::incidents::great_persons::{ use crate::content::incidents::great_persons::{
great_person_action_card, great_person_description, GreatPersonType, great_person_card, tech_great_person_description,
}; };
use crate::content::persistent_events::{PaymentRequest, PositionRequest}; use crate::content::persistent_events::{PaymentRequest, PositionRequest};
use crate::events::{EventOrigin, EventPlayer, check_event_origin}; use crate::events::{EventOrigin, EventPlayer, check_event_origin};
@ -18,14 +18,15 @@ use itertools::Itertools;
pub(crate) fn great_explorer() -> ActionCard { pub(crate) fn great_explorer() -> ActionCard {
let groups = vec![AdvanceGroup::Seafaring]; let groups = vec![AdvanceGroup::Seafaring];
let mut builder = great_person_action_card( let mut builder = great_person_card(
18, 18,
GreatPersonType::ActionCard,
"Great Explorer", "Great Explorer",
&format!( &format!(
"{} Then, you may explore a region adjacent to a region \ "{} Then, you may explore a region adjacent to a region \
where you have a city. If you do, you may found a city in the explored region,\ where you have a city. If you do, you may found a city in the explored region,\
without using a Settler.", without using a Settler.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,

View file

@ -33,6 +33,25 @@ pub(crate) const GREAT_PERSON_DESCRIPTION: &str = "You may take the Event Card t
hand for 1 culture token. If you pass, any other player (in player order) may take it \ hand for 1 culture token. If you pass, any other player (in player order) may take it \
for 2 culture tokens: Action card: "; for 2 culture tokens: Action card: ";
pub(crate) const PUBLIC_GREAT_PERSON_DESCRIPTION: &str = "You make place the Event Card in front \
of you 1 culture token. If you pass, any other player (in player order) may do so \
for 2 culture tokens: ";
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum GreatPersonType {
ActionCard,
Public,
}
impl GreatPersonType {
pub fn description(&self) -> &str {
match self {
GreatPersonType::ActionCard => GREAT_PERSON_DESCRIPTION,
GreatPersonType::Public => PUBLIC_GREAT_PERSON_DESCRIPTION,
}
}
}
pub(crate) fn great_person_incidents() -> Vec<Incident> { pub(crate) fn great_person_incidents() -> Vec<Incident> {
vec![ vec![
incident(IncidentBaseEffect::ExhaustedLand, great_explorer(), |b| b), incident(IncidentBaseEffect::ExhaustedLand, great_explorer(), |b| b),
@ -130,8 +149,9 @@ fn incident(
on_gain(b).build() on_gain(b).build()
} }
pub(crate) fn great_person_action_card<F>( pub(crate) fn great_person_card<F>(
incident_id: u8, incident_id: u8,
great_person_type: GreatPersonType,
name: &str, name: &str,
description: &str, description: &str,
cost: impl Fn(ActionCostBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static, cost: impl Fn(ActionCostBuilder) -> ActionCostOncePerTurn + Send + Sync + 'static,
@ -144,10 +164,11 @@ where
ActionCard::builder( ActionCard::builder(
incident_id + GREAT_PERSON_OFFSET, incident_id + GREAT_PERSON_OFFSET,
name, name,
description, &format!("{}{}", great_person_type.description(), description),
cost, cost,
move |game, player, _| can_play(game, player), move |game, player, _| can_play(game, player),
) )
.public(great_person_type == GreatPersonType::Public)
.add_advance_request( .add_advance_request(
|e| &mut e.play_action_card, |e| &mut e.play_action_card,
10, 10,
@ -169,12 +190,13 @@ where
fn great_artist() -> ActionCard { fn great_artist() -> ActionCard {
let groups = vec![AdvanceGroup::Culture]; let groups = vec![AdvanceGroup::Culture];
great_person_action_card( great_person_card(
19, 19,
GreatPersonType::ActionCard,
"Great Artist", "Great Artist",
&format!( &format!(
"{} Then, you make one of your cities Happy.", "{} Then, you make one of your cities Happy.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -206,12 +228,13 @@ fn great_artist() -> ActionCard {
fn great_prophet() -> ActionCard { fn great_prophet() -> ActionCard {
let groups = vec![AdvanceGroup::Spirituality]; let groups = vec![AdvanceGroup::Spirituality];
great_person_action_card( great_person_card(
20, 20,
GreatPersonType::ActionCard,
"Great Prophet", "Great Prophet",
&format!( &format!(
"{} Then, you build a Temple without activating the city.", "{} Then, you build a Temple without activating the city.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -293,9 +316,9 @@ fn temple_cost(game: &Game, player: &Player) -> PaymentOptions {
.cost .cost
} }
pub(crate) fn great_person_description(free_advance_groups: &[AdvanceGroup]) -> String { pub(crate) fn tech_great_person_description(free_advance_groups: &[AdvanceGroup]) -> String {
format!( format!(
"{GREAT_PERSON_DESCRIPTION} You may advance \ "You may advance \
in any {} technology for free and without changing the Game Event counter.", in any {} technology for free and without changing the Game Event counter.",
format_list( format_list(
&free_advance_groups &free_advance_groups
@ -310,10 +333,14 @@ pub(crate) fn great_person_description(free_advance_groups: &[AdvanceGroup]) ->
fn great_philosopher() -> ActionCard { fn great_philosopher() -> ActionCard {
let groups = vec![AdvanceGroup::Education]; let groups = vec![AdvanceGroup::Education];
great_person_action_card( great_person_card(
21, 21,
GreatPersonType::ActionCard,
"Great Philosopher", "Great Philosopher",
&format!("{} Then, gain 2 ideas.", great_person_description(&groups)), &format!(
"{} Then, gain 2 ideas.",
tech_great_person_description(&groups)
),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
|_game, _player| true, |_game, _player| true,
@ -330,12 +357,13 @@ fn great_philosopher() -> ActionCard {
fn great_scientist() -> ActionCard { fn great_scientist() -> ActionCard {
let groups = vec![AdvanceGroup::Science]; let groups = vec![AdvanceGroup::Science];
great_person_action_card( great_person_card(
22, 22,
GreatPersonType::ActionCard,
"Great Scientist", "Great Scientist",
&format!( &format!(
"{} Then, gain 1 idea and 1 Action Card.", "{} Then, gain 1 idea and 1 Action Card.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -357,12 +385,13 @@ fn elder_statesman() -> ActionCard {
.into_iter() .into_iter()
.map(|a| a.advance_group) .map(|a| a.advance_group)
.collect_vec(); .collect_vec();
great_person_action_card( great_person_card(
23, 23,
GreatPersonType::ActionCard,
"Elder Statesman", "Elder Statesman",
&format!( &format!(
"{} Then, draw 2 Action Cards.", "{} Then, draw 2 Action Cards.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -382,12 +411,13 @@ fn elder_statesman() -> ActionCard {
fn great_merchant() -> ActionCard { fn great_merchant() -> ActionCard {
let groups = vec![AdvanceGroup::Economy]; let groups = vec![AdvanceGroup::Economy];
economy::add_trade_routes( economy::add_trade_routes(
great_person_action_card( great_person_card(
25, 25,
GreatPersonType::ActionCard,
"Great Merchant", "Great Merchant",
&format!( &format!(
"{} Then, if you have the Trade Routes advance, gain the Trade Routes income.", "{} Then, if you have the Trade Routes advance, gain the Trade Routes income.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -400,12 +430,13 @@ fn great_merchant() -> ActionCard {
fn great_athlete() -> ActionCard { fn great_athlete() -> ActionCard {
let groups = vec![AdvanceGroup::Culture]; let groups = vec![AdvanceGroup::Culture];
great_person_action_card( great_person_card(
56, 56,
GreatPersonType::ActionCard,
"Great Athlete", "Great Athlete",
&format!( &format!(
"{} Then, you may convert any amount of culture tokens to mood tokens or vice versa.", "{} Then, you may convert any amount of culture tokens to mood tokens or vice versa.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,
@ -475,15 +506,14 @@ fn great_athlete() -> ActionCard {
} }
fn great_seer() -> ActionCard { fn great_seer() -> ActionCard {
let mut b = great_person_action_card::<_>( let mut b = great_person_card::<_>(
58, 58,
GreatPersonType::ActionCard,
"Great Seer", "Great Seer",
&format!( "Draw 1 objective card per player. \
"{GREAT_PERSON_DESCRIPTION} Draw 1 objective card per player. \ Choose one for each player, including yourself. \
Choose one for each player, including yourself. \ The next time the player draws an objective card from the pile, \
The next time the player draws an objective card from the pile, \ they draw the designated card instead.",
they draw the designated card instead.",
),
|c| c.action().no_resources(), |c| c.action().no_resources(),
vec![], vec![],
|_game, _player| true, |_game, _player| true,

View file

@ -4,7 +4,7 @@ use crate::combat::CombatModifier;
use crate::content::ability::Ability; use crate::content::ability::Ability;
use crate::content::advances::AdvanceGroup; use crate::content::advances::AdvanceGroup;
use crate::content::incidents::great_persons::{ use crate::content::incidents::great_persons::{
great_person_action_card, great_person_description, GreatPersonType, great_person_card, tech_great_person_description,
}; };
use crate::game::GameState; use crate::game::GameState;
use crate::game::GameState::Movement; use crate::game::GameState::Movement;
@ -13,13 +13,14 @@ use std::mem;
pub(crate) fn great_warlord() -> ActionCard { pub(crate) fn great_warlord() -> ActionCard {
let groups = vec![AdvanceGroup::Warfare]; let groups = vec![AdvanceGroup::Warfare];
great_person_action_card( great_person_card(
24, 24,
GreatPersonType::ActionCard,
"Great Warlord", "Great Warlord",
&format!( &format!(
"{} Then, gain a Move action. On the first battle you fight, \ "{} Then, gain a Move action. On the first battle you fight, \
gain 2 combat value in every round.", gain 2 combat value in every round.",
great_person_description(&groups) tech_great_person_description(&groups)
), ),
|c| c.action().no_resources(), |c| c.action().no_resources(),
groups, groups,

View file

@ -63,7 +63,11 @@ fn pandemics() -> Incident {
|game, p, i| { |game, p, i| {
let player = p.get(game); let player = p.get(game);
Some(HandCardsRequest::new( Some(HandCardsRequest::new(
hand_cards(player, &[HandCardType::Action, HandCardType::Objective]), hand_cards(
player,
&[HandCardType::Action, HandCardType::Objective],
game,
),
PandemicsContributions::range(player, i, 1), PandemicsContributions::range(player, i, 1),
"Select cards to lose (or select resources instead later)", "Select cards to lose (or select resources instead later)",
)) ))

View file

@ -1,3 +1,4 @@
use crate::log::ActionLogBalance;
use crate::objective_card::{Objective, ObjectiveProgress}; use crate::objective_card::{Objective, ObjectiveProgress};
use crate::resource::ResourceType; use crate::resource::ResourceType;
use crate::resource_pile::ResourcePile; use crate::resource_pile::ResourcePile;
@ -66,7 +67,7 @@ pub(crate) fn pay_resources(
.collect() .collect()
}) })
.status_phase_update(move |game, player| { .status_phase_update(move |game, player| {
player.lose_resources(game, pay.clone()); player.lose_resources(game, pay.clone(), ActionLogBalance::Pay);
player.log(game, &format!("Pay {pay} for {objective}",)); player.log(game, &format!("Pay {pay} for {objective}",));
}) })
.build() .build()

View file

@ -10,10 +10,11 @@ use crate::combat_stats::CombatStats;
use crate::construct::ConstructInfo; use crate::construct::ConstructInfo;
pub use crate::content::civilizations::aztecs::Captive; pub use crate::content::civilizations::aztecs::Captive;
use crate::content::custom_actions::CustomActionActivation; use crate::content::custom_actions::CustomActionActivation;
use crate::cultural_influence::InfluenceCultureInfo; use crate::cultural_influence::InfluenceCultureBoostInfo;
use crate::events::EventOrigin; use crate::events::EventOrigin;
use crate::explore::ExploreResolutionState; use crate::explore::ExploreResolutionState;
use crate::game::Game; use crate::game::Game;
use crate::log::ActionLogItem;
use crate::map::Rotation; use crate::map::Rotation;
use crate::objective_card::{SelectObjectivesInfo, present_instant_objective_cards}; use crate::objective_card::{SelectObjectivesInfo, present_instant_objective_cards};
use crate::payment::{PaymentOptions, ResourceReward}; use crate::payment::{PaymentOptions, ResourceReward};
@ -104,7 +105,7 @@ impl PersistentEventPlayer {
pub enum PersistentEventType { pub enum PersistentEventType {
Collect(CollectInfo), Collect(CollectInfo),
ExploreResolution(ExploreResolutionState), ExploreResolution(ExploreResolutionState),
InfluenceCulture(InfluenceCultureInfo), InfluenceCultureBoost(InfluenceCultureBoostInfo),
UnitsKilled(KilledUnits), UnitsKilled(KilledUnits),
CombatStart(Combat), CombatStart(Combat),
CombatRoundStart(CombatRoundStart), CombatRoundStart(CombatRoundStart),
@ -371,7 +372,7 @@ impl EventResponse {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TriggerPersistentEventParams<V> { pub struct TriggerPersistentEventParams<V> {
pub log: Option<String>, pub log: Option<ActionLogItem>,
pub next_player: fn(&mut V) -> (), pub next_player: fn(&mut V) -> (),
pub origin_override: Option<EventOrigin>, pub origin_override: Option<EventOrigin>,
} }
@ -416,7 +417,7 @@ where
.is_none_or(|s| s.event_type != current_event_type) .is_none_or(|s| s.event_type != current_event_type)
{ {
if let Some(log) = params.log { if let Some(log) = params.log {
game.add_info_log_item(&log); game.add_log_item(log);
} }
game.events.push(PersistentEventState::new( game.events.push(PersistentEventState::new(
players[0], players[0],

Some files were not shown because too many files have changed in this diff Show more