Игра запускается и играется: три рантайм-бага и адаптивная вёрстка

Проверено вживую в Chrome: лобби -> матч -> бот ходит -> результат ->
статистика в лобби. Полный матч отыгран, оба исхода видел.

Баги, которые собирались и типизировались, но падали только в рантайме:

1. Canvas не менял размер под экран. Своего cc.Widget у него не было,
   а alignCanvasWithScreen правит только камеру. Canvas оставался
   1280x720, и все растянутые по нему дети — тоже.
2. [...map.values()] превращается сборкой в [].concat(map.values()),
   а concat не разворачивает итератор, а кладёт его одним элементом.
   Отсюда "view.cancelAnimations is not a function" на первой же уборке
   карт. Теперь Array.from.
3. Рубашка козыря рисовалась поверх колоды, а не под ней.

Вёрстка переделана под требование UI.md (4:3 .. 21:9):
- fitWidth даёт постоянную ширину, но не высоту: на 4:3 видно только
  ±720 юнитов. Кнопка "Leave" на y=840 и низ руки на -860 были за
  экраном именно там, где это важнее всего
- рука и панель действий считаются от нижней границы экрана,
  "Leave" прибит виджетом к левому верхнему углу
- стол — один ряд до шести карт вместо двух рядов по три: экономит
  ~215 юнитов высоты, которых на 4:3 нет. Ряд центрируется по тем
  картам, что реально на столе
- затемнение под окном результата рисуется непрозрачным спрайтом:
  тонировать и без того полупрозрачный спрайт почти ничего не даёт

Инструменты:
- npm run serve — отдаёт сборку и роут /_aspects: игра в трёх
  фиксированных iframe-ах 4:3 / 16:9 / 21:9. Движок подгоняет себя
  под окно, поэтому iframe — единственный простой способ увидеть
  вёрстку в форме, которой окно не имеет
- npm run check:spreads — ловит спред неитерируемого в массив
- npm run check — чистота core, спреды, сцены, типы, тесты

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
ftc
2026-09-13 12:41:47 +03:00
co-authored by Claude Opus 5
parent 43f5bc5df3
commit 7fbe4c324d
14 changed files with 710 additions and 152 deletions
+61 -20
View File
@@ -1,6 +1,6 @@
import {
_decorator, Button, Component, EventTouch, Label, Node, Prefab,
instantiate, tween, UIOpacity, v3, Vec3,
instantiate, tween, UIOpacity, UITransform, v3, Vec3,
} from 'cc';
import { Card } from '../../core/cards/Card';
import { BasicBot } from '../../core/bot/BasicBot';
@@ -9,7 +9,7 @@ import { Action, ActionType, Actions, IllegalActionError } from '../../core/rule
import { Phase, PlayerId } from '../../core/rules/GameState';
import { legalActions } from '../../core/rules/DurakRules';
import { intentFor } from '../../core/rules/intent';
import { Layout, Palette, Timing } from '../common/Theme';
import { bottomAnchors, Layout, Palette, tableSlotX, Timing } from '../common/Theme';
import { Strings } from '../common/Strings';
import { CardLibrary } from './CardLibrary';
import { CardView } from './CardView';
@@ -79,6 +79,9 @@ export class GameScreen extends Component {
@property({ type: Button, tooltip: 'Dismisses the result overlay.' })
continueButton: Button | null = null;
@property({ type: Node, tooltip: 'Holds Take and Done; follows the bottom edge.' })
actionBar: Node | null = null;
/** Set by `MainFlow`. */
onFinished: ((outcome: MatchOutcome) => void) | null = null;
onQuitRequested: (() => void) | null = null;
@@ -145,7 +148,12 @@ export class GameScreen extends Component {
/** Releases every card node and forgets the match. Safe to call twice. */
teardown(): void {
this.unscheduleAllCallbacks();
for (const view of [...this._views.values(), ...this._anonymous]) {
// Array.from, not [...map.values()]. The build transpiles array spread
// to [].concat(...), which appends a Map iterator as a single element
// instead of expanding it — so the loop would run once over the iterator
// itself. See docs/DECISIONS.md.
const live = Array.from(this._views.values()).concat(this._anonymous);
for (const view of live) {
view.cancelAnimations();
this._recycle(view);
}
@@ -289,6 +297,13 @@ export class GameScreen extends Component {
// Rendering
// -----------------------------------------------------------------------
/** Half the canvas height, which is how far the layout may reach from centre. */
private _halfHeight(): number {
const transform = this.node.getComponent(UITransform);
const height = transform && transform.height > 0 ? transform.height : Layout.designHeight;
return height / 2;
}
/** Lays the whole table out from the current state, tweening over `duration`. */
render(duration: number): void {
const match = this._match;
@@ -298,16 +313,23 @@ export class GameScreen extends Component {
const state = match.state;
const view = match.viewFor(HUMAN);
const live = new Set<Card>();
const anchors = bottomAnchors(this._halfHeight());
// Trump card, lying under the deck.
this._layOutHud(anchors.actionBarY);
// The trump card lies face up under the draw pile, turned sideways so the
// suit shows. _place lifts whatever it touches to the top of the layer,
// so it is pushed back down afterwards.
if (state.deck.length > 0) {
live.add(state.trumpCard);
this._place(state.trumpCard, true,
v3(Layout.region.trump.x, Layout.region.trump.y, 0), 0.62, 90, duration);
v3(Layout.trump.x, Layout.trump.y, 0), Layout.tableCardScale, 90, duration);
this._views.get(state.trumpCard)?.node.setSiblingIndex(0);
}
// The player's hand: a straight row, tightened as it grows.
const hand = [...view.hand].sort(byTrumpThenRank(state.trumpSuit));
// The player's hand: a straight row, tightened as it grows, and sitting
// against the bottom edge wherever that happens to be.
const hand = view.hand.slice().sort(byTrumpThenRank(state.trumpSuit));
const step = Math.min(
Layout.handStep,
hand.length > 1 ? (Layout.handMaxWidth - Layout.cardWidth) / (hand.length - 1) : Layout.handStep,
@@ -317,15 +339,13 @@ export class GameScreen extends Component {
live.add(card);
const lifted = card === this._selected ? Layout.handLift : 0;
this._place(card, true,
v3(handLeft + i * step, Layout.region.playerHandY + lifted, 0), 1, 0, duration);
v3(handLeft + i * step, anchors.handY + lifted, 0), 1, 0, duration);
});
// The table: attacking cards with whatever beat them, three to a row.
// The table: one centred row of attacking cards, each with whatever beat it.
state.table.forEach((slot, i) => {
const column = i % 3;
const row = Math.floor(i / 3);
const x = (column - 1) * Layout.region.tableColumnStep;
const y = Layout.region.tableTopY - row * Layout.region.tableRowStep;
const x = tableSlotX(i, state.table.length);
const y = Layout.tableY;
live.add(slot.attack);
this._place(slot.attack, true, v3(x, y, 0), Layout.tableCardScale, 0, duration);
@@ -343,6 +363,20 @@ export class GameScreen extends Component {
this._renderChrome(view.opponents[0]?.handSize ?? 0);
}
/**
* Puts the scene's fixed furniture where this screen shape wants it. Doing it
* here rather than in the scene keeps one source of truth for the layout, and
* the action bar has to move with the hand anyway.
*/
private _layOutHud(actionBarY: number): void {
moveNodeY(this.actionBar, actionBarY);
moveNodeY(this.opponentLabel?.node ?? null, Layout.opponentLabelY);
moveNodeY(this.messageLabel?.node ?? null, Layout.messageY);
if (this.deckAnchor) {
this.deckAnchor.setPosition(Layout.deck.x, Layout.deckLabelY, 0);
}
}
/** Face-down nodes: a short stack for the deck, and the opponent's hand. */
private _renderAnonymous(deckSize: number, opponentHand: number, duration: number): void {
// Three backs are enough to read as a pile; drawing twenty-four is waste.
@@ -358,8 +392,8 @@ export class GameScreen extends Component {
for (let i = 0; i < deckBacks; i++) {
this._anonymous[i].moveTo(
v3(Layout.region.deck.x + i * 3, Layout.region.deck.y + i * 3, 0),
0.62, 0, duration,
v3(Layout.deck.x + i * 3, Layout.deck.y + i * 3, 0),
Layout.tableCardScale, 0, duration,
);
}
@@ -367,7 +401,7 @@ export class GameScreen extends Component {
const left = -step * (opponentHand - 1) / 2;
for (let i = 0; i < opponentHand; i++) {
this._anonymous[deckBacks + i].moveTo(
v3(left + i * step, Layout.region.opponentHandY, 0),
v3(left + i * step, Layout.opponentHandY, 0),
Layout.opponentCardScale, 0, duration,
);
}
@@ -409,7 +443,7 @@ export class GameScreen extends Component {
if (!view) {
view = this._take(card, faceUp);
// A card appearing for the first time slides out of the deck.
view.moveTo(v3(Layout.region.deck.x, Layout.region.deck.y, 0), 0.62, 0, 0);
view.moveTo(v3(Layout.deck.x, Layout.deck.y, 0), Layout.tableCardScale, 0, 0);
this._views.set(card, view);
}
view.flipTo(faceUp);
@@ -419,14 +453,15 @@ export class GameScreen extends Component {
/** Cards that have left the visible table — they went to the discard or a hand. */
private _retireCardsNotIn(live: Set<Card>, duration: number): void {
for (const [card, view] of [...this._views]) {
// Array.from, not [...map] — see the note in teardown.
for (const [card, view] of Array.from(this._views.entries())) {
if (live.has(card)) continue;
this._views.delete(card);
const goingToOpponent = !this._match?.state.discard.includes(card);
const target = goingToOpponent
? v3(0, Layout.region.opponentHandY, 0)
: v3(Layout.region.discard.x, Layout.region.discard.y, 0);
? v3(0, Layout.opponentHandY, 0)
: v3(Layout.discard.x, Layout.discard.y, 0);
view.moveTo(target, 0.4, 0, duration);
view.flipTo(false);
@@ -512,6 +547,12 @@ function setActive(node: Node | null, active: boolean): void {
if (node) node.active = active;
}
function moveNodeY(node: Node | null, y: number): void {
if (node && node.position.y !== y) {
node.setPosition(node.position.x, y, 0);
}
}
function setButton(button: Button | null, enabled: boolean): void {
if (!button) return;
button.node.active = enabled;