Skip to content

Если кому-то интересно, то можно обновить/улучшить Словотрон, добавив возможность запуска в локальном режиме. - #129

Closed
IvanChaev wants to merge 4 commits into
AnnaCodit:devfrom
IvanChaev:main

Conversation

@IvanChaev

@IvanChaev IvanChaev commented Aug 1, 2026

Copy link
Copy Markdown

Если интересно, то можно обновить/улучшить Словотрон, добавив возможность запуска в "локальном" режиме. Под локальным режимом я подразумеваю запуск solo.html

solo.html

solo.js

solo.html нужно положить в корневую папку, а solo.js в папку js

Для чего это нужно?

  1. Быстрая проверка бекендов
  2. Потренироваться/понять бекэнд
  3. Поиск багов

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Added a standalone solo game mode playable without Twitch.
    • Introduced Russian-language screens for guesses, hints, results, statistics, and leaderboards.
    • Added responsive controls, customizable backgrounds, winner and restart views, and reset options.
    • Players can submit guesses by clicking or pressing Enter, with validation, hints, and Easter eggs.
  • Documentation
    • Added setup guidance for required Windows command-line tools.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your trial has ended. Reactivate Greptile to resume code reviews.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a standalone Russian-language solo game page. The runtime initializes rounds, validates and queues guesses, handles hints and Easter eggs, updates the interface, and excludes Twitch initialization.

Changes

Standalone solo gameplay

Layer / File(s) Summary
Solo page and gameplay surface
solo.html
Adds the solo page shell, word-entry controls, hint progress, settings, leaderboard, statistics, winner, restart, and guessing-result sections. It loads the standalone script set without Twitch initialization or analytics scripts.
Round initialization and guess processing
js/solo.js
Initializes rounds, disables input until the secret word is ready, validates and normalizes guesses, handles hints and Easter eggs, queues guesses, updates UI state, and wires click and keyboard submission.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Player
  participant solo.html
  participant js/solo.js
  participant Game APIs

  Player->>solo.html: Enter guess or press Enter
  solo.html->>js/solo.js: Submit guess
  js/solo.js->>Game APIs: Generate secret word or process queued guess
  Game APIs-->>js/solo.js: Return initialization or guess result
  js/solo.js-->>solo.html: Update input, guess count, and game state
  solo.html-->>Player: Display feedback
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title identifies the main change: adding local mode to Slovotron, although it uses unnecessary conditional wording.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@IvanChaev
IvanChaev changed the base branch from main to dev August 1, 2026 11:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@js/solo.js`:
- Around line 28-36: Update app(), solo_guess(), and process_message() to gate
guesses on successful initialization: disable the input controls before awaiting
generate_secret_word(), reject or avoid queuing submissions until secret_word_id
is set, and re-enable controls only after initialization succeeds. Keep the
controls disabled when initialization throws or otherwise fails, and ensure
queued guesses cannot reach the scoring API without a valid challenge ID.

In `@solo.html`:
- Line 81: Update the logo anchor in solo.html to use a relative solo.html
destination instead of root-relative "/" so file:// local mode keeps navigation
within the local game; preserve the existing logo styling and title.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eaf439fe-07c8-4035-a127-49f8d525b5cf

📥 Commits

Reviewing files that changed from the base of the PR and between e3f3d27 and 2f63563.

📒 Files selected for processing (2)
  • js/solo.js
  • solo.html

Comment thread js/solo.js
Comment thread solo.html Outdated
greptile-apps[bot]

This comment was marked as spam.

Оба замечания CodeRabbit исправлены локально:

Race-условие (Major) — js/solo.js:10-15, 43, 66-69: ввод теперь блокируется (disabled на инпуте и кнопке), пока generate_secret_word() не вернул ключ; при неудаче инициализации остаётся заблокированным, а solo_guess() дополнительно не пускает запросы с пустым secret_word_id (текст в поле при этом сохраняется).
Логотип (Minor) — solo.html:81: href="/" заменён на относительный href="index.html", чтобы клик не уводил из игры при открытии через file://.
greptile-apps[bot]

This comment was marked as spam.

greptile-apps[bot]

This comment was marked as spam.

greptile-apps[bot]

This comment was marked as spam.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
js/solo.js (1)

87-96: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject all whitespace separators.

Line 87 checks only U+0020. A tab-separated value passes the multi-word check, then Line 96 removes the tab and queues the concatenated text as one guess. Reject /\s/ after trimming.

Proposed fix
-    if (message.split(' ').length > 1 || message.length > 20 || message.length <= 1 || !isNaN(message)) {
+    if (/\s/.test(message) || message.length > 20 || message.length <= 1 || !isNaN(message)) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@js/solo.js` around lines 87 - 96, Update the validation condition in the
message-processing block to reject any whitespace separator, including tabs,
rather than checking only literal spaces. Trim the input as needed and apply a
whitespace check using the existing `message` value before the normalization and
character-filtering replacements, while preserving the current rejection message
and return behavior.
🧹 Nitpick comments (1)
AGENTS.md (1)

1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Do not commit machine-specific tool paths.

These absolute Windows paths apply only to one workstation. They can mislead contributors and automation on other machines. Replace them with portable tool names, or keep local path overrides outside the repository.

Proposed documentation change
-# Пути к инструментам (не в PATH этой сессии):
-git: D:\programs\Git\cmd\git.exe
-gh:  D:\programs\GitHub CLI\gh.exe
+# Configure local paths for `git` and `gh` outside the repository.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@AGENTS.md` around lines 1 - 3, Remove the machine-specific absolute Git and
GitHub CLI paths from the tool-path documentation in AGENTS.md. Replace them
with portable tool names or omit the entries, keeping any local path overrides
outside the repository.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@js/solo.js`:
- Around line 45-51: Validate that game.gameId is present and non-empty before
calling generate_secret_word in the solo-round initialization flow. If it is
missing, fail initialization and return without setting solo_ready, enabling
controls, or displaying the ready message; preserve the existing setup path when
a valid gameId is available.

---

Outside diff comments:
In `@js/solo.js`:
- Around line 87-96: Update the validation condition in the message-processing
block to reject any whitespace separator, including tabs, rather than checking
only literal spaces. Trim the input as needed and apply a whitespace check using
the existing `message` value before the normalization and character-filtering
replacements, while preserving the current rejection message and return
behavior.

---

Nitpick comments:
In `@AGENTS.md`:
- Around line 1-3: Remove the machine-specific absolute Git and GitHub CLI paths
from the tool-path documentation in AGENTS.md. Replace them with portable tool
names or omit the entries, keeping any local path overrides outside the
repository.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 31b7342d-0054-484c-9e5b-365580126741

📥 Commits

Reviewing files that changed from the base of the PR and between 2f63563 and fe7cab2.

📒 Files selected for processing (3)
  • AGENTS.md
  • js/solo.js
  • solo.html

Comment thread js/solo.js
Comment on lines +45 to +51
// получение секретного слова для отгадывания
secret_word_id = await generate_secret_word();
console.log('Ключ игры: ', secret_word_id);

solo_ready = true;
setSoloControlsEnabled(true);
addTextToLastWords('🎯 Слово загадано! Введите свой вариант ниже');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 6 '\bcreateGame\s*\(|\bgameId\b' --glob '*.js'

Repository: AnnaCodit/Slovotron

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Tracked JavaScript files:\n'
git ls-files '*.js' | sed -n '1,120p'

printf '\nAPI-related identifiers:\n'
rg -n -C 4 'generate_secret_word|create_game|gameId|solo_ready|solo_guess|secret_word_id' -g '*.js' . || true

printf '\nFile sizes:\n'
wc -l js/*.js 2>/dev/null || true

Repository: AnnaCodit/Slovotron

Length of output: 13510


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'js/api.js createGame implementations and generate_secret_word:\n'
sed -n '130,275p' js/api.js | cat -n
printf '\n'
sed -n '285,365p' js/api.js | cat -n

printf '\njs/solo.js initialization path:\n'
sed -n '35,70p' js/solo.js | cat -n

Repository: AnnaCodit/Slovotron

Length of output: 12209


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '150,200p' js/api.js | cat -n

printf '\nBehavioral probe for solo initialization with empty game IDs:\n'
node - <<'JS'
const initialValues = {
  secret_word_id: '',
  solo_ready: false
};
function generate_secret_word(payloadId = '') {
  return payloadId; // matches game.gameId passthrough
}
function setSoloControlsEnabled(enabled) {}
const result = {
  secret_word_id: generate_secret_word(''),
  console_log: 'Ключ игры: ',
  solo_ready: true,
  controls_enabled: true,
  message: '🎯 Слово загадано! Введите свой вариант ниже'
};
const canGuess = (message2) => result.solo_ready && !!(message2 || '').trim() !== '' && result.secret_word_id;
console.log(JSON.stringify({ result, guess_rejected_when_submitted: !canGuess('пример') }, null, 2));
JS

Repository: AnnaCodit/Slovotron

Length of output: 2585


Validate game.gameId before starting the solo round.

The current backends accept room_id even when it is empty, and generate_secret_word() then passes it to js/solo.js. This leaves solo_ready = true and input enabled, but solo_guess() rejects the submission because secret_word_id is falsy. Fail the initialization before enabling the controls when game.gameId is missing or empty.

🧰 Tools
🪛 ast-grep (0.45.0)

[error] 49-49: React's useState should not be directly called
Context: setSoloControlsEnabled(true)
Note: [CWE-710] Improper Adherence to Coding Standards. Security best practice.

(usestate-direct-usage)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@js/solo.js` around lines 45 - 51, Validate that game.gameId is present and
non-empty before calling generate_secret_word in the solo-round initialization
flow. If it is missing, fail initialization and return without setting
solo_ready, enabling controls, or displaying the ready message; preserve the
existing setup path when a valid gameId is available.

greptile-apps[bot]

This comment was marked as spam.

@AnnaCodit

AnnaCodit commented Aug 2, 2026

Copy link
Copy Markdown
Owner

Мистер Мирус привет! 👋😀
Спасибо за предложение функционала но я вынуждена отклонить слияние. Объясню: в целом, в соло можно играть и так сейчас, достаточно ввести адрес любого твич канала и там в оффлайн чате писать слова =)
Но! сам по себе концепт того что можно вводить слова прям на странице словотрона, не открывая дополнительную вкладку и не парясь о том что кто-то увидит тесты в истории чата - вполне себе хороший.
Но! ) реализация в твоем случае получилась неудачная. Из-за дублирования index.html в solo и частичного дублирования init.js, в будущем, внося изменения в проект придется помнить об этом и вносить дубликаты изменений в оба дополнительных файла, это неудобно, это может запутать нейронки итд.

Чисто в теории, этот функционал можно сделать как опциональную галочку в разделе настроек, добавить поле ввода на index.html по умолчанию скрытое и обработчик в один из существующих js. отдельных файлов не нужно будет (ну или обработчик вынести в отдельный js, но там не будет дублирования другого функционала).

Или, если исходить из того что это создается лишь в целях тестирования, то можно и в общедоступных настройках не делать пункт, а сделать секретную кнопочку например как у нас сейчас есть точка внизу под логотипом гитхаба, которая будет включать блок с вводом текста =) или перехват параметра в урле типа ?manual_input=1

ну в общем типа того.
Еще раз спасибо за предложение Мирус! я думаю в будущем к нему вернусь если раньше никто не предложит реализацию.

Блин капец этот бот от greptile насрал в PR =)) А говорили блин что для опенсорс реп у них бесплатные ревью... Отключила.

@AnnaCodit AnnaCodit closed this Aug 2, 2026
@AnnaCodit

Copy link
Copy Markdown
Owner

и интерфейс ввода упростить
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants