diff --git a/QWEN.md b/QWEN.md index 55def0f..dd23887 100644 --- a/QWEN.md +++ b/QWEN.md @@ -2,19 +2,27 @@ ## Project Overview -**hexo** is an educational game project - a clone of [DiceWars](https://www.gamedesign.jp/games/dicewars/). The project is in early development stage. +**hexo** is an educational game project - a clone of [DiceWars](https://www.gamedesign.jp/games/dicewars/). ### Game Concept A strategy dice game played on a hexagonal grid where players command armies of dice and battle to conquer territories. +### Features + +- **2-4 Players**: Support for multiple human and/or AI players +- **AI Bots**: Computer-controlled players with smart move selection +- **Hexagonal Grid**: 20×20 map with proper adjacency +- **Dice Combat**: Roll-based battle system +- **Solid Territory Supply**: Supply = size of largest connected territory + ### Core Game Mechanics #### Map System - Generatable hexagonal grid map (20x20 cells) -- Each cell can be either playable or blocked/impassable +- Each cell can be passable or blocked/impassable - Each field can hold up to 8 dice -- Each player-owned field provides +1 supply unit to the player +- Cells are connected to 6 neighbors (hexagonal adjacency) #### Dice System - Standard 6-sided dice @@ -25,75 +33,74 @@ A strategy dice game played on a hexagonal grid where players command armies of Where: - `cnt` = number of dice on the field - `full_dice` = maximum die value (6) - - `current_dice` = top die current value (1-6, calculated during gameplay) + - `current_dice` = top die current value (1-6) #### Game Rules -1. **Setup**: Multiple dice are placed on the map for each player at the start -2. **Movement Conditions**: A user can move a unit if its strength > 1 - - When moving: strength-1 transfers to target cell, strength 1 remains on source cell -3. **Combat**: When attacking a cell with enemy dice, both players roll: - - **Attacker**: `F_attack = rnd(F-1)` (random value less than original strength minus 1) - - **Defender**: `F_defence = current_strength` (full field strength) - - **Victory**: If `F_attack > F_defence`, attacker wins; otherwise defender repels the attack - - **On Victory**: Attacker leaves strength 1 on source cell, transfers `F_attack-1` to target - - **On Defeat**: Defender retains `F_defence - F_attack` (minimum 1) -4. **Supply Phase**: After all players have moved, each receives supply: - - `S = sum(Cell)` where Cell = supply value from each player-owned cell - - Maximum per cell: `8 * full_dice` (48 dice points) - - If all cells already have maximum strength, no supply is added +1. **Setup**: Each player starts with dice on their starting position +2. **Movement**: Can move if strength > 1 + - Source cell left with 1, target receives strength-1 +3. **Combat**: Both sides roll dice (1 to their strength) + - **Attacker wins**: Takes cell with attack_roll-1, source becomes 1 + - **Defender wins**: Attacker reduced to 1, defender keeps defense_roll-attack_roll (min 1) +4. **Supply**: After turn ends, player receives supply = largest connected territory size + - Distributed 1 by 1 to random non-max cells + - Max per cell: 48 (8 dice × 6) + +#### AI Bot Logic +- Evaluates all possible moves +- Prioritizes: winning attacks > expansion to empty > reinforcement +- Includes thinking delay for natural gameplay ## Directory Structure ``` hexo/ -├── README.md # Game specifications and rules (in Russian) -├── QWEN.md # This file - project context for AI assistance -├── .gitignore # Git ignore rules (Python-focused template) -├── jsdom-pkg/ # Local copy of jsdom library -│ └── package/ -│ └── lib/ -│ ├── api.js # Main jsdom API entry point -│ └── jsdom/ # jsdom core implementation -│ ├── browser/ # Browser emulation (Window, parser, resources) -│ ├── living/ # DOM living standard implementations -│ ├── generated/ # Auto-generated Web IDL bindings -│ └── ... # Various DOM/CSS/SVG/XHR implementations -└── node_modules/ - └── jsdom/ # Installed jsdom dependency +├── README.md # Game rules and documentation (Russian) +├── QWEN.md # This file - project context +├── package.json # NPM configuration +├── server.js # Simple HTTP server for development +├── .gitignore # Git ignore rules +├── jsdom-pkg/ # Local jsdom library copy +├── public/ # Web application files +│ ├── index.html # Main HTML page with start screen +│ ├── styles.css # Game UI styles +│ ├── game.js # Main game logic and rendering +│ ├── map.js # HexMap module (browser version) +│ └── ai-bot.js # AI bot player logic +├── src/ # Server-side modules +│ ├── index.js # Console demo entry point +│ └── map.js # HexMap module (Node.js version) +└── test/ # Unit tests + └── map.test.js # Map and cell tests ``` ## Technology Stack -- **Runtime**: Node.js (inferred from jsdom usage) -- **Core Library**: [jsdom](https://github.com/jsdom/jsdom) - JavaScript implementation of DOM and HTML standards - - Provides browser-like environment for server-side JavaScript - - Enables DOM manipulation, event handling, and web API emulation - -## Development Status - -**Early Stage**: The project currently contains: -- Game design documentation (README.md) -- jsdom library setup (both local copy and node_modules installation) -- No main game source files yet +- **Runtime**: Node.js +- **Frontend**: Vanilla JavaScript (ES Modules), HTML5 Canvas, CSS3 +- **Backend**: Simple HTTP server (server.js) +- **Testing**: Node.js built-in test runner (`node --test`) ## Building and Running -> **TODO**: Build and run commands are not yet defined. The project is in initial setup phase. - -Expected setup once development begins: ```bash -# Install dependencies -npm install +# Start web server (http://localhost:8080) +npm run serve -# Run the game (TBD) +# Run console demo npm start -# Run tests (TBD) +# Run tests npm test ``` ## Development Conventions +- ES Modules for browser code (`import`/`export`) +- CommonJS for Node.js code (`require`/`module.exports`) +- Map module exports both ES and CommonJS for compatibility +- Tests use Node.js built-in `node:test` module + > **TODO**: Coding standards and testing practices are not yet established. ### Inferred Practices (based on jsdom usage) diff --git a/README.md b/README.md index 9c6b5ca..94e9569 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,69 @@ # hexo -Это учебный проект. Игра, клон https://www.gamedesign.jp/games/dicewars/ +Учебный проект. Игра, клон https://www.gamedesign.jp/games/dicewars/ -1. Генерируемкая карта - 1. ккаждое поле - ячейка гексагон - 2. размер карты 20 х 20 ячеек - 3. каждое поле может быть доступно для игроков или быть непроходимо для всех - 4. каджое принадлежащее игроку поле дет ему +1 единицу снабжения +## Запуск игры -2. игрок управляет кубиками - 1. кубик игральный 6 граннный - 2. на каждом поле может быть до 8 кубиков - 3. сила текущего юнита (ячейка с кубиками) расчитывается, - F = (cnt-1)*full_dice + current_dice, - где cnt - количество кубиков, - full_dice - максимальное значение на кубике = 6 - сurrent_dice - верхний кубик с текущим значением от 1 до 6, расчитываемое в ходе игры +```bash +npm run serve # Запустить веб-сервер (http://localhost:8080) +npm test # Запустить тесты +npm start # Консольная версия карты +``` -3. правила игры - 1. вначале на карты помещается несколько кубиков для каждых игроков - 2. юзер может ходить юнитом, если - 1. его сила больше 1, при этом на захваченную клетку перемещается сила-1, а на исходной остается кубик с силой 1 - 2. если на захватываемой клетке вражеские кубики, то оба игрока бросают кости - 1. у нападающего количество максимальной силыменьше на 1 исходной, F_attac=rnd(F-1) - 2. у защищающегося полная сила поля, F_defence=ктв(F) - 3. - 4. условия победы - 1. если F_attac>F_defence - то победа нападающего иначе защищающийся отбил атаку - 2. при победе нападающего он оставляет на исходной клетке кубик с силой 1, на захватываемую переводит F_attac-1, - 3. при пройгрыше у защищающегося отсается F_defence-F_attac, но не меньше 1 - 3. После того, как все игроки походили, каждый получает снабжение по формуле - S=sum(Cell), где Cell - значение снабжения с каждой клетки, принадлежащей игроку - 1. Саксимальное кол-во на клетке может быть 8*Full_dice - 2. Если все клетки игрока имеют максимальное колво силы, то ничего не добавляется. +## Настройки игры + +При запуске можно выбрать: +- Количество игроков: 2-4 +- Тип каждого игрока: Человек (Human) или AI бот + +## Правила игры + +### 1. Карта +- Гексагональная сетка 20×20 ячеек +- Каждая ячейка может быть: + - Проходима (пустая или принадлежит игроку) + - Непроходима (заблокирована) + +### 2. Игровые единицы +- Кубик: 6-гранный, значения 1-6 +- На поле может быть до 8 кубиков +- **Сила юнита**: `F = (cnt-1)*6 + current_dice` + - `cnt` — количество кубиков + - `current_dice` — значение верхнего кубика + +### 3. Ход игры + +#### Перемещение/Атака +- Можно ходить, если сила > 1 +- На целевую клетку переходит `сила-1`, на исходной остаётся 1 +- При атаке оба игрока бросают кости: + - Атакующий: `attack_roll = rnd(1..сила-1)` + - Защищающийся: `defense_roll = rnd(1..сила)` + +#### Результат боя +- Если `attack_roll > defense_roll`: + - Атакующий побеждает, занимает клетку с `attack_roll-1` + - На исходной клетке остаётся 1 +- Если `attack_roll <= defense_roll`: + - Атака отбита, атакующий уменьшается до 1 + - Защитник остаётся с `defense_roll - attack_roll` (мин. 1) + +#### Снабжение +- После хода игрок получает снабжение +- **Снабжение = размер наибольшей непрерывной территории** +- Непрерывная территория — связанные между собой клетки игрока +- Если территория разорвана врагом — считается только largest кусок +- Снабжение распределяется по 1 единице случайным клеткам (не максимальным) +- Максимум на клетке: 48 (8 кубиков × 6) + +### 4. Победа +- Последний игрок, оставшийся с клетками на карте + +## Управление + +- **Клик** на свою клетку → выбор +- **Клик** на соседнюю вражескую/пустую → атака +- **Cancel** → отмена выбора +- **End Turn** → завершить ход \ No newline at end of file