Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6137923ca1 | ||
|
|
f59e461405 | ||
|
|
fb58dfb4ae | ||
|
|
2d0e605dfa | ||
|
|
0eb407ead5 | ||
|
|
c6be0cac7a | ||
|
|
e4a6e05cf3 | ||
|
|
a3ec1501e4 | ||
|
|
071430865f | ||
|
|
849e735ed0 | ||
|
|
ae1344d2ec | ||
|
|
c08272fb4a | ||
|
|
5c0f80247f | ||
|
|
841b561fd8 | ||
|
|
1c3c65ce17 | ||
|
|
d29be382f6 | ||
|
|
bab4442e66 | ||
|
|
3f446e1e60 | ||
|
|
16228fe3b7 | ||
|
|
e68ef34fe0 | ||
|
|
0563dd8c63 | ||
|
|
6e9af2a2f3 | ||
|
|
be24e58b6e | ||
|
|
4ef6679129 | ||
|
|
4ede6a1ee3 | ||
|
|
bcaa0f859a | ||
|
|
c1c34d2b71 | ||
|
|
810dc49cc6 | ||
|
|
c78a8b0d6f | ||
|
|
41462e44e1 | ||
|
|
fe182d6798 | ||
|
|
1bcea6743e | ||
|
|
e13d058f4b | ||
|
|
0a77c3a208 | ||
|
|
27f07b0be5 | ||
|
|
03e12f6f5c | ||
|
|
6e16717697 | ||
|
|
5cdce98f72 | ||
|
|
cab748037a | ||
|
|
e41c7c46dc | ||
|
|
1b7550061d |
@@ -0,0 +1,7 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.jar binary
|
||||||
|
*.png binary
|
||||||
|
*.webp binary
|
||||||
|
*.ogg binary
|
||||||
|
*.jks binary
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Something doesn't work as expected
|
||||||
|
title: "[Bug] "
|
||||||
|
---
|
||||||
|
|
||||||
|
**What happened**
|
||||||
|
|
||||||
|
|
||||||
|
**Steps to reproduce**
|
||||||
|
|
||||||
|
1.
|
||||||
|
2.
|
||||||
|
3.
|
||||||
|
|
||||||
|
**What you expected**
|
||||||
|
|
||||||
|
|
||||||
|
**Environment**
|
||||||
|
|
||||||
|
- App version:
|
||||||
|
- Installed from: Gitea / F-Droid
|
||||||
|
- Device and Android version:
|
||||||
|
- Mode: vs AI / puzzles / openings / Bluetooth / LAN
|
||||||
|
|
||||||
|
**Screenshots or logs** (optional)
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea that fits the app
|
||||||
|
title: "[Feature] "
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- Please check the "Out of scope" list in CONTRIBUTING.md before opening this. -->
|
||||||
|
|
||||||
|
**What problem does this solve**
|
||||||
|
|
||||||
|
|
||||||
|
**Proposed solution**
|
||||||
|
|
||||||
|
|
||||||
|
**Alternatives you considered**
|
||||||
|
|
||||||
|
|
||||||
|
- [ ] I'd like to implement this myself
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
name: Puzzle or opening issue
|
||||||
|
about: Report a wrong puzzle solution or opening line
|
||||||
|
title: "[Content] "
|
||||||
|
---
|
||||||
|
|
||||||
|
- Puzzle or opening name:
|
||||||
|
- Position (describe or attach a screenshot):
|
||||||
|
- What the app expects:
|
||||||
|
- What you think is correct, and why:
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
name: Translation fix
|
||||||
|
about: Report a wrong or awkward translation
|
||||||
|
title: "[Translation] "
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- Supported languages: English, Russian, German, Japanese, Lithuanian, Chinese. New languages are not accepted. -->
|
||||||
|
|
||||||
|
- Language:
|
||||||
|
- Screen or place in the app:
|
||||||
|
- Current text:
|
||||||
|
- Suggested text:
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
## What does this change
|
||||||
|
|
||||||
|
|
||||||
|
## Related issue
|
||||||
|
|
||||||
|
Closes #
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] Discussed in an issue first (not needed for small fixes)
|
||||||
|
- [ ] `./gradlew assembleDebug` and `./gradlew testDebugUnitTest` pass
|
||||||
|
- [ ] Tested on a device or emulator (Android version: )
|
||||||
|
- [ ] Multiplayer changes tested on two physical devices
|
||||||
|
- [ ] No ads, analytics, trackers or Google Play Services / Firebase dependencies
|
||||||
|
- [ ] New strings added to `values/strings.xml` (missing translations noted below)
|
||||||
|
- [ ] Screenshots added for UI changes
|
||||||
|
- [ ] I agree that my contribution is licensed under GPL-3.0-or-later
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
|
|
||||||
All notable builds of Matewave are tracked here. `v1.0.42` is the current, official latest build. `v1.0.32`-`v1.0.36` and `v1.0.38`-`v1.0.42` have no recoverable build timestamp (reproducible builds normalize internal timestamps).
|
|
||||||
|
|
||||||
| Version | Build date (UTC) | APK | Size | SHA-256 |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| v1.0.42 | unknown | [`Matewawe-v1.0.42.apk`](https://github.com/kalarina-bit/Matewave/releases/download/1.0.42/Matewawe-v1.0.42.apk) | 3.04 MB | `d918de53e530096f7a0422a89a7e7bae44672daa1e7565d6b8f1044a1a4e130b` |
|
|
||||||
| v1.0.41 | unknown | [`Matewawe-v1.0.41.apk`](https://github.com/kalarina-bit/Matewave/releases/download/1.0.41/Matewawe-v1.0.41.apk) | 3.06 MB | `a42d4ba8fa394ae882c6de1378a9dcc862dba93b17498ddcf93ae59ca38dd2f5` |
|
|
||||||
| v1.0.40 | unknown | [`Matewawe-v1.0.40.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.40/Matewawe-v1.0.40.apk) | 3.11 MB | `df012e092a58a78174696b680a5e97450cc83c505281ddc2f8fe2ac2bd2c38c2` |
|
|
||||||
| v1.0.39 | unknown | [`Matewawe-v1.0.39.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.39/Matewawe-v1.0.39.apk) | 2.54 MB | `ba4a714f069b4948cf3ba7bdb1203543147f1e31ed9ecd9217d2caa12ada4052` |
|
|
||||||
| v1.0.38 | unknown | [`Matewawe-v1.0.38.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.38/Matewawe-v1.0.38.apk) | 2.23 MB | `1e528a920de91863f5daf1dca6fbf26b20e56f5e7192ad6c3e2acb9a620f8b05` |
|
|
||||||
| v1.0.37 | 2026-09-26 14:47:58 | [`Matewawe-v1.0.37.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.37/Matewawe-v1.0.37.apk) | 2.22 MB | `2bea8aa9307b4c6e4d12cf577879941fe98c262cf63fd173445bb69ba782b9a1` |
|
|
||||||
| v1.0.36 | unknown | [`Matewawe-v1.0.36.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.36/Matewawe-v1.0.36.apk) | 12.93 MB | `78915408540e257ab7867f4314a44042c8f8a18775c4f60bc0b7368c1410f987` |
|
|
||||||
| v1.0.35 | unknown | [`Matewawe-v1.0.35.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.35/Matewawe-v1.0.35.apk) | 13.70 MB | `6bf23265107666816833b7a1cf6aabf5212068b1af315d64f9631798c84790c6` |
|
|
||||||
| v1.0.34 | unknown | [`Matewawe-v1.0.34.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.34/Matewawe-v1.0.34.apk) | 13.70 MB | `22fe9d93da9e6db4899b7c1238d2934ce9ce4de292a0bc5e97ce11df4ac52091` |
|
|
||||||
| v1.0.33 | unknown | [`Matewawe-v1.0.33.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.33/Matewawe-v1.0.33.apk) | 13.70 MB | `be579a82b2257181ff308b0ad3912af51fc1ce32f4aec036a7685da360594e38` |
|
|
||||||
| v1.0.32 | unknown | [`Matewawe-v1.0.32.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.32/Matewawe-v1.0.32.apk) | 13.70 MB | `7100c6d6e2a158c802a720393479b3b0d40186352e0d54dc951846dbe812d929` |
|
|
||||||
| v1.0.31 | 2026-09-26 14:18:46 | [`Matewawe-v1.0.31.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.31/Matewawe-v1.0.31.apk) | 2.20 MB | `801357eaf576c4f7641c709339079886f17f36a1003534e5e2598b61a563df15` |
|
|
||||||
| v1.0.30 | 2026-09-26 14:18:44 | [`Matewawe-v1.0.30.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.30/Matewawe-v1.0.30.apk) | 2.22 MB | `d3a032d83f131cac55c196b5dcba864576c4502fd3303fc5a48945d988369952` |
|
|
||||||
| v1.0.29 | 2026-09-26 14:17:16 | [`Matewawe-v1.0.29.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.29/Matewawe-v1.0.29.apk) | 2.22 MB | `2bea8aa9307b4c6e4d12cf577879941fe98c262cf63fd173445bb69ba782b9a1` |
|
|
||||||
| v1.0.28 | 2026-09-26 14:17:16 | [`Matewawe-v1.0.28.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.28/Matewawe-v1.0.28.apk) | 2.22 MB | `f1777a3e19fcd2f3c008995fed954ae1d63391dc799d9bd895db5a33f7bf734f` |
|
|
||||||
| v1.0.27 | 2026-09-24 20:09:08 | [`Matewawe-v1.0.27.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.27/Matewawe-v1.0.27.apk) | 2.17 MB | `1dd9990b0a99581fd25133e7137f8b2fafe8832254a343d25897ffe3fbc4a67b` |
|
|
||||||
| v1.0.26 | 2026-09-24 19:24:34 | [`Matewawe-v1.0.26.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.26/Matewawe-v1.0.26.apk) | 2.17 MB | `03320f2b70575ede6637806d7278d897b2129c51098caf913720b215f8ac1158` |
|
|
||||||
| v1.0.25 | 2026-09-24 18:42:10 | [`Matewawe-v1.0.25.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.25/Matewawe-v1.0.25.apk) | 2.17 MB | `b5cd45ea214eb451c54f73c34b7dff1ef4c9820f0dd8542631c687eeec324f80` |
|
|
||||||
| v1.0.24 | 2026-09-20 13:47:22 | [`Matewawe-v1.0.24.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.24/Matewawe-v1.0.24.apk) | 2.17 MB | `ab82a55f07a00f8a7b1ebbaadf1cc50c151645bc3a1a09d7bd7078b26caf07ec` |
|
|
||||||
| v1.0.23 | 2026-09-20 12:43:54 | [`Matewawe-v1.0.23.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.23/Matewawe-v1.0.23.apk) | 2.12 MB | `619f0e3fc3738148cb6ce2705a861990fcc27c5826a6dcbe68b1d9613602368d` |
|
|
||||||
| v1.0.22 | 2026-09-20 12:16:18 | [`Matewawe-v1.0.22.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.22/Matewawe-v1.0.22.apk) | 2.12 MB | `4521859f4d7e258043cfaeb5429f03d5e3994d47a3d743489e57e7091b1e6b32` |
|
|
||||||
| v1.0.21 | 2026-09-20 11:13:24 | [`Matewawe-v1.0.21.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.21/Matewawe-v1.0.21.apk) | 2.08 MB | `ed5b874142a4a2629b7e6f24ddd17a9cd294e887bd5ec3535eb182aa150f0a56` |
|
|
||||||
| v1.0.20 | 2026-09-20 08:47:32 | [`Matewawe-v1.0.20.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.20/Matewawe-v1.0.20.apk) | 13.67 MB | `3ecb641bbe4231695fd22a62593f1b58c046346a7119ce218408d43bcc6ff984` |
|
|
||||||
| v1.0.19 | 2026-09-19 19:02:58 | [`Matewawe-v1.0.19.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.19/Matewawe-v1.0.19.apk) | 13.68 MB | `2bb58f82ef0f6d6bd2677973771659d0f5ccfb029125a38a166fcd87ae79d44b` |
|
|
||||||
| v1.0.18 | 2026-09-19 14:05:10 | [`Matewawe-v1.0.18.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.18/Matewawe-v1.0.18.apk) | 13.63 MB | `6fd29406fa9169834c485dbe03621cdde7f9ee412186d72293504848c300b995` |
|
|
||||||
| v1.0.17 | 2026-09-18 15:40:22 | [`Matewawe-v1.0.17.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.17/Matewawe-v1.0.17.apk) | 13.61 MB | `f76c10ea625e8d5441567a62422488ad699916bb6fcfede30e8977ad7d09151c` |
|
|
||||||
| v1.0.16 | 2026-09-14 14:57:40 | [`Matewawe-v1.0.16.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.16/Matewawe-v1.0.16.apk) | 13.68 MB | `c528fcfc5bd3e4b245eab2b69a71832bac4fd2ba4f2cab14bfa6c046859a4fb5` |
|
|
||||||
| v1.0.15 | 2026-09-13 16:05:32 | [`Matewawe-v1.0.15.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.15/Matewawe-v1.0.15.apk) | 13.00 MB | `e7c9e59938625ab73a761dd2a2f0fd8b6e5b112dc30c7ac01128e86346cdee39` |
|
|
||||||
| v1.0.14 | 2026-09-12 16:56:38 | [`Matewawe-v1.0.14.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.14/Matewawe-v1.0.14.apk) | 12.98 MB | `8814bdeb171f3b9abf3f2dce5e42e4d9d2690263a3fe6bd1726c21ecbb16a474` |
|
|
||||||
| v1.0.13 | 2026-09-12 15:53:32 | [`Matewawe-v1.0.13.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.13/Matewawe-v1.0.13.apk) | 12.98 MB | `1c331f9e8f82c27fa206130847d4f07a31f356919bb26fbb6c38ec71ed65c5d4` |
|
|
||||||
| v1.0.12 | 2026-09-12 15:33:10 | [`Matewawe-v1.0.12.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.12/Matewawe-v1.0.12.apk) | 12.98 MB | `df24ef36a0d211febc8b52077eaaa448f1102dee22b0d7047ca5300b56f241a7` |
|
|
||||||
| v1.0.11 | 2026-09-12 14:41:24 | [`Matewawe-v1.0.11.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.11/Matewawe-v1.0.11.apk) | 12.98 MB | `f50e079c8ee2b761ff3c796bd1a4e2ab20eb0547301d87cb6ba407e11f850faa` |
|
|
||||||
| v1.0.10 | 2026-09-12 10:26:18 | [`Matewawe-v1.0.10.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.10/Matewawe-v1.0.10.apk) | 12.96 MB | `f2770184ca2ec5087703719ae04801ba1f9410b24fee3167e62b84f42698f595` |
|
|
||||||
| v1.0.9 | 2026-09-12 10:00:18 | [`Matewawe-v1.0.9.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.9/Matewawe-v1.0.9.apk) | 12.96 MB | `934ff81456d19286d337b4463e521c292c285299318c2d28bb48d93cb714b105` |
|
|
||||||
| v1.0.8 | 2026-09-12 09:49:10 | [`Matewawe-v1.0.8.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.8/Matewawe-v1.0.8.apk) | 12.96 MB | `934ff81456d19286d337b4463e521c292c285299318c2d28bb48d93cb714b105` |
|
|
||||||
| v1.0.7 | 2026-09-12 09:36:08 | [`Matewawe-v1.0.7.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.7/Matewawe-v1.0.7.apk) | 12.96 MB | `d20610c84d61f4a6ca9039a44625a086258be390e707474a8e64f40e221abcdd` |
|
|
||||||
| v1.0.6 | 2026-09-11 20:57:14 | [`Matewawe-v1.0.6.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.6/Matewawe-v1.0.6.apk) | 12.96 MB | `e96ebcc9d4d7212a05b82602d5cbbe4bb859a6518cd72dd0093f1464ce1911be` |
|
|
||||||
| v1.0.5 | 2026-09-11 16:55:40 | [`Matewawe-v1.0.5.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.5/Matewawe-v1.0.5.apk) | 12.96 MB | `39af374d7285ccd664de7679e92d1ba394457b7562908b4a949d5875c028d2e2` |
|
|
||||||
| v1.0.4 | 2026-09-11 15:40:26 | [`Matewawe-v1.0.4.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.4/Matewawe-v1.0.4.apk) | 12.96 MB | `f2fe8c0bb3856ee47f2f0db5da3b1f30e48744673e0ba2da32ccf275dd3789d7` |
|
|
||||||
| v1.0.3 | 2026-09-10 18:03:12 | [`Matewawe-v1.0.3.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.3/Matewawe-v1.0.3.apk) | 12.96 MB | `754db9aeba44127fbe937fb9d8d18dafcf9c0e129160a7d14fb9391f2a26f4cf` |
|
|
||||||
| v1.0.2 | 2026-09-10 17:37:30 | [`Matewawe-v1.0.2.apk`](https://github.com/kalarina-bit/Matewave/releases/download/v1.0.2/Matewawe-v1.0.2.apk) | 12.94 MB | `013311efc7279d9242d34d5c432ca7a1e39d60f8d00cb7f7dfba20ce04649523` |
|
|
||||||
| v1.0.1 | 2026-09-10 15:41:34 | [`Matewawe-v1.0.1.apk`](https://github.com/kalarina-bit/Matewave/releases/download/1.0.1/Matewawe-v1.0.1.apk) | 12.95 MB | `08f40d204d7a092bb669bf032bc871a265f5da93042adeb74585e258b7cb0b4b` |
|
|
||||||
| v1.0.0 | 2026-09-08 17:49:32 | [`Matewawe-v1.0.0.apk`](https://github.com/kalarina-bit/Matewave/releases/download/1.0.0/Matewawe-v1.0.0.apk) | 12.88 MB | `26d3674f1fb363c30cd6d08858610e284a4cd89c4c62cf9e6fff438ba8d96451` |
|
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# Contributing to Matewave
|
||||||
|
|
||||||
|
Thanks for wanting to help! This guide explains where to contribute, what fits the project and how to send changes.
|
||||||
|
|
||||||
|
## Where to contribute
|
||||||
|
|
||||||
|
Issues and pull requests go to the repository on [Gitea](https://git.skysparkle.cc/kalarina/Matewave).
|
||||||
|
|
||||||
|
## Ways to help
|
||||||
|
|
||||||
|
- **Report a bug** — use the *Bug report* template.
|
||||||
|
- **Report a wrong puzzle or opening line** — use the *Puzzle or opening issue* template.
|
||||||
|
- **Suggest a feature** — use the *Feature request* template; check [Out of scope](#out-of-scope) first.
|
||||||
|
- **Fix a translation** — use the *Translation fix* template or send a pull request.
|
||||||
|
- **Write code** — see [Pull requests](#pull-requests).
|
||||||
|
|
||||||
|
## Before you start
|
||||||
|
|
||||||
|
- **Small changes** (typos, obvious bugs, translation fixes): send a pull request directly.
|
||||||
|
- **Anything bigger** (new features, UI changes, new dependencies): open an issue first and wait for a go-ahead, so your work isn't wasted.
|
||||||
|
|
||||||
|
## Ground rules
|
||||||
|
|
||||||
|
- No ads, analytics, trackers, crash reporters or accounts.
|
||||||
|
- No Google Play Services, Firebase or other proprietary libraries — the app must stay buildable for F-Droid.
|
||||||
|
- New dependencies must be open source and justified in the pull request.
|
||||||
|
- Be respectful in issues and reviews.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
These will not be accepted:
|
||||||
|
|
||||||
|
- Bundled or external chess engines such as Stockfish.
|
||||||
|
- An analysis board, PGN/FEN import or a board editor.
|
||||||
|
- Two players on one device.
|
||||||
|
- Online play through servers, invite links or Wi-Fi Direct — multiplayer stays Bluetooth and local network only.
|
||||||
|
- More radio stations — the built-in jazz radio stays a single ad-free station.
|
||||||
|
- A light theme or automatic light/dark switching — Matewave is dark only.
|
||||||
|
- New UI languages (see [Translations](#translations)).
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
|
||||||
|
Matewave is available in exactly six languages: English, Russian, German, Japanese, Lithuanian and Chinese. Fixes to these are welcome; new languages are not accepted.
|
||||||
|
|
||||||
|
- App strings: `app/src/main/res/values-<lang>/strings.xml` (English is `values/`).
|
||||||
|
- Store listing: `fastlane/metadata/android/<locale>/`.
|
||||||
|
|
||||||
|
If your code adds new strings, add them to `values/strings.xml`. Translations for the other languages are welcome but not required — mention missing ones in the pull request.
|
||||||
|
|
||||||
|
## Pull requests
|
||||||
|
|
||||||
|
1. Fork the repository and create a branch from `main`.
|
||||||
|
2. Keep one topic per pull request.
|
||||||
|
3. Follow the existing Kotlin and Jetpack Compose style; keep comments short and in English; don't reformat unrelated code.
|
||||||
|
4. Make sure `./gradlew assembleDebug` and `./gradlew testDebugUnitTest` pass.
|
||||||
|
5. Changes to multiplayer must be tested on two physical devices.
|
||||||
|
6. Write short, plain commit messages in English (for example `Fix castling check in LAN games`).
|
||||||
|
7. Add screenshots for UI changes.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
Please don't post details of security issues publicly. Open a short issue titled "Security contact" without any details, and the maintainer will reach out privately.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
By contributing, you agree that your contribution is licensed under the [GNU General Public License v3.0 or later](LICENSE), the same as the rest of the project.
|
||||||
@@ -1,72 +1,73 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="assets/icon-rounded.png" width="128" alt="Matewave icon">
|
<img src="assets/icon-rounded.png" width="112" alt="Matewave icon">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h1 align="center">Matewave</h1>
|
<h1 align="center">Matewave</h1>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://git.skysparkle.cc/kalarina/Matewave/releases"><img src="assets/get-it-on-gitea.png" height="60" alt="Get it on Gitea"></a>
|
<b>A beautiful, open-source chess app for Android.</b><br>
|
||||||
|
Play against the AI, solve puzzles, learn openings, or play friends nearby over Bluetooth and Wi-Fi/LAN.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/github/downloads/kalarina-bit/Matewave/latest/total?label=downloads&color=2e7d32&labelColor=1b1b1b" alt="downloads counter">
|
<a href="https://github.com/kalarina-bit/Matewave/releases/latest"><img src="https://img.shields.io/github/v/release/kalarina-bit/Matewave?style=for-the-badge&label=release&labelColor=1b1b1b&color=2e7d32" alt="Latest release"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**A beautiful, open-source chess app for Android.**
|
|
||||||
|
|
||||||
Play chess against AI, solve chess puzzles, learn and practice
|
|
||||||
chess openings, or play local multiplayer games with friends
|
|
||||||
over Bluetooth and Wi-Fi/LAN.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- 🤖 AI opponent with adjustable difficulty
|
|
||||||
- 🧩 Chess puzzles and tactical training
|
|
||||||
- 📖 Chess openings — learn and practice opening lines
|
|
||||||
- ♟️ Opening practice for different variations and move sequences
|
|
||||||
- 📶 Local multiplayer over Bluetooth/LAN
|
|
||||||
- 👥 Nearby player discovery over local Wi-Fi
|
|
||||||
- 🌙 Dark theme
|
|
||||||
- 🌍 English, Russian, German, Japanese, Lithuanian and Chinese
|
|
||||||
- 🔓 100% open source
|
|
||||||
|
|
||||||
## Screenshots
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="assets/screenshots/5-move-count.png" width="200" alt="Make your next move count">
|
<a href="https://f-droid.org/packages/cc.skysparkle.matewave/"><img src="assets/get-it-on%20(1).png" height="56" alt="Get it on F-Droid"></a>
|
||||||
<img src="assets/screenshots/4-home.png" width="200" alt="Home screen">
|
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Matewave"><img src="assets/badge_obtainium.png" height="56" alt="Get it on Obtainium"></a>
|
||||||
<img src="assets/screenshots/1-friendly-matches.png" width="200" alt="From solo games to friendly matches">
|
<a href="https://github.com/kalarina-bit/Matewave/releases/latest"><img src="assets/get-it-on-github.png" height="56" alt="Get it on GitHub"></a>
|
||||||
<img src="assets/screenshots/3-play-together.png" width="200" alt="Play together">
|
<a href="https://git.skysparkle.cc/kalarina/Matewave/releases"><img src="assets/get-it-on-gitea.png" height="56" alt="Get it on Gitea"></a>
|
||||||
<img src="assets/screenshots/2-keep-growing.png" width="200" alt="Keep growing">
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
## Installation
|
<p align="center">
|
||||||
|
<img src="assets/screenshots/5-move-count.png" width="160" alt="Make your next move count">
|
||||||
|
<img src="assets/screenshots/4-home.png" width="160" alt="Home screen">
|
||||||
|
<img src="assets/screenshots/1-friendly-matches.png" width="160" alt="From solo games to friendly matches">
|
||||||
|
<img src="assets/screenshots/3-play-together.png" width="160" alt="Play together">
|
||||||
|
<img src="assets/screenshots/2-keep-growing.png" width="160" alt="Keep growing">
|
||||||
|
</p>
|
||||||
|
|
||||||
<img src="assets/icon-install.png" width="36" align="left">
|
> [!TIP]
|
||||||
|
> If you find Matewave useful, please consider giving it a ⭐ — it helps others discover the project.
|
||||||
|
|
||||||
1. Download the APK for the version you want from the [Releases page](https://github.com/kalarina-bit/Matewave/releases).
|
## ✨ Features
|
||||||
2. On your Android device, allow installs from unknown sources for the app you use to open the file (Settings → Apps → Special access → Install unknown apps).
|
|
||||||
3. Open the downloaded `.apk` file and confirm the install.
|
|
||||||
|
|
||||||
Or via `adb` (after downloading):
|
- 🤖 **AI opponent** with adjustable difficulty
|
||||||
|
- 🧩 **Puzzles** and tactical training
|
||||||
|
- 📖 **Opening trainer** — learn and practice opening lines and their variations
|
||||||
|
- 📶 **Local multiplayer** over Bluetooth or Wi-Fi/LAN, with nearby player discovery
|
||||||
|
- 👀 **Watch friends play** — up to 20 spectators on the same Wi-Fi can follow a live LAN game
|
||||||
|
- 📲 **Share the app** with a nearby friend via QR code over the local network
|
||||||
|
- 🎷 **Optional jazz radio**
|
||||||
|
- 🌙 **Dark theme**
|
||||||
|
- 🌍 **Six languages** — English, Russian, German, Japanese, Lithuanian and Chinese
|
||||||
|
|
||||||
|
## <img src="assets/icon-install.png" width="32" alt=""> Installation
|
||||||
|
|
||||||
|
- **[F-Droid](https://f-droid.org/packages/cc.skysparkle.matewave/)** — install and update through the F-Droid client.
|
||||||
|
- **[Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://git.skysparkle.cc/kalarina/Matewave)** — installs the APK straight from Gitea releases and keeps it up to date.
|
||||||
|
- **Manually** — download the latest APK from [GitHub](https://github.com/kalarina-bit/Matewave/releases/latest) or [Gitea](https://git.skysparkle.cc/kalarina/Matewave/releases), allow installs from unknown sources for the app you open it with (Settings → Apps → Special access → Install unknown apps), then open the `.apk` and confirm.
|
||||||
|
|
||||||
|
## <img src="assets/icon-verify.png" width="32" alt=""> Verifying a download
|
||||||
|
|
||||||
|
Every official APK is signed with the same key. Check it before installing:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
adb install Matewawe-v1.0.42.apk
|
apksigner verify --print-certs Matewave-v<version>.apk
|
||||||
```
|
```
|
||||||
|
|
||||||
## Verifying a download
|
The SHA-256 fingerprint of the signing certificate must be:
|
||||||
|
|
||||||
<img src="assets/icon-verify.png" width="36" align="left">
|
```
|
||||||
|
1C:3E:54:54:9D:09:9A:9D:3D:5B:BE:ED:C5:63:F5:7F:60:12:56:3C:88:85:99:B1:88:B4:FB:17:E3:46:46:A9
|
||||||
Compare the SHA-256 checksum against the value listed in [CHANGELOG.md](CHANGELOG.md):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
sha256sum Matewawe-v1.0.42.apk
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Building from source
|
`apksigner` prints the same value in lowercase without colons. On Android you can check it with [AppVerifier](https://github.com/soupslurpr/AppVerifier) (app ID `cc.skysparkle.matewave`).
|
||||||
|
|
||||||
Open the project in Android Studio (a version that supports AGP 9.2) and run the `app` configuration, or:
|
## <img src="assets/icon-structure.png" width="32" alt=""> Building from source
|
||||||
|
|
||||||
|
Requires JDK 17+ and Android Studio with AGP 9.2 support.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
./gradlew assembleDebug
|
./gradlew assembleDebug
|
||||||
@@ -75,25 +76,10 @@ Open the project in Android Studio (a version that supports AGP 9.2) and run the
|
|||||||
|
|
||||||
Nearby multiplayer needs two physical devices — the emulator has no real Bluetooth, and mDNS discovery is often blocked on emulator networks.
|
Nearby multiplayer needs two physical devices — the emulator has no real Bluetooth, and mDNS discovery is often blocked on emulator networks.
|
||||||
|
|
||||||
## Repository structure
|
## 🤝 Contributing
|
||||||
|
|
||||||
<img src="assets/icon-structure.png" width="36" align="left">
|
Bug reports, puzzle and opening fixes, translation fixes and pull requests are welcome in the [issue tracker](https://git.skysparkle.cc/kalarina/Matewave/issues). Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — it explains what fits the project and how to send changes. To open an issue or a pull request, [create an account](https://git.skysparkle.cc/user/sign_up) on this Gitea.
|
||||||
|
|
||||||
```
|
## 📄 License
|
||||||
.
|
|
||||||
├── app/ # Android app source (Kotlin, Jetpack Compose) and unit tests
|
|
||||||
├── assets/ # Icon and README images
|
|
||||||
│ └── screenshots/ # App screenshots
|
|
||||||
├── fastlane/ # F-Droid store listing, screenshots and changelogs
|
|
||||||
├── fdroid/ # Build recipe for fdroiddata
|
|
||||||
├── gradle/ # Gradle wrapper
|
|
||||||
├── CHANGELOG.md # Per-version build dates, sizes and checksums (links to GitHub Releases)
|
|
||||||
├── LICENSE # GNU GPLv3
|
|
||||||
└── README.md
|
|
||||||
```
|
|
||||||
|
|
||||||
APK builds themselves are published as assets on the [Releases page](https://github.com/kalarina-bit/Matewave/releases), not stored in this repository.
|
[GNU General Public License v3.0 or later](LICENSE).
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
This project is licensed under the **GNU General Public License v3.0** — see the [LICENSE](LICENSE) file for details.
|
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "cc.skysparkle.matewave"
|
applicationId = "cc.skysparkle.matewave"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = 4
|
||||||
versionName = "1.0.43"
|
versionName = "1.0.46"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -25,6 +25,8 @@ android {
|
|||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro"
|
"proguard-rules.pro"
|
||||||
)
|
)
|
||||||
|
// Keeps release builds reproducible (F-Droid).
|
||||||
|
vcsInfo.include = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import androidx.activity.compose.setContent
|
|||||||
import cc.skysparkle.matewave.audio.SoundManager
|
import cc.skysparkle.matewave.audio.SoundManager
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
@@ -110,6 +112,10 @@ private fun AppNavHost() {
|
|||||||
|
|
||||||
// Presence is shared with the background service, so the lists stay the same in both.
|
// Presence is shared with the background service, so the lists stay the same in both.
|
||||||
val presence = remember { PresenceHub.get(context) }
|
val presence = remember { PresenceHub.get(context) }
|
||||||
|
|
||||||
|
var spectateTarget by androidx.compose.runtime.saveable.rememberSaveable(saver = SpectateTargetSaver) {
|
||||||
|
androidx.compose.runtime.mutableStateOf<cc.skysparkle.matewave.spectate.SpectateTarget?>(null)
|
||||||
|
}
|
||||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||||
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
|
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
|
||||||
cc.skysparkle.matewave.presence.PresenceService.start(context)
|
cc.skysparkle.matewave.presence.PresenceService.start(context)
|
||||||
@@ -231,6 +237,10 @@ private fun AppNavHost() {
|
|||||||
FriendsScreen(
|
FriendsScreen(
|
||||||
presence = presence,
|
presence = presence,
|
||||||
onPlay = { navController.navigate("connectionNearby") },
|
onPlay = { navController.navigate("connectionNearby") },
|
||||||
|
onWatch = { target ->
|
||||||
|
spectateTarget = target
|
||||||
|
navController.navigate("spectate")
|
||||||
|
},
|
||||||
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
|
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
|
||||||
onSettingsClick = {
|
onSettingsClick = {
|
||||||
navController.popBackStack("menu", inclusive = false)
|
navController.popBackStack("menu", inclusive = false)
|
||||||
@@ -243,6 +253,19 @@ private fun AppNavHost() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
composable("spectate") {
|
||||||
|
val target = spectateTarget
|
||||||
|
val backToFriends: () -> Unit = {
|
||||||
|
if (!navController.popBackStack("friends", inclusive = false)) navController.popBackStack()
|
||||||
|
}
|
||||||
|
if (target == null) {
|
||||||
|
LaunchedEffect(Unit) { backToFriends() }
|
||||||
|
} else {
|
||||||
|
PlayScreenMusic()
|
||||||
|
cc.skysparkle.matewave.ui.screens.SpectatorScreen(target = target, onBackToFriends = backToFriends)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
composable("vsAiSetup") {
|
composable("vsAiSetup") {
|
||||||
VsAiSetupScreen(
|
VsAiSetupScreen(
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
@@ -260,6 +283,7 @@ private fun AppNavHost() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
composable("game") {
|
composable("game") {
|
||||||
|
PlayScreenMusic()
|
||||||
GameScreen(
|
GameScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onExit = { navController.popBackStack("menu", inclusive = false) }
|
onExit = { navController.popBackStack("menu", inclusive = false) }
|
||||||
@@ -267,6 +291,7 @@ private fun AppNavHost() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
composable("openingStudy") {
|
composable("openingStudy") {
|
||||||
|
PlayScreenMusic()
|
||||||
cc.skysparkle.matewave.ui.screens.OpeningStudyScreen(
|
cc.skysparkle.matewave.ui.screens.OpeningStudyScreen(
|
||||||
viewModel = studyViewModel,
|
viewModel = studyViewModel,
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
@@ -275,6 +300,7 @@ private fun AppNavHost() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
composable("openingTrainer") {
|
composable("openingTrainer") {
|
||||||
|
PlayScreenMusic()
|
||||||
cc.skysparkle.matewave.ui.screens.OpeningTrainerScreen(
|
cc.skysparkle.matewave.ui.screens.OpeningTrainerScreen(
|
||||||
viewModel = studyViewModel,
|
viewModel = studyViewModel,
|
||||||
onBack = { navController.popBackStack() }
|
onBack = { navController.popBackStack() }
|
||||||
@@ -282,6 +308,7 @@ private fun AppNavHost() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
composable("puzzleSolve") {
|
composable("puzzleSolve") {
|
||||||
|
PlayScreenMusic()
|
||||||
PuzzleSolveScreen(
|
PuzzleSolveScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
onBack = { navController.popBackStack("menu", inclusive = false) },
|
onBack = { navController.popBackStack("menu", inclusive = false) },
|
||||||
@@ -320,6 +347,18 @@ private fun AppNavHost() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val SpectateTargetSaver = androidx.compose.runtime.saveable.Saver<
|
||||||
|
androidx.compose.runtime.MutableState<cc.skysparkle.matewave.spectate.SpectateTarget?>, List<Any>
|
||||||
|
>(
|
||||||
|
save = { state -> state.value?.let { arrayListOf<Any>(it.host, it.port, it.gameTag) } },
|
||||||
|
restore = { saved ->
|
||||||
|
val target = if (saved.size == 3) {
|
||||||
|
cc.skysparkle.matewave.spectate.SpectateTarget(saved[0] as String, saved[1] as Int, saved[2] as String)
|
||||||
|
} else null
|
||||||
|
androidx.compose.runtime.mutableStateOf(target)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
private val TAB_ROUTES = setOf("menu", "friends", "settings", "account")
|
private val TAB_ROUTES = setOf("menu", "friends", "settings", "account")
|
||||||
|
|
||||||
private fun isTabSwitch(from: String?, to: String?): Boolean =
|
private fun isTabSwitch(from: String?, to: String?): Boolean =
|
||||||
@@ -355,3 +394,12 @@ private fun sharedAxisOut(forward: Boolean): androidx.compose.animation.ExitTran
|
|||||||
androidx.compose.animation.fadeOut(
|
androidx.compose.animation.fadeOut(
|
||||||
androidx.compose.animation.core.tween(durationMillis = 120, easing = androidx.compose.animation.core.LinearEasing)
|
androidx.compose.animation.core.tween(durationMillis = 120, easing = androidx.compose.animation.core.LinearEasing)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Offline music switches to the game track while a game, puzzle or opening study is open
|
||||||
|
@Composable
|
||||||
|
private fun PlayScreenMusic() {
|
||||||
|
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||||
|
SoundManager.enterPlayScreen()
|
||||||
|
onDispose { SoundManager.leavePlayScreen() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import android.media.AudioFocusRequest
|
|||||||
import android.media.AudioManager
|
import android.media.AudioManager
|
||||||
import android.media.MediaPlayer
|
import android.media.MediaPlayer
|
||||||
import android.media.SoundPool
|
import android.media.SoundPool
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
@@ -20,11 +23,15 @@ enum class RadioState { IDLE, CONNECTING, PLAYING, ERROR }
|
|||||||
|
|
||||||
object SoundManager {
|
object SoundManager {
|
||||||
private val RADIO_SOURCES = listOf(
|
private val RADIO_SOURCES = listOf(
|
||||||
"http://stream.srg-ssr.ch/srgssr/rsj/aac/192",
|
|
||||||
"https://stream.srg-ssr.ch/srgssr/rsj/mp3/128",
|
"https://stream.srg-ssr.ch/srgssr/rsj/mp3/128",
|
||||||
"http://stream.srg-ssr.ch/srgssr/rsj/aac/96"
|
"https://stream.srg-ssr.ch/srgssr/rsj/aac/192",
|
||||||
|
"https://stream.srg-ssr.ch/srgssr/rsj/aac/96"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Played instead of the radio when it can't be reached
|
||||||
|
private const val MENU_TRACK = "music/midnight_grove_conversations.ogg"
|
||||||
|
private const val PLAY_TRACK = "music/raindrops_and_pawns.ogg"
|
||||||
|
|
||||||
private const val PREFS = "chess_sound_prefs"
|
private const val PREFS = "chess_sound_prefs"
|
||||||
private const val KEY_MUSIC = "music_enabled"
|
private const val KEY_MUSIC = "music_enabled"
|
||||||
private const val KEY_SFX = "sfx_enabled"
|
private const val KEY_SFX = "sfx_enabled"
|
||||||
@@ -45,11 +52,21 @@ object SoundManager {
|
|||||||
private var sourceIndex = 0
|
private var sourceIndex = 0
|
||||||
private var connectTimeoutRunnable: Runnable? = null
|
private var connectTimeoutRunnable: Runnable? = null
|
||||||
private var audioManager: AudioManager? = null
|
private var audioManager: AudioManager? = null
|
||||||
|
private var connectivity: ConnectivityManager? = null
|
||||||
|
private var networkCallbackRegistered = false
|
||||||
private var focusRequest: AudioFocusRequest? = null
|
private var focusRequest: AudioFocusRequest? = null
|
||||||
|
private var focusGranted = false
|
||||||
private var noisyReceiverRegistered = false
|
private var noisyReceiverRegistered = false
|
||||||
private val mainHandler = Handler(Looper.getMainLooper())
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
var musicEnabled: Boolean = true
|
private var offlinePlayer: MediaPlayer? = null
|
||||||
|
private var offlinePrepared = false
|
||||||
|
private var offlineTrack: String? = null
|
||||||
|
private var playScreens = 0
|
||||||
|
private var appInForeground = false
|
||||||
|
|
||||||
|
/** Jazz radio. Off until the user turns it on, so nothing connects on start. */
|
||||||
|
var musicEnabled: Boolean = false
|
||||||
private set
|
private set
|
||||||
var sfxEnabled: Boolean = true
|
var sfxEnabled: Boolean = true
|
||||||
private set
|
private set
|
||||||
@@ -57,28 +74,58 @@ object SoundManager {
|
|||||||
private val _radioState = MutableStateFlow(RadioState.IDLE)
|
private val _radioState = MutableStateFlow(RadioState.IDLE)
|
||||||
val radioState: StateFlow<RadioState> = _radioState
|
val radioState: StateFlow<RadioState> = _radioState
|
||||||
|
|
||||||
private fun pauseRadio() {
|
private fun setRadioState(state: RadioState) {
|
||||||
val player = musicPlayer ?: return
|
_radioState.value = state
|
||||||
if (playerPrepared) runCatching { if (player.isPlaying) player.pause() }
|
updateOfflineMusic()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pauseAll() {
|
||||||
|
musicPlayer?.let { player -> if (playerPrepared) runCatching { if (player.isPlaying) player.pause() } }
|
||||||
|
offlinePlayer?.let { player -> if (offlinePrepared) runCatching { if (player.isPlaying) player.pause() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setVolumeAll(volume: Float) {
|
||||||
|
runCatching { musicPlayer?.setVolume(volume, volume) }
|
||||||
|
runCatching { offlinePlayer?.setVolume(volume, volume) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private val noisyReceiver = object : BroadcastReceiver() {
|
private val noisyReceiver = object : BroadcastReceiver() {
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) pauseRadio()
|
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) pauseAll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val focusChangeListener = AudioManager.OnAudioFocusChangeListener { change ->
|
private val focusChangeListener = AudioManager.OnAudioFocusChangeListener { change ->
|
||||||
when (change) {
|
when (change) {
|
||||||
AudioManager.AUDIOFOCUS_LOSS -> stopRadioInternal()
|
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> pauseRadio()
|
stopRadioInternal()
|
||||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ->
|
releaseOfflinePlayer()
|
||||||
runCatching { musicPlayer?.setVolume(BASE_VOLUME * 0.3f, BASE_VOLUME * 0.3f) }
|
abandonAudioFocus()
|
||||||
|
}
|
||||||
|
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||||
|
focusGranted = false
|
||||||
|
pauseAll()
|
||||||
|
}
|
||||||
|
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> setVolumeAll(BASE_VOLUME * 0.3f)
|
||||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||||
|
focusGranted = true
|
||||||
|
setVolumeAll(BASE_VOLUME)
|
||||||
val player = musicPlayer
|
val player = musicPlayer
|
||||||
if (player != null && playerPrepared) runCatching {
|
if (player != null && playerPrepared) runCatching { if (!player.isPlaying) player.start() }
|
||||||
player.setVolume(BASE_VOLUME, BASE_VOLUME)
|
val offline = offlinePlayer
|
||||||
if (!player.isPlaying) player.start()
|
if (offline != null && offlinePrepared && shouldPlayOffline()) {
|
||||||
|
runCatching { if (!offline.isPlaying) offline.start() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Brings the radio back once the device is online again
|
||||||
|
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(network: Network) {
|
||||||
|
mainHandler.post {
|
||||||
|
if (musicEnabled && appInForeground && musicPlayer == null && _radioState.value == RadioState.ERROR) {
|
||||||
|
startRadio()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,9 +137,10 @@ object SoundManager {
|
|||||||
val ctx = context.applicationContext
|
val ctx = context.applicationContext
|
||||||
appContext = ctx
|
appContext = ctx
|
||||||
audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
audioManager = ctx.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
||||||
|
connectivity = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||||
|
|
||||||
val prefs = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
val prefs = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
musicEnabled = prefs.getBoolean(KEY_MUSIC, true)
|
musicEnabled = prefs.getBoolean(KEY_MUSIC, false)
|
||||||
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
||||||
|
|
||||||
ensureSoundPool(ctx)
|
ensureSoundPool(ctx)
|
||||||
@@ -104,22 +152,27 @@ object SoundManager {
|
|||||||
|
|
||||||
private fun requestAudioFocus(): Boolean {
|
private fun requestAudioFocus(): Boolean {
|
||||||
val am = audioManager ?: return false
|
val am = audioManager ?: return false
|
||||||
val attrs = AudioAttributes.Builder()
|
if (focusGranted) return true
|
||||||
|
// Asked again after a denial or a transient loss, e.g. during a phone call
|
||||||
|
val request = focusRequest ?: AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||||
|
.setAudioAttributes(
|
||||||
|
AudioAttributes.Builder()
|
||||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||||
.build()
|
.build()
|
||||||
val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
)
|
||||||
.setAudioAttributes(attrs)
|
|
||||||
.setOnAudioFocusChangeListener(focusChangeListener, mainHandler)
|
.setOnAudioFocusChangeListener(focusChangeListener, mainHandler)
|
||||||
.build()
|
.build()
|
||||||
focusRequest = request
|
.also { focusRequest = it }
|
||||||
return am.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
focusGranted = am.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
||||||
|
return focusGranted
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun abandonAudioFocus() {
|
private fun abandonAudioFocus() {
|
||||||
val am = audioManager ?: return
|
val am = audioManager ?: return
|
||||||
focusRequest?.let { am.abandonAudioFocusRequest(it) }
|
focusRequest?.let { am.abandonAudioFocusRequest(it) }
|
||||||
focusRequest = null
|
focusRequest = null
|
||||||
|
focusGranted = false
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun registerNoisyReceiver() {
|
private fun registerNoisyReceiver() {
|
||||||
@@ -142,21 +195,47 @@ object SoundManager {
|
|||||||
noisyReceiverRegistered = false
|
noisyReceiverRegistered = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun registerNetworkCallback() {
|
||||||
|
val cm = connectivity ?: return
|
||||||
|
if (networkCallbackRegistered) return
|
||||||
|
runCatching { cm.registerDefaultNetworkCallback(networkCallback) }
|
||||||
|
.onSuccess { networkCallbackRegistered = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unregisterNetworkCallback() {
|
||||||
|
val cm = connectivity ?: return
|
||||||
|
if (!networkCallbackRegistered) return
|
||||||
|
runCatching { cm.unregisterNetworkCallback(networkCallback) }
|
||||||
|
networkCallbackRegistered = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isOnline(): Boolean {
|
||||||
|
val cm = connectivity ?: return true
|
||||||
|
val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false
|
||||||
|
return caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
}
|
||||||
|
|
||||||
private fun startRadio() {
|
private fun startRadio() {
|
||||||
val ctx = appContext ?: return
|
val ctx = appContext ?: return
|
||||||
if (musicPlayer != null) return
|
if (musicPlayer != null) return
|
||||||
if (!requestAudioFocus()) {
|
if (!requestAudioFocus()) {
|
||||||
Log.w(TAG, "Audio focus denied, radio not started")
|
Log.w(TAG, "Audio focus denied, radio not started")
|
||||||
_radioState.value = RadioState.ERROR
|
setRadioState(RadioState.ERROR)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
registerNoisyReceiver()
|
registerNoisyReceiver()
|
||||||
|
registerNetworkCallback()
|
||||||
retryCount = 0
|
retryCount = 0
|
||||||
|
if (!isOnline()) {
|
||||||
|
// No point waiting for timeouts: play offline music until the network is back
|
||||||
|
setRadioState(RadioState.ERROR)
|
||||||
|
return
|
||||||
|
}
|
||||||
connect(ctx)
|
connect(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun connect(ctx: Context) {
|
private fun connect(ctx: Context) {
|
||||||
_radioState.value = RadioState.CONNECTING
|
setRadioState(RadioState.CONNECTING)
|
||||||
val url = RADIO_SOURCES[sourceIndex % RADIO_SOURCES.size]
|
val url = RADIO_SOURCES[sourceIndex % RADIO_SOURCES.size]
|
||||||
try {
|
try {
|
||||||
val player = MediaPlayer()
|
val player = MediaPlayer()
|
||||||
@@ -173,9 +252,9 @@ object SoundManager {
|
|||||||
player.setOnPreparedListener {
|
player.setOnPreparedListener {
|
||||||
cancelConnectTimeout()
|
cancelConnectTimeout()
|
||||||
playerPrepared = true
|
playerPrepared = true
|
||||||
it.start()
|
|
||||||
retryCount = 0
|
retryCount = 0
|
||||||
_radioState.value = RadioState.PLAYING
|
if (appInForeground) it.start()
|
||||||
|
setRadioState(RadioState.PLAYING)
|
||||||
}
|
}
|
||||||
player.setOnErrorListener { mp, _, _ ->
|
player.setOnErrorListener { mp, _, _ ->
|
||||||
cancelConnectTimeout()
|
cancelConnectTimeout()
|
||||||
@@ -231,18 +310,18 @@ object SoundManager {
|
|||||||
private fun scheduleRetry(ctx: Context) {
|
private fun scheduleRetry(ctx: Context) {
|
||||||
cancelConnectTimeout()
|
cancelConnectTimeout()
|
||||||
if (!musicEnabled) {
|
if (!musicEnabled) {
|
||||||
_radioState.value = RadioState.IDLE
|
setRadioState(RadioState.IDLE)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (retryCount >= MAX_RETRIES) {
|
if (retryCount >= MAX_RETRIES || !isOnline()) {
|
||||||
_radioState.value = RadioState.ERROR
|
if (retryCount >= MAX_RETRIES) Log.w(TAG, "Could not connect to the radio after $MAX_RETRIES attempts")
|
||||||
Log.w(TAG, "Could not connect to the radio after $MAX_RETRIES attempts")
|
setRadioState(RadioState.ERROR)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
sourceIndex++
|
sourceIndex++
|
||||||
val delay = RETRY_DELAYS_MS.getOrElse(retryCount) { RETRY_DELAYS_MS.last() }
|
val delay = RETRY_DELAYS_MS.getOrElse(retryCount) { RETRY_DELAYS_MS.last() }
|
||||||
retryCount++
|
retryCount++
|
||||||
_radioState.value = RadioState.CONNECTING
|
setRadioState(RadioState.CONNECTING)
|
||||||
mainHandler.postDelayed({
|
mainHandler.postDelayed({
|
||||||
if (musicEnabled && musicPlayer == null) connect(ctx)
|
if (musicEnabled && musicPlayer == null) connect(ctx)
|
||||||
}, delay)
|
}, delay)
|
||||||
@@ -254,16 +333,21 @@ object SoundManager {
|
|||||||
musicPlayer = null
|
musicPlayer = null
|
||||||
playerPrepared = false
|
playerPrepared = false
|
||||||
unregisterNoisyReceiver()
|
unregisterNoisyReceiver()
|
||||||
|
unregisterNetworkCallback()
|
||||||
abandonAudioFocus()
|
abandonAudioFocus()
|
||||||
mainHandler.removeCallbacksAndMessages(null)
|
mainHandler.removeCallbacksAndMessages(null)
|
||||||
_radioState.value = RadioState.IDLE
|
setRadioState(RadioState.IDLE)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onAppResumed() {
|
fun onAppResumed() {
|
||||||
|
appInForeground = true
|
||||||
if (musicEnabled && musicPlayer == null) startRadio()
|
if (musicEnabled && musicPlayer == null) startRadio()
|
||||||
|
updateOfflineMusic()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onAppPaused() {
|
fun onAppPaused() {
|
||||||
|
appInForeground = false
|
||||||
|
releaseOfflinePlayer()
|
||||||
stopRadioInternal()
|
stopRadioInternal()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,7 +355,89 @@ object SoundManager {
|
|||||||
musicEnabled = enabled
|
musicEnabled = enabled
|
||||||
appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)?.edit()
|
appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)?.edit()
|
||||||
?.putBoolean(KEY_MUSIC, enabled)?.apply()
|
?.putBoolean(KEY_MUSIC, enabled)?.apply()
|
||||||
if (enabled) startRadio() else stopRadioInternal()
|
if (enabled) {
|
||||||
|
startRadio()
|
||||||
|
} else {
|
||||||
|
releaseOfflinePlayer()
|
||||||
|
stopRadioInternal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Games, puzzles and opening study call this while they are on screen. */
|
||||||
|
fun enterPlayScreen() {
|
||||||
|
playScreens++
|
||||||
|
updateOfflineMusic()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun leavePlayScreen() {
|
||||||
|
playScreens = maxOf(0, playScreens - 1)
|
||||||
|
updateOfflineMusic()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The radio is on but can't be reached: no network, or the first attempt already failed
|
||||||
|
private fun radioUnavailable(): Boolean = when (_radioState.value) {
|
||||||
|
RadioState.ERROR -> true
|
||||||
|
RadioState.CONNECTING -> retryCount > 0
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shouldPlayOffline() = musicEnabled && appInForeground && radioUnavailable()
|
||||||
|
|
||||||
|
private fun updateOfflineMusic() {
|
||||||
|
if (!shouldPlayOffline()) {
|
||||||
|
releaseOfflinePlayer()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val track = if (playScreens > 0) PLAY_TRACK else MENU_TRACK
|
||||||
|
val player = offlinePlayer
|
||||||
|
if (player != null && offlineTrack == track) {
|
||||||
|
if (offlinePrepared && !player.isPlaying && requestAudioFocus()) runCatching { player.start() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
releaseOfflinePlayer()
|
||||||
|
if (!requestAudioFocus()) return
|
||||||
|
registerNoisyReceiver()
|
||||||
|
playOfflineTrack(track)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun playOfflineTrack(track: String) {
|
||||||
|
val ctx = appContext ?: return
|
||||||
|
try {
|
||||||
|
val player = MediaPlayer()
|
||||||
|
offlinePlayer = player
|
||||||
|
offlineTrack = track
|
||||||
|
offlinePrepared = false
|
||||||
|
player.setAudioAttributes(
|
||||||
|
AudioAttributes.Builder()
|
||||||
|
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||||
|
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
ctx.assets.openFd(track).use { fd ->
|
||||||
|
player.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
|
||||||
|
}
|
||||||
|
player.isLooping = true
|
||||||
|
player.setVolume(BASE_VOLUME, BASE_VOLUME)
|
||||||
|
player.setOnPreparedListener {
|
||||||
|
offlinePrepared = true
|
||||||
|
if (shouldPlayOffline() && focusGranted) it.start()
|
||||||
|
}
|
||||||
|
player.setOnErrorListener { mp, _, _ ->
|
||||||
|
if (offlinePlayer === mp) releaseOfflinePlayer()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
player.prepareAsync()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Offline music error ($track): ${e.message}")
|
||||||
|
releaseOfflinePlayer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseOfflinePlayer() {
|
||||||
|
try { offlinePlayer?.release() } catch (_: Exception) {}
|
||||||
|
offlinePlayer = null
|
||||||
|
offlineTrack = null
|
||||||
|
offlinePrepared = false
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setSfxEnabled(enabled: Boolean) {
|
fun setSfxEnabled(enabled: Boolean) {
|
||||||
|
|||||||
@@ -67,6 +67,9 @@ sealed class GameMessage {
|
|||||||
val newGameId: String = ""
|
val newGameId: String = ""
|
||||||
) : GameMessage()
|
) : GameMessage()
|
||||||
|
|
||||||
|
/** Host to guest: how many spectators watch. Older versions skip it as an unknown type. */
|
||||||
|
data class SpectatorCountMsg(val count: Int, val gameId: String = "") : GameMessage()
|
||||||
|
|
||||||
fun toJson(): String {
|
fun toJson(): String {
|
||||||
val o = JSONObject()
|
val o = JSONObject()
|
||||||
when (this) {
|
when (this) {
|
||||||
@@ -99,6 +102,7 @@ sealed class GameMessage {
|
|||||||
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
|
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
|
||||||
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
|
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
|
||||||
}
|
}
|
||||||
|
is SpectatorCountMsg -> { o.put("type", "spectators"); o.put("n", count); o.put("gameId", gameId) }
|
||||||
is ProfileMsg -> {
|
is ProfileMsg -> {
|
||||||
o.put("type", "profile")
|
o.put("type", "profile")
|
||||||
o.put("userId", userId)
|
o.put("userId", userId)
|
||||||
@@ -154,6 +158,7 @@ sealed class GameMessage {
|
|||||||
o.optString("gameId", ""),
|
o.optString("gameId", ""),
|
||||||
o.optString("newGameId", "")
|
o.optString("newGameId", "")
|
||||||
)
|
)
|
||||||
|
"spectators" -> SpectatorCountMsg(o.getInt("n"), o.optString("gameId", ""))
|
||||||
"profile" -> ProfileMsg(
|
"profile" -> ProfileMsg(
|
||||||
|
|
||||||
userId = o.optString("userId", "").ifBlank { o.getString("name") },
|
userId = o.optString("userId", "").ifBlank { o.getString("name") },
|
||||||
|
|||||||
@@ -30,7 +30,11 @@ data class LanPeer(
|
|||||||
|
|
||||||
val signature: String = "",
|
val signature: String = "",
|
||||||
/** Raw NSD service name, used to remove the peer when the service is lost. */
|
/** Raw NSD service name, used to remove the peer when the service is lost. */
|
||||||
val serviceName: String = ""
|
val serviceName: String = "",
|
||||||
|
/** Tag of the LAN game the peer plays, empty when not in one. */
|
||||||
|
val gameTag: String = "",
|
||||||
|
/** Spectator port when the peer hosts a watchable game, otherwise 0. */
|
||||||
|
val spectatePort: Int = 0
|
||||||
) {
|
) {
|
||||||
val id: String get() = "$host:$port"
|
val id: String get() = "$host:$port"
|
||||||
}
|
}
|
||||||
@@ -224,6 +228,7 @@ class LanTransport(
|
|||||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
||||||
context, presencePayload(profile.userId, shownName, profile.elo)
|
context, presencePayload(profile.userId, shownName, profile.elo)
|
||||||
)?.let { setAttribute("sig", it) }
|
)?.let { setAttribute("sig", it) }
|
||||||
|
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val listener = object : NsdManager.RegistrationListener {
|
val listener = object : NsdManager.RegistrationListener {
|
||||||
@@ -353,6 +358,7 @@ class LanTransport(
|
|||||||
fun attr(key: String): String = runCatching {
|
fun attr(key: String): String = runCatching {
|
||||||
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
|
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
|
||||||
}.getOrDefault("")
|
}.getOrDefault("")
|
||||||
|
val game = cc.skysparkle.matewave.spectate.SpectatorAdvert.parse(::attr)
|
||||||
return LanPeer(
|
return LanPeer(
|
||||||
name = displayNameOf(info.serviceName),
|
name = displayNameOf(info.serviceName),
|
||||||
host = host,
|
host = host,
|
||||||
@@ -363,7 +369,9 @@ class LanTransport(
|
|||||||
|
|
||||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||||
signature = attr("sig"),
|
signature = attr("sig"),
|
||||||
serviceName = info.serviceName ?: ""
|
serviceName = info.serviceName ?: "",
|
||||||
|
gameTag = game.gameTag,
|
||||||
|
spectatePort = game.spectatePort
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -517,7 +525,7 @@ class LanTransport(
|
|||||||
try {
|
try {
|
||||||
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
|
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
|
||||||
while (true) {
|
while (true) {
|
||||||
val read = readBoundedLine(reader)
|
val read = readBoundedLine(reader, MAX_MESSAGE_CHARS)
|
||||||
if (read is LineResult.EndOfStream) break
|
if (read is LineResult.EndOfStream) break
|
||||||
if (sock !== socket) break
|
if (sock !== socket) break
|
||||||
if (read is LineResult.TooLong) {
|
if (read is LineResult.TooLong) {
|
||||||
@@ -577,27 +585,6 @@ class LanTransport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class LineResult {
|
|
||||||
data class Line(val text: String) : LineResult()
|
|
||||||
object TooLong : LineResult()
|
|
||||||
object EndOfStream : LineResult()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun readBoundedLine(reader: BufferedReader): LineResult {
|
|
||||||
val builder = StringBuilder()
|
|
||||||
while (true) {
|
|
||||||
val ch = reader.read()
|
|
||||||
if (ch == -1) {
|
|
||||||
return if (builder.isEmpty()) LineResult.EndOfStream
|
|
||||||
else LineResult.Line(builder.toString())
|
|
||||||
}
|
|
||||||
if (ch == '\n'.code) return LineResult.Line(builder.toString())
|
|
||||||
if (ch == '\r'.code) continue
|
|
||||||
if (builder.length >= MAX_MESSAGE_CHARS) return LineResult.TooLong
|
|
||||||
builder.append(ch.toChar())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun send(message: GameMessage) {
|
override fun send(message: GameMessage) {
|
||||||
val json = message.toJson()
|
val json = message.toJson()
|
||||||
val size = json.length
|
val size = json.length
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package cc.skysparkle.matewave.network
|
||||||
|
|
||||||
|
import java.io.Reader
|
||||||
|
|
||||||
|
/** Result of reading one newline-delimited message from a socket. */
|
||||||
|
sealed class LineResult {
|
||||||
|
data class Line(val text: String) : LineResult()
|
||||||
|
object TooLong : LineResult()
|
||||||
|
object EndOfStream : LineResult()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads one line of at most [maxChars] characters; longer lines are reported, not buffered. */
|
||||||
|
fun readBoundedLine(reader: Reader, maxChars: Int): LineResult {
|
||||||
|
val builder = StringBuilder()
|
||||||
|
while (true) {
|
||||||
|
val ch = reader.read()
|
||||||
|
if (ch == -1) {
|
||||||
|
return if (builder.isEmpty()) LineResult.EndOfStream
|
||||||
|
else LineResult.Line(builder.toString())
|
||||||
|
}
|
||||||
|
if (ch == '\n'.code) return LineResult.Line(builder.toString())
|
||||||
|
if (ch == '\r'.code) continue
|
||||||
|
if (builder.length >= maxChars) return LineResult.TooLong
|
||||||
|
builder.append(ch.toChar())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,10 @@ data class DiscoveredPeer(
|
|||||||
val elo: Int,
|
val elo: Int,
|
||||||
val fingerprint: String,
|
val fingerprint: String,
|
||||||
|
|
||||||
val address: String
|
val address: String,
|
||||||
|
val host: String = "",
|
||||||
|
val gameTag: String = "",
|
||||||
|
val spectatePort: Int = 0
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -159,7 +162,10 @@ class LocalPresence(
|
|||||||
name = peer.displayName.ifEmpty { peer.name },
|
name = peer.displayName.ifEmpty { peer.name },
|
||||||
elo = peer.elo,
|
elo = peer.elo,
|
||||||
fingerprint = peer.fingerprint,
|
fingerprint = peer.fingerprint,
|
||||||
address = peer.id
|
address = peer.id,
|
||||||
|
host = peer.host,
|
||||||
|
gameTag = peer.gameTag,
|
||||||
|
spectatePort = peer.spectatePort
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
_peers.value = result
|
_peers.value = result
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
enum class PresenceStatus { ONLINE, IN_GAME, OFFLINE }
|
||||||
|
|
||||||
|
/** Where to watch a game: the host's address and spectator port. */
|
||||||
|
data class SpectateTarget(val host: String, val port: Int, val gameTag: String)
|
||||||
|
|
||||||
|
/** A player seen on the network, reduced to what spectating needs. */
|
||||||
|
data class NearbyPlayerGame(
|
||||||
|
val playerId: String,
|
||||||
|
val host: String,
|
||||||
|
val gameTag: String,
|
||||||
|
val spectatePort: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
data class FriendGameStatus(
|
||||||
|
val status: PresenceStatus,
|
||||||
|
val target: SpectateTarget? = null,
|
||||||
|
/** Live count from the host, null until it has answered. */
|
||||||
|
val spectators: Int? = null,
|
||||||
|
val max: Int = MAX_SPECTATORS
|
||||||
|
) {
|
||||||
|
val full: Boolean get() = spectators != null && spectators >= max
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Online, In game or Offline for one player, and where to watch. Both players of a game announce
|
||||||
|
* the same tag, but only the host serves spectators, so the guest's game is watched through the
|
||||||
|
* host. A host that says its game has ended overrides an announcement that is not updated yet.
|
||||||
|
*/
|
||||||
|
object FriendStatusResolver {
|
||||||
|
fun resolve(
|
||||||
|
playerId: String,
|
||||||
|
nearby: Map<String, NearbyPlayerGame>,
|
||||||
|
probes: Map<SpectateTarget, SpectatorMessage.Status>
|
||||||
|
): FriendGameStatus {
|
||||||
|
val player = nearby[playerId] ?: return FriendGameStatus(PresenceStatus.OFFLINE)
|
||||||
|
if (player.gameTag.isEmpty()) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||||
|
val host = hostOf(player, nearby) ?: return FriendGameStatus(PresenceStatus.IN_GAME)
|
||||||
|
val target = SpectateTarget(host.host, host.spectatePort, host.gameTag)
|
||||||
|
val probe = probes[target]
|
||||||
|
if (probe != null && !probe.inGame) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||||
|
return FriendGameStatus(PresenceStatus.IN_GAME, target, probe?.count, probe?.max ?: MAX_SPECTATORS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every host worth asking for a live spectator count. */
|
||||||
|
fun targets(nearby: Collection<NearbyPlayerGame>): Set<SpectateTarget> =
|
||||||
|
nearby.filter { it.gameTag.isNotEmpty() && it.spectatePort > 0 && it.host.isNotEmpty() }
|
||||||
|
.map { SpectateTarget(it.host, it.spectatePort, it.gameTag) }
|
||||||
|
.toSet()
|
||||||
|
|
||||||
|
private fun hostOf(player: NearbyPlayerGame, nearby: Map<String, NearbyPlayerGame>): NearbyPlayerGame? {
|
||||||
|
if (player.spectatePort > 0 && player.host.isNotEmpty()) return player
|
||||||
|
return nearby.values.firstOrNull {
|
||||||
|
it.playerId != player.playerId && it.gameTag == player.gameTag && it.spectatePort > 0 && it.host.isNotEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What this device adds to its network announcement while it plays a watchable LAN game: a short
|
||||||
|
* tag shared by both players of the game, and, on the host, the spectator port. Older app versions
|
||||||
|
* ignore these attributes.
|
||||||
|
*/
|
||||||
|
object SpectatorAdvert {
|
||||||
|
const val KEY_GAME = "g"
|
||||||
|
const val KEY_PORT = "sp"
|
||||||
|
|
||||||
|
data class State(val gameTag: String = "", val spectatePort: Int = 0)
|
||||||
|
|
||||||
|
@Volatile var current = State()
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** Returns true when the announcement has to be published again. */
|
||||||
|
@Synchronized
|
||||||
|
fun update(state: State): Boolean {
|
||||||
|
if (state == current) return false
|
||||||
|
current = state
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear(): Boolean = update(State())
|
||||||
|
|
||||||
|
fun attributes(state: State = current): Map<String, String> = buildMap {
|
||||||
|
if (state.gameTag.isNotEmpty()) put(KEY_GAME, state.gameTag)
|
||||||
|
if (state.gameTag.isNotEmpty() && state.spectatePort > 0) put(KEY_PORT, state.spectatePort.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads the attributes of a discovered player; anything malformed counts as absent. */
|
||||||
|
fun parse(attribute: (String) -> String): State {
|
||||||
|
val tag = attribute(KEY_GAME).takeIf { TAG_PATTERN.matches(it) } ?: return State()
|
||||||
|
val port = attribute(KEY_PORT).toIntOrNull()?.takeIf { it in 1..65_535 } ?: 0
|
||||||
|
return State(tag, port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Short tag of a game id, so the game id itself is not announced. */
|
||||||
|
fun tagOf(gameId: String): String {
|
||||||
|
if (gameId.isEmpty()) return ""
|
||||||
|
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
||||||
|
return digest.take(4).joinToString("") { "%02x".format(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.network.LineResult
|
||||||
|
import cc.skysparkle.matewave.network.readBoundedLine
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.RejectedExecutionException
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One spectator's connection to a hosted game. Events arrive on a background thread, in order.
|
||||||
|
* Silence longer than [Timing.silenceTimeoutMs] (the host pings every few seconds) means the host
|
||||||
|
* is gone, which also covers Wi-Fi switching off on either side.
|
||||||
|
*/
|
||||||
|
class SpectatorClient(
|
||||||
|
private val host: String,
|
||||||
|
private val port: Int,
|
||||||
|
private val onEvent: (Event) -> Unit,
|
||||||
|
private val timing: Timing = Timing(),
|
||||||
|
private val version: Int = SpectatorProtocol.VERSION,
|
||||||
|
private val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
) {
|
||||||
|
data class Timing(val connectTimeoutMs: Int = 5_000, val silenceTimeoutMs: Int = 15_000)
|
||||||
|
|
||||||
|
enum class Failure { UNREACHABLE, FULL, NO_GAME, UPDATE_THIS_APP, UPDATE_HOST_APP }
|
||||||
|
|
||||||
|
sealed class Event {
|
||||||
|
data class Joined(val welcome: SpectatorMessage.Welcome) : Event()
|
||||||
|
data class Received(val message: SpectatorMessage) : Event()
|
||||||
|
data class JoinFailed(val failure: Failure) : Event()
|
||||||
|
|
||||||
|
/** The connection ended after joining; [hostClosed] is true when the host said goodbye. */
|
||||||
|
data class Disconnected(val hostClosed: Boolean) : Event()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile private var socket: Socket? = null
|
||||||
|
@Volatile private var output: BufferedWriter? = null
|
||||||
|
@Volatile private var stopped = false
|
||||||
|
private val writer = Executors.newSingleThreadExecutor { r ->
|
||||||
|
Thread(r, "spectator-send").apply { isDaemon = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
Thread({ run() }, "spectator-receive").apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestResync() = send(SpectatorMessage.Resync)
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
if (stopped) return
|
||||||
|
stopped = true
|
||||||
|
try {
|
||||||
|
writer.execute {
|
||||||
|
writeLine(SpectatorMessage.Leave)
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
writer.shutdown()
|
||||||
|
// A send stuck on a dead connection must not keep the socket open.
|
||||||
|
Thread({
|
||||||
|
try { Thread.sleep(STOP_GRACE_MS) } catch (_: InterruptedException) {}
|
||||||
|
closeSocket()
|
||||||
|
}, "spectator-stop").apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun run() {
|
||||||
|
val s = Socket()
|
||||||
|
socket = s
|
||||||
|
val reader: BufferedReader
|
||||||
|
try {
|
||||||
|
if (stopped) throw IOException("Stopped")
|
||||||
|
s.tcpNoDelay = true
|
||||||
|
s.connect(InetSocketAddress(host, port), timing.connectTimeoutMs)
|
||||||
|
s.soTimeout = timing.silenceTimeoutMs
|
||||||
|
output = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
} catch (e: IOException) {
|
||||||
|
closeSocket()
|
||||||
|
emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
send(SpectatorMessage.Hello(minVersion))
|
||||||
|
|
||||||
|
var joined = false
|
||||||
|
var hostClosed = false
|
||||||
|
try {
|
||||||
|
while (!stopped) {
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
if (read !is LineResult.Line) break
|
||||||
|
val envelope = SpectatorProtocol.decode(read.text) ?: continue
|
||||||
|
val message = envelope.message
|
||||||
|
if (!joined) {
|
||||||
|
// reject keeps its shape across versions, so read it before the version gate.
|
||||||
|
if (message is SpectatorMessage.Reject) {
|
||||||
|
emit(Event.JoinFailed(failureOf(message)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (envelope.version < minVersion) {
|
||||||
|
emit(Event.JoinFailed(Failure.UPDATE_HOST_APP))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (message is SpectatorMessage.Welcome) {
|
||||||
|
joined = true
|
||||||
|
emit(Event.Joined(message))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
when (message) {
|
||||||
|
null -> Unit
|
||||||
|
SpectatorMessage.Closing -> hostClosed = true
|
||||||
|
is SpectatorMessage.Ping -> {
|
||||||
|
send(SpectatorMessage.Pong)
|
||||||
|
emit(Event.Received(message))
|
||||||
|
}
|
||||||
|
else -> emit(Event.Received(message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Silence timeout or connection reset.
|
||||||
|
} finally {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
if (joined) emit(Event.Disconnected(hostClosed)) else emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failureOf(reject: SpectatorMessage.Reject): Failure = when (reject.reason) {
|
||||||
|
RejectReason.FULL -> Failure.FULL
|
||||||
|
RejectReason.NO_GAME -> Failure.NO_GAME
|
||||||
|
RejectReason.UPDATE_REQUIRED ->
|
||||||
|
if (version < reject.minVersion) Failure.UPDATE_THIS_APP else Failure.UPDATE_HOST_APP
|
||||||
|
RejectReason.OTHER -> Failure.UNREACHABLE
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun emit(event: Event) {
|
||||||
|
if (!stopped) onEvent(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun send(message: SpectatorMessage) {
|
||||||
|
try {
|
||||||
|
writer.execute { writeLine(message) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
// Stopped.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeLine(message: SpectatorMessage) {
|
||||||
|
val out = output ?: return
|
||||||
|
try {
|
||||||
|
out.write(SpectatorProtocol.encode(message, version))
|
||||||
|
out.write("\n")
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeSocket() {
|
||||||
|
try { socket?.close() } catch (_: IOException) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val STOP_GRACE_MS = 500L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-shot status query, used to show live spectator counts in the Friends list. */
|
||||||
|
object SpectatorProbe {
|
||||||
|
fun query(host: String, port: Int, timeoutMs: Int = 2_000): SpectatorMessage.Status? = try {
|
||||||
|
Socket().use { s ->
|
||||||
|
s.connect(InetSocketAddress(host, port), timeoutMs)
|
||||||
|
s.soTimeout = timeoutMs
|
||||||
|
val out = s.getOutputStream()
|
||||||
|
out.write((SpectatorProtocol.encode(SpectatorMessage.StatusQuery) + "\n").toByteArray(Charsets.UTF_8))
|
||||||
|
out.flush()
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
(read as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text)?.message as? SpectatorMessage.Status }
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.Board
|
||||||
|
import cc.skysparkle.matewave.engine.ChessEngine
|
||||||
|
import cc.skysparkle.matewave.engine.GameStatus
|
||||||
|
import cc.skysparkle.matewave.engine.Move
|
||||||
|
import cc.skysparkle.matewave.engine.Notation
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.opposite
|
||||||
|
|
||||||
|
/** What a spectator sees of a game. */
|
||||||
|
data class SpectatorView(
|
||||||
|
val gameId: String,
|
||||||
|
val white: SpectatorPlayer,
|
||||||
|
val black: SpectatorPlayer,
|
||||||
|
val startBoard: Board,
|
||||||
|
val board: Board,
|
||||||
|
val movesUci: List<String>,
|
||||||
|
val moveSans: List<String>,
|
||||||
|
val lastMove: Move?,
|
||||||
|
val initialSeconds: Int,
|
||||||
|
val incrementSeconds: Int,
|
||||||
|
val clock: SpectatorClock?,
|
||||||
|
val result: SpectatorResult?
|
||||||
|
) {
|
||||||
|
val ply: Int get() = movesUci.size
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The spectator's copy of the game, rebuilt from a snapshot and moved forward by live moves. Moves
|
||||||
|
* are checked against the rules; anything that does not follow on asks for a fresh snapshot.
|
||||||
|
*/
|
||||||
|
class SpectatorGame {
|
||||||
|
enum class Applied { APPLIED, IGNORED, NEEDS_RESYNC }
|
||||||
|
|
||||||
|
var view: SpectatorView? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
fun load(snapshot: SpectatorSnapshot): Boolean {
|
||||||
|
val start = Board.startPosition()
|
||||||
|
var board = start
|
||||||
|
val sans = ArrayList<String>(snapshot.movesUci.size)
|
||||||
|
var last: Move? = null
|
||||||
|
for (uci in snapshot.movesUci) {
|
||||||
|
val move = resolve(board, uci) ?: return false
|
||||||
|
sans.add(Notation.toSan(board, move))
|
||||||
|
board = ChessEngine.applyMove(board, move)
|
||||||
|
last = move
|
||||||
|
}
|
||||||
|
view = SpectatorView(
|
||||||
|
gameId = snapshot.gameId,
|
||||||
|
white = snapshot.white,
|
||||||
|
black = snapshot.black,
|
||||||
|
startBoard = start,
|
||||||
|
board = board,
|
||||||
|
movesUci = snapshot.movesUci,
|
||||||
|
moveSans = sans,
|
||||||
|
lastMove = last,
|
||||||
|
initialSeconds = snapshot.initialSeconds,
|
||||||
|
incrementSeconds = snapshot.incrementSeconds,
|
||||||
|
clock = snapshot.clock,
|
||||||
|
result = snapshot.result
|
||||||
|
)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMove(message: SpectatorMessage.MovePlayed): Applied {
|
||||||
|
val current = view ?: return Applied.NEEDS_RESYNC
|
||||||
|
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||||
|
if (current.result != null || message.ply <= current.ply) return Applied.IGNORED
|
||||||
|
if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
||||||
|
val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
||||||
|
view = current.copy(
|
||||||
|
board = ChessEngine.applyMove(current.board, move),
|
||||||
|
movesUci = current.movesUci + move.toUci(),
|
||||||
|
moveSans = current.moveSans + Notation.toSan(current.board, move),
|
||||||
|
lastMove = move,
|
||||||
|
clock = message.clock ?: current.clock
|
||||||
|
)
|
||||||
|
return Applied.APPLIED
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onGameOver(message: SpectatorMessage.GameOver): Applied {
|
||||||
|
val current = view ?: return Applied.NEEDS_RESYNC
|
||||||
|
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||||
|
view = current.copy(
|
||||||
|
result = message.result,
|
||||||
|
clock = (message.clock ?: current.clock)?.copy(running = null)
|
||||||
|
)
|
||||||
|
return Applied.APPLIED
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onClock(clock: SpectatorClock?) {
|
||||||
|
val current = view ?: return
|
||||||
|
if (clock == null || current.result != null) return
|
||||||
|
view = current.copy(clock = clock)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolve(board: Board, uci: String): Move? {
|
||||||
|
if (uci.length !in 4..5) return null
|
||||||
|
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
||||||
|
if (candidate.from !in 0..63 || candidate.to !in 0..63) return null
|
||||||
|
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
||||||
|
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Turns successive host snapshots into the messages spectators need to follow along. */
|
||||||
|
object SpectatorDiff {
|
||||||
|
fun between(old: SpectatorSnapshot?, new: SpectatorSnapshot): List<SpectatorMessage> {
|
||||||
|
if (old == null) return emptyList()
|
||||||
|
if (old.gameId != new.gameId || old.white != new.white || old.black != new.black) {
|
||||||
|
return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
val events = ArrayList<SpectatorMessage>()
|
||||||
|
val before = old.movesUci
|
||||||
|
val after = new.movesUci
|
||||||
|
if (after != before) {
|
||||||
|
if (after.size <= before.size || after.subList(0, before.size) != before) {
|
||||||
|
return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
for (i in before.size until after.size) {
|
||||||
|
val isLast = i == after.lastIndex
|
||||||
|
events += SpectatorMessage.MovePlayed(new.gameId, i + 1, after[i], if (isLast) new.clock else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
old.result == null && new.result != null -> events += SpectatorMessage.GameOver(new.gameId, new.result, new.clock)
|
||||||
|
old.result != null && new.result != old.result -> return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
return events
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Result of a finished game as spectators are told it. */
|
||||||
|
object SpectatorResults {
|
||||||
|
fun of(
|
||||||
|
status: GameStatus,
|
||||||
|
sideToMove: PieceColor,
|
||||||
|
timedOutSide: PieceColor?,
|
||||||
|
resignedSide: PieceColor?,
|
||||||
|
leftMidGame: Boolean
|
||||||
|
): SpectatorResult? = when (status) {
|
||||||
|
GameStatus.ONGOING -> null
|
||||||
|
GameStatus.CHECKMATE -> SpectatorResult(SpectatorOutcome.CHECKMATE, sideToMove.opposite())
|
||||||
|
GameStatus.STALEMATE -> SpectatorResult(SpectatorOutcome.STALEMATE, null)
|
||||||
|
GameStatus.DRAW_50_MOVES -> SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null)
|
||||||
|
GameStatus.DRAW_REPETITION -> SpectatorResult(SpectatorOutcome.REPETITION, null)
|
||||||
|
GameStatus.DRAW_MATERIAL -> SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null)
|
||||||
|
GameStatus.TIMEOUT -> SpectatorResult(SpectatorOutcome.TIMEOUT, timedOutSide?.opposite())
|
||||||
|
GameStatus.TIMEOUT_DRAW -> SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null)
|
||||||
|
GameStatus.RESIGNATION -> SpectatorResult(
|
||||||
|
if (leftMidGame) SpectatorOutcome.LEFT else SpectatorOutcome.RESIGNATION,
|
||||||
|
resignedSide?.opposite()
|
||||||
|
)
|
||||||
|
GameStatus.DRAW_AGREEMENT -> SpectatorResult(SpectatorOutcome.AGREEMENT, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun leftBy(side: PieceColor) = SpectatorResult(SpectatorOutcome.LEFT, side.opposite())
|
||||||
|
|
||||||
|
val interrupted = SpectatorResult(SpectatorOutcome.INTERRUPTED, null)
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.network.LineResult
|
||||||
|
import cc.skysparkle.matewave.network.readBoundedLine
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
import java.net.Socket
|
||||||
|
import java.net.SocketTimeoutException
|
||||||
|
import java.util.concurrent.ArrayBlockingQueue
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.RejectedExecutionException
|
||||||
|
import java.util.concurrent.ThreadFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs on the host player's device and streams the game to up to [maxSpectators] spectators on
|
||||||
|
* its own listening socket; the players' connection is never touched. Each spectator gets its own
|
||||||
|
* bounded queue and writer thread, so a slow or vanished spectator is dropped without delaying
|
||||||
|
* the game or anyone else. Spectators can only listen: anything they send besides keepalives and
|
||||||
|
* resync requests is ignored.
|
||||||
|
*/
|
||||||
|
class SpectatorHub(
|
||||||
|
private val maxSpectators: Int = MAX_SPECTATORS,
|
||||||
|
private val timing: Timing = Timing(),
|
||||||
|
private val log: (String) -> Unit = {}
|
||||||
|
) {
|
||||||
|
data class Timing(
|
||||||
|
val helloTimeoutMs: Int = 5_000,
|
||||||
|
val pingIntervalMs: Long = 5_000,
|
||||||
|
/** A spectator that answers no ping for this long is gone (e.g. its Wi-Fi went off). */
|
||||||
|
val silenceTimeoutMs: Int = 20_000,
|
||||||
|
val queueCapacity: Int = 512
|
||||||
|
)
|
||||||
|
|
||||||
|
private val lock = Any()
|
||||||
|
private val spectators = LinkedHashSet<Spectator>()
|
||||||
|
private var latest: SpectatorSnapshot? = null
|
||||||
|
private var latestAtNanos = 0L
|
||||||
|
private var closed = false
|
||||||
|
private var server: ServerSocket? = null
|
||||||
|
private val handshaking = AtomicInteger()
|
||||||
|
|
||||||
|
private val threads = Executors.newCachedThreadPool(daemonThreads("spectator"))
|
||||||
|
private val ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("spectator-ping"))
|
||||||
|
|
||||||
|
private val _count = MutableStateFlow(0)
|
||||||
|
val count: StateFlow<Int> = _count
|
||||||
|
|
||||||
|
val port: Int get() = server?.localPort ?: 0
|
||||||
|
|
||||||
|
/** Opens the spectator socket on [bindAddress] (all interfaces by default) and returns its port. */
|
||||||
|
fun start(bindAddress: InetAddress? = null): Int {
|
||||||
|
val socket = synchronized(lock) {
|
||||||
|
check(!closed) { "Hub is closed" }
|
||||||
|
server?.let { return it.localPort }
|
||||||
|
ServerSocket().also {
|
||||||
|
it.reuseAddress = true
|
||||||
|
it.bind(InetSocketAddress(bindAddress, 0))
|
||||||
|
server = it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
threads.execute { acceptLoop(socket) }
|
||||||
|
ticker.scheduleAtFixedRate(
|
||||||
|
{ runCatching { sendPings() } },
|
||||||
|
timing.pingIntervalMs, timing.pingIntervalMs, TimeUnit.MILLISECONDS
|
||||||
|
)
|
||||||
|
return socket.localPort
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the current game state and sends [events] to every spectator, atomically. */
|
||||||
|
fun publish(snapshot: SpectatorSnapshot, events: List<SpectatorMessage> = emptyList()) {
|
||||||
|
synchronized(lock) {
|
||||||
|
if (closed) return
|
||||||
|
latest = snapshot
|
||||||
|
latestAtNanos = System.nanoTime()
|
||||||
|
if (events.isEmpty() || spectators.isEmpty()) return
|
||||||
|
val targets = spectators.toList()
|
||||||
|
events.forEach { deliver(targets, SpectatorProtocol.encode(it)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sends [finalEvents] and a goodbye to everyone, then stops accepting and closes. */
|
||||||
|
fun close(finalEvents: List<SpectatorMessage> = emptyList()) {
|
||||||
|
val targets = synchronized(lock) {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
spectators.toList().also { spectators.clear() }
|
||||||
|
}
|
||||||
|
_count.value = 0
|
||||||
|
val lines = finalEvents.map { SpectatorProtocol.encode(it) } + SpectatorProtocol.encode(SpectatorMessage.Closing)
|
||||||
|
targets.forEach { spectator ->
|
||||||
|
lines.forEach { spectator.offer(it) }
|
||||||
|
spectator.finish()
|
||||||
|
}
|
||||||
|
closeQuietly(server)
|
||||||
|
ticker.shutdownNow()
|
||||||
|
threads.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun acceptLoop(socket: ServerSocket) {
|
||||||
|
while (!socket.isClosed) {
|
||||||
|
val client = try {
|
||||||
|
socket.accept()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
if (socket.isClosed) return
|
||||||
|
log("Spectator accept failed: ${e.message}")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (handshaking.incrementAndGet() > MAX_HANDSHAKING) {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
closeQuietly(client)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
threads.execute { serve(client) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
closeQuietly(client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun serve(client: Socket) {
|
||||||
|
var spectator: Spectator? = null
|
||||||
|
var reader: BufferedReader? = null
|
||||||
|
try {
|
||||||
|
client.tcpNoDelay = true
|
||||||
|
client.soTimeout = timing.helloTimeoutMs
|
||||||
|
reader = BufferedReader(InputStreamReader(client.getInputStream(), Charsets.UTF_8))
|
||||||
|
val first = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||||
|
val envelope = (first as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text) }
|
||||||
|
when (envelope?.message) {
|
||||||
|
SpectatorMessage.StatusQuery -> reply(client, status())
|
||||||
|
is SpectatorMessage.Hello -> {
|
||||||
|
if (envelope.version < SpectatorProtocol.MIN_COMPATIBLE_VERSION) {
|
||||||
|
log("Spectator with protocol ${envelope.version} told to update")
|
||||||
|
reply(client, SpectatorMessage.Reject(RejectReason.UPDATE_REQUIRED, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||||
|
} else {
|
||||||
|
spectator = admit(client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Timed out or closed before saying hello.
|
||||||
|
} finally {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
if (spectator == null) closeQuietly(client)
|
||||||
|
}
|
||||||
|
val admitted = spectator ?: return
|
||||||
|
listen(admitted, reader ?: return)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun admit(client: Socket): Spectator? {
|
||||||
|
var reject: RejectReason? = null
|
||||||
|
var spectator: Spectator? = null
|
||||||
|
synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
when {
|
||||||
|
closed || game == null -> reject = RejectReason.NO_GAME
|
||||||
|
spectators.size >= maxSpectators -> reject = RejectReason.FULL
|
||||||
|
else -> {
|
||||||
|
val joined = Spectator(client, timing.queueCapacity)
|
||||||
|
val others = spectators.toList()
|
||||||
|
spectators.add(joined)
|
||||||
|
val n = spectators.size
|
||||||
|
_count.value = n
|
||||||
|
joined.offer(SpectatorProtocol.encode(SpectatorMessage.Welcome(n, maxSpectators, liveSnapshot(game))))
|
||||||
|
deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(n, maxSpectators)))
|
||||||
|
spectator = joined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reject?.let {
|
||||||
|
reply(client, SpectatorMessage.Reject(it, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val joined = spectator ?: return null
|
||||||
|
try {
|
||||||
|
threads.execute { write(joined) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
drop(joined)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return joined
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun listen(spectator: Spectator, reader: BufferedReader) {
|
||||||
|
try {
|
||||||
|
spectator.socket.soTimeout = timing.silenceTimeoutMs
|
||||||
|
while (true) {
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||||
|
if (read !is LineResult.Line) break
|
||||||
|
when (SpectatorProtocol.decode(read.text)?.message) {
|
||||||
|
SpectatorMessage.Resync -> synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
if (game != null && !closed) {
|
||||||
|
deliver(listOf(spectator), SpectatorProtocol.encode(SpectatorMessage.NewGame(liveSnapshot(game))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SpectatorMessage.Leave -> break
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: SocketTimeoutException) {
|
||||||
|
log("Spectator silent for ${timing.silenceTimeoutMs / 1000} s, dropped")
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Connection reset.
|
||||||
|
} finally {
|
||||||
|
drop(spectator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun write(spectator: Spectator) {
|
||||||
|
try {
|
||||||
|
val out = BufferedWriter(OutputStreamWriter(spectator.socket.getOutputStream(), Charsets.UTF_8))
|
||||||
|
while (true) {
|
||||||
|
val item = spectator.queue.take()
|
||||||
|
if (item === POISON) break
|
||||||
|
out.write(item as String)
|
||||||
|
out.write("\n")
|
||||||
|
if (spectator.queue.isEmpty()) out.flush()
|
||||||
|
}
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Spectator went away.
|
||||||
|
} catch (e: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
} finally {
|
||||||
|
drop(spectator)
|
||||||
|
closeQuietly(spectator.socket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendPings() {
|
||||||
|
val line: String
|
||||||
|
val targets: List<Spectator>
|
||||||
|
synchronized(lock) {
|
||||||
|
if (closed || spectators.isEmpty()) return
|
||||||
|
line = SpectatorProtocol.encode(SpectatorMessage.Ping(liveClock()))
|
||||||
|
targets = spectators.toList()
|
||||||
|
}
|
||||||
|
deliver(targets, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deliver(targets: List<Spectator>, line: String) {
|
||||||
|
for (spectator in targets) {
|
||||||
|
if (!spectator.offer(line)) {
|
||||||
|
log("Spectator too slow, dropped")
|
||||||
|
drop(spectator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun drop(spectator: Spectator) {
|
||||||
|
val others: List<Spectator>
|
||||||
|
val remaining: Int
|
||||||
|
synchronized(lock) {
|
||||||
|
// Already dropped, or the hub is closing and its writer is flushing the goodbye.
|
||||||
|
if (!spectators.remove(spectator)) return
|
||||||
|
remaining = spectators.size
|
||||||
|
_count.value = remaining
|
||||||
|
others = spectators.toList()
|
||||||
|
}
|
||||||
|
spectator.shutdown()
|
||||||
|
if (!closed) deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(remaining, maxSpectators)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun status(): SpectatorMessage.Status = synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
SpectatorMessage.Status(
|
||||||
|
inGame = !closed && game != null && game.result == null,
|
||||||
|
count = spectators.size,
|
||||||
|
max = maxSpectators,
|
||||||
|
minVersion = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun elapsedMs(): Long = (System.nanoTime() - latestAtNanos) / 1_000_000L
|
||||||
|
|
||||||
|
private fun liveClock(): SpectatorClock? = latest?.clock?.advancedBy(elapsedMs())
|
||||||
|
|
||||||
|
private fun liveSnapshot(game: SpectatorSnapshot): SpectatorSnapshot =
|
||||||
|
if (game.clock == null) game else game.copy(clock = game.clock.advancedBy(elapsedMs()))
|
||||||
|
|
||||||
|
private fun reply(client: Socket, message: SpectatorMessage) {
|
||||||
|
try {
|
||||||
|
val out = client.getOutputStream()
|
||||||
|
out.write((SpectatorProtocol.encode(message) + "\n").toByteArray(Charsets.UTF_8))
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Nothing more to tell a peer that is gone.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One spectator's outgoing queue; one slot is kept free for the end marker. */
|
||||||
|
private class Spectator(val socket: Socket, private val capacity: Int) {
|
||||||
|
val queue = ArrayBlockingQueue<Any>(capacity + 1)
|
||||||
|
private var open = true
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun offer(line: String): Boolean = open && queue.size < capacity && queue.offer(line)
|
||||||
|
|
||||||
|
/** Lets the writer send what is queued, then close. */
|
||||||
|
@Synchronized
|
||||||
|
fun finish() {
|
||||||
|
if (!open) return
|
||||||
|
open = false
|
||||||
|
queue.offer(POISON)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops at once, discarding anything unsent. */
|
||||||
|
@Synchronized
|
||||||
|
fun shutdown() {
|
||||||
|
open = false
|
||||||
|
queue.clear()
|
||||||
|
queue.offer(POISON)
|
||||||
|
closeQuietly(socket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
val POISON = Any()
|
||||||
|
|
||||||
|
/** Connections allowed to sit in the hello phase at once. */
|
||||||
|
const val MAX_HANDSHAKING = 32
|
||||||
|
|
||||||
|
fun closeQuietly(c: Closeable?) {
|
||||||
|
try { c?.close() } catch (_: IOException) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun daemonThreads(name: String): ThreadFactory {
|
||||||
|
val n = AtomicInteger()
|
||||||
|
return ThreadFactory { r -> Thread(r, "$name-${n.incrementAndGet()}").apply { isDaemon = true } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Feeds a hub from the host's game: each new snapshot becomes the messages spectators need. */
|
||||||
|
class SpectatorBroadcaster(val hub: SpectatorHub) {
|
||||||
|
private var last: SpectatorSnapshot? = null
|
||||||
|
|
||||||
|
fun update(snapshot: SpectatorSnapshot) {
|
||||||
|
val events = SpectatorDiff.between(last, snapshot)
|
||||||
|
last = snapshot
|
||||||
|
hub.publish(snapshot, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops spectating; [final] is the last state, e.g. the result of a game left midway. */
|
||||||
|
fun close(final: SpectatorSnapshot? = null) {
|
||||||
|
val events = if (final != null) SpectatorDiff.between(last, final) else emptyList()
|
||||||
|
hub.close(events)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/** Most spectators one hosted game accepts at the same time. */
|
||||||
|
const val MAX_SPECTATORS = 20
|
||||||
|
|
||||||
|
data class SpectatorPlayer(val id: String, val name: String, val elo: Int)
|
||||||
|
|
||||||
|
data class SpectatorClock(val whiteMs: Long, val blackMs: Long, val running: PieceColor?) {
|
||||||
|
/** The same clock [elapsedMs] later. */
|
||||||
|
fun advancedBy(elapsedMs: Long): SpectatorClock {
|
||||||
|
if (elapsedMs <= 0) return this
|
||||||
|
return when (running) {
|
||||||
|
PieceColor.WHITE -> copy(whiteMs = (whiteMs - elapsedMs).coerceAtLeast(0))
|
||||||
|
PieceColor.BLACK -> copy(blackMs = (blackMs - elapsedMs).coerceAtLeast(0))
|
||||||
|
null -> this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class SpectatorOutcome(val wire: String) {
|
||||||
|
CHECKMATE("checkmate"),
|
||||||
|
STALEMATE("stalemate"),
|
||||||
|
FIFTY_MOVES("fifty"),
|
||||||
|
REPETITION("repetition"),
|
||||||
|
INSUFFICIENT_MATERIAL("material"),
|
||||||
|
TIMEOUT("timeout"),
|
||||||
|
TIMEOUT_DRAW("timeout_draw"),
|
||||||
|
RESIGNATION("resign"),
|
||||||
|
AGREEMENT("agreement"),
|
||||||
|
LEFT("left"),
|
||||||
|
INTERRUPTED("interrupted"),
|
||||||
|
UNKNOWN("unknown");
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromWire(value: String): SpectatorOutcome = entries.firstOrNull { it.wire == value } ?: UNKNOWN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a game ended; [winner] is null for draws and interrupted games. */
|
||||||
|
data class SpectatorResult(val outcome: SpectatorOutcome, val winner: PieceColor?)
|
||||||
|
|
||||||
|
/** Everything a spectator needs to show a game from any point: players, moves, clocks, result. */
|
||||||
|
data class SpectatorSnapshot(
|
||||||
|
val gameId: String,
|
||||||
|
val white: SpectatorPlayer,
|
||||||
|
val black: SpectatorPlayer,
|
||||||
|
val movesUci: List<String>,
|
||||||
|
val initialSeconds: Int,
|
||||||
|
val incrementSeconds: Int,
|
||||||
|
val clock: SpectatorClock?,
|
||||||
|
val result: SpectatorResult? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class RejectReason(val wire: String) {
|
||||||
|
FULL("full"),
|
||||||
|
UPDATE_REQUIRED("update"),
|
||||||
|
NO_GAME("no_game"),
|
||||||
|
OTHER("other");
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromWire(value: String): RejectReason = entries.firstOrNull { it.wire == value } ?: OTHER
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class SpectatorMessage {
|
||||||
|
// Spectator to host.
|
||||||
|
data class Hello(val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION) : SpectatorMessage()
|
||||||
|
data object StatusQuery : SpectatorMessage()
|
||||||
|
data object Pong : SpectatorMessage()
|
||||||
|
data object Resync : SpectatorMessage()
|
||||||
|
data object Leave : SpectatorMessage()
|
||||||
|
|
||||||
|
// Host to spectator.
|
||||||
|
data class Welcome(val count: Int, val max: Int, val game: SpectatorSnapshot) : SpectatorMessage()
|
||||||
|
data class Status(val inGame: Boolean, val count: Int, val max: Int, val minVersion: Int) : SpectatorMessage()
|
||||||
|
data class Reject(val reason: RejectReason, val minVersion: Int) : SpectatorMessage()
|
||||||
|
data class MovePlayed(val gameId: String, val ply: Int, val uci: String, val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data class GameOver(val gameId: String, val result: SpectatorResult, val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data class NewGame(val game: SpectatorSnapshot) : SpectatorMessage()
|
||||||
|
data class Count(val count: Int, val max: Int) : SpectatorMessage()
|
||||||
|
data class Ping(val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data object Closing : SpectatorMessage()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One decoded line: the sender's protocol version and the message, or null for an unknown type. */
|
||||||
|
data class SpectatorEnvelope(val version: Int, val message: SpectatorMessage?)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wire format between a hosted game and its spectators: one JSON object per line, each carrying
|
||||||
|
* the sender's protocol version in "sv". Unknown types are skipped, never fatal.
|
||||||
|
*/
|
||||||
|
object SpectatorProtocol {
|
||||||
|
/**
|
||||||
|
* Bump on incompatible changes and raise [MIN_COMPATIBLE_VERSION] to the oldest version still
|
||||||
|
* understood. hello, status and reject keep their shape so any two versions can still tell
|
||||||
|
* each other that an update is required.
|
||||||
|
*/
|
||||||
|
const val VERSION = 1
|
||||||
|
const val MIN_COMPATIBLE_VERSION = 1
|
||||||
|
|
||||||
|
const val MAX_HOST_LINE_CHARS = 64_000
|
||||||
|
const val MAX_CLIENT_LINE_CHARS = 1_024
|
||||||
|
|
||||||
|
private const val MAX_NAME_CHARS = 40
|
||||||
|
private const val MAX_PLIES = 2_000
|
||||||
|
|
||||||
|
fun encode(message: SpectatorMessage, version: Int = VERSION): String {
|
||||||
|
val o = JSONObject()
|
||||||
|
o.put("sv", version)
|
||||||
|
when (message) {
|
||||||
|
is SpectatorMessage.Hello -> { o.put("type", "hello"); o.put("min", message.minVersion) }
|
||||||
|
SpectatorMessage.StatusQuery -> o.put("type", "query")
|
||||||
|
SpectatorMessage.Pong -> o.put("type", "pong")
|
||||||
|
SpectatorMessage.Resync -> o.put("type", "resync")
|
||||||
|
SpectatorMessage.Leave -> o.put("type", "leave")
|
||||||
|
is SpectatorMessage.Welcome -> {
|
||||||
|
o.put("type", "welcome"); o.put("n", message.count); o.put("max", message.max)
|
||||||
|
o.put("game", snapshotJson(message.game))
|
||||||
|
}
|
||||||
|
is SpectatorMessage.Status -> {
|
||||||
|
o.put("type", "status"); o.put("live", message.inGame)
|
||||||
|
o.put("n", message.count); o.put("max", message.max); o.put("min", message.minVersion)
|
||||||
|
}
|
||||||
|
is SpectatorMessage.Reject -> {
|
||||||
|
o.put("type", "reject"); o.put("reason", message.reason.wire); o.put("min", message.minVersion)
|
||||||
|
}
|
||||||
|
is SpectatorMessage.MovePlayed -> {
|
||||||
|
o.put("type", "move"); o.put("gid", message.gameId); o.put("ply", message.ply); o.put("uci", message.uci)
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
is SpectatorMessage.GameOver -> {
|
||||||
|
o.put("type", "end"); o.put("gid", message.gameId); o.put("result", resultJson(message.result))
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
is SpectatorMessage.NewGame -> { o.put("type", "game"); o.put("game", snapshotJson(message.game)) }
|
||||||
|
is SpectatorMessage.Count -> { o.put("type", "count"); o.put("n", message.count); o.put("max", message.max) }
|
||||||
|
is SpectatorMessage.Ping -> {
|
||||||
|
o.put("type", "ping")
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
SpectatorMessage.Closing -> o.put("type", "closing")
|
||||||
|
}
|
||||||
|
return o.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null when the line is not a protocol message at all. */
|
||||||
|
fun decode(line: String): SpectatorEnvelope? {
|
||||||
|
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||||
|
val type = o.optString("type", "")
|
||||||
|
if (type.isEmpty()) return null
|
||||||
|
val version = o.optInt("sv", 0)
|
||||||
|
val message = runCatching { decodeMessage(type, o) }.getOrNull()
|
||||||
|
return SpectatorEnvelope(version, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeMessage(type: String, o: JSONObject): SpectatorMessage? = when (type) {
|
||||||
|
"hello" -> SpectatorMessage.Hello(o.optInt("min", o.optInt("sv", 0)))
|
||||||
|
"query" -> SpectatorMessage.StatusQuery
|
||||||
|
"pong" -> SpectatorMessage.Pong
|
||||||
|
"resync" -> SpectatorMessage.Resync
|
||||||
|
"leave" -> SpectatorMessage.Leave
|
||||||
|
"welcome" -> SpectatorMessage.Welcome(o.getInt("n"), o.getInt("max"), parseSnapshot(o.getJSONObject("game")))
|
||||||
|
"status" -> SpectatorMessage.Status(o.getBoolean("live"), o.getInt("n"), o.getInt("max"), o.optInt("min", 0))
|
||||||
|
"reject" -> SpectatorMessage.Reject(RejectReason.fromWire(o.getString("reason")), o.optInt("min", 0))
|
||||||
|
"move" -> SpectatorMessage.MovePlayed(
|
||||||
|
o.getString("gid"), o.getInt("ply"), o.getString("uci"), o.optJSONObject("clock")?.let(::parseClock)
|
||||||
|
)
|
||||||
|
"end" -> SpectatorMessage.GameOver(
|
||||||
|
o.getString("gid"), parseResult(o.getJSONObject("result")), o.optJSONObject("clock")?.let(::parseClock)
|
||||||
|
)
|
||||||
|
"game" -> SpectatorMessage.NewGame(parseSnapshot(o.getJSONObject("game")))
|
||||||
|
"count" -> SpectatorMessage.Count(o.getInt("n"), o.getInt("max"))
|
||||||
|
"ping" -> SpectatorMessage.Ping(o.optJSONObject("clock")?.let(::parseClock))
|
||||||
|
"closing" -> SpectatorMessage.Closing
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sideWire(side: PieceColor?): String = when (side) {
|
||||||
|
PieceColor.WHITE -> "w"
|
||||||
|
PieceColor.BLACK -> "b"
|
||||||
|
null -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sideOf(wire: String): PieceColor? = when (wire) {
|
||||||
|
"w" -> PieceColor.WHITE
|
||||||
|
"b" -> PieceColor.BLACK
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clockJson(c: SpectatorClock) = JSONObject().apply {
|
||||||
|
put("w", c.whiteMs); put("b", c.blackMs)
|
||||||
|
if (c.running != null) put("r", sideWire(c.running))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseClock(o: JSONObject) = SpectatorClock(
|
||||||
|
whiteMs = o.getLong("w").coerceAtLeast(0),
|
||||||
|
blackMs = o.getLong("b").coerceAtLeast(0),
|
||||||
|
running = sideOf(o.optString("r", ""))
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun resultJson(r: SpectatorResult) = JSONObject().apply {
|
||||||
|
put("o", r.outcome.wire)
|
||||||
|
if (r.winner != null) put("w", sideWire(r.winner))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseResult(o: JSONObject) = SpectatorResult(
|
||||||
|
outcome = SpectatorOutcome.fromWire(o.getString("o")),
|
||||||
|
winner = sideOf(o.optString("w", ""))
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun playerJson(p: SpectatorPlayer) = JSONObject().apply {
|
||||||
|
put("id", p.id); put("name", p.name); put("elo", p.elo)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parsePlayer(o: JSONObject) = SpectatorPlayer(
|
||||||
|
id = o.optString("id", "").take(64),
|
||||||
|
name = o.optString("name", "").take(MAX_NAME_CHARS),
|
||||||
|
elo = o.optInt("elo", 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun snapshotJson(s: SpectatorSnapshot) = JSONObject().apply {
|
||||||
|
put("gid", s.gameId)
|
||||||
|
put("wp", playerJson(s.white))
|
||||||
|
put("bp", playerJson(s.black))
|
||||||
|
put("moves", JSONArray().also { array -> s.movesUci.forEach { array.put(it) } })
|
||||||
|
put("ti", s.initialSeconds)
|
||||||
|
put("tx", s.incrementSeconds)
|
||||||
|
s.clock?.let { put("clock", clockJson(it)) }
|
||||||
|
s.result?.let { put("result", resultJson(it)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseSnapshot(o: JSONObject): SpectatorSnapshot {
|
||||||
|
val array = o.getJSONArray("moves")
|
||||||
|
require(array.length() <= MAX_PLIES)
|
||||||
|
return SpectatorSnapshot(
|
||||||
|
gameId = o.getString("gid"),
|
||||||
|
white = parsePlayer(o.getJSONObject("wp")),
|
||||||
|
black = parsePlayer(o.getJSONObject("bp")),
|
||||||
|
movesUci = List(array.length()) { array.getString(it) },
|
||||||
|
initialSeconds = o.optInt("ti", 0),
|
||||||
|
incrementSeconds = o.optInt("tx", 0),
|
||||||
|
clock = o.optJSONObject("clock")?.let(::parseClock),
|
||||||
|
result = o.optJSONObject("result")?.let(::parseResult)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -78,14 +78,16 @@ fun ChessBoardView(
|
|||||||
interactionEnabled: Boolean = true,
|
interactionEnabled: Boolean = true,
|
||||||
/** A square briefly tinted to confirm or reject a move (puzzles). */
|
/** A square briefly tinted to confirm or reject a move (puzzles). */
|
||||||
flashSquare: Int? = null,
|
flashSquare: Int? = null,
|
||||||
flashColor: Color = Color.Transparent
|
flashColor: Color = Color.Transparent,
|
||||||
|
/** Overrides the last-move setting; null follows it. */
|
||||||
|
highlightLastMove: Boolean? = null
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val appearance = remember { BoardAppearance(context) }
|
val appearance = remember { BoardAppearance(context) }
|
||||||
val theme = appearance.theme
|
val theme = appearance.theme
|
||||||
val showCoords = appearance.showCoordinates
|
val showCoords = appearance.showCoordinates
|
||||||
val imagePieces = appearance.useImagePieces
|
val imagePieces = appearance.useImagePieces
|
||||||
val showLastMove = appearance.showLastMove
|
val showLastMove = highlightLastMove ?: appearance.showLastMove
|
||||||
val showCheck = appearance.showCheckHighlight
|
val showCheck = appearance.showCheckHighlight
|
||||||
|
|
||||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
import cc.skysparkle.matewave.engine.Piece
|
import cc.skysparkle.matewave.engine.Piece
|
||||||
@@ -39,6 +42,14 @@ fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss:
|
|||||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
listOf(PieceType.QUEEN, PieceType.ROOK, PieceType.BISHOP, PieceType.KNIGHT).forEach { type ->
|
listOf(PieceType.QUEEN, PieceType.ROOK, PieceType.BISHOP, PieceType.KNIGHT).forEach { type ->
|
||||||
val optionShape = RoundedCornerShape(UiCornerRadius)
|
val optionShape = RoundedCornerShape(UiCornerRadius)
|
||||||
|
val label = stringResource(
|
||||||
|
when (type) {
|
||||||
|
PieceType.QUEEN -> R.string.piece_queen
|
||||||
|
PieceType.ROOK -> R.string.piece_rook
|
||||||
|
PieceType.BISHOP -> R.string.piece_bishop
|
||||||
|
else -> R.string.piece_knight
|
||||||
|
}
|
||||||
|
)
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.weight(1f)
|
.weight(1f)
|
||||||
@@ -46,7 +57,8 @@ fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss:
|
|||||||
.clip(optionShape)
|
.clip(optionShape)
|
||||||
.background(ink.copy(alpha = 0.10f))
|
.background(ink.copy(alpha = 0.10f))
|
||||||
.border(1.dp, PanelBorder, optionShape)
|
.border(1.dp, PanelBorder, optionShape)
|
||||||
.clickable { onChoose(type) }
|
.clickable(onClickLabel = label, role = Role.Button) { onChoose(type) }
|
||||||
|
.semantics { contentDescription = label }
|
||||||
.padding(8.dp),
|
.padding(8.dp),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package cc.skysparkle.matewave.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cc.skysparkle.matewave.R
|
||||||
|
import cc.skysparkle.matewave.ui.theme.ink
|
||||||
|
|
||||||
|
/** Small, quiet spectator counter for the top bar: an eye and "7" or "7/20". */
|
||||||
|
@Composable
|
||||||
|
fun SpectatorBadge(count: Int, max: Int? = null, modifier: Modifier = Modifier) {
|
||||||
|
val description = stringResource(R.string.spectators_description, count)
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.padding(end = 12.dp)
|
||||||
|
.clip(RoundedCornerShape(50))
|
||||||
|
.background(ink.copy(alpha = 0.10f))
|
||||||
|
.padding(horizontal = 10.dp, vertical = 4.dp)
|
||||||
|
.clearAndSetSemantics { contentDescription = description },
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
AppIcon(R.drawable.ic_spectators, size = 16.dp, tint = ink.copy(alpha = 0.7f))
|
||||||
|
Text(
|
||||||
|
if (max != null) "$count/$max" else count.toString(),
|
||||||
|
color = ink.copy(alpha = 0.8f),
|
||||||
|
style = MaterialTheme.typography.labelMedium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,6 +46,15 @@ import cc.skysparkle.matewave.ui.components.AppIcon
|
|||||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
|
import cc.skysparkle.matewave.spectate.FriendGameStatus
|
||||||
|
import cc.skysparkle.matewave.spectate.FriendStatusResolver
|
||||||
|
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
|
||||||
|
import cc.skysparkle.matewave.spectate.PresenceStatus
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProbe
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.awaitAll
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun FriendsScreen(
|
fun FriendsScreen(
|
||||||
@@ -53,7 +62,8 @@ fun FriendsScreen(
|
|||||||
onHomeClick: () -> Unit,
|
onHomeClick: () -> Unit,
|
||||||
onSettingsClick: () -> Unit,
|
onSettingsClick: () -> Unit,
|
||||||
onAccountClick: () -> Unit,
|
onAccountClick: () -> Unit,
|
||||||
onPlay: () -> Unit = {}
|
onPlay: () -> Unit = {},
|
||||||
|
onWatch: (SpectateTarget) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
var onlineOnly by remember { mutableStateOf(false) }
|
var onlineOnly by remember { mutableStateOf(false) }
|
||||||
var version by remember { mutableStateOf(0) }
|
var version by remember { mutableStateOf(0) }
|
||||||
@@ -64,6 +74,28 @@ fun FriendsScreen(
|
|||||||
val peers by presence.peers.collectAsState()
|
val peers by presence.peers.collectAsState()
|
||||||
val friends = remember(peers, version) { FriendsStore.list() }
|
val friends = remember(peers, version) { FriendsStore.list() }
|
||||||
|
|
||||||
|
// Who plays a LAN game, and live spectator counts from each host while the list is open.
|
||||||
|
val nearbyGames = remember(peers) {
|
||||||
|
peers.values.associate { it.playerId to NearbyPlayerGame(it.playerId, it.host, it.gameTag, it.spectatePort) }
|
||||||
|
}
|
||||||
|
val hosts = remember(nearbyGames) { FriendStatusResolver.targets(nearbyGames.values) }
|
||||||
|
var probes by remember { mutableStateOf<Map<SpectateTarget, SpectatorMessage.Status>>(emptyMap()) }
|
||||||
|
androidx.compose.runtime.LaunchedEffect(hosts) {
|
||||||
|
if (hosts.isEmpty()) {
|
||||||
|
probes = emptyMap()
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
|
while (true) {
|
||||||
|
probes = kotlinx.coroutines.coroutineScope {
|
||||||
|
hosts.map { host ->
|
||||||
|
async(kotlinx.coroutines.Dispatchers.IO) { SpectatorProbe.query(host.host, host.port)?.let { host to it } }
|
||||||
|
}.awaitAll().filterNotNull().toMap()
|
||||||
|
}
|
||||||
|
kotlinx.coroutines.delay(PROBE_INTERVAL_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val statusOf: (String) -> FriendGameStatus = { id -> FriendStatusResolver.resolve(id, nearbyGames, probes) }
|
||||||
|
|
||||||
// Fresh search on opening, then refresh "5 min ago" labels while the screen is visible.
|
// Fresh search on opening, then refresh "5 min ago" labels while the screen is visible.
|
||||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||||
presence.refresh()
|
presence.refresh()
|
||||||
@@ -115,18 +147,20 @@ fun FriendsScreen(
|
|||||||
FriendGroup(
|
FriendGroup(
|
||||||
title = stringResource(R.string.friends_group_favorites),
|
title = stringResource(R.string.friends_group_favorites),
|
||||||
list = favorites,
|
list = favorites,
|
||||||
isOnline = presence::isOnline,
|
statusOf = statusOf,
|
||||||
onOpen = { opened = it },
|
onOpen = { opened = it },
|
||||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
FriendGroup(
|
FriendGroup(
|
||||||
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
|
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
|
||||||
list = others,
|
list = others,
|
||||||
isOnline = presence::isOnline,
|
statusOf = statusOf,
|
||||||
onOpen = { opened = it },
|
onOpen = { opened = it },
|
||||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
|
|
||||||
if (strangers.isNotEmpty()) {
|
if (strangers.isNotEmpty()) {
|
||||||
@@ -134,11 +168,13 @@ fun FriendsScreen(
|
|||||||
ListGroup {
|
ListGroup {
|
||||||
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
|
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
|
||||||
if (index > 0) ListDivider(inset = 68)
|
if (index > 0) ListDivider(inset = 68)
|
||||||
|
val status = statusOf(peer.playerId)
|
||||||
ListRow(
|
ListRow(
|
||||||
title = displayName(peer.name, peer.playerId),
|
title = displayName(peer.name, peer.playerId),
|
||||||
subtitle = stringResource(R.string.friends_rating, peer.elo),
|
subtitle = stringResource(R.string.friends_rating, peer.elo) + " · " + statusText(status.status, 0),
|
||||||
|
subtitleColor = statusColor(status.status),
|
||||||
leading = { AvatarCircle(base64 = null, size = 40.dp) },
|
leading = { AvatarCircle(base64 = null, size = 40.dp) },
|
||||||
trailing = { PlayChip(onPlay) }
|
trailing = { StatusAction(status, onPlay, onWatch) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +185,7 @@ fun FriendsScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
opened?.let { friend ->
|
opened?.let { friend ->
|
||||||
FriendCard(friend = friend, online = presence.isOnline(friend.userId), onDismiss = { opened = null })
|
FriendCard(friend = friend, status = statusOf(friend.userId).status, onDismiss = { opened = null })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -158,10 +194,11 @@ fun FriendsScreen(
|
|||||||
private fun FriendGroup(
|
private fun FriendGroup(
|
||||||
title: String?,
|
title: String?,
|
||||||
list: List<FriendEntry>,
|
list: List<FriendEntry>,
|
||||||
isOnline: (String) -> Boolean,
|
statusOf: (String) -> FriendGameStatus,
|
||||||
onOpen: (FriendEntry) -> Unit,
|
onOpen: (FriendEntry) -> Unit,
|
||||||
onToggleFavorite: (FriendEntry) -> Unit,
|
onToggleFavorite: (FriendEntry) -> Unit,
|
||||||
onPlay: () -> Unit
|
onPlay: () -> Unit,
|
||||||
|
onWatch: (SpectateTarget) -> Unit
|
||||||
) {
|
) {
|
||||||
if (list.isEmpty()) return
|
if (list.isEmpty()) return
|
||||||
if (title != null) SectionCaption(title)
|
if (title != null) SectionCaption(title)
|
||||||
@@ -170,10 +207,11 @@ private fun FriendGroup(
|
|||||||
if (index > 0) ListDivider(inset = 68)
|
if (index > 0) ListDivider(inset = 68)
|
||||||
FriendRow(
|
FriendRow(
|
||||||
friend = friend,
|
friend = friend,
|
||||||
online = isOnline(friend.userId),
|
status = statusOf(friend.userId),
|
||||||
onOpen = { onOpen(friend) },
|
onOpen = { onOpen(friend) },
|
||||||
onToggleFavorite = { onToggleFavorite(friend) },
|
onToggleFavorite = { onToggleFavorite(friend) },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,7 +243,7 @@ private fun PlayChip(onClick: () -> Unit) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Unit) {
|
private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: () -> Unit) {
|
||||||
Dialog(onDismissRequest = onDismiss) {
|
Dialog(onDismissRequest = onDismiss) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -257,9 +295,12 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
|
|||||||
}
|
}
|
||||||
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
Text(
|
Text(
|
||||||
if (online) stringResource(R.string.friends_online)
|
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||||
else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
color = when (status) {
|
||||||
color = if (online) Color(0xFF7BE495) else ink.copy(alpha = 0.6f),
|
PresenceStatus.ONLINE -> Color(0xFF7BE495)
|
||||||
|
PresenceStatus.IN_GAME -> InGameColor
|
||||||
|
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.6f)
|
||||||
|
},
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium
|
||||||
)
|
)
|
||||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||||
@@ -276,32 +317,33 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
|
|||||||
@Composable
|
@Composable
|
||||||
private fun FriendRow(
|
private fun FriendRow(
|
||||||
friend: FriendEntry,
|
friend: FriendEntry,
|
||||||
online: Boolean,
|
status: FriendGameStatus,
|
||||||
onOpen: () -> Unit,
|
onOpen: () -> Unit,
|
||||||
onToggleFavorite: () -> Unit,
|
onToggleFavorite: () -> Unit,
|
||||||
onPlay: () -> Unit
|
onPlay: () -> Unit,
|
||||||
|
onWatch: (SpectateTarget) -> Unit
|
||||||
) {
|
) {
|
||||||
ListRow(
|
ListRow(
|
||||||
title = displayName(friend.name, friend.userId),
|
title = displayName(friend.name, friend.userId),
|
||||||
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
|
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
|
||||||
(if (online) stringResource(R.string.friends_online) else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs))),
|
statusText(status.status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||||
subtitleColor = if (online) ChessGreen else ink.copy(alpha = 0.55f),
|
subtitleColor = statusColor(status.status),
|
||||||
leading = {
|
leading = {
|
||||||
Box {
|
Box {
|
||||||
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
|
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
|
||||||
if (online) {
|
if (status.status != PresenceStatus.OFFLINE) {
|
||||||
Box(
|
Box(
|
||||||
Modifier
|
Modifier
|
||||||
.align(Alignment.BottomEnd)
|
.align(Alignment.BottomEnd)
|
||||||
.size(11.dp)
|
.size(11.dp)
|
||||||
.clip(CircleShape)
|
.clip(CircleShape)
|
||||||
.background(ChessGreen)
|
.background(if (status.status == PresenceStatus.IN_GAME) InGameColor else ChessGreen)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
trailing = {
|
trailing = {
|
||||||
if (online) PlayChip(onPlay)
|
StatusAction(status, onPlay, onWatch)
|
||||||
AppIcon(
|
AppIcon(
|
||||||
R.drawable.ic_star,
|
R.drawable.ic_star,
|
||||||
size = 20.dp,
|
size = 20.dp,
|
||||||
@@ -317,6 +359,58 @@ private fun FriendRow(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val InGameColor = Color(0xFFFFB86B)
|
||||||
|
|
||||||
|
private const val PROBE_INTERVAL_MS = 3_000L
|
||||||
|
|
||||||
|
/** Play for someone who is free, Watch (with the live count) for someone in a LAN game. */
|
||||||
|
@Composable
|
||||||
|
private fun StatusAction(status: FriendGameStatus, onPlay: () -> Unit, onWatch: (SpectateTarget) -> Unit) {
|
||||||
|
when (status.status) {
|
||||||
|
PresenceStatus.ONLINE -> PlayChip(onPlay)
|
||||||
|
PresenceStatus.IN_GAME -> status.target?.let { target -> WatchChip(status) { onWatch(target) } }
|
||||||
|
PresenceStatus.OFFLINE -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun WatchChip(status: FriendGameStatus, onClick: () -> Unit) {
|
||||||
|
val enabled = !status.full
|
||||||
|
val spectators = status.spectators
|
||||||
|
val label = when {
|
||||||
|
status.full -> stringResource(R.string.friends_watch_full)
|
||||||
|
spectators != null -> stringResource(R.string.friends_watch_count, spectators, status.max)
|
||||||
|
else -> stringResource(R.string.friends_watch)
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
color = if (enabled) Color.White else ink.copy(alpha = 0.5f),
|
||||||
|
style = MaterialTheme.typography.labelLarge,
|
||||||
|
maxLines = 1,
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(50))
|
||||||
|
.background(if (enabled) ChessGreen else ink.copy(alpha = 0.12f))
|
||||||
|
.then(if (enabled) Modifier.clickable(onClick = onClick) else Modifier)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun statusText(status: PresenceStatus, lastSeenMs: Long): String = when (status) {
|
||||||
|
PresenceStatus.ONLINE -> stringResource(R.string.friends_online)
|
||||||
|
PresenceStatus.IN_GAME -> stringResource(R.string.friends_in_game)
|
||||||
|
PresenceStatus.OFFLINE ->
|
||||||
|
if (lastSeenMs <= 0) stringResource(R.string.friends_offline)
|
||||||
|
else stringResource(R.string.friends_offline) + " · " + lastSeenText(lastSeenMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun statusColor(status: PresenceStatus): Color = when (status) {
|
||||||
|
PresenceStatus.ONLINE -> ChessGreen
|
||||||
|
PresenceStatus.IN_GAME -> InGameColor
|
||||||
|
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.55f)
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun lastSeenText(lastSeenMs: Long): String {
|
private fun lastSeenText(lastSeenMs: Long): String {
|
||||||
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
|
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
|
||||||
|
|||||||
@@ -101,6 +101,11 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
GlassScaffold(
|
GlassScaffold(
|
||||||
title = "",
|
title = "",
|
||||||
onBack = requestExit,
|
onBack = requestExit,
|
||||||
|
actions = {
|
||||||
|
if (state.mode == GameMode.VS_PLAYER_NETWORK && state.spectatorCount > 0) {
|
||||||
|
cc.skysparkle.matewave.ui.components.SpectatorBadge(state.spectatorCount)
|
||||||
|
}
|
||||||
|
},
|
||||||
titleContent = if (showOpening && opening != null) {
|
titleContent = if (showOpening && opening != null) {
|
||||||
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
||||||
} else null
|
} else null
|
||||||
@@ -490,7 +495,7 @@ private fun PlayerRow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun BigClock(millis: Long, active: Boolean) {
|
internal fun BigClock(millis: Long, active: Boolean) {
|
||||||
val totalSeconds = millis / 1000
|
val totalSeconds = millis / 1000
|
||||||
val low = active && totalSeconds < 20
|
val low = active && totalSeconds < 20
|
||||||
val color = when {
|
val color = when {
|
||||||
|
|||||||
@@ -82,6 +82,11 @@ fun SettingsScreen(
|
|||||||
val status = remember(statusTick) {
|
val status = remember(statusTick) {
|
||||||
cc.skysparkle.matewave.network.NetworkRequirements.check(context)
|
cc.skysparkle.matewave.network.NetworkRequirements.check(context)
|
||||||
}
|
}
|
||||||
|
// Wi-Fi alone used to count as "All set" even with the nearby permission denied
|
||||||
|
val permissionsMissing = remember(statusTick) {
|
||||||
|
!status.permissionsGranted ||
|
||||||
|
(cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled && !status.notificationsGranted)
|
||||||
|
}
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
while (true) { kotlinx.coroutines.delay(3_000); statusTick++ }
|
while (true) { kotlinx.coroutines.delay(3_000); statusTick++ }
|
||||||
}
|
}
|
||||||
@@ -149,10 +154,10 @@ fun SettingsScreen(
|
|||||||
ListGroup {
|
ListGroup {
|
||||||
ListRow(
|
ListRow(
|
||||||
title = stringResource(R.string.permissions_card_title),
|
title = stringResource(R.string.permissions_card_title),
|
||||||
icon = if (status.onlineBlocked) R.drawable.ic_permissions else R.drawable.ic_check_permission,
|
icon = if (permissionsMissing) R.drawable.ic_permissions else R.drawable.ic_check_permission,
|
||||||
iconTint = if (status.onlineBlocked) Color(0xFFFF6B6B) else ChessGreen,
|
iconTint = if (permissionsMissing) Color(0xFFFF6B6B) else ChessGreen,
|
||||||
value = stringResource(if (status.onlineBlocked) R.string.permissions_card_blocked_short else R.string.permissions_card_ok_short),
|
value = stringResource(if (permissionsMissing) R.string.permissions_card_blocked_short else R.string.permissions_card_ok_short),
|
||||||
valueColor = if (status.onlineBlocked) Color(0xFFFF6B6B) else ink.copy(alpha = 0.55f),
|
valueColor = if (permissionsMissing) Color(0xFFFF6B6B) else ink.copy(alpha = 0.55f),
|
||||||
chevron = true,
|
chevron = true,
|
||||||
onClick = onOpenPermissions
|
onClick = onOpenPermissions
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,269 @@
|
|||||||
|
package cc.skysparkle.matewave.ui.screens
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import cc.skysparkle.matewave.R
|
||||||
|
import cc.skysparkle.matewave.data.FriendsStore
|
||||||
|
import cc.skysparkle.matewave.engine.ChessEngine
|
||||||
|
import cc.skysparkle.matewave.engine.Material
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.opposite
|
||||||
|
import cc.skysparkle.matewave.network.NetworkRequirements
|
||||||
|
import cc.skysparkle.matewave.openings.OpeningBook
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorView
|
||||||
|
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||||
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.CapturedPiecesRow
|
||||||
|
import cc.skysparkle.matewave.ui.components.ChessBoardView
|
||||||
|
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||||
|
import cc.skysparkle.matewave.ui.components.DialogText
|
||||||
|
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||||
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
|
import cc.skysparkle.matewave.ui.components.MovesBar
|
||||||
|
import cc.skysparkle.matewave.ui.components.SpectatorBadge
|
||||||
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
|
import cc.skysparkle.matewave.ui.theme.ink
|
||||||
|
import cc.skysparkle.matewave.viewmodel.SpectatePhase
|
||||||
|
import cc.skysparkle.matewave.viewmodel.SpectateUiState
|
||||||
|
import cc.skysparkle.matewave.viewmodel.SpectatorViewModel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
/** Read-only view of a friend's LAN game. */
|
||||||
|
@Composable
|
||||||
|
fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
|
||||||
|
val viewModel: SpectatorViewModel = viewModel()
|
||||||
|
LaunchedEffect(target) { viewModel.start(target) }
|
||||||
|
val state by viewModel.uiState.collectAsState()
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
var left by remember { mutableStateOf(false) }
|
||||||
|
val backToFriends: () -> Unit = {
|
||||||
|
if (!left) {
|
||||||
|
left = true
|
||||||
|
onBackToFriends()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
androidx.activity.compose.BackHandler(onBack = backToFriends)
|
||||||
|
|
||||||
|
// Wi-Fi switched off here: say so at once instead of waiting for the connection to time out.
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
while (true) {
|
||||||
|
delay(WIFI_CHECK_MS)
|
||||||
|
if (!NetworkRequirements.check(context).wifiConnected) viewModel.onNetworkLost()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val view = state.view
|
||||||
|
var resultHidden by remember(view?.gameId, state.phase) { mutableStateOf(false) }
|
||||||
|
|
||||||
|
GlassScaffold(
|
||||||
|
title = stringResource(R.string.spectate_title),
|
||||||
|
onBack = backToFriends,
|
||||||
|
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) }
|
||||||
|
) {
|
||||||
|
if (state.phase == SpectatePhase.CONNECTING) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
CircularProgressIndicator(color = ink, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||||
|
Text(stringResource(R.string.spectate_joining), color = ink, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (view == null) return@GlassScaffold
|
||||||
|
|
||||||
|
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
||||||
|
val material = remember(view.board) { Material.balance(view.board) }
|
||||||
|
val checkSquare = if (ChessEngine.isInCheck(view.board, view.board.sideToMove)) {
|
||||||
|
view.board.kingSquare(view.board.sideToMove)
|
||||||
|
} else null
|
||||||
|
|
||||||
|
SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
||||||
|
ChessBoardView(
|
||||||
|
board = view.board,
|
||||||
|
selectedSquare = null,
|
||||||
|
legalTargets = emptyList(),
|
||||||
|
kingInCheckSquare = checkSquare,
|
||||||
|
flipped = state.flipped,
|
||||||
|
onSquareClick = {},
|
||||||
|
lastMove = view.lastMove,
|
||||||
|
interactionEnabled = false,
|
||||||
|
highlightLastMove = true
|
||||||
|
)
|
||||||
|
SpectatorPlayerRow(view, bottom, state, material)
|
||||||
|
|
||||||
|
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
|
||||||
|
MovesBar(
|
||||||
|
sans = view.moveSans,
|
||||||
|
startBoard = view.startBoard,
|
||||||
|
currentIndex = view.moveSans.size,
|
||||||
|
opening = null,
|
||||||
|
bookPlies = bookPlies
|
||||||
|
)
|
||||||
|
|
||||||
|
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_board_view)
|
||||||
|
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.phase == SpectatePhase.ENDED && resultHidden) {
|
||||||
|
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
when (state.phase) {
|
||||||
|
SpectatePhase.ENDED -> {
|
||||||
|
val result = view?.result
|
||||||
|
if (result != null && !resultHidden) {
|
||||||
|
AppDialog(
|
||||||
|
onDismissRequest = { resultHidden = true },
|
||||||
|
title = stringResource(R.string.game_over_title),
|
||||||
|
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||||
|
) {
|
||||||
|
DialogText(resultText(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SpectatePhase.LOST -> {
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
delay(LOST_RETURN_MS)
|
||||||
|
backToFriends()
|
||||||
|
}
|
||||||
|
AppDialog(
|
||||||
|
onDismissRequest = backToFriends,
|
||||||
|
title = stringResource(R.string.connection_lost),
|
||||||
|
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||||
|
) {
|
||||||
|
DialogText(stringResource(R.string.spectate_lost_text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SpectatePhase.FAILED -> {
|
||||||
|
val (title, text) = failureTexts(state.failure, state.max)
|
||||||
|
AppDialog(
|
||||||
|
onDismissRequest = backToFriends,
|
||||||
|
title = title,
|
||||||
|
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
|
||||||
|
) {
|
||||||
|
DialogText(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun failureTexts(failure: SpectatorClient.Failure?, max: Int): Pair<String, String> = when (failure) {
|
||||||
|
SpectatorClient.Failure.FULL ->
|
||||||
|
stringResource(R.string.spectate_full_title) to stringResource(R.string.spectate_full_text, max)
|
||||||
|
SpectatorClient.Failure.UPDATE_THIS_APP ->
|
||||||
|
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_this)
|
||||||
|
SpectatorClient.Failure.UPDATE_HOST_APP ->
|
||||||
|
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_host)
|
||||||
|
SpectatorClient.Failure.NO_GAME ->
|
||||||
|
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_no_game)
|
||||||
|
SpectatorClient.Failure.UNREACHABLE, null ->
|
||||||
|
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_unreachable)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun resultText(result: SpectatorResult): String {
|
||||||
|
val white = stringResource(R.string.color_white)
|
||||||
|
val black = stringResource(R.string.color_black)
|
||||||
|
val winner = result.winner
|
||||||
|
fun name(side: PieceColor) = if (side == PieceColor.WHITE) white else black
|
||||||
|
return when (result.outcome) {
|
||||||
|
SpectatorOutcome.CHECKMATE -> winner?.let { stringResource(R.string.checkmate_winner, name(it)) }
|
||||||
|
SpectatorOutcome.TIMEOUT -> winner?.let { stringResource(R.string.timeout_winner, name(it)) }
|
||||||
|
SpectatorOutcome.RESIGNATION -> winner?.let { stringResource(R.string.resignation_winner, name(it)) }
|
||||||
|
SpectatorOutcome.LEFT -> winner?.let { stringResource(R.string.spectate_left_win, name(it.opposite()), name(it)) }
|
||||||
|
SpectatorOutcome.STALEMATE -> stringResource(R.string.stalemate)
|
||||||
|
SpectatorOutcome.FIFTY_MOVES -> stringResource(R.string.draw_50_moves)
|
||||||
|
SpectatorOutcome.REPETITION -> stringResource(R.string.draw_repetition)
|
||||||
|
SpectatorOutcome.INSUFFICIENT_MATERIAL -> stringResource(R.string.draw_material)
|
||||||
|
SpectatorOutcome.TIMEOUT_DRAW -> stringResource(R.string.timeout_draw)
|
||||||
|
SpectatorOutcome.AGREEMENT -> stringResource(R.string.draw_agreement)
|
||||||
|
SpectatorOutcome.INTERRUPTED -> stringResource(R.string.spectate_interrupted)
|
||||||
|
SpectatorOutcome.UNKNOWN -> null
|
||||||
|
} ?: stringResource(R.string.game_over_title)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SpectatorPlayerRow(
|
||||||
|
view: SpectatorView,
|
||||||
|
side: PieceColor,
|
||||||
|
state: SpectateUiState,
|
||||||
|
material: cc.skysparkle.matewave.engine.MaterialBalance
|
||||||
|
) {
|
||||||
|
val player = if (side == PieceColor.WHITE) view.white else view.black
|
||||||
|
val active = view.result == null && view.board.sideToMove == side
|
||||||
|
// Known friends get their saved avatar; nothing large travels to spectators.
|
||||||
|
val avatar = remember(player.id) {
|
||||||
|
if (player.id.isEmpty()) null else FriendsStore.list().firstOrNull { it.userId == player.id }?.avatarBase64
|
||||||
|
}
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(8.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(if (active) ChessGreen else ink.copy(alpha = 0.15f))
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
AvatarCircle(base64 = avatar, size = 34.dp)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
player.name.ifBlank { stringResource(R.string.player_default_name) },
|
||||||
|
color = if (active) ink else ink.copy(alpha = 0.75f),
|
||||||
|
style = MaterialTheme.typography.titleSmall,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis
|
||||||
|
)
|
||||||
|
if (player.elo > 0) {
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.friends_elo_value, player.elo),
|
||||||
|
color = ink.copy(alpha = 0.55f),
|
||||||
|
style = MaterialTheme.typography.labelSmall
|
||||||
|
)
|
||||||
|
}
|
||||||
|
CapturedPiecesRow(
|
||||||
|
captured = if (side == PieceColor.WHITE) material.capturedByWhite else material.capturedByBlack,
|
||||||
|
capturedColor = side.opposite(),
|
||||||
|
advantage = if (side == PieceColor.WHITE) material.advantage else -material.advantage
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val millis = if (side == PieceColor.WHITE) state.whiteMs else state.blackMs
|
||||||
|
if (millis != null) BigClock(millis, active)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val WIFI_CHECK_MS = 2_000L
|
||||||
|
private const val LOST_RETURN_MS = 4_000L
|
||||||
@@ -33,6 +33,15 @@ import cc.skysparkle.matewave.security.KnownPeers
|
|||||||
import cc.skysparkle.matewave.security.SessionAuth
|
import cc.skysparkle.matewave.security.SessionAuth
|
||||||
import cc.skysparkle.matewave.security.TrustResult
|
import cc.skysparkle.matewave.security.TrustResult
|
||||||
import cc.skysparkle.matewave.settings.Haptics
|
import cc.skysparkle.matewave.settings.Haptics
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorAdvert
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorHub
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
import cc.skysparkle.matewave.stats.Stats
|
import cc.skysparkle.matewave.stats.Stats
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -95,7 +104,10 @@ data class GameUiState(
|
|||||||
val opponentLeftMidGame: Boolean = false,
|
val opponentLeftMidGame: Boolean = false,
|
||||||
val rematchOfferFromOpponent: Boolean = false,
|
val rematchOfferFromOpponent: Boolean = false,
|
||||||
|
|
||||||
val activeTransport: TransportType? = null
|
val activeTransport: TransportType? = null,
|
||||||
|
|
||||||
|
/** Spectators watching this LAN game, shown to both players. */
|
||||||
|
val spectatorCount: Int = 0
|
||||||
)
|
)
|
||||||
|
|
||||||
data class PendingPromotion(val from: Int, val to: Int)
|
data class PendingPromotion(val from: Int, val to: Int)
|
||||||
@@ -172,6 +184,16 @@ class GameViewModel : ViewModel() {
|
|||||||
private var currentPly: Int = 0
|
private var currentPly: Int = 0
|
||||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
||||||
|
|
||||||
|
// Spectating: the host serves spectators, both players announce the game's tag.
|
||||||
|
private var spectators: SpectatorBroadcaster? = null
|
||||||
|
private var spectatorWatcher: Job? = null
|
||||||
|
private var spectatorCountJob: Job? = null
|
||||||
|
private var spectatingDecided = false
|
||||||
|
private var spectateTag: String = ""
|
||||||
|
private var spectatorPlayers: Pair<SpectatorPlayer, SpectatorPlayer>? = null
|
||||||
|
private var spectatorPlayersKey: String = ""
|
||||||
|
private var lastSentSpectatorCount = 0
|
||||||
|
|
||||||
init {
|
init {
|
||||||
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
||||||
}
|
}
|
||||||
@@ -689,6 +711,7 @@ class GameViewModel : ViewModel() {
|
|||||||
pendingLeave = null
|
pendingLeave = null
|
||||||
handshakeTimeoutJob?.cancel()
|
handshakeTimeoutJob?.cancel()
|
||||||
handshakeTimeoutJob = null
|
handshakeTimeoutJob = null
|
||||||
|
stopSpectating()
|
||||||
cancelAi()
|
cancelAi()
|
||||||
// A paused game against the AI stays saved and can be continued later.
|
// A paused game against the AI stays saved and can be continued later.
|
||||||
persistIfResumable()
|
persistIfResumable()
|
||||||
@@ -729,6 +752,8 @@ class GameViewModel : ViewModel() {
|
|||||||
heartbeat?.stop()
|
heartbeat?.stop()
|
||||||
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
|
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
|
||||||
|
|
||||||
|
spectatorWatcher = viewModelScope.launch { _uiState.collect { onStateForSpectators(it) } }
|
||||||
|
|
||||||
var profileSent = false
|
var profileSent = false
|
||||||
var connectedOnce = false
|
var connectedOnce = false
|
||||||
val connectStartedAt = System.currentTimeMillis()
|
val connectStartedAt = System.currentTimeMillis()
|
||||||
@@ -965,6 +990,10 @@ class GameViewModel : ViewModel() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
is GameMessage.PingMsg -> Unit
|
is GameMessage.PingMsg -> Unit
|
||||||
|
is GameMessage.SpectatorCountMsg -> {
|
||||||
|
if (isNetworkHost) return
|
||||||
|
_uiState.value = _uiState.value.copy(spectatorCount = msg.count.coerceIn(0, MAX_SPECTATORS))
|
||||||
|
}
|
||||||
is GameMessage.TimeoutMsg -> {
|
is GameMessage.TimeoutMsg -> {
|
||||||
if (!belongsToCurrentGame(msg.gameId)) return
|
if (!belongsToCurrentGame(msg.gameId)) return
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
@@ -1113,6 +1142,9 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun endNetworkSession() {
|
private fun endNetworkSession() {
|
||||||
|
val state = _uiState.value
|
||||||
|
// The players lost each other: spectators see the game end as interrupted.
|
||||||
|
stopSpectating(if (state.status == GameStatus.ONGOING) SpectatorResults.interrupted else null)
|
||||||
opponentFlagJob?.cancel()
|
opponentFlagJob?.cancel()
|
||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
clock?.stop()
|
clock?.stop()
|
||||||
@@ -1137,7 +1169,9 @@ class GameViewModel : ViewModel() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING) {
|
val leftMidGame = state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING
|
||||||
|
stopSpectating(if (leftMidGame) SpectatorResults.leftBy(state.myColor) else null)
|
||||||
|
if (leftMidGame) {
|
||||||
applyNetworkResultElo(0.0)
|
applyNetworkResultElo(0.0)
|
||||||
}
|
}
|
||||||
opponentFlagJob?.cancel()
|
opponentFlagJob?.cancel()
|
||||||
@@ -1218,7 +1252,8 @@ class GameViewModel : ViewModel() {
|
|||||||
handshake = state.handshake,
|
handshake = state.handshake,
|
||||||
activeTransport = state.activeTransport,
|
activeTransport = state.activeTransport,
|
||||||
opponentUnverified = state.opponentUnverified,
|
opponentUnverified = state.opponentUnverified,
|
||||||
chatMessages = state.chatMessages
|
chatMessages = state.chatMessages,
|
||||||
|
spectatorCount = state.spectatorCount
|
||||||
)
|
)
|
||||||
setupClock(timeControl)
|
setupClock(timeControl)
|
||||||
}
|
}
|
||||||
@@ -1333,6 +1368,119 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
// endregion
|
// endregion
|
||||||
|
|
||||||
|
// region Spectators
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Once a LAN game is under way, the host opens its spectator socket and both players announce
|
||||||
|
* the game's tag; players who chose not to be visible on the network are not watchable.
|
||||||
|
*/
|
||||||
|
private fun onStateForSpectators(state: GameUiState) {
|
||||||
|
if (state.mode != GameMode.VS_PLAYER_NETWORK) return
|
||||||
|
spectators?.update(spectatorSnapshot(state))
|
||||||
|
if (spectatingDecided) return
|
||||||
|
val live = state.handshake == HandshakeState.PLAYING &&
|
||||||
|
state.connectionState == ConnectionState.CONNECTED &&
|
||||||
|
state.activeTransport == TransportType.LAN
|
||||||
|
if (!live) return
|
||||||
|
val ctx = appContext ?: return
|
||||||
|
spectatingDecided = true
|
||||||
|
if (!cc.skysparkle.matewave.presence.PresenceSettings(ctx).announceEnabled) return
|
||||||
|
spectateTag = SpectatorAdvert.tagOf(networkGameId)
|
||||||
|
if (spectateTag.isEmpty()) return
|
||||||
|
if (isNetworkHost) startSpectatorHub(ctx) else advertiseGame(ctx, SpectatorAdvert.State(spectateTag, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startSpectatorHub(ctx: android.content.Context) {
|
||||||
|
val generation = sessionGeneration
|
||||||
|
val hub = SpectatorHub(log = { NetworkLog.log("SPECTATE", it) })
|
||||||
|
viewModelScope.launch {
|
||||||
|
var serving = false
|
||||||
|
try {
|
||||||
|
val port = withContext(Dispatchers.IO) { runCatching { hub.start() }.getOrNull() }
|
||||||
|
if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port")
|
||||||
|
// The game may have ended while the port was opening.
|
||||||
|
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
broadcaster.update(spectatorSnapshot(_uiState.value))
|
||||||
|
spectators = broadcaster
|
||||||
|
serving = true
|
||||||
|
spectatorCountJob = viewModelScope.launch { hub.count.collect { onSpectatorCount(it) } }
|
||||||
|
advertiseGame(ctx, SpectatorAdvert.State(spectateTag, port))
|
||||||
|
NetworkLog.log("SPECTATE", "Spectators can join on port $port")
|
||||||
|
} finally {
|
||||||
|
if (!serving) hub.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onSpectatorCount(count: Int) {
|
||||||
|
if (_uiState.value.spectatorCount != count) {
|
||||||
|
_uiState.value = _uiState.value.copy(spectatorCount = count)
|
||||||
|
}
|
||||||
|
if (count != lastSentSpectatorCount && canSendGameMessages() &&
|
||||||
|
sendGameMessage(GameMessage.SpectatorCountMsg(count, networkGameId))
|
||||||
|
) {
|
||||||
|
lastSentSpectatorCount = count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun advertiseGame(ctx: android.content.Context, state: SpectatorAdvert.State) {
|
||||||
|
if (SpectatorAdvert.update(state)) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ends spectating for this session; [final] tells spectators how a game cut short ended. */
|
||||||
|
private fun stopSpectating(final: SpectatorResult? = null) {
|
||||||
|
spectatorWatcher?.cancel()
|
||||||
|
spectatorWatcher = null
|
||||||
|
spectatorCountJob?.cancel()
|
||||||
|
spectatorCountJob = null
|
||||||
|
spectators?.let { broadcaster ->
|
||||||
|
val last = final?.let { spectatorSnapshot(_uiState.value).copy(result = it) }
|
||||||
|
broadcaster.close(last)
|
||||||
|
}
|
||||||
|
spectators = null
|
||||||
|
spectatingDecided = false
|
||||||
|
spectateTag = ""
|
||||||
|
spectatorPlayers = null
|
||||||
|
spectatorPlayersKey = ""
|
||||||
|
lastSentSpectatorCount = 0
|
||||||
|
appContext?.let { ctx ->
|
||||||
|
if (SpectatorAdvert.clear()) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
|
||||||
|
}
|
||||||
|
if (_uiState.value.spectatorCount != 0) {
|
||||||
|
_uiState.value = _uiState.value.copy(spectatorCount = 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun spectatorSnapshot(state: GameUiState): SpectatorSnapshot {
|
||||||
|
val opponent = state.opponentProfile
|
||||||
|
val key = networkGameId + "|" + (opponent?.userId ?: "")
|
||||||
|
val players = spectatorPlayers?.takeIf { spectatorPlayersKey == key } ?: run {
|
||||||
|
val me = ProfileStore.get()
|
||||||
|
val mine = SpectatorPlayer(me.userId, me.name, me.elo)
|
||||||
|
val theirs = SpectatorPlayer(opponent?.userId ?: "", opponent?.name ?: "", opponent?.elo ?: 0)
|
||||||
|
(if (state.myColor == PieceColor.WHITE) mine to theirs else theirs to mine).also {
|
||||||
|
spectatorPlayers = it
|
||||||
|
spectatorPlayersKey = key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val timeControl = lastNetworkTimeControl
|
||||||
|
return SpectatorSnapshot(
|
||||||
|
gameId = networkGameId,
|
||||||
|
white = players.first,
|
||||||
|
black = players.second,
|
||||||
|
movesUci = moveLog.toList(),
|
||||||
|
initialSeconds = timeControl?.initialSeconds ?: 0,
|
||||||
|
incrementSeconds = timeControl?.incrementSeconds ?: 0,
|
||||||
|
clock = clock?.state?.value?.let { SpectatorClock(it.whiteMillis, it.blackMillis, it.running) },
|
||||||
|
result = SpectatorResults.of(
|
||||||
|
state.status, state.board.sideToMove, state.timedOutSide, state.resignedSide, state.opponentLeftMidGame
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// endregion
|
||||||
|
|
||||||
// region Clock
|
// region Clock
|
||||||
|
|
||||||
private fun disposeClock() {
|
private fun disposeClock() {
|
||||||
@@ -1418,6 +1566,7 @@ class GameViewModel : ViewModel() {
|
|||||||
pendingLeave?.first?.cancel()
|
pendingLeave?.first?.cancel()
|
||||||
pendingLeave?.second?.disconnect()
|
pendingLeave?.second?.disconnect()
|
||||||
pendingLeave = null
|
pendingLeave = null
|
||||||
|
stopSpectating()
|
||||||
persistIfResumable()
|
persistIfResumable()
|
||||||
clock?.stop()
|
clock?.stop()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package cc.skysparkle.matewave.viewmodel
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import cc.skysparkle.matewave.network.NetworkLog
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorView
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
enum class SpectatePhase { CONNECTING, WATCHING, ENDED, LOST, FAILED }
|
||||||
|
|
||||||
|
data class SpectateUiState(
|
||||||
|
val phase: SpectatePhase = SpectatePhase.CONNECTING,
|
||||||
|
val failure: SpectatorClient.Failure? = null,
|
||||||
|
val view: SpectatorView? = null,
|
||||||
|
val whiteMs: Long? = null,
|
||||||
|
val blackMs: Long? = null,
|
||||||
|
val spectators: Int = 0,
|
||||||
|
val max: Int = MAX_SPECTATORS,
|
||||||
|
/** Board turned for this spectator only. */
|
||||||
|
val flipped: Boolean = false
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Watches one LAN game read-only. Nothing here can reach the players. */
|
||||||
|
class SpectatorViewModel : ViewModel() {
|
||||||
|
private val _uiState = MutableStateFlow(SpectateUiState())
|
||||||
|
val uiState: StateFlow<SpectateUiState> = _uiState
|
||||||
|
|
||||||
|
private val game = SpectatorGame()
|
||||||
|
private val events = Channel<SpectatorClient.Event>(Channel.UNLIMITED)
|
||||||
|
private var client: SpectatorClient? = null
|
||||||
|
private var target: SpectateTarget? = null
|
||||||
|
private var clockAtNanos = 0L
|
||||||
|
private var ticker: Job? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch { for (event in events) handle(event) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start(target: SpectateTarget) {
|
||||||
|
if (this.target == target) return
|
||||||
|
this.target = target
|
||||||
|
client?.stop()
|
||||||
|
_uiState.value = SpectateUiState(flipped = _uiState.value.flipped)
|
||||||
|
client = SpectatorClient(target.host, target.port, { events.trySend(it) }).also { it.start() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun flip() {
|
||||||
|
_uiState.update { it.copy(flipped = !it.flipped) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wi-Fi went away on this device: no need to wait for the connection to time out. */
|
||||||
|
fun onNetworkLost() {
|
||||||
|
when (_uiState.value.phase) {
|
||||||
|
SpectatePhase.CONNECTING -> fail(SpectatorClient.Failure.UNREACHABLE)
|
||||||
|
SpectatePhase.WATCHING -> lose()
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handle(event: SpectatorClient.Event) {
|
||||||
|
when (event) {
|
||||||
|
is SpectatorClient.Event.Joined -> {
|
||||||
|
_uiState.update { it.copy(spectators = event.welcome.count, max = event.welcome.max) }
|
||||||
|
load(event.welcome.game)
|
||||||
|
}
|
||||||
|
is SpectatorClient.Event.Received -> onMessage(event.message)
|
||||||
|
is SpectatorClient.Event.JoinFailed -> fail(event.failure)
|
||||||
|
is SpectatorClient.Event.Disconnected -> {
|
||||||
|
// After the result the host may leave; the result stays on screen.
|
||||||
|
if (_uiState.value.phase != SpectatePhase.ENDED) lose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onMessage(message: SpectatorMessage) {
|
||||||
|
val phase = _uiState.value.phase
|
||||||
|
if (phase == SpectatePhase.LOST || phase == SpectatePhase.FAILED) return
|
||||||
|
when (message) {
|
||||||
|
is SpectatorMessage.MovePlayed -> applied(game.onMove(message))
|
||||||
|
is SpectatorMessage.GameOver -> applied(game.onGameOver(message))
|
||||||
|
is SpectatorMessage.NewGame -> load(message.game)
|
||||||
|
is SpectatorMessage.Count -> _uiState.update { it.copy(spectators = message.count, max = message.max) }
|
||||||
|
is SpectatorMessage.Ping -> {
|
||||||
|
game.onClock(message.clock)
|
||||||
|
publish(clockUpdated = message.clock != null)
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applied(result: SpectatorGame.Applied) {
|
||||||
|
when (result) {
|
||||||
|
SpectatorGame.Applied.APPLIED -> publish(clockUpdated = true)
|
||||||
|
SpectatorGame.Applied.NEEDS_RESYNC -> client?.requestResync()
|
||||||
|
SpectatorGame.Applied.IGNORED -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun load(snapshot: SpectatorSnapshot) {
|
||||||
|
if (game.load(snapshot)) {
|
||||||
|
publish(clockUpdated = true)
|
||||||
|
} else {
|
||||||
|
NetworkLog.log("SPECTATE", "Received game could not be replayed")
|
||||||
|
lose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publish(clockUpdated: Boolean) {
|
||||||
|
val view = game.view ?: return
|
||||||
|
if (clockUpdated) clockAtNanos = System.nanoTime()
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(
|
||||||
|
phase = if (view.result != null) SpectatePhase.ENDED else SpectatePhase.WATCHING,
|
||||||
|
failure = null,
|
||||||
|
view = view
|
||||||
|
)
|
||||||
|
}
|
||||||
|
showClocks()
|
||||||
|
if (ticker?.isActive != true) {
|
||||||
|
ticker = viewModelScope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
delay(TICK_MS)
|
||||||
|
if (_uiState.value.phase == SpectatePhase.WATCHING) showClocks()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clocks count down locally between the host's updates. */
|
||||||
|
private fun showClocks() {
|
||||||
|
val view = game.view ?: return
|
||||||
|
val clock = view.clock
|
||||||
|
if (clock == null) {
|
||||||
|
_uiState.update { it.copy(whiteMs = null, blackMs = null) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val shown = if (view.result == null) clock.advancedBy((System.nanoTime() - clockAtNanos) / 1_000_000L) else clock
|
||||||
|
_uiState.update { it.copy(whiteMs = shown.whiteMs, blackMs = shown.blackMs) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lose() {
|
||||||
|
client?.stop()
|
||||||
|
_uiState.update { it.copy(phase = SpectatePhase.LOST) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fail(failure: SpectatorClient.Failure) {
|
||||||
|
client?.stop()
|
||||||
|
_uiState.update { it.copy(phase = SpectatePhase.FAILED, failure = failure) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCleared() {
|
||||||
|
client?.stop()
|
||||||
|
client = null
|
||||||
|
events.close()
|
||||||
|
super.onCleared()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TICK_MS = 250L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,16 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:pathData="M2,12C4.5,7.5 8,5.5 12,5.5C16,5.5 19.5,7.5 22,12C19.5,16.5 16,18.5 12,18.5C8,18.5 4.5,16.5 2,12Z"
|
||||||
|
android:strokeWidth="2"
|
||||||
|
android:strokeColor="#FFFFFFFF"
|
||||||
|
android:strokeLineJoin="round"
|
||||||
|
android:fillColor="#00000000" />
|
||||||
|
<path
|
||||||
|
android:pathData="M8.8,12a3.2,3.2 0,1 0,6.4 0a3.2,3.2 0,1 0,-6.4 0Z"
|
||||||
|
android:fillColor="#FFFFFFFF" />
|
||||||
|
</vector>
|
||||||
@@ -25,9 +25,9 @@
|
|||||||
<string name="settings_version">Version %1$s</string>
|
<string name="settings_version">Version %1$s</string>
|
||||||
<string name="settings_repo_title">Quellcode</string>
|
<string name="settings_repo_title">Quellcode</string>
|
||||||
<string name="settings_radio">Jazzradio</string>
|
<string name="settings_radio">Jazzradio</string>
|
||||||
<string name="settings_radio_subtitle">Internetradio im Hintergrund statt Stille</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz. Ohne Verbindung läuft eingebaute Musik</string>
|
||||||
<string name="settings_radio_connecting">Verbinde...</string>
|
<string name="settings_radio_connecting">Verbinde...</string>
|
||||||
<string name="settings_radio_error">Verbindung fehlgeschlagen</string>
|
<string name="settings_radio_error">Keine Verbindung, eingebaute Musik</string>
|
||||||
<string name="settings_sfx">Soundeffekte</string>
|
<string name="settings_sfx">Soundeffekte</string>
|
||||||
<string name="settings_sfx_subtitle">Figur wählen, ziehen, schlagen</string>
|
<string name="settings_sfx_subtitle">Figur wählen, ziehen, schlagen</string>
|
||||||
<string name="back">Zurück</string>
|
<string name="back">Zurück</string>
|
||||||
@@ -354,4 +354,30 @@
|
|||||||
<string name="nearby_bt_off_hint">Schalte es ein, um Spieler per Bluetooth zu finden</string>
|
<string name="nearby_bt_off_hint">Schalte es ein, um Spieler per Bluetooth zu finden</string>
|
||||||
<string name="nearby_wifi_hint">Spieler im selben WLAN werden erst gefunden, wenn du verbunden bist</string>
|
<string name="nearby_wifi_hint">Spieler im selben WLAN werden erst gefunden, wenn du verbunden bist</string>
|
||||||
<string name="permission_open_settings">Einstellungen öffnen</string>
|
<string name="permission_open_settings">Einstellungen öffnen</string>
|
||||||
|
<string name="piece_queen">Dame</string>
|
||||||
|
<string name="piece_rook">Turm</string>
|
||||||
|
<string name="piece_bishop">Läufer</string>
|
||||||
|
<string name="piece_knight">Springer</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">Im Spiel</string>
|
||||||
|
<string name="friends_watch">Zuschauen</string>
|
||||||
|
<string name="friends_watch_count">Zuschauen · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">Voll</string>
|
||||||
|
<string name="spectators_description">Zuschauer: %1$d</string>
|
||||||
|
<string name="spectate_title">Zuschauen</string>
|
||||||
|
<string name="spectate_joining">Verbinde mit der Partie…</string>
|
||||||
|
<string name="spectate_flip">Brett drehen</string>
|
||||||
|
<string name="spectate_back_to_friends">Zurück zu Freunden</string>
|
||||||
|
<string name="spectate_lost_text">Das Gerät, auf dem die Partie läuft, ist nicht mehr erreichbar.</string>
|
||||||
|
<string name="spectate_full_title">Partie ist voll</string>
|
||||||
|
<string name="spectate_full_text">Diese Partie hat bereits die maximale Zahl von %1$d Zuschauern. Versuch es später noch einmal.</string>
|
||||||
|
<string name="spectate_update_title">Update erforderlich</string>
|
||||||
|
<string name="spectate_update_this">Aktualisiere Matewave, um diese Partie anzusehen.</string>
|
||||||
|
<string name="spectate_update_host">Der Spieler, der diese Partie ausrichtet, muss Matewave aktualisieren, bevor man zuschauen kann.</string>
|
||||||
|
<string name="spectate_failed_title">Zuschauen nicht möglich</string>
|
||||||
|
<string name="spectate_no_game">Diese Partie ist nicht mehr verfügbar.</string>
|
||||||
|
<string name="spectate_unreachable">Das Gerät, auf dem die Partie läuft, ist nicht erreichbar. Achte darauf, dass du im selben WLAN bist.</string>
|
||||||
|
<string name="spectate_left_win">%1$s hat die Partie verlassen. %2$s gewinnt.</string>
|
||||||
|
<string name="spectate_interrupted">Partie unterbrochen: Die Spieler haben die Verbindung verloren.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -25,9 +25,9 @@
|
|||||||
<string name="settings_version">バージョン %1$s</string>
|
<string name="settings_version">バージョン %1$s</string>
|
||||||
<string name="settings_repo_title">ソースコード</string>
|
<string name="settings_repo_title">ソースコード</string>
|
||||||
<string name="settings_radio">ジャズラジオ</string>
|
<string name="settings_radio">ジャズラジオ</string>
|
||||||
<string name="settings_radio_subtitle">無音のかわりにインターネットラジオをバックグラウンドで再生</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz。接続がないときは内蔵の音楽を再生</string>
|
||||||
<string name="settings_radio_connecting">接続中...</string>
|
<string name="settings_radio_connecting">接続中...</string>
|
||||||
<string name="settings_radio_error">接続できませんでした</string>
|
<string name="settings_radio_error">接続なし・内蔵の音楽</string>
|
||||||
<string name="settings_sfx">効果音</string>
|
<string name="settings_sfx">効果音</string>
|
||||||
<string name="settings_sfx_subtitle">駒の選択、移動、取る音</string>
|
<string name="settings_sfx_subtitle">駒の選択、移動、取る音</string>
|
||||||
<string name="back">戻る</string>
|
<string name="back">戻る</string>
|
||||||
@@ -353,4 +353,30 @@
|
|||||||
<string name="nearby_bt_off_hint">オンにすると、Bluetoothでプレイヤーを探せます</string>
|
<string name="nearby_bt_off_hint">オンにすると、Bluetoothでプレイヤーを探せます</string>
|
||||||
<string name="nearby_wifi_hint">接続するまで、同じWi-Fiのプレイヤーは見つかりません</string>
|
<string name="nearby_wifi_hint">接続するまで、同じWi-Fiのプレイヤーは見つかりません</string>
|
||||||
<string name="permission_open_settings">設定を開く</string>
|
<string name="permission_open_settings">設定を開く</string>
|
||||||
|
<string name="piece_queen">クイーン</string>
|
||||||
|
<string name="piece_rook">ルーク</string>
|
||||||
|
<string name="piece_bishop">ビショップ</string>
|
||||||
|
<string name="piece_knight">ナイト</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">対局中</string>
|
||||||
|
<string name="friends_watch">観戦</string>
|
||||||
|
<string name="friends_watch_count">観戦 · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">満員</string>
|
||||||
|
<string name="spectators_description">観戦者: %1$d人</string>
|
||||||
|
<string name="spectate_title">観戦</string>
|
||||||
|
<string name="spectate_joining">対局に接続中…</string>
|
||||||
|
<string name="spectate_flip">盤を反転</string>
|
||||||
|
<string name="spectate_back_to_friends">フレンドに戻る</string>
|
||||||
|
<string name="spectate_lost_text">対局をホストしている端末に接続できなくなりました。</string>
|
||||||
|
<string name="spectate_full_title">満員です</string>
|
||||||
|
<string name="spectate_full_text">この対局の観戦者はすでに上限の%1$d人です。しばらくしてからもう一度お試しください。</string>
|
||||||
|
<string name="spectate_update_title">アップデートが必要です</string>
|
||||||
|
<string name="spectate_update_this">この対局を観戦するには Matewave をアップデートしてください。</string>
|
||||||
|
<string name="spectate_update_host">この対局を観戦するには、対局をホストしているプレイヤーが Matewave をアップデートする必要があります。</string>
|
||||||
|
<string name="spectate_failed_title">観戦できません</string>
|
||||||
|
<string name="spectate_no_game">この対局はもう観戦できません。</string>
|
||||||
|
<string name="spectate_unreachable">対局をホストしている端末に接続できません。同じWi-Fiネットワークに接続しているか確認してください。</string>
|
||||||
|
<string name="spectate_left_win">%1$sが対局から退出しました。%2$sの勝ち</string>
|
||||||
|
<string name="spectate_interrupted">対局が中断されました。プレイヤー間の接続が切れました。</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -25,9 +25,9 @@
|
|||||||
<string name="settings_version">Versija %1$s</string>
|
<string name="settings_version">Versija %1$s</string>
|
||||||
<string name="settings_repo_title">Šaltinio kodas</string>
|
<string name="settings_repo_title">Šaltinio kodas</string>
|
||||||
<string name="settings_radio">Džiazo radijas</string>
|
<string name="settings_radio">Džiazo radijas</string>
|
||||||
<string name="settings_radio_subtitle">Interneto radijas fone vietoj tylos</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz. Be ryšio groja įdiegta muzika</string>
|
||||||
<string name="settings_radio_connecting">Jungiamasi...</string>
|
<string name="settings_radio_connecting">Jungiamasi...</string>
|
||||||
<string name="settings_radio_error">Nepavyko prisijungti</string>
|
<string name="settings_radio_error">Nėra ryšio, įdiegta muzika</string>
|
||||||
<string name="settings_sfx">Garso efektai</string>
|
<string name="settings_sfx">Garso efektai</string>
|
||||||
<string name="settings_sfx_subtitle">Figūros pasirinkimas, ėjimas, paėmimas</string>
|
<string name="settings_sfx_subtitle">Figūros pasirinkimas, ėjimas, paėmimas</string>
|
||||||
<string name="back">Atgal</string>
|
<string name="back">Atgal</string>
|
||||||
@@ -356,4 +356,30 @@
|
|||||||
<string name="nearby_bt_off_hint">Įjunkite, kad rastumėte žaidėjus per „Bluetooth“</string>
|
<string name="nearby_bt_off_hint">Įjunkite, kad rastumėte žaidėjus per „Bluetooth“</string>
|
||||||
<string name="nearby_wifi_hint">Žaidėjų tame pačiame „Wi-Fi“ tinkle nerasite, kol neprisijungsite</string>
|
<string name="nearby_wifi_hint">Žaidėjų tame pačiame „Wi-Fi“ tinkle nerasite, kol neprisijungsite</string>
|
||||||
<string name="permission_open_settings">Atidaryti nustatymus</string>
|
<string name="permission_open_settings">Atidaryti nustatymus</string>
|
||||||
|
<string name="piece_queen">Valdovė</string>
|
||||||
|
<string name="piece_rook">Bokštas</string>
|
||||||
|
<string name="piece_bishop">Rikis</string>
|
||||||
|
<string name="piece_knight">Žirgas</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">Žaidžia</string>
|
||||||
|
<string name="friends_watch">Stebėti</string>
|
||||||
|
<string name="friends_watch_count">Stebėti · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">Pilna</string>
|
||||||
|
<string name="spectators_description">Žiūrovų: %1$d</string>
|
||||||
|
<string name="spectate_title">Partijos stebėjimas</string>
|
||||||
|
<string name="spectate_joining">Jungiamasi prie partijos…</string>
|
||||||
|
<string name="spectate_flip">Apversti lentą</string>
|
||||||
|
<string name="spectate_back_to_friends">Atgal į draugus</string>
|
||||||
|
<string name="spectate_lost_text">Įrenginio, kuriame vyksta partija, nebepavyksta pasiekti.</string>
|
||||||
|
<string name="spectate_full_title">Vietų nebėra</string>
|
||||||
|
<string name="spectate_full_text">Šią partiją jau stebi didžiausias leidžiamas žiūrovų skaičius (%1$d). Pabandykite vėliau.</string>
|
||||||
|
<string name="spectate_update_title">Reikia atnaujinti</string>
|
||||||
|
<string name="spectate_update_this">Atnaujinkite Matewave, kad galėtumėte stebėti šią partiją.</string>
|
||||||
|
<string name="spectate_update_host">Partiją rengiantis žaidėjas turi atnaujinti Matewave, kad ją būtų galima stebėti.</string>
|
||||||
|
<string name="spectate_failed_title">Šios partijos stebėti negalima</string>
|
||||||
|
<string name="spectate_no_game">Ši partija nebepasiekiama.</string>
|
||||||
|
<string name="spectate_unreachable">Nepavyksta pasiekti įrenginio, kuriame vyksta partija. Įsitikinkite, kad esate prisijungę prie to paties „Wi-Fi“ tinklo.</string>
|
||||||
|
<string name="spectate_left_win">%1$s paliko partiją. Laimėjo %2$s.</string>
|
||||||
|
<string name="spectate_interrupted">Partija nutraukta: žaidėjų ryšys nutrūko.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -30,9 +30,9 @@
|
|||||||
<string name="settings_version">Версия %1$s</string>
|
<string name="settings_version">Версия %1$s</string>
|
||||||
<string name="settings_repo_title">Исходный код</string>
|
<string name="settings_repo_title">Исходный код</string>
|
||||||
<string name="settings_radio">Джаз-радио</string>
|
<string name="settings_radio">Джаз-радио</string>
|
||||||
<string name="settings_radio_subtitle">Фоновый интернет-эфир вместо тишины</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz. Без связи играет встроенная музыка</string>
|
||||||
<string name="settings_radio_connecting">Подключение...</string>
|
<string name="settings_radio_connecting">Подключение...</string>
|
||||||
<string name="settings_radio_error">Не удалось подключиться</string>
|
<string name="settings_radio_error">Нет связи, встроенная музыка</string>
|
||||||
<string name="settings_sfx">Звуковые эффекты</string>
|
<string name="settings_sfx">Звуковые эффекты</string>
|
||||||
<string name="settings_sfx_subtitle">Выбор фигуры, ход, взятие</string>
|
<string name="settings_sfx_subtitle">Выбор фигуры, ход, взятие</string>
|
||||||
<string name="back">Назад</string>
|
<string name="back">Назад</string>
|
||||||
@@ -362,4 +362,30 @@
|
|||||||
<string name="nearby_bt_off_hint">Включите, чтобы находить игроков по Bluetooth</string>
|
<string name="nearby_bt_off_hint">Включите, чтобы находить игроков по Bluetooth</string>
|
||||||
<string name="nearby_wifi_hint">Игроков в той же сети Wi-Fi не найти, пока вы не подключитесь</string>
|
<string name="nearby_wifi_hint">Игроков в той же сети Wi-Fi не найти, пока вы не подключитесь</string>
|
||||||
<string name="permission_open_settings">Открыть настройки</string>
|
<string name="permission_open_settings">Открыть настройки</string>
|
||||||
|
<string name="piece_queen">Ферзь</string>
|
||||||
|
<string name="piece_rook">Ладья</string>
|
||||||
|
<string name="piece_bishop">Слон</string>
|
||||||
|
<string name="piece_knight">Конь</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">В игре</string>
|
||||||
|
<string name="friends_watch">Смотреть</string>
|
||||||
|
<string name="friends_watch_count">Смотреть · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">Мест нет</string>
|
||||||
|
<string name="spectators_description">Зрителей: %1$d</string>
|
||||||
|
<string name="spectate_title">Просмотр партии</string>
|
||||||
|
<string name="spectate_joining">Подключение к партии…</string>
|
||||||
|
<string name="spectate_flip">Перевернуть доску</string>
|
||||||
|
<string name="spectate_back_to_friends">Назад к друзьям</string>
|
||||||
|
<string name="spectate_lost_text">Устройство, на котором идёт партия, больше недоступно.</string>
|
||||||
|
<string name="spectate_full_title">Мест нет</string>
|
||||||
|
<string name="spectate_full_text">У этой партии уже максимум зрителей (%1$d). Попробуйте позже.</string>
|
||||||
|
<string name="spectate_update_title">Требуется обновление</string>
|
||||||
|
<string name="spectate_update_this">Обновите Matewave, чтобы смотреть эту партию.</string>
|
||||||
|
<string name="spectate_update_host">Игроку, который проводит эту партию, нужно обновить Matewave, чтобы её можно было смотреть.</string>
|
||||||
|
<string name="spectate_failed_title">Не удаётся посмотреть партию</string>
|
||||||
|
<string name="spectate_no_game">Эта партия больше недоступна.</string>
|
||||||
|
<string name="spectate_unreachable">Устройство, на котором идёт партия, недоступно. Убедитесь, что вы подключены к той же сети Wi-Fi.</string>
|
||||||
|
<string name="spectate_left_win">%1$s покинули партию. Победили %2$s.</string>
|
||||||
|
<string name="spectate_interrupted">Партия прервана: игроки потеряли связь.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -25,9 +25,9 @@
|
|||||||
<string name="settings_version">版本 %1$s</string>
|
<string name="settings_version">版本 %1$s</string>
|
||||||
<string name="settings_repo_title">源代码</string>
|
<string name="settings_repo_title">源代码</string>
|
||||||
<string name="settings_radio">爵士电台</string>
|
<string name="settings_radio">爵士电台</string>
|
||||||
<string name="settings_radio_subtitle">在后台播放网络电台,告别寂静</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz。无网络时播放内置音乐</string>
|
||||||
<string name="settings_radio_connecting">正在连接...</string>
|
<string name="settings_radio_connecting">正在连接...</string>
|
||||||
<string name="settings_radio_error">无法连接</string>
|
<string name="settings_radio_error">无连接,播放内置音乐</string>
|
||||||
<string name="settings_sfx">音效</string>
|
<string name="settings_sfx">音效</string>
|
||||||
<string name="settings_sfx_subtitle">选子、走子、吃子</string>
|
<string name="settings_sfx_subtitle">选子、走子、吃子</string>
|
||||||
<string name="back">返回</string>
|
<string name="back">返回</string>
|
||||||
@@ -353,4 +353,30 @@
|
|||||||
<string name="nearby_bt_off_hint">开启后即可通过蓝牙查找玩家</string>
|
<string name="nearby_bt_off_hint">开启后即可通过蓝牙查找玩家</string>
|
||||||
<string name="nearby_wifi_hint">连接 Wi-Fi 后才能找到同一网络中的玩家</string>
|
<string name="nearby_wifi_hint">连接 Wi-Fi 后才能找到同一网络中的玩家</string>
|
||||||
<string name="permission_open_settings">打开设置</string>
|
<string name="permission_open_settings">打开设置</string>
|
||||||
|
<string name="piece_queen">后</string>
|
||||||
|
<string name="piece_rook">车</string>
|
||||||
|
<string name="piece_bishop">象</string>
|
||||||
|
<string name="piece_knight">马</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">对局中</string>
|
||||||
|
<string name="friends_watch">观战</string>
|
||||||
|
<string name="friends_watch_count">观战 · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">已满</string>
|
||||||
|
<string name="spectators_description">观战人数:%1$d</string>
|
||||||
|
<string name="spectate_title">观战</string>
|
||||||
|
<string name="spectate_joining">正在加入对局…</string>
|
||||||
|
<string name="spectate_flip">翻转棋盘</string>
|
||||||
|
<string name="spectate_back_to_friends">返回好友</string>
|
||||||
|
<string name="spectate_lost_text">无法再连接到主持对局的设备。</string>
|
||||||
|
<string name="spectate_full_title">观战人数已满</string>
|
||||||
|
<string name="spectate_full_text">此对局的观战人数已达上限(%1$d 人),请稍后再试。</string>
|
||||||
|
<string name="spectate_update_title">需要更新</string>
|
||||||
|
<string name="spectate_update_this">请更新 Matewave 以观看此对局。</string>
|
||||||
|
<string name="spectate_update_host">主持此对局的玩家需要更新 Matewave 后才能观战。</string>
|
||||||
|
<string name="spectate_failed_title">无法观看此对局</string>
|
||||||
|
<string name="spectate_no_game">此对局已不可观看。</string>
|
||||||
|
<string name="spectate_unreachable">无法连接到主持对局的设备。请确认你们连接的是同一个 Wi-Fi 网络。</string>
|
||||||
|
<string name="spectate_left_win">%1$s离开了对局,%2$s获胜。</string>
|
||||||
|
<string name="spectate_interrupted">对局中断:玩家之间的连接已断开。</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -25,9 +25,9 @@
|
|||||||
<string name="settings_version">Version %1$s</string>
|
<string name="settings_version">Version %1$s</string>
|
||||||
<string name="settings_repo_title">Source code</string>
|
<string name="settings_repo_title">Source code</string>
|
||||||
<string name="settings_radio">Jazz radio</string>
|
<string name="settings_radio">Jazz radio</string>
|
||||||
<string name="settings_radio_subtitle">Background internet radio instead of silence</string>
|
<string name="settings_radio_subtitle">Radio Swiss Jazz. Without a connection, built-in music plays</string>
|
||||||
<string name="settings_radio_connecting">Connecting...</string>
|
<string name="settings_radio_connecting">Connecting...</string>
|
||||||
<string name="settings_radio_error">Couldn\'t connect</string>
|
<string name="settings_radio_error">No connection, built-in music</string>
|
||||||
<string name="settings_sfx">Sound effects</string>
|
<string name="settings_sfx">Sound effects</string>
|
||||||
<string name="settings_sfx_subtitle">Selecting a piece, moving, capturing</string>
|
<string name="settings_sfx_subtitle">Selecting a piece, moving, capturing</string>
|
||||||
<string name="back">Back</string>
|
<string name="back">Back</string>
|
||||||
@@ -354,4 +354,30 @@
|
|||||||
<string name="nearby_bt_off_hint">Turn it on to find players over Bluetooth</string>
|
<string name="nearby_bt_off_hint">Turn it on to find players over Bluetooth</string>
|
||||||
<string name="nearby_wifi_hint">Players on the same Wi-Fi network can\'t be found until you connect</string>
|
<string name="nearby_wifi_hint">Players on the same Wi-Fi network can\'t be found until you connect</string>
|
||||||
<string name="permission_open_settings">Open settings</string>
|
<string name="permission_open_settings">Open settings</string>
|
||||||
|
<string name="piece_queen">Queen</string>
|
||||||
|
<string name="piece_rook">Rook</string>
|
||||||
|
<string name="piece_bishop">Bishop</string>
|
||||||
|
<string name="piece_knight">Knight</string>
|
||||||
|
|
||||||
|
<!-- Spectators -->
|
||||||
|
<string name="friends_in_game">In game</string>
|
||||||
|
<string name="friends_watch">Watch</string>
|
||||||
|
<string name="friends_watch_count">Watch · %1$d/%2$d</string>
|
||||||
|
<string name="friends_watch_full">Full</string>
|
||||||
|
<string name="spectators_description">Spectators: %1$d</string>
|
||||||
|
<string name="spectate_title">Watching</string>
|
||||||
|
<string name="spectate_joining">Joining the game…</string>
|
||||||
|
<string name="spectate_flip">Flip board</string>
|
||||||
|
<string name="spectate_back_to_friends">Back to Friends</string>
|
||||||
|
<string name="spectate_lost_text">The host\'s device can no longer be reached.</string>
|
||||||
|
<string name="spectate_full_title">Game is full</string>
|
||||||
|
<string name="spectate_full_text">This game already has the maximum of %1$d spectators. Try again later.</string>
|
||||||
|
<string name="spectate_update_title">Update required</string>
|
||||||
|
<string name="spectate_update_this">Update Matewave to watch this game.</string>
|
||||||
|
<string name="spectate_update_host">The player hosting this game needs to update Matewave before it can be watched.</string>
|
||||||
|
<string name="spectate_failed_title">Can\'t watch this game</string>
|
||||||
|
<string name="spectate_no_game">This game is no longer available.</string>
|
||||||
|
<string name="spectate_unreachable">The host\'s device can\'t be reached. Make sure you\'re on the same Wi-Fi network.</string>
|
||||||
|
<string name="spectate_left_win">%1$s left the game. %2$s wins.</string>
|
||||||
|
<string name="spectate_interrupted">Game interrupted: the players lost their connection.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<network-security-config>
|
<network-security-config>
|
||||||
<domain-config cleartextTrafficPermitted="true">
|
<base-config cleartextTrafficPermitted="false" />
|
||||||
<domain includeSubdomains="true">stream.srg-ssr.ch</domain>
|
|
||||||
</domain-config>
|
|
||||||
</network-security-config>
|
</network-security-config>
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.spectate.FriendStatusResolver
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
|
||||||
|
import cc.skysparkle.matewave.spectate.PresenceStatus
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorAdvert
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FriendStatusTest {
|
||||||
|
private val tag = SpectatorAdvert.tagOf("game-1")
|
||||||
|
private val host = NearbyPlayerGame("host", "192.168.1.10", tag, 40_123)
|
||||||
|
private val guest = NearbyPlayerGame("guest", "192.168.1.11", tag, 0)
|
||||||
|
private val idle = NearbyPlayerGame("idle", "192.168.1.12", "", 0)
|
||||||
|
private val nearby = listOf(host, guest, idle).associateBy { it.playerId }
|
||||||
|
private val target = SpectateTarget("192.168.1.10", 40_123, tag)
|
||||||
|
|
||||||
|
private fun status(count: Int, live: Boolean = true) = SpectatorMessage.Status(live, count, MAX_SPECTATORS, 1)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun notVisibleIsOffline() {
|
||||||
|
assertEquals(PresenceStatus.OFFLINE, FriendStatusResolver.resolve("nobody", nearby, emptyMap()).status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun visibleWithoutAGameIsOnline() {
|
||||||
|
val s = FriendStatusResolver.resolve("idle", nearby, emptyMap())
|
||||||
|
assertEquals(PresenceStatus.ONLINE, s.status)
|
||||||
|
assertNull(s.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostInGameCanBeWatchedWithTheLiveCount() {
|
||||||
|
val s = FriendStatusResolver.resolve("host", nearby, mapOf(target to status(7)))
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertEquals(target, s.target)
|
||||||
|
assertEquals(7, s.spectators)
|
||||||
|
assertFalse(s.full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun guestIsWatchedThroughTheHost() {
|
||||||
|
val s = FriendStatusResolver.resolve("guest", nearby, mapOf(target to status(3)))
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertEquals(target, s.target)
|
||||||
|
assertEquals(3, s.spectators)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fullGameIsReportedAsFull() {
|
||||||
|
assertTrue(FriendStatusResolver.resolve("host", nearby, mapOf(target to status(MAX_SPECTATORS))).full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun countIsUnknownUntilTheHostAnswers() {
|
||||||
|
val s = FriendStatusResolver.resolve("host", nearby, emptyMap())
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertNull(s.spectators)
|
||||||
|
assertFalse(s.full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostSayingTheGameEndedWinsOverAStaleAnnouncement() {
|
||||||
|
val ended = mapOf(target to status(0, live = false))
|
||||||
|
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("host", nearby, ended).status)
|
||||||
|
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("guest", nearby, ended).status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun guestWhoseHostIsHiddenIsInGameWithoutWatch() {
|
||||||
|
val s = FriendStatusResolver.resolve("guest", mapOf("guest" to guest), emptyMap())
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertNull(s.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun onlyHostsAreProbed() {
|
||||||
|
assertEquals(setOf(target), FriendStatusResolver.targets(nearby.values))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun advertRoundTripsAndRejectsJunk() {
|
||||||
|
val state = SpectatorAdvert.State(tag, 40_123)
|
||||||
|
val attrs = SpectatorAdvert.attributes(state)
|
||||||
|
assertEquals(state, SpectatorAdvert.parse { attrs[it] ?: "" })
|
||||||
|
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { "" })
|
||||||
|
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { if (it == "g") "not-a-tag" else "1" })
|
||||||
|
assertEquals(SpectatorAdvert.State(tag, 0), SpectatorAdvert.parse { if (it == "g") tag else "99999" })
|
||||||
|
assertEquals(emptyMap<String, String>(), SpectatorAdvert.attributes(SpectatorAdvert.State()))
|
||||||
|
assertEquals(8, tag.length)
|
||||||
|
assertEquals("", SpectatorAdvert.tagOf(""))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ class GameMessageTest {
|
|||||||
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
|
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
|
||||||
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
|
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
|
||||||
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
|
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
|
||||||
|
@Test fun spectatorCount() = roundTrip(GameMessage.SpectatorCountMsg(7, "g1"))
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun profileCarriesGameIdAndVersion() {
|
fun profileCarriesGameIdAndVersion() {
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.GameStatus
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorDiff
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame.Applied
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SpectatorGameTest {
|
||||||
|
private fun snapshot(moves: List<String>, gameId: String = "g1", result: SpectatorResult? = null) = SpectatorSnapshot(
|
||||||
|
gameId = gameId,
|
||||||
|
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||||
|
movesUci = moves,
|
||||||
|
initialSeconds = 180,
|
||||||
|
incrementSeconds = 2,
|
||||||
|
clock = SpectatorClock(170_000, 175_000, if (moves.size % 2 == 0) PieceColor.WHITE else PieceColor.BLACK),
|
||||||
|
result = result
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun move(ply: Int, uci: String, gameId: String = "g1") = SpectatorMessage.MovePlayed(gameId, ply, uci, null)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun loadReplaysTheMoveListWithTurnAndLastMove() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
assertTrue(game.load(snapshot(listOf("e2e4", "e7e5", "e1e2"))))
|
||||||
|
val view = game.view!!
|
||||||
|
assertEquals(listOf("e4", "e5", "Ke2"), view.moveSans)
|
||||||
|
assertEquals(PieceColor.BLACK, view.board.sideToMove)
|
||||||
|
assertEquals("e1e2", view.lastMove!!.toUci())
|
||||||
|
assertEquals(3, view.ply)
|
||||||
|
assertEquals(180, view.initialSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun illegalHistoryIsRefused() {
|
||||||
|
assertFalse(SpectatorGame().load(snapshot(listOf("e2e5"))))
|
||||||
|
assertFalse(SpectatorGame().load(snapshot(listOf("zz99"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun liveMovesFollowOnAndDuplicatesAreIgnored() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("d2d4")))
|
||||||
|
assertEquals(Applied.APPLIED, game.onMove(move(2, "d7d5")))
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(2, "d7d5")))
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(1, "d2d4")))
|
||||||
|
assertEquals(listOf("d4", "d5"), game.view!!.moveSans)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gapsIllegalMovesAndForeignGamesAskForResync() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("d2d4")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(3, "c2c4")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d4d5")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d7d5", gameId = "other")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, SpectatorGame().onMove(move(1, "e2e4")))
|
||||||
|
assertEquals(1, game.view!!.ply)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun promotionIsKept() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
val moves = listOf("h2h4", "g7g5", "h4g5", "h7h6", "g5h6", "g8f6", "h6h7", "f6g8")
|
||||||
|
assertTrue(game.load(snapshot(moves)))
|
||||||
|
assertEquals(Applied.APPLIED, game.onMove(move(9, "h7g8n")))
|
||||||
|
assertEquals(PieceType.KNIGHT, game.view!!.lastMove!!.promotion)
|
||||||
|
assertEquals("hxg8=N", game.view!!.moveSans.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gameOverStopsTheClockAndLaterMovesAreIgnored() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4")))
|
||||||
|
val result = SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK)
|
||||||
|
assertEquals(Applied.APPLIED, game.onGameOver(SpectatorMessage.GameOver("g1", result, null)))
|
||||||
|
assertEquals(result, game.view!!.result)
|
||||||
|
assertNull(game.view!!.clock!!.running)
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(5, "a2a3")))
|
||||||
|
game.onClock(SpectatorClock(1, 1, PieceColor.WHITE))
|
||||||
|
assertNull(game.view!!.clock!!.running)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffTurnsNewMovesIntoLiveMessagesWithTheLatestClock() {
|
||||||
|
val before = snapshot(listOf("e2e4"))
|
||||||
|
val after = snapshot(listOf("e2e4", "e7e5", "g1f3"))
|
||||||
|
val events = SpectatorDiff.between(before, after)
|
||||||
|
assertEquals(2, events.size)
|
||||||
|
val first = events[0] as SpectatorMessage.MovePlayed
|
||||||
|
val second = events[1] as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals(2 to "e7e5", first.ply to first.uci)
|
||||||
|
assertNull(first.clock)
|
||||||
|
assertEquals(3 to "g1f3", second.ply to second.uci)
|
||||||
|
assertEquals(after.clock, second.clock)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffReportsTheEndOnceAndRestartsOnANewGame() {
|
||||||
|
val playing = snapshot(listOf("e2e4"))
|
||||||
|
val over = playing.copy(result = SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.WHITE))
|
||||||
|
assertEquals(listOf(SpectatorMessage.GameOver("g1", over.result!!, over.clock)), SpectatorDiff.between(playing, over))
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(over, over))
|
||||||
|
val rematch = snapshot(emptyList(), gameId = "g2")
|
||||||
|
assertEquals(listOf(SpectatorMessage.NewGame(rematch)), SpectatorDiff.between(over, rematch))
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(null, rematch))
|
||||||
|
// Clock ticks alone are carried by pings, not extra messages.
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(playing, playing.copy(clock = SpectatorClock(1, 2, null))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffFallsBackToAFullSnapshotWhenHistoryChanges() {
|
||||||
|
val a = snapshot(listOf("e2e4", "e7e5"))
|
||||||
|
val b = snapshot(listOf("d2d4"))
|
||||||
|
assertEquals(listOf(SpectatorMessage.NewGame(b)), SpectatorDiff.between(a, b))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun resultsMapEveryWayAGameCanEnd() {
|
||||||
|
fun of(status: GameStatus, timedOut: PieceColor? = null, resigned: PieceColor? = null, left: Boolean = false) =
|
||||||
|
SpectatorResults.of(status, PieceColor.WHITE, timedOut, resigned, left)
|
||||||
|
assertNull(of(GameStatus.ONGOING))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK), of(GameStatus.CHECKMATE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT, PieceColor.WHITE), of(GameStatus.TIMEOUT, timedOut = PieceColor.BLACK))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.BLACK), of(GameStatus.RESIGNATION, resigned = PieceColor.WHITE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.WHITE), of(GameStatus.RESIGNATION, resigned = PieceColor.BLACK, left = true))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.STALEMATE, null), of(GameStatus.STALEMATE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null), of(GameStatus.DRAW_50_MOVES))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.REPETITION, null), of(GameStatus.DRAW_REPETITION))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null), of(GameStatus.DRAW_MATERIAL))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null), of(GameStatus.TIMEOUT_DRAW))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.AGREEMENT, null), of(GameStatus.DRAW_AGREEMENT))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.BLACK), SpectatorResults.leftBy(PieceColor.WHITE))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.RejectReason
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient.Event
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient.Failure
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorHub
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProbe
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Assert.fail
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class SpectatorHubTest {
|
||||||
|
private val loopback: InetAddress = InetAddress.getLoopbackAddress()
|
||||||
|
private val hubTiming = SpectatorHub.Timing(helloTimeoutMs = 1_000, pingIntervalMs = 150, silenceTimeoutMs = 900)
|
||||||
|
private val clientTiming = SpectatorClient.Timing(connectTimeoutMs = 2_000, silenceTimeoutMs = 900)
|
||||||
|
|
||||||
|
private val hubs = CopyOnWriteArrayList<SpectatorHub>()
|
||||||
|
private val clients = CopyOnWriteArrayList<SpectatorClient>()
|
||||||
|
private val closeables = CopyOnWriteArrayList<Closeable>()
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
clients.forEach { it.stop() }
|
||||||
|
hubs.forEach { it.close() }
|
||||||
|
closeables.forEach { runCatching { it.close() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun snapshot(
|
||||||
|
moves: List<String> = emptyList(),
|
||||||
|
clock: SpectatorClock? = SpectatorClock(300_000, 300_000, PieceColor.WHITE),
|
||||||
|
gameId: String = "g1"
|
||||||
|
) = SpectatorSnapshot(
|
||||||
|
gameId = gameId,
|
||||||
|
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||||
|
movesUci = moves,
|
||||||
|
initialSeconds = 300,
|
||||||
|
incrementSeconds = 0,
|
||||||
|
clock = clock
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun hub(initial: SpectatorSnapshot? = snapshot()): SpectatorHub {
|
||||||
|
val hub = SpectatorHub(timing = hubTiming)
|
||||||
|
hubs += hub
|
||||||
|
hub.start(loopback)
|
||||||
|
if (initial != null) hub.publish(initial)
|
||||||
|
return hub
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Recorder {
|
||||||
|
val events = LinkedBlockingQueue<Event>()
|
||||||
|
|
||||||
|
fun next(timeoutMs: Long = 3_000): Event =
|
||||||
|
events.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: throw AssertionError("No event within $timeoutMs ms")
|
||||||
|
|
||||||
|
/** Skips pings and counts until an event matching [predicate]. */
|
||||||
|
fun awaitEvent(timeoutMs: Long = 3_000, predicate: (Event) -> Boolean): Event {
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
while (true) {
|
||||||
|
val left = deadline - System.currentTimeMillis()
|
||||||
|
if (left <= 0) throw AssertionError("Expected event did not arrive")
|
||||||
|
val event = events.poll(left, TimeUnit.MILLISECONDS) ?: continue
|
||||||
|
if (predicate(event)) return event
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun awaitMessage(timeoutMs: Long = 3_000, predicate: (SpectatorMessage) -> Boolean): SpectatorMessage =
|
||||||
|
(awaitEvent(timeoutMs) { it is Event.Received && predicate(it.message) } as Event.Received).message
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun watch(
|
||||||
|
port: Int,
|
||||||
|
recorder: Recorder = Recorder(),
|
||||||
|
version: Int = SpectatorProtocol.VERSION,
|
||||||
|
minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
): Pair<SpectatorClient, Recorder> {
|
||||||
|
val client = SpectatorClient("127.0.0.1", port, { recorder.events.add(it) }, clientTiming, version, minVersion)
|
||||||
|
clients += client
|
||||||
|
client.start()
|
||||||
|
return client to recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitCount(hub: SpectatorHub, expected: Int, timeoutMs: Long = 3_000) {
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
while (hub.count.value != expected) {
|
||||||
|
if (System.currentTimeMillis() > deadline) fail("Spectator count ${hub.count.value}, expected $expected")
|
||||||
|
Thread.sleep(10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun joined(recorder: Recorder): SpectatorMessage.Welcome {
|
||||||
|
val event = recorder.next()
|
||||||
|
assertTrue("Expected to join, got $event", event is Event.Joined)
|
||||||
|
return (event as Event.Joined).welcome
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun twentySpectatorsJoinAndTheTwentyFirstIsRefused() {
|
||||||
|
val hub = hub()
|
||||||
|
val watchers = List(MAX_SPECTATORS) { watch(hub.port).second }
|
||||||
|
watchers.forEach { joined(it) }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS)
|
||||||
|
|
||||||
|
val (_, late) = watch(hub.port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.FULL), late.next())
|
||||||
|
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||||
|
|
||||||
|
// Everyone already watching still gets the game.
|
||||||
|
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||||
|
watchers.forEach { recorder ->
|
||||||
|
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals("e2e4", move.uci)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun simultaneousJoinsNeverExceedTheLimit() {
|
||||||
|
val hub = hub()
|
||||||
|
val start = CountDownLatch(1)
|
||||||
|
val recorders = List(MAX_SPECTATORS + 10) { Recorder() }
|
||||||
|
val threads = recorders.map { r -> Thread { start.await(); watch(hub.port, r) }.apply { start() } }
|
||||||
|
start.countDown()
|
||||||
|
threads.forEach { it.join() }
|
||||||
|
|
||||||
|
val outcomes = recorders.map { it.next(5_000) }
|
||||||
|
assertEquals(MAX_SPECTATORS, outcomes.count { it is Event.Joined })
|
||||||
|
assertEquals(10, outcomes.count { it == Event.JoinFailed(Failure.FULL) })
|
||||||
|
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun joiningMidGameGetsFullStateThenFollowsLive() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val opening = listOf("e2e4", "e7e5", "g1f3")
|
||||||
|
broadcaster.update(snapshot())
|
||||||
|
broadcaster.update(snapshot(opening, SpectatorClock(290_000, 295_000, PieceColor.BLACK)))
|
||||||
|
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
val welcome = joined(recorder)
|
||||||
|
assertEquals(1, welcome.count)
|
||||||
|
assertEquals(opening, welcome.game.movesUci)
|
||||||
|
assertEquals("Alice", welcome.game.white.name)
|
||||||
|
assertEquals(300, welcome.game.initialSeconds)
|
||||||
|
val clock = welcome.game.clock!!
|
||||||
|
assertEquals(PieceColor.BLACK, clock.running)
|
||||||
|
assertEquals(290_000, clock.whiteMs)
|
||||||
|
assertTrue(clock.blackMs in 290_000..295_000)
|
||||||
|
|
||||||
|
val game = SpectatorGame()
|
||||||
|
assertTrue(game.load(welcome.game))
|
||||||
|
assertEquals(PieceColor.BLACK, game.view!!.board.sideToMove)
|
||||||
|
assertEquals(listOf("e4", "e5", "Nf3"), game.view!!.moveSans)
|
||||||
|
|
||||||
|
broadcaster.update(snapshot(opening + "b8c6", SpectatorClock(290_000, 293_000, PieceColor.WHITE)))
|
||||||
|
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals(4, move.ply)
|
||||||
|
assertEquals(SpectatorGame.Applied.APPLIED, game.onMove(move))
|
||||||
|
assertEquals(PieceColor.WHITE, game.view!!.board.sideToMove)
|
||||||
|
assertEquals("Nc6", game.view!!.moveSans.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostLeavingMidGameShowsTheResultThenSaysGoodbye() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val playing = snapshot(listOf("e2e4"))
|
||||||
|
broadcaster.update(playing)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
|
||||||
|
broadcaster.close(playing.copy(result = SpectatorResults.leftBy(PieceColor.WHITE)))
|
||||||
|
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||||
|
assertEquals(SpectatorOutcome.LEFT, end.result.outcome)
|
||||||
|
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = true), recorder.awaitEvent { it is Event.Disconnected })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostDroppingOffIsSeenAsConnectionLost() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
val (_, recorder) = watch(link.port)
|
||||||
|
joined(recorder)
|
||||||
|
|
||||||
|
link.cut()
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = false), recorder.awaitEvent { it is Event.Disconnected })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun wifiSwitchingOffIsDetectedOnBothSides() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
val (_, cutOff) = watch(link.port)
|
||||||
|
val (_, direct) = watch(hub.port)
|
||||||
|
joined(cutOff)
|
||||||
|
joined(direct)
|
||||||
|
awaitCount(hub, 2)
|
||||||
|
|
||||||
|
// No more packets either way, but no connection reset: what a dead Wi-Fi link looks like.
|
||||||
|
link.silent = true
|
||||||
|
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = false), cutOff.awaitEvent { it is Event.Disconnected })
|
||||||
|
awaitCount(hub, 1)
|
||||||
|
// The remaining spectator's counter follows.
|
||||||
|
assertNotNull(direct.awaitMessage { it is SpectatorMessage.Count && it.count == 1 })
|
||||||
|
|
||||||
|
// The spectator who still has a connection keeps watching.
|
||||||
|
hub.publish(snapshot(listOf("d2d4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "d2d4", null)))
|
||||||
|
assertNotNull(direct.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun spectatorsLeavingFreeTheirSlotsWhileOthersKeepWatching() {
|
||||||
|
val hub = hub()
|
||||||
|
val watchers = List(MAX_SPECTATORS) { watch(hub.port) }
|
||||||
|
watchers.forEach { joined(it.second) }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS)
|
||||||
|
|
||||||
|
watchers.take(5).forEach { it.first.stop() }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS - 5)
|
||||||
|
|
||||||
|
val (_, newcomer) = watch(hub.port)
|
||||||
|
assertEquals(MAX_SPECTATORS - 4, joined(newcomer).count)
|
||||||
|
|
||||||
|
hub.publish(snapshot(listOf("c2c4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "c2c4", null)))
|
||||||
|
(watchers.drop(5).map { it.second } + newcomer).forEach {
|
||||||
|
assertNotNull(it.awaitMessage { m -> m is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stalledSpectatorsNeverSlowDownTheHost() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
repeat(5) { joined(watch(link.port).second) }
|
||||||
|
link.silent = true
|
||||||
|
|
||||||
|
val started = System.nanoTime()
|
||||||
|
repeat(2_000) { i ->
|
||||||
|
hub.publish(snapshot(), listOf(SpectatorMessage.Count(i, MAX_SPECTATORS)))
|
||||||
|
}
|
||||||
|
val elapsedMs = (System.nanoTime() - started) / 1_000_000
|
||||||
|
assertTrue("publish took $elapsedMs ms", elapsedMs < 1_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun outdatedSpectatorIsToldToUpdate() {
|
||||||
|
val hub = hub()
|
||||||
|
val (_, recorder) = watch(hub.port, version = 0, minVersion = 0)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UPDATE_THIS_APP), recorder.next())
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun outdatedHostIsReported() {
|
||||||
|
val hub = hub()
|
||||||
|
val newer = SpectatorProtocol.VERSION + 1
|
||||||
|
val (_, recorder) = watch(hub.port, version = newer, minVersion = newer)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UPDATE_HOST_APP), recorder.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rawOldClientGetsAClearRejectInsteadOfACrash() {
|
||||||
|
val hub = hub()
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 2_000
|
||||||
|
s.getOutputStream().write("{\"type\":\"hello\",\"sv\":0}\n".toByteArray())
|
||||||
|
val reply = BufferedReader(InputStreamReader(s.getInputStream())).readLine()
|
||||||
|
val reject = SpectatorProtocol.decode(reply)!!.message as SpectatorMessage.Reject
|
||||||
|
assertEquals(RejectReason.UPDATE_REQUIRED, reject.reason)
|
||||||
|
assertEquals(SpectatorProtocol.MIN_COMPATIBLE_VERSION, reject.minVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun garbageAndOversizedInputCloseOnlyThatConnection() {
|
||||||
|
val hub = hub()
|
||||||
|
val (_, watcher) = watch(hub.port)
|
||||||
|
joined(watcher)
|
||||||
|
|
||||||
|
for (payload in listOf("hello?\n", "x".repeat(SpectatorProtocol.MAX_CLIENT_LINE_CHARS + 10) + "\n")) {
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 2_000
|
||||||
|
s.getOutputStream().write(payload.toByteArray())
|
||||||
|
// Closed with unread input the host may answer with a reset instead of a clean close.
|
||||||
|
val read = try { s.getInputStream().read() } catch (e: IOException) { -1 }
|
||||||
|
assertEquals(-1, read)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(1, hub.count.value)
|
||||||
|
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||||
|
assertNotNull(watcher.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun silentConnectionThatNeverSaysHelloIsClosed() {
|
||||||
|
val hub = hub()
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 3_000
|
||||||
|
assertEquals(-1, s.getInputStream().read())
|
||||||
|
}
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun noGameYetIsRefused() {
|
||||||
|
val hub = hub(initial = null)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.NO_GAME), recorder.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun statusProbeReportsLiveCountWithoutTakingASlot() {
|
||||||
|
val hub = hub()
|
||||||
|
repeat(3) { joined(watch(hub.port).second) }
|
||||||
|
awaitCount(hub, 3)
|
||||||
|
val status = SpectatorProbe.query("127.0.0.1", hub.port)!!
|
||||||
|
assertTrue(status.inGame)
|
||||||
|
assertEquals(3, status.count)
|
||||||
|
assertEquals(MAX_SPECTATORS, status.max)
|
||||||
|
assertEquals(3, hub.count.value)
|
||||||
|
|
||||||
|
hub.publish(snapshot().copy(result = SpectatorResults.interrupted))
|
||||||
|
assertFalse(SpectatorProbe.query("127.0.0.1", hub.port)!!.inGame)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun probeOfAClosedHostIsNull() {
|
||||||
|
val hub = hub()
|
||||||
|
val port = hub.port
|
||||||
|
hub.close()
|
||||||
|
assertEquals(null, SpectatorProbe.query("127.0.0.1", port, timeoutMs = 500))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun resyncSendsAFreshSnapshot() {
|
||||||
|
val hub = hub(snapshot(listOf("e2e4", "c7c5")))
|
||||||
|
val (client, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
client.requestResync()
|
||||||
|
val fresh = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||||
|
assertEquals(listOf("e2e4", "c7c5"), fresh.game.movesUci)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rematchReachesSpectatorsAsANewGame() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val first = snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4"))
|
||||||
|
broadcaster.update(first)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
broadcaster.update(first.copy(result = SpectatorResults.of(
|
||||||
|
cc.skysparkle.matewave.engine.GameStatus.CHECKMATE, PieceColor.WHITE, null, null, false
|
||||||
|
)))
|
||||||
|
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||||
|
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||||
|
|
||||||
|
broadcaster.update(snapshot(gameId = "g2"))
|
||||||
|
val next = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||||
|
assertEquals("g2", next.game.gameId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clocksKeepRunningBetweenHostUpdates() {
|
||||||
|
val hub = hub(snapshot(clock = SpectatorClock(60_000, 60_000, PieceColor.WHITE)))
|
||||||
|
Thread.sleep(400)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
val clock = joined(recorder).game.clock!!
|
||||||
|
assertTrue("white ${clock.whiteMs}", clock.whiteMs in 50_000..59_700)
|
||||||
|
assertEquals(60_000, clock.blackMs)
|
||||||
|
val ping = recorder.awaitMessage { it is SpectatorMessage.Ping } as SpectatorMessage.Ping
|
||||||
|
assertTrue(ping.clock!!.whiteMs <= clock.whiteMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun closingTheHubEndsEveryoneAndRefusesNewcomers() {
|
||||||
|
val hub = hub()
|
||||||
|
val recorders = List(3) { watch(hub.port).second }
|
||||||
|
recorders.forEach { joined(it) }
|
||||||
|
val port = hub.port
|
||||||
|
hub.close()
|
||||||
|
recorders.forEach { assertEquals(Event.Disconnected(hostClosed = true), it.awaitEvent { e -> e is Event.Disconnected }) }
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
val (_, late) = watch(port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UNREACHABLE), late.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A TCP relay that can go silent (dead Wi-Fi) or drop every connection (host gone). */
|
||||||
|
private inner class FlakyLink(target: Int) : Closeable {
|
||||||
|
private val server = ServerSocket(0, 50, loopback)
|
||||||
|
private val sockets = CopyOnWriteArrayList<Socket>()
|
||||||
|
@Volatile var silent = false
|
||||||
|
val port: Int get() = server.localPort
|
||||||
|
|
||||||
|
init {
|
||||||
|
closeables += this
|
||||||
|
Thread {
|
||||||
|
while (!server.isClosed) {
|
||||||
|
val inbound = try { server.accept() } catch (e: IOException) { break }
|
||||||
|
val outbound = Socket(loopback, target)
|
||||||
|
sockets += inbound
|
||||||
|
sockets += outbound
|
||||||
|
pump(inbound, outbound)
|
||||||
|
pump(outbound, inbound)
|
||||||
|
}
|
||||||
|
}.apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pump(from: Socket, to: Socket) = Thread {
|
||||||
|
val buffer = ByteArray(8_192)
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
val n = from.getInputStream().read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
if (!silent) to.getOutputStream().write(buffer, 0, n)
|
||||||
|
}
|
||||||
|
} catch (_: IOException) {
|
||||||
|
} finally {
|
||||||
|
runCatching { from.close() }
|
||||||
|
runCatching { to.close() }
|
||||||
|
}
|
||||||
|
}.apply { isDaemon = true }.start()
|
||||||
|
|
||||||
|
fun cut() = sockets.forEach { runCatching { it.close() } }
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
runCatching { server.close() }
|
||||||
|
cut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.RejectReason
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SpectatorProtocolTest {
|
||||||
|
private val clock = SpectatorClock(295_000, 300_000, PieceColor.BLACK)
|
||||||
|
private val snapshot = SpectatorSnapshot(
|
||||||
|
gameId = "g1",
|
||||||
|
white = SpectatorPlayer("u1", "Владимир", 1350),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1200),
|
||||||
|
movesUci = listOf("e2e4", "e7e5", "g1f3"),
|
||||||
|
initialSeconds = 300,
|
||||||
|
incrementSeconds = 2,
|
||||||
|
clock = clock
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun roundTrip(message: SpectatorMessage) {
|
||||||
|
val envelope = SpectatorProtocol.decode(SpectatorProtocol.encode(message))
|
||||||
|
assertNotNull(envelope)
|
||||||
|
assertEquals(SpectatorProtocol.VERSION, envelope!!.version)
|
||||||
|
assertEquals(message, envelope.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun hello() = roundTrip(SpectatorMessage.Hello(1))
|
||||||
|
@Test fun query() = roundTrip(SpectatorMessage.StatusQuery)
|
||||||
|
@Test fun pong() = roundTrip(SpectatorMessage.Pong)
|
||||||
|
@Test fun resync() = roundTrip(SpectatorMessage.Resync)
|
||||||
|
@Test fun leave() = roundTrip(SpectatorMessage.Leave)
|
||||||
|
@Test fun welcome() = roundTrip(SpectatorMessage.Welcome(7, MAX_SPECTATORS, snapshot))
|
||||||
|
@Test fun status() = roundTrip(SpectatorMessage.Status(true, 7, MAX_SPECTATORS, 1))
|
||||||
|
@Test fun reject() = roundTrip(SpectatorMessage.Reject(RejectReason.FULL, 1))
|
||||||
|
@Test fun move() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "b8c6", clock))
|
||||||
|
@Test fun moveWithoutClock() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "e7e8q", null))
|
||||||
|
@Test fun count() = roundTrip(SpectatorMessage.Count(3, MAX_SPECTATORS))
|
||||||
|
@Test fun ping() = roundTrip(SpectatorMessage.Ping(clock))
|
||||||
|
@Test fun closing() = roundTrip(SpectatorMessage.Closing)
|
||||||
|
@Test fun newGame() = roundTrip(SpectatorMessage.NewGame(snapshot.copy(movesUci = emptyList(), clock = null)))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gameOverKeepsWinnerAndDraws() {
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.WHITE), clock.copy(running = null)))
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.AGREEMENT, null), null))
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.INTERRUPTED, null), null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun everyMessageCarriesTheSenderVersion() {
|
||||||
|
val line = SpectatorProtocol.encode(SpectatorMessage.Pong, version = 7)
|
||||||
|
assertEquals(7, SpectatorProtocol.decode(line)!!.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unknownTypeFromANewerVersionIsSkippedNotFatal() {
|
||||||
|
val envelope = SpectatorProtocol.decode("""{"type":"emote","sv":9,"what":"wave"}""")
|
||||||
|
assertNotNull(envelope)
|
||||||
|
assertEquals(9, envelope!!.version)
|
||||||
|
assertNull(envelope.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unknownOutcomeAndRejectReasonDegradeGracefully() {
|
||||||
|
val end = SpectatorProtocol.decode("""{"type":"end","sv":2,"gid":"g1","result":{"o":"abandoned"}}""")!!.message
|
||||||
|
assertEquals(SpectatorOutcome.UNKNOWN, (end as SpectatorMessage.GameOver).result.outcome)
|
||||||
|
val reject = SpectatorProtocol.decode("""{"type":"reject","sv":2,"reason":"banned","min":2}""")!!.message
|
||||||
|
assertEquals(RejectReason.OTHER, (reject as SpectatorMessage.Reject).reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun malformedInputNeverThrows() {
|
||||||
|
assertNull(SpectatorProtocol.decode("not json"))
|
||||||
|
assertNull(SpectatorProtocol.decode("{}"))
|
||||||
|
assertNull(SpectatorProtocol.decode(""))
|
||||||
|
// Known type with missing fields: skipped like an unknown one.
|
||||||
|
assertNull(SpectatorProtocol.decode("""{"type":"move","sv":1}""")!!.message)
|
||||||
|
assertNull(SpectatorProtocol.decode("""{"type":"welcome","sv":1,"n":1}""")!!.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun oldHelloWithoutMinimumStillParses() {
|
||||||
|
val hello = SpectatorProtocol.decode("""{"type":"hello","sv":1}""")!!.message
|
||||||
|
assertEquals(SpectatorMessage.Hello(1), hello)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clockAdvancesOnlyForTheRunningSide() {
|
||||||
|
val later = clock.advancedBy(1_500)
|
||||||
|
assertEquals(295_000, later.whiteMs)
|
||||||
|
assertEquals(298_500, later.blackMs)
|
||||||
|
assertEquals(0, SpectatorClock(1_000, 5_000, PieceColor.WHITE).advancedBy(9_000).whiteMs)
|
||||||
|
assertEquals(clock.copy(running = null), clock.copy(running = null).advancedBy(5_000))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hugeMoveListIsRejected() {
|
||||||
|
val moves = (1..2_001).joinToString(",") { "\"e2e4\"" }
|
||||||
|
val line = """{"type":"game","sv":1,"game":{"gid":"g","wp":{},"bp":{},"moves":[$moves]}}"""
|
||||||
|
assertNull(SpectatorProtocol.decode(line)!!.message)
|
||||||
|
assertTrue(SpectatorProtocol.MAX_CLIENT_LINE_CHARS < SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,5 @@
|
|||||||
|
• Ruhige Musik auf dem Startbildschirm, in den Einstellungen abschaltbar
|
||||||
|
• Jazzradio ist standardmäßig aus und streamt nur über HTTPS
|
||||||
|
• Der App-Start stoppt keine Musik in anderen Apps mehr
|
||||||
|
• Screenreader nennen die Figuren bei der Bauernumwandlung
|
||||||
|
• Sauberere Springer-Bilder auf den Eröffnungskarten
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• Eingebaute Musik, wenn das Jazzradio keine Verbindung hat, mit eigenem Stück für Partien und Aufgaben. Sie ersetzt die bisherige Menümusik
|
||||||
|
• Musik spielt nicht mehr, während ein Anruf oder eine andere App den Ton nutzt
|
||||||
|
• Die Einstellungen zeigen „Aktion nötig“, solange Berechtigungen fehlen
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Partien von Freunden ansehen: bis zu 20 Zuschauer im selben WLAN können eine laufende LAN-Partie im Bereich „Freunde“ verfolgen
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<p>Mach jede Schachpartie wertvoll. Spiel in deinem eigenen Tempo, schärfe deine Taktik und gewinne Sicherheit in der Eröffnung – ob du allein trainierst oder dich mit einem Freund ans Brett setzt.</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>Fordere eine KI heraus und wähle die Schwierigkeit, die zu dir passt.</li>
|
||||||
|
<li>Löse Schachaufgaben und setze deine Taktik in die Praxis um.</li>
|
||||||
|
<li>Lerne und übe Eröffnungen, Varianten und Zugfolgen.</li>
|
||||||
|
<li>Spiele lokal mit Freunden über WLAN, LAN oder Bluetooth.</li>
|
||||||
|
<li>Genieße eine aufgeräumte Open-Source-Schach-App mit dunklem Design und sechs Sprachen.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>Wähle einen Modus und leg los: Trainiere gegen die KI, löse Aufgaben, studiere Eröffnungslinien oder verbinde dich über dein lokales Netzwerk mit einem Spieler in der Nähe. Matewave ist für Einsteiger gemacht, die das Spiel lernen, und für erfahrene Spieler, die konzentriert üben wollen – ganz ohne Online-Matchmaking.</p>
|
||||||
|
|
||||||
|
<p>Lade Matewave herunter und mach deinen nächsten Zug.</p>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Schach offline: Taktik schärfen und Eröffnungen üben, gegen KI oder Freunde.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Matewave
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• Calm music on the main screen, can be turned off in Settings
|
||||||
|
• Jazz radio is off by default and streams over HTTPS only
|
||||||
|
• Starting the app no longer stops music in other apps
|
||||||
|
• Screen readers name the pieces in the promotion dialog
|
||||||
|
• Cleaner opening card artwork
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• Built-in music when the jazz radio has no connection, with its own track for games and puzzles. It replaces the separate menu music
|
||||||
|
• Music no longer plays while a call or another app is using the sound
|
||||||
|
• Settings show "Action needed" while permissions are missing
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Watch friends' games: up to 20 spectators on the same Wi-Fi can follow a live LAN game from the Friends section
|
||||||
@@ -1,38 +1,13 @@
|
|||||||
<p>Matewave is an offline-first chess app. Play against the AI, solve puzzles, learn openings, or play a friend nearby over Bluetooth or Wi-Fi. No accounts, no servers, no ads and no tracking.</p>
|
<p>Make every chess session count. Play at your own pace, sharpen your tactics, and build opening confidence — whether you're practicing solo or sitting down with a friend.</p>
|
||||||
|
|
||||||
<p><b>Play against the AI</b></p>
|
|
||||||
<ul>
|
<ul>
|
||||||
<li>Four difficulty levels, from beginner to strong club player.</li>
|
<li>Challenge an AI opponent and choose a difficulty that suits you.</li>
|
||||||
<li>Time controls from bullet 1+0 to classical 30+20, or no time limit.</li>
|
<li>Solve chess puzzles to put your tactics to work.</li>
|
||||||
<li>An unfinished game is saved with its whole move list and clock and can be continued later.</li>
|
<li>Learn and practice openings, variations, and move sequences.</li>
|
||||||
|
<li>Play local multiplayer with friends over Wi-Fi, LAN, or Bluetooth.</li>
|
||||||
|
<li>Enjoy a clean, open-source chess app with a dark theme and support for six languages.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p><b>Puzzles</b></p>
|
<p>Choose a mode and start playing: practice against the AI, work through puzzles, study opening lines, or connect with a nearby player on your local network. Matewave is made for beginners learning the game and experienced players who want focused practice without online matchmaking.</p>
|
||||||
<ul>
|
|
||||||
<li>1,207 puzzles from the Lichess puzzle database, picked to match your rating.</li>
|
|
||||||
<li>Hints, the solution on request, and progress through multi-move puzzles.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>Learn openings with spaced repetition</b></p>
|
<p>Download Matewave and make your next move.</p>
|
||||||
<ul>
|
|
||||||
<li>24 main lines for White and Black.</li>
|
|
||||||
<li>New moves are learned with the piece highlighted; reviews ask only the moves that are due.</li>
|
|
||||||
<li>Earn up to three stars per opening with flawless scheduled reviews.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>Play with friends nearby</b></p>
|
|
||||||
<ul>
|
|
||||||
<li>Over Bluetooth LE (no pairing) or the same Wi-Fi network, without internet.</li>
|
|
||||||
<li>Chat with images, draw offers, resignation and rematch.</li>
|
|
||||||
<li>Games are encrypted end to end, and each device has its own key, so a friend cannot be impersonated.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>Also</b></p>
|
|
||||||
<ul>
|
|
||||||
<li>The opening name and whether the game is still in theory, shown during games.</li>
|
|
||||||
<li>Rating with a history graph, captured pieces and material balance.</li>
|
|
||||||
<li>Four board color themes.</li>
|
|
||||||
<li>Optional Radio Swiss Jazz background stream (the only feature that uses the internet).</li>
|
|
||||||
<li>Share the app to another phone with a QR code over Wi-Fi.</li>
|
|
||||||
<li>Available in English, Russian, German, Lithuanian, Japanese and Chinese.</li>
|
|
||||||
</ul>
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
Offline chess: AI, puzzles, opening training and play with friends nearby
|
Play chess offline, sharpen tactics, and practice openings with AI or friends.
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• ホーム画面で穏やかな音楽(設定でオフ可能)
|
||||||
|
• ジャズラジオは初期状態でオフ、HTTPS のみで配信
|
||||||
|
• 起動時に他のアプリの音楽を止めなくなりました
|
||||||
|
• スクリーンリーダーが昇格画面の駒を読み上げます
|
||||||
|
• オープニングカードのナイト画像を整えました
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• ジャズラジオに接続できないときは内蔵の音楽を再生。対局とパズルには専用の曲。メニュー音楽はこれに置き換わりました
|
||||||
|
• 通話や他のアプリが音声を使っている間は音楽を再生しません
|
||||||
|
• 権限が足りない間、設定に「要対応」と表示されます
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• 友達の対局を観戦:同じWi-Fiにいる最大20人が「フレンド」から進行中のLAN対局を見られます
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<p>一局一局を、意味のある時間に。自分のペースで対局し、戦術を磨き、オープニングに自信をつけましょう。ひとりでの練習でも、友達との対局でも。</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>AI対戦相手に挑戦し、自分に合った難易度を選べます。</li>
|
||||||
|
<li>チェスパズルを解いて、戦術を実戦で活かしましょう。</li>
|
||||||
|
<li>オープニング、変化、手順を学んで練習できます。</li>
|
||||||
|
<li>Wi-Fi、LAN、Bluetoothで友達とローカル対戦。</li>
|
||||||
|
<li>ダークテーマと6言語に対応した、シンプルなオープンソースのチェスアプリ。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>モードを選んでスタート:AIと練習する、パズルを解く、オープニングの手順を学ぶ、またはローカルネットワークで近くのプレイヤーとつながる。Matewaveは、チェスを覚え始めた初心者にも、オンラインのマッチングなしで集中して練習したい上級者にもぴったりです。</p>
|
||||||
|
|
||||||
|
<p>Matewaveをダウンロードして、次の一手を。</p>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
オフラインでチェス。AIや友達と対局し、戦術を磨いてオープニングを練習。
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Matewave
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• Rami muzika pagrindiniame ekrane, išjungiama nustatymuose
|
||||||
|
• Džiazo radijas pagal numatymą išjungtas ir veikia tik per HTTPS
|
||||||
|
• Paleidus programėlę, kitų programėlių muzika nebesustoja
|
||||||
|
• Ekrano skaitytuvai įvardija figuras virstant pėstininkui
|
||||||
|
• Tvarkingesni žirgų paveikslėliai debiutų kortelėse
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• Įdiegta muzika, kai džiazo radijas neturi ryšio, su atskiru kūriniu partijoms ir uždaviniams. Ji pakeitė atskirą meniu muziką
|
||||||
|
• Muzika nebegroja, kol garsą naudoja skambutis ar kita programėlė
|
||||||
|
• Nustatymuose rodoma „Reikia veiksmo“, kol trūksta leidimų
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Draugų partijų stebėjimas: iki 20 žiūrovų tame pačiame Wi-Fi tinkle gali sekti vykstančią LAN partiją skiltyje „Draugai“
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<p>Tegul kiekviena šachmatų partija būna prasminga. Žaiskite savo tempu, lavinkite taktiką ir įgykite pasitikėjimo debiutuose – nesvarbu, ar treniruojatės vieni, ar sėdate prie lentos su draugu.</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>Išmėginkite jėgas prieš DI varžovą ir pasirinkite jums tinkamą sunkumą.</li>
|
||||||
|
<li>Spręskite šachmatų uždavinius ir pritaikykite taktiką praktikoje.</li>
|
||||||
|
<li>Mokykitės ir treniruokite debiutus, variantus ir ėjimų sekas.</li>
|
||||||
|
<li>Žaiskite su draugais per Wi-Fi, vietinį tinklą (LAN) arba Bluetooth.</li>
|
||||||
|
<li>Mėgaukitės tvarkinga atvirojo kodo šachmatų programėle su tamsia tema ir šešiomis kalbomis.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>Pasirinkite režimą ir pradėkite: treniruokitės prieš DI, spręskite uždavinius, studijuokite debiutų linijas arba prisijunkite prie netoliese esančio žaidėjo vietiniame tinkle. Matewave sukurta tiek pradedantiesiems, kurie mokosi žaidimo, tiek patyrusiems žaidėjams, norintiems susikaupusios praktikos be internetinio varžovų parinkimo.</p>
|
||||||
|
|
||||||
|
<p>Atsisiųskite Matewave ir atlikite kitą ėjimą.</p>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Šachmatai be interneto: taktika ir debiutai, žaidimas su DI ar draugais.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Matewave
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• Спокойная музыка на главном экране, отключается в настройках
|
||||||
|
• Джаз-радио выключено по умолчанию и работает только по HTTPS
|
||||||
|
• Запуск приложения больше не останавливает музыку в других приложениях
|
||||||
|
• Экранные дикторы называют фигуры при превращении пешки
|
||||||
|
• Очищены картинки коней на карточках дебютов
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• Встроенная музыка, когда у джаз-радио нет связи, со своим треком для партий и задач. Она заменила отдельную музыку в меню
|
||||||
|
• Музыка больше не играет, пока звук занят звонком или другим приложением
|
||||||
|
• В настройках показывается «Нужно действие», пока не хватает разрешений
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Просмотр партий друзей: до 20 зрителей в той же Wi-Fi сети могут следить за идущей LAN-партией в разделе «Друзья»
|
||||||
@@ -1,38 +1,13 @@
|
|||||||
<p>Matewave — шахматы, которым не нужен интернет. Играйте с ИИ, решайте задачи, учите дебюты или играйте с другом рядом по Bluetooth или Wi-Fi. Без аккаунтов, серверов, рекламы и слежки.</p>
|
<p>Пусть каждая шахматная сессия приносит пользу. Играйте в своём темпе, оттачивайте тактику и обретайте уверенность в дебютах — тренируетесь ли вы в одиночку или садитесь за доску с другом.</p>
|
||||||
|
|
||||||
<p><b>Игра с ИИ</b></p>
|
|
||||||
<ul>
|
<ul>
|
||||||
<li>Четыре уровня сложности — от новичка до сильного любителя.</li>
|
<li>Сразитесь с ИИ-соперником и выберите подходящий уровень сложности.</li>
|
||||||
<li>Контроль времени от пули 1+0 до классики 30+20 или без ограничения.</li>
|
<li>Решайте шахматные задачи и применяйте тактику на практике.</li>
|
||||||
<li>Незаконченная партия сохраняется вместе со всеми ходами и часами, её можно продолжить позже.</li>
|
<li>Изучайте и отрабатывайте дебюты, варианты и последовательности ходов.</li>
|
||||||
|
<li>Играйте с друзьями по Wi-Fi, локальной сети или Bluetooth.</li>
|
||||||
|
<li>Аккуратное шахматное приложение с открытым исходным кодом, тёмной темой и поддержкой шести языков.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p><b>Задачи</b></p>
|
<p>Выберите режим и начинайте: тренируйтесь против ИИ, решайте задачи, изучайте дебютные линии или подключитесь к игроку рядом по локальной сети. Matewave создан и для новичков, которые осваивают игру, и для опытных игроков, которым нужна сосредоточенная практика без онлайн-подбора соперников.</p>
|
||||||
<ul>
|
|
||||||
<li>1207 задач из базы Lichess, подобранных под ваш рейтинг.</li>
|
|
||||||
<li>Подсказки, решение по запросу и прогресс в многоходовых задачах.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>Изучение дебютов с интервальными повторениями</b></p>
|
<p>Скачайте Matewave и сделайте свой следующий ход.</p>
|
||||||
<ul>
|
|
||||||
<li>24 основных варианта за белых и за чёрных.</li>
|
|
||||||
<li>Новые ходы учатся с подсвеченной фигурой, а на повторении спрашиваются только те ходы, которым пора.</li>
|
|
||||||
<li>До трёх звёзд за дебют за безошибочные повторения по расписанию.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>Игра с друзьями рядом</b></p>
|
|
||||||
<ul>
|
|
||||||
<li>По Bluetooth LE (без сопряжения) или в одной сети Wi-Fi, без интернета.</li>
|
|
||||||
<li>Чат с картинками, предложение ничьей, сдача и реванш.</li>
|
|
||||||
<li>Партии зашифрованы, у каждого устройства свой ключ, поэтому выдать себя за друга нельзя.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p><b>А ещё</b></p>
|
|
||||||
<ul>
|
|
||||||
<li>Название дебюта во время партии и отметка, идёт ли игра ещё по теории.</li>
|
|
||||||
<li>Рейтинг с графиком, взятые фигуры и материальный перевес.</li>
|
|
||||||
<li>Четыре цветовые темы доски.</li>
|
|
||||||
<li>Фоновое радио Radio Swiss Jazz по желанию — единственная функция, которой нужен интернет.</li>
|
|
||||||
<li>Передача приложения на другой телефон через QR-код по Wi-Fi.</li>
|
|
||||||
<li>Языки: английский, русский, немецкий, литовский, японский и китайский.</li>
|
|
||||||
</ul>
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
Шахматы без интернета: ИИ, задачи, изучение дебютов и игра с друзьями рядом
|
Играйте в шахматы офлайн, оттачивайте тактику и учите дебюты с ИИ или друзьями.
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
• 主屏幕新增舒缓音乐,可在设置中关闭
|
||||||
|
• 爵士电台默认关闭,且仅通过 HTTPS 播放
|
||||||
|
• 启动应用时不再中断其他应用的音乐
|
||||||
|
• 屏幕阅读器会读出兵升变时的棋子名称
|
||||||
|
• 开局卡片上的马图更干净
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
• 爵士电台无法连接时播放内置音乐,对局和谜题有专属曲目,取代了原来的菜单音乐
|
||||||
|
• 通话或其他应用占用声音时不再播放音乐
|
||||||
|
• 缺少权限时,设置中会显示“需要处理”
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• 观看好友对局:同一 Wi-Fi 下最多 20 名观众可在“好友”中观看正在进行的局域网对局
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<p>让每一局都有收获。按自己的节奏下棋,磨练战术,建立开局信心——无论是独自练习还是和朋友对弈。</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>挑战 AI 对手,选择适合你的难度。</li>
|
||||||
|
<li>解答国际象棋谜题,把战术用于实战。</li>
|
||||||
|
<li>学习并练习开局、变着和着法顺序。</li>
|
||||||
|
<li>通过 Wi-Fi、局域网或蓝牙与朋友本地对战。</li>
|
||||||
|
<li>简洁的开源国际象棋应用,深色主题,支持六种语言。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>选择模式开始下棋:与 AI 练习、解谜题、研究开局变化,或通过本地网络连接附近的棋手。Matewave 适合正在学棋的新手,也适合想要专注练习、无需在线匹配的老手。</p>
|
||||||
|
|
||||||
|
<p>下载 Matewave,走出你的下一步。</p>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
离线下国际象棋:与 AI 或朋友对弈,磨练战术,练习开局。
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Matewave
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
Categories:
|
|
||||||
- Games
|
|
||||||
License: GPL-3.0-or-later
|
|
||||||
SourceCode: https://git.skysparkle.cc/kalarina/Matewave
|
|
||||||
IssueTracker: https://git.skysparkle.cc/kalarina/Matewave/issues
|
|
||||||
|
|
||||||
AutoName: Matewave
|
|
||||||
|
|
||||||
RepoType: git
|
|
||||||
Repo: https://git.skysparkle.cc/kalarina/Matewave.git
|
|
||||||
|
|
||||||
Builds:
|
|
||||||
- versionName: 1.0.43
|
|
||||||
versionCode: 1
|
|
||||||
commit: v1.0.43
|
|
||||||
subdir: app
|
|
||||||
gradle:
|
|
||||||
- yes
|
|
||||||
|
|
||||||
AutoUpdateMode: Version
|
|
||||||
UpdateCheckMode: Tags
|
|
||||||
CurrentVersion: 1.0.43
|
|
||||||
CurrentVersionCode: 1
|
|
||||||