diff --git a/en/news/2024-05_memory-logic.md b/en/news/2024-05_memory-logic.md new file mode 100644 index 0000000..8932859 --- /dev/null +++ b/en/news/2024-05_memory-logic.md @@ -0,0 +1,87 @@ +Title: "Memory" game logic +Date: 2024-05-03 00:00 +Category: News +Slug: memory-logic +Lang: en + +# "Memory" game logic + +In April I implemented "Memory" game logic in Python as limited language model and successfully converted the code to C++ by the instrument under development. + +Limited language model assumes the following architecture of two parts: + +1. state context +1. pure functions without side effects working only with the context + +Game logic state context in Python currently looks like this ([C++][ctx_cxx]): + +```python +class memory_Context: + def __init__(self): + self.hiddenItems = [] + self.mismatchedItems = [] + self.playfieldItems = {} + self.playfieldSize = 0 + self.recentField = "none" + self.selectedId = -1 + self.selectedItems = [] + self.victory = False +``` + +Since the instrument only works with functions at the moment, I had to write C++ context code manually. + +Functions look like this ([C++][func_cxx]): + +```python +# Select item +@llm_by_value +def memory_selectItem( + c: memory_Context +) -> memory_Context: + if ( + len(c.selectedItems) == 2 + ): + c.selectedItems.clear() + #} + c.selectedItems.append(c.selectedId) + c.recentField = "selectedItems" + return c +#} +``` + +Limited language model functions have the following features: + +* `@llm_by_value` Python decorator is used to pass arguments by value instead of by reference (which is default in Python) +* passing arguments by value is mandatory to limit function scope to only single context field, it's formalized Single Responsibility Principle +* context contains `recentField` representing a stored "event"; this allows functions to run only when necessary field changes +* function must use `recentField` to specify which field it changed or provide `none` if no action was performed +* function takes only context as an input and only returns (an updated) context as an output + + +"Memory" game logic has the following functions: + +| № | Function | Caller| Description | +| --- | --- | --- | --- | +| 1 | `memory_generateConstPlayfield` | User | Generate simplified playfield with items of the same group following each other sequentially | +| 2 | `memory_selectItem` | User | Select playfield item | +| 3 | `memory_shouldDeselectMismatchedItems` | System | Reaction to deselect a pair of the selected items of different groups | +| 4 | `memory_shouldDetectVictory` | System | Reaction to detect victory when all items got hidden | +| 5 | `memory_shouldHideMatchingItems` | System | Reaction to hide a pair of the selected items of the same group | + +To verify functions work identically in both Python and C++, I cover each function with at least one test: + +* `memory_test_generateConstPlayfield` +* `memory_test_selectItem_1x` +* `memory_test_selectItem_2x` +* `memory_test_selectItem_3x` +* `memory_test_shouldDeselectMismatchedItems` +* `memory_test_shouldDeselectMismatchedItems_itemTwice` +* `memory_test_shouldDetectVictory` +* `memory_test_shouldHideMatchingItems` + +# May plans + +I'll make a text UI for "Memory" game. + +[ctx_cxx]: https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h +[func_cxx]: https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory.cpp#L29 diff --git a/en/news/index.html b/en/news/index.html index 3786b5e..5df7341 100644 --- a/en/news/index.html +++ b/en/news/index.html @@ -30,6 +30,31 @@

News

+
+

+ "Memory" game logic +

+

+ 2024-05-03 00:00 +

+
+

"Memory" game logic

+

In April I implemented "Memory" game logic in Python as limited language model and successfully converted the code to C++ by the instrument under development.

+

Limited language model assumes the following architecture of two parts:

+
    +
  1. state context
  2. +
  3. pure functions without side effects working only with the context
  4. +
+

Game logic state context in Python currently looks like this (C++):

+

```python +class memory_Context: + def init(self): + self.hiddenItems = []. . .

+
+ +

The first example of a portable code @@ -204,23 +229,6 @@ It seems that right now we have less completed features than before the release Continue reading

-
-

- On the way to durable applications -

-

- 2019-08-05 00:00 -

-
-

Pskov's veche

-

This article describes our first durable application for desktop PCs: PSKOV static site generator.

-

Durability

-

A durable application is an application that functions without a single change on operating systems released in years 2010-2030. In other words, a durable application has backward compatibility of 10 years and has the stability to run for 10 years. Actually, PSKOV runs even under Windows 2000, so PSKOV has backward compatibility of 19 years.. . .

-
- -

Page 1 of 7

diff --git a/en/news/index2.html b/en/news/index2.html index 01e30c9..49598b7 100644 --- a/en/news/index2.html +++ b/en/news/index2.html @@ -30,6 +30,23 @@

News

+
+

+ On the way to durable applications +

+

+ 2019-08-05 00:00 +

+
+

Pskov's veche

+

This article describes our first durable application for desktop PCs: PSKOV static site generator.

+

Durability

+

A durable application is an application that functions without a single change on operating systems released in years 2010-2030. In other words, a durable application has backward compatibility of 10 years and has the stability to run for 10 years. Actually, PSKOV runs even under Windows 2000, so PSKOV has backward compatibility of 19 years.. . .

+
+ +
-
-

- First techdemo of OGS Mahjong 2: Gameplay -

-

- 2018-02-16 00:00 -

-
-

End of a Mahjong party

-

We are glad to announce the release of the first technical demonstration of OGS Mahjong 2. The purpose of this release was to verify gameplay across supported platforms.

-

Get techdemo for your platform:

- -

Notes:

-
    -
  • iOS version is not released because it cannot be easily shared outside AppStore.. . .
  • -
-
- -

Page 2 of 7

diff --git a/en/news/index3.html b/en/news/index3.html index 06f09be..5f324ad 100644 --- a/en/news/index3.html +++ b/en/news/index3.html @@ -30,6 +30,33 @@

News

+
+

+ First techdemo of OGS Mahjong 2: Gameplay +

+

+ 2018-02-16 00:00 +

+
+

End of a Mahjong party

+

We are glad to announce the release of the first technical demonstration of OGS Mahjong 2. The purpose of this release was to verify gameplay across supported platforms.

+

Get techdemo for your platform:

+ +

Notes:

+
    +
  • iOS version is not released because it cannot be easily shared outside AppStore.. . .
  • +
+
+ +
-
-

- OpenSceneGraph sample -

-

- 2017-05-12 00:00 -

-
-

Rocket in the distance

-

This article describes creation of the tutorials for building sample OpenSceneGraph application under Linux, macOS, Windows, and Android in April 2017.

-

Previous tutorials described how to install OpenSceneGraph under Linux, macOS, Windows and render a model using the standard osgviewer tool. This time we worked on a sample OpenSceneGraph application that would run under Linux, macOS, Windows, and Android.. . .

-
- -

Page 3 of 7

diff --git a/en/news/index4.html b/en/news/index4.html index de84675..cec445b 100644 --- a/en/news/index4.html +++ b/en/news/index4.html @@ -30,6 +30,22 @@

News

+
+

+ OpenSceneGraph sample +

+

+ 2017-05-12 00:00 +

+
+

Rocket in the distance

+

This article describes creation of the tutorials for building sample OpenSceneGraph application under Linux, macOS, Windows, and Android in April 2017.

+

Previous tutorials described how to install OpenSceneGraph under Linux, macOS, Windows and render a model using the standard osgviewer tool. This time we worked on a sample OpenSceneGraph application that would run under Linux, macOS, Windows, and Android.. . .

+
+ +

It's all fine @@ -184,25 +200,6 @@ Continue reading

-
-

- OGS Editor 0.10 and live session materials -

-

- 2016-10-03 00:00 -

-
-

OGS Editor with Mahjong game

-

Note: we won't release 0.10 for macOS due to technical difficulties with the build system. macOS support will be back for 0.11.

- -
- -

Page 4 of 7

diff --git a/en/news/index5.html b/en/news/index5.html index 45743e6..a516d38 100644 --- a/en/news/index5.html +++ b/en/news/index5.html @@ -30,6 +30,25 @@

News

+
+

+ OGS Editor 0.10 and live session materials +

+

+ 2016-10-03 00:00 +

+
+

OGS Editor with Mahjong game

+

Note: we won't release 0.10 for macOS due to technical difficulties with the build system. macOS support will be back for 0.11.

+ +
+ +

A few words about live session yesterday @@ -168,24 +187,6 @@ It's time to create simple Mahjong solitaire game.

Continue reading

-
-

- May live session (Editor 0.9) -

-

- 2016-04-24 00:00 -

-
-

As you know, the previously published roadmap assumed, that we would hold a live session in April and it would feature a ping-pong game created with Editor 0.9.

-

We have to admit, our abilities to plan are not yet good enough. That's why the next live session will take place by the end of May. The exact date will be announced later.

-

Here's a short preview of the coming game:

- -

. . .

-
- -

Page 5 of 7

diff --git a/en/news/index6.html b/en/news/index6.html index d745842..0b12e32 100644 --- a/en/news/index6.html +++ b/en/news/index6.html @@ -30,6 +30,24 @@

News

+
+

+ May live session (Editor 0.9) +

+

+ 2016-04-24 00:00 +

+
+

As you know, the previously published roadmap assumed, that we would hold a live session in April and it would feature a ping-pong game created with Editor 0.9.

+

We have to admit, our abilities to plan are not yet good enough. That's why the next live session will take place by the end of May. The exact date will be announced later.

+

Here's a short preview of the coming game:

+ +

. . .

+
+ +
-
-

- Desura no more, hello Humble Bundle Widget -

-

- 2015-07-23 00:00 -

-
-

After the recent bankruptcy of Desura's parent company, we decided, that we need a new place for our Deluxe version. Something better, more modern and more trustworthy. We have chosen the Humble Widget, with which you can buy the deluxe version of the game without leaving our site.

-

Here it is:

- -

We haven't received a single penny from Desura (due to the minimal cache out limitations), but if you bought the deluxe version from them and experiencing any problems with downloading it (right now we see no problems with that), send us a letter, tell your name on Desura, we'll figure something out.. . .

-
- -

Page 6 of 7

diff --git a/en/news/index7.html b/en/news/index7.html index 4400a5b..ad37789 100644 --- a/en/news/index7.html +++ b/en/news/index7.html @@ -30,6 +30,23 @@

News

+
+

+ Desura no more, hello Humble Bundle Widget +

+

+ 2015-07-23 00:00 +

+
+

After the recent bankruptcy of Desura's parent company, we decided, that we need a new place for our Deluxe version. Something better, more modern and more trustworthy. We have chosen the Humble Widget, with which you can buy the deluxe version of the game without leaving our site.

+

Here it is:

+ +

We haven't received a single penny from Desura (due to the minimal cache out limitations), but if you bought the deluxe version from them and experiencing any problems with downloading it (right now we see no problems with that), send us a letter, tell your name on Desura, we'll figure something out.. . .

+
+ +

Test chamber for everyone (Editor 0.7.0) diff --git a/en/news/memory-logic.html b/en/news/memory-logic.html new file mode 100644 index 0000000..1008c1d --- /dev/null +++ b/en/news/memory-logic.html @@ -0,0 +1,162 @@ + + + + + + + + + +

In the news...

+
+
+

+ "Memory" game logic +

+

+ 2024-05-03 00:00 +

+
+

"Memory" game logic

+

In April I implemented "Memory" game logic in Python as limited language model and successfully converted the code to C++ by the instrument under development.

+

Limited language model assumes the following architecture of two parts:

+
    +
  1. state context
  2. +
  3. pure functions without side effects working only with the context
  4. +
+

Game logic state context in Python currently looks like this (C++):

+
class memory_Context:
+  def __init__(self):
+    self.hiddenItems = []
+    self.mismatchedItems = []
+    self.playfieldItems = {}
+    self.playfieldSize = 0
+    self.recentField = "none"
+    self.selectedId = -1
+    self.selectedItems = []
+    self.victory = False
+
+

Since the instrument only works with functions at the moment, I had to write C++ context code manually.

+

Functions look like this (C++):

+
# Select item
+@llm_by_value
+def memory_selectItem(
+  c: memory_Context
+) -> memory_Context:
+  if (
+    len(c.selectedItems) == 2
+  ):
+    c.selectedItems.clear()
+  #}
+  c.selectedItems.append(c.selectedId)
+  c.recentField = "selectedItems"
+  return c
+#}
+
+

Limited language model functions have the following features:

+
    +
  • @llm_by_value Python decorator is used to pass arguments by value instead of by reference (which is default in Python)
  • +
  • passing arguments by value is mandatory to limit function scope to only single context field, it's formalized Single Responsibility Principle
  • +
  • context contains recentField representing a stored "event"; this allows functions to run only when necessary field changes
  • +
  • function must use recentField to specify which field it changed or provide none if no action was performed
  • +
  • function takes only context as an input and only returns (an updated) context as an output
  • +
+

"Memory" game logic has the following functions:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionCallerDescription
1memory_generateConstPlayfieldUserGenerate simplified playfield with items of the same group following each other sequentially
2memory_selectItemUserSelect playfield item
3memory_shouldDeselectMismatchedItemsSystemReaction to deselect a pair of the selected items of different groups
4memory_shouldDetectVictorySystemReaction to detect victory when all items got hidden
5memory_shouldHideMatchingItemsSystemReaction to hide a pair of the selected items of the same group
+

To verify functions work identically in both Python and C++, I cover each function with at least one test:

+
    +
  • memory_test_generateConstPlayfield
  • +
  • memory_test_selectItem_1x
  • +
  • memory_test_selectItem_2x
  • +
  • memory_test_selectItem_3x
  • +
  • memory_test_shouldDeselectMismatchedItems
  • +
  • memory_test_shouldDeselectMismatchedItems_itemTwice
  • +
  • memory_test_shouldDetectVictory
  • +
  • memory_test_shouldHideMatchingItems
  • +
+

May plans

+

I'll make a text UI for "Memory" game.

+
+
+
+ + + +
+ + diff --git a/ru/news/2024-05_memory-logic.md b/ru/news/2024-05_memory-logic.md new file mode 100644 index 0000000..67d4842 --- /dev/null +++ b/ru/news/2024-05_memory-logic.md @@ -0,0 +1,86 @@ +Title: Игровая логика «Памяти» +Date: 2024-05-03 00:00 +Category: News +Slug: memory-logic +Lang: ru + +# Игровая логика «Памяти» + +В апреле реализовал игровую логику игры «Память» на Python в виде модели ограниченного языка и успешно перевёл её инструментом в C++. + +Модель ограниченного языка предполагает следующую архитектуру из двух частей: + +1. контекст состояния +1. чистые функции без побочных эффектов, работающие лишь с контекстом + +Контекст состояния игровой логики на Python получился следующим ([C++][ctx_cxx]): + +```python +class memory_Context: + def __init__(self): + self.hiddenItems = [] + self.mismatchedItems = [] + self.playfieldItems = {} + self.playfieldSize = 0 + self.recentField = "none" + self.selectedId = -1 + self.selectedItems = [] + self.victory = False +``` + +Т.к. инструмент на текущий момент работает лишь с функциями, то контекст для Python и С++ пока пишем руками. + +Функции получились примерно такими ([C++][func_cxx]): + +```python +# Select item +@llm_by_value +def memory_selectItem( + c: memory_Context +) -> memory_Context: + if ( + len(c.selectedItems) == 2 + ): + c.selectedItems.clear() + #} + c.selectedItems.append(c.selectedId) + c.recentField = "selectedItems" + return c +#} +``` + +Особенности функций для модели ограниченного языка: + +* декоратор `@llm_by_value` в Python нужен для передачи аргументов по значению, а не по ссылке (по умолчанию - по ссылке) +* передача по значению обязательна для ограничения сферы действия функции ровно одним исходящим полем контекста, т.е. это реализация Принципа Единственной Ответственности (Single Responsibility Principle) +* контекст содержит поле `recentField`, представляющее собой хранимое «событие»; это поле позволяет функциям среагировать лишь в момент изменения значения интересующего поля +* функция обязана в поле `recentField` указать изменённое поле контекста либо `none` в случае отсутствия изменений +* функция принимает на вход контекст и выдаёт (изменённый) контекст на выход + +Полный список фукций игровой логики «Памяти»: + +| № | Функция | Инициатор вызова | Описание | +| --- | --- | --- | --- | +| 1 | `memory_generateConstPlayfield` | Пользователь | Генерируем упрощённое игровое поле, в котором последовательно парами идут элементы одной группы | +| 2 | `memory_selectItem` | Пользователь | Выбор элемента игрового поля | +| 3 | `memory_shouldDeselectMismatchedItems` | Система | Реакция снятия выделения с пары выбранных фишек различающихся групп | +| 4 | `memory_shouldDetectVictory` | Система | Реакция определения победы после скрытия всех фишек | +| 5 | `memory_shouldHideMatchingItems` | Система | Реакция скрытия пары выбранных фишек одной группы | + +Для удостоверения работоспособности и идентичности работы этих функций как в Python, так и в C++, на каждую функцию ввёл минимум по одной функции проверки: + +* `memory_test_generateConstPlayfield` +* `memory_test_selectItem_1x` +* `memory_test_selectItem_2x` +* `memory_test_selectItem_3x` +* `memory_test_shouldDeselectMismatchedItems` +* `memory_test_shouldDeselectMismatchedItems_itemTwice` +* `memory_test_shouldDetectVictory` +* `memory_test_shouldHideMatchingItems` + +# Планы на май + +Сделаю возможность сыграть одну партию игры «Память» в текстовом интерфейсе. + +[ctx_cxx]: https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h +[func_cxx]: https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory.cpp#L29 diff --git a/ru/news/index.html b/ru/news/index.html index c6f6d7b..8e90505 100644 --- a/ru/news/index.html +++ b/ru/news/index.html @@ -30,6 +30,32 @@

Новости

+
+

+ Игровая логика «Памяти» +

+

+ 2024-05-03 00:00 +

+
+

Игровая логика «Памяти»

+

В апреле реализовал игровую логику игры «Память» на Python в виде модели ограниченного языка и успешно перевёл её инструментом в C++.

+

Модель ограниченного языка предполагает следующую архитектуру из двух частей:

+
    +
  1. контекст состояния
  2. +
  3. чистые функции без побочных эффектов, работающие лишь с контекстом
  4. +
+

Контекст состояния игровой логики на Python получился следующим (C++):

+

```python +class memory_Context: + def init(self): + self.hiddenItems = [] + self.mismatchedItems = []. . .

+
+ +

Первый пример портируемого кода @@ -203,23 +229,6 @@ Ubuntu Edge. Особенностью продукта должна была Читать далее

-
-

- На пути к долговечным приложениям -

-

- 2019-08-05 00:00 -

-
-

Псковское вече

-

В этой статье мы расскажем о нашем первом долговечном приложении для настольных ПК - генераторе статических сайтов ПСКОВ.

-

Долговечность

-

Под долговечным приложением мы понимаем такое приложение, которое работает без единого изменения на операционных системах, выпущенных в период 2010-2030 годов. Иными словами, долговечное приложение обладает 10-летней обратной совместимостью и 10-летней прочностью. Впрочем, ПСКОВ работает даже на Windows 2000, так что у него 19-летняя обратная совместимость.. . .

-
- -

Страница 1 из 7

diff --git a/ru/news/index2.html b/ru/news/index2.html index 995346f..fba807d 100644 --- a/ru/news/index2.html +++ b/ru/news/index2.html @@ -30,6 +30,23 @@

Новости

+
+

+ На пути к долговечным приложениям +

+

+ 2019-08-05 00:00 +

+
+

Псковское вече

+

В этой статье мы расскажем о нашем первом долговечном приложении для настольных ПК - генераторе статических сайтов ПСКОВ.

+

Долговечность

+

Под долговечным приложением мы понимаем такое приложение, которое работает без единого изменения на операционных системах, выпущенных в период 2010-2030 годов. Иными словами, долговечное приложение обладает 10-летней обратной совместимостью и 10-летней прочностью. Впрочем, ПСКОВ работает даже на Windows 2000, так что у него 19-летняя обратная совместимость.. . .

+
+ +
-
-

- Первая технодемка OGS Mahjong 2: Игровая механика -

-

- 2018-02-16 00:00 -

-
-

Конец партии Маджонг

-

Мы ради сообщить о выпуске первой технической демонастрации OGS Mahjong 2. Её цель была в проверке игровой механики на всех поддерживаемых платформах.

-

Проверьте технодемку на своей платформе:

- -

Замечания:. . .

-
- -

Страница 2 из 7

diff --git a/ru/news/index3.html b/ru/news/index3.html index e30a198..7641e51 100644 --- a/ru/news/index3.html +++ b/ru/news/index3.html @@ -30,6 +30,30 @@

Новости

+
+

+ Первая технодемка OGS Mahjong 2: Игровая механика +

+

+ 2018-02-16 00:00 +

+
+

Конец партии Маджонг

+

Мы ради сообщить о выпуске первой технической демонастрации OGS Mahjong 2. Её цель была в проверке игровой механики на всех поддерживаемых платформах.

+

Проверьте технодемку на своей платформе:

+ +

Замечания:. . .

+
+ +
-
-

- Приложение OpenSceneGraph -

-

- 2017-05-12 00:00 -

-
-

Ракета в дали

-

Эта статья описывает создание самоучителей по сборке приложения OpenSceneGraph на Linux, macOS, Windows и Android в апреле 2017.

-

Предыдущие самоучители описывали установку OpenSceneGraph на Linux, macOS, Windows и отображение модели с помощью стандартного инструмента osgviewer. На этот раз результатом нашей работы стало приложение OpenSceneGraph, которое работает на Linux, macOS, Windows и Android.. . .

-
- -

Страница 3 из 7

diff --git a/ru/news/index4.html b/ru/news/index4.html index 1884768..64085f8 100644 --- a/ru/news/index4.html +++ b/ru/news/index4.html @@ -30,6 +30,22 @@

Новости

+
+

+ Приложение OpenSceneGraph +

+

+ 2017-05-12 00:00 +

+
+

Ракета в дали

+

Эта статья описывает создание самоучителей по сборке приложения OpenSceneGraph на Linux, macOS, Windows и Android в апреле 2017.

+

Предыдущие самоучители описывали установку OpenSceneGraph на Linux, macOS, Windows и отображение модели с помощью стандартного инструмента osgviewer. На этот раз результатом нашей работы стало приложение OpenSceneGraph, которое работает на Linux, macOS, Windows и Android.. . .

+
+ +
-
-

- OGS Editor 0.10 и материалы прямого эфира -

-

- 2016-10-03 00:00 -

-
-

Редактор с игрой Маджонг

-

Внимание: мы не выпустим версию 0.10 для macOS из-за технических проблем с системой сборки. Поддержку macOS вернём к 0.11.

- -
- -

Страница 4 из 7

diff --git a/ru/news/index5.html b/ru/news/index5.html index bea100a..f3256aa 100644 --- a/ru/news/index5.html +++ b/ru/news/index5.html @@ -30,6 +30,25 @@

Новости

+
+

+ OGS Editor 0.10 и материалы прямого эфира +

+

+ 2016-10-03 00:00 +

+
+

Редактор с игрой Маджонг

+

Внимание: мы не выпустим версию 0.10 для macOS из-за технических проблем с системой сборки. Поддержку macOS вернём к 0.11.

+ +
+ +
-
-

- Майский прямой эфир (Редактор 0.9) -

-

- 2016-04-24 00:00 -

-
-

Как вы знаете, ранее опубликованная дорожная карта предполагала, что в апреле будет прямой эфир, в котором с помощью Редактора 0.9 мы создадим игру пинг-понг.

-

Мы должны признать, что наши способности к планированию всё ещё недостаточно высоки, поэтому следующий прямой эфир состоится в конце мая. Точную дату мы объявим позже.

-

Вот пара моментов из будущей игры:

- -

. . .

-
- -

Страница 5 из 7

diff --git a/ru/news/index6.html b/ru/news/index6.html index 709f18b..848d234 100644 --- a/ru/news/index6.html +++ b/ru/news/index6.html @@ -30,6 +30,24 @@

Новости

+
+

+ Майский прямой эфир (Редактор 0.9) +

+

+ 2016-04-24 00:00 +

+
+

Как вы знаете, ранее опубликованная дорожная карта предполагала, что в апреле будет прямой эфир, в котором с помощью Редактора 0.9 мы создадим игру пинг-понг.

+

Мы должны признать, что наши способности к планированию всё ещё недостаточно высоки, поэтому следующий прямой эфир состоится в конце мая. Точную дату мы объявим позже.

+

Вот пара моментов из будущей игры:

+ +

. . .

+
+ +
-
-

- Прощай, Desura. Здравствуй, Humble Bundle Widget -

-

- 2015-07-23 00:00 -

-
-

После недавнего банкротства родительской компании сервиса Desura мы пришли к выводу, что нам необходима новая площадка для распространения Deluxe-версии игры. Более современная, удобная, надежная. -Наш выбор пал на Humble Widget, благодаря которому вы можете приобрести Deluxe-версию игры прямо у нас на сайте.

-

Вот он:

- -

. . .

-
- -

Страница 6 из 7

diff --git a/ru/news/index7.html b/ru/news/index7.html index aa2310c..4c6f50e 100644 --- a/ru/news/index7.html +++ b/ru/news/index7.html @@ -30,6 +30,24 @@

Новости

+
+

+ Прощай, Desura. Здравствуй, Humble Bundle Widget +

+

+ 2015-07-23 00:00 +

+
+

После недавнего банкротства родительской компании сервиса Desura мы пришли к выводу, что нам необходима новая площадка для распространения Deluxe-версии игры. Более современная, удобная, надежная. +Наш выбор пал на Humble Widget, благодаря которому вы можете приобрести Deluxe-версию игры прямо у нас на сайте.

+

Вот он:

+ +

. . .

+
+ +

Тестовый цех каждому (Редактор 0.7.0) diff --git a/ru/news/memory-logic.html b/ru/news/memory-logic.html new file mode 100644 index 0000000..5368b5b --- /dev/null +++ b/ru/news/memory-logic.html @@ -0,0 +1,162 @@ + + + + + + + + + +

В новостях...

+
+
+

+ Игровая логика «Памяти» +

+

+ 2024-05-03 00:00 +

+
+

Игровая логика «Памяти»

+

В апреле реализовал игровую логику игры «Память» на Python в виде модели ограниченного языка и успешно перевёл её инструментом в C++.

+

Модель ограниченного языка предполагает следующую архитектуру из двух частей:

+
    +
  1. контекст состояния
  2. +
  3. чистые функции без побочных эффектов, работающие лишь с контекстом
  4. +
+

Контекст состояния игровой логики на Python получился следующим (C++):

+
class memory_Context:
+  def __init__(self):
+    self.hiddenItems = []
+    self.mismatchedItems = []
+    self.playfieldItems = {}
+    self.playfieldSize = 0
+    self.recentField = "none"
+    self.selectedId = -1
+    self.selectedItems = []
+    self.victory = False
+
+

Т.к. инструмент на текущий момент работает лишь с функциями, то контекст для Python и С++ пока пишем руками.

+

Функции получились примерно такими (C++):

+
# Select item
+@llm_by_value
+def memory_selectItem(
+  c: memory_Context
+) -> memory_Context:
+  if (
+    len(c.selectedItems) == 2
+  ):
+    c.selectedItems.clear()
+  #}
+  c.selectedItems.append(c.selectedId)
+  c.recentField = "selectedItems"
+  return c
+#}
+
+

Особенности функций для модели ограниченного языка:

+
    +
  • декоратор @llm_by_value в Python нужен для передачи аргументов по значению, а не по ссылке (по умолчанию - по ссылке)
  • +
  • передача по значению обязательна для ограничения сферы действия функции ровно одним исходящим полем контекста, т.е. это реализация Принципа Единственной Ответственности (Single Responsibility Principle)
  • +
  • контекст содержит поле recentField, представляющее собой хранимое «событие»; это поле позволяет функциям среагировать лишь в момент изменения значения интересующего поля
  • +
  • функция обязана в поле recentField указать изменённое поле контекста либо none в случае отсутствия изменений
  • +
  • функция принимает на вход контекст и выдаёт (изменённый) контекст на выход
  • +
+

Полный список фукций игровой логики «Памяти»:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ФункцияИнициатор вызоваОписание
1memory_generateConstPlayfieldПользовательГенерируем упрощённое игровое поле, в котором последовательно парами идут элементы одной группы
2memory_selectItemПользовательВыбор элемента игрового поля
3memory_shouldDeselectMismatchedItemsСистемаРеакция снятия выделения с пары выбранных фишек различающихся групп
4memory_shouldDetectVictoryСистемаРеакция определения победы после скрытия всех фишек
5memory_shouldHideMatchingItemsСистемаРеакция скрытия пары выбранных фишек одной группы
+

Для удостоверения работоспособности и идентичности работы этих функций как в Python, так и в C++, на каждую функцию ввёл минимум по одной функции проверки:

+
    +
  • memory_test_generateConstPlayfield
  • +
  • memory_test_selectItem_1x
  • +
  • memory_test_selectItem_2x
  • +
  • memory_test_selectItem_3x
  • +
  • memory_test_shouldDeselectMismatchedItems
  • +
  • memory_test_shouldDeselectMismatchedItems_itemTwice
  • +
  • memory_test_shouldDetectVictory
  • +
  • memory_test_shouldHideMatchingItems
  • +
+

Планы на май

+

Сделаю возможность сыграть одну партию игры «Память» в текстовом интерфейсе.

+
+
+
+ + + +
+ +