Переглянути джерело

Статья за май | May article

master
Михаил Капелько 2 тижднів тому
джерело
коміт
5321a9a1c4
18 змінених файлів з 774 додано та 226 видалено
  1. +87
    -0
      en/news/2024-05_memory-logic.md
  2. +25
    -17
      en/news/index.html
  3. +17
    -27
      en/news/index2.html
  4. +27
    -16
      en/news/index3.html
  5. +16
    -19
      en/news/index4.html
  6. +19
    -18
      en/news/index5.html
  7. +18
    -17
      en/news/index6.html
  8. +17
    -0
      en/news/index7.html
  9. +162
    -0
      en/news/memory-logic.html
  10. +86
    -0
      ru/news/2024-05_memory-logic.md
  11. +26
    -17
      ru/news/index.html
  12. +17
    -24
      ru/news/index2.html
  13. +24
    -16
      ru/news/index3.html
  14. +16
    -19
      ru/news/index4.html
  15. +19
    -18
      ru/news/index5.html
  16. +18
    -18
      ru/news/index6.html
  17. +18
    -0
      ru/news/index7.html
  18. +162
    -0
      ru/news/memory-logic.html

+ 87
- 0
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

+ 25
- 17
en/news/index.html Переглянути файл

@@ -30,6 +30,31 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="memory-logic.html">"Memory" game logic</a>
</h2>
<p class="news_item_date">
2024-05-03 00:00
</p>
<div class="news_item_contents">
<h1 id="memorygamelogic">"Memory" game logic</h1>
<p>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.</p>
<p>Limited language model assumes the following architecture of two parts:</p>
<ol>
<li>state context</li>
<li>pure functions without side effects working only with the context</li>
</ol>
<p>Game logic state context in Python currently looks like this (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h">C++</a>):</p>
<p>```python
class memory_Context:
def <strong>init</strong>(self):
self.hiddenItems = []. . .</p>
</div>
<div class="news_item_more">
<a href="memory-logic.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="llm-first-py-cxx.html">The first example of a portable code</a>
@@ -204,23 +229,6 @@ It seems that right now we have less completed features than before the release
<a href="the-pros-and-cons-of-restarting-from-scratch.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="on-the-way-to-durable-applications.html">On the way to durable applications</a>
</h2>
<p class="news_item_date">
2019-08-05 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2019-08-05_on-the-way-to-durable-applications.jpg" alt="Pskov's veche" /></p>
<p>This article describes our first durable application for desktop PCs: PSKOV static site generator.</p>
<p><strong>Durability</strong></p>
<p>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, <a href="http://opengamestudio.org/pskov">PSKOV</a> runs even under Windows 2000, so PSKOV has backward compatibility of 19 years.. . .</p>
</div>
<div class="news_item_more">
<a href="on-the-way-to-durable-applications.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 1 of 7</p>
<p>


+ 17
- 27
en/news/index2.html Переглянути файл

@@ -30,6 +30,23 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="on-the-way-to-durable-applications.html">On the way to durable applications</a>
</h2>
<p class="news_item_date">
2019-08-05 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2019-08-05_on-the-way-to-durable-applications.jpg" alt="Pskov's veche" /></p>
<p>This article describes our first durable application for desktop PCs: PSKOV static site generator.</p>
<p><strong>Durability</strong></p>
<p>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, <a href="http://opengamestudio.org/pskov">PSKOV</a> runs even under Windows 2000, so PSKOV has backward compatibility of 19 years.. . .</p>
</div>
<div class="news_item_more">
<a href="on-the-way-to-durable-applications.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="defending-availability.html">Defending availability</a>
@@ -185,33 +202,6 @@
<a href="openscenegraph-examples.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-techdemo1-gameplay.html">First techdemo of OGS Mahjong 2: Gameplay</a>
</h2>
<p class="news_item_date">
2018-02-16 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2018-02-16-mahjong-techdemo1-gameplay.png" alt="End of a Mahjong party" /></p>
<p>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.</p>
<p>Get techdemo for your platform:</p>
<ul>
<li>Run <a href="https://ogstudio.github.io/game-mahjong/versions/013/mjin-player.html">Web version</a> in your browser</li>
<li>Get <a href="https://drive.google.com/open?id=1KW8IEN8Dpz8ODeg8BctVSJyzj9-AL9hR">Android version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1oj0-OXSmEatttzn86u2vgP9SRAIC0ozB">Windows version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1EX7kLIThLiMz9_W7VmBPySms3mlrF-i6">Linux version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1KWnvbHzan8MpMcZPG2QC-7KWoEYbqrM2">macOS version</a></li>
</ul>
<p>Notes:</p>
<ul>
<li>iOS version is not released because it cannot be easily shared outside AppStore.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="mahjong-techdemo1-gameplay.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 2 of 7</p>
<p>


+ 27
- 16
en/news/index3.html Переглянути файл

@@ -30,6 +30,33 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-techdemo1-gameplay.html">First techdemo of OGS Mahjong 2: Gameplay</a>
</h2>
<p class="news_item_date">
2018-02-16 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2018-02-16-mahjong-techdemo1-gameplay.png" alt="End of a Mahjong party" /></p>
<p>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.</p>
<p>Get techdemo for your platform:</p>
<ul>
<li>Run <a href="https://ogstudio.github.io/game-mahjong/versions/013/mjin-player.html">Web version</a> in your browser</li>
<li>Get <a href="https://drive.google.com/open?id=1KW8IEN8Dpz8ODeg8BctVSJyzj9-AL9hR">Android version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1oj0-OXSmEatttzn86u2vgP9SRAIC0ozB">Windows version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1EX7kLIThLiMz9_W7VmBPySms3mlrF-i6">Linux version</a></li>
<li>Get <a href="https://drive.google.com/open?id=1KWnvbHzan8MpMcZPG2QC-7KWoEYbqrM2">macOS version</a></li>
</ul>
<p>Notes:</p>
<ul>
<li>iOS version is not released because it cannot be easily shared outside AppStore.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="mahjong-techdemo1-gameplay.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-recreation-start.html">Mahjong recreation start</a>
@@ -177,22 +204,6 @@
<a href="ios-tutorial.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="osg-sample.html">OpenSceneGraph sample</a>
</h2>
<p class="news_item_date">
2017-05-12 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2017-05_osg-sample.png" alt="Rocket in the distance" /></p>
<p>This article describes creation of the tutorials for building sample OpenSceneGraph application under Linux, macOS, Windows, and Android in April 2017.</p>
<p>Previous tutorials described how to install OpenSceneGraph under Linux, macOS, Windows and render a model using the standard <strong>osgviewer</strong> tool. This time we worked on a <a href="https://github.com/OGStudio/openscenegraph-cross-platform-guide-application">sample OpenSceneGraph application</a> that would run under Linux, macOS, Windows, and Android.. . .</p>
</div>
<div class="news_item_more">
<a href="osg-sample.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 3 of 7</p>
<p>


+ 16
- 19
en/news/index4.html Переглянути файл

@@ -30,6 +30,22 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="osg-sample.html">OpenSceneGraph sample</a>
</h2>
<p class="news_item_date">
2017-05-12 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2017-05_osg-sample.png" alt="Rocket in the distance" /></p>
<p>This article describes creation of the tutorials for building sample OpenSceneGraph application under Linux, macOS, Windows, and Android in April 2017.</p>
<p>Previous tutorials described how to install OpenSceneGraph under Linux, macOS, Windows and render a model using the standard <strong>osgviewer</strong> tool. This time we worked on a <a href="https://github.com/OGStudio/openscenegraph-cross-platform-guide-application">sample OpenSceneGraph application</a> that would run under Linux, macOS, Windows, and Android.. . .</p>
</div>
<div class="news_item_more">
<a href="osg-sample.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="its-all-fine.html">It's all fine</a>
@@ -184,25 +200,6 @@
<a href="2016-september-recap.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="ogs-editor-0.10.html">OGS Editor 0.10 and live session materials</a>
</h2>
<p class="news_item_date">
2016-10-03 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2016-10-03_ogs-editor-0.10.png" alt="OGS Editor with Mahjong game" /></p>
<p>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.</p>
<ul>
<li><strong>OGS Editor 0.10</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Editor/jenkins/51_2016-10-01_06-39-48_0.10.0/">is available at SourceForge</a>. Simply unpack the archive and launch the run script.</li>
<li><strong>Mahjong Solitaire game</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Games/MahjongSolitaire/">is available at SourceForge</a>, too. Simply unpack the archive and launch the run script.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="ogs-editor-0.10.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 4 of 7</p>
<p>


+ 19
- 18
en/news/index5.html Переглянути файл

@@ -30,6 +30,25 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="ogs-editor-0.10.html">OGS Editor 0.10 and live session materials</a>
</h2>
<p class="news_item_date">
2016-10-03 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2016-10-03_ogs-editor-0.10.png" alt="OGS Editor with Mahjong game" /></p>
<p>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.</p>
<ul>
<li><strong>OGS Editor 0.10</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Editor/jenkins/51_2016-10-01_06-39-48_0.10.0/">is available at SourceForge</a>. Simply unpack the archive and launch the run script.</li>
<li><strong>Mahjong Solitaire game</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Games/MahjongSolitaire/">is available at SourceForge</a>, too. Simply unpack the archive and launch the run script.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="ogs-editor-0.10.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="yesterdays-live-session-short-overview.html">A few words about live session yesterday</a>
@@ -168,24 +187,6 @@ It's time to create simple Mahjong solitaire game.</p>
<a href="may-live-session-announcement.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="may-live-session-decision.html">May live session (Editor 0.9)</a>
</h2>
<p class="news_item_date">
2016-04-24 00:00
</p>
<div class="news_item_contents">
<p>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.</p>
<p>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.</p>
<p>Here's a short preview of the coming game:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/V3EvCVPc6kg" frameborder="0" allowfullscreen></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="may-live-session-decision.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 5 of 7</p>
<p>


+ 18
- 17
en/news/index6.html Переглянути файл

@@ -30,6 +30,24 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="may-live-session-decision.html">May live session (Editor 0.9)</a>
</h2>
<p class="news_item_date">
2016-04-24 00:00
</p>
<div class="news_item_contents">
<p>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.</p>
<p>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.</p>
<p>Here's a short preview of the coming game:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/V3EvCVPc6kg" frameborder="0" allowfullscreen></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="may-live-session-decision.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="rolling-ball.html">"Rolling ball" live session videos and downloads</a>
@@ -166,23 +184,6 @@
<a href="soon-game-creation-editor-07.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="bye-desura-hello-humblebundle.html">Desura no more, hello Humble Bundle Widget</a>
</h2>
<p class="news_item_date">
2015-07-23 00:00
</p>
<div class="news_item_contents">
<p>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.</p>
<p>Here it is:</p>
<iframe src="https://www.humblebundle.com/widget/v2/product/ogsmahjong/ySGF3h34?theme=transparent-light" width="526" height="325" style="border: none;" scrolling="no" frameborder="0"></iframe>
<p>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.. . .</p>
</div>
<div class="news_item_more">
<a href="bye-desura-hello-humblebundle.html">Continue reading</a>
</div>
</div>

<p class="pagination_title">Page 6 of 7</p>
<p>


+ 17
- 0
en/news/index7.html Переглянути файл

@@ -30,6 +30,23 @@
<center>
<h1>News</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="bye-desura-hello-humblebundle.html">Desura no more, hello Humble Bundle Widget</a>
</h2>
<p class="news_item_date">
2015-07-23 00:00
</p>
<div class="news_item_contents">
<p>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.</p>
<p>Here it is:</p>
<iframe src="https://www.humblebundle.com/widget/v2/product/ogsmahjong/ySGF3h34?theme=transparent-light" width="526" height="325" style="border: none;" scrolling="no" frameborder="0"></iframe>
<p>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.. . .</p>
</div>
<div class="news_item_more">
<a href="bye-desura-hello-humblebundle.html">Continue reading</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="test-chamber-for-everyone.html">Test chamber for everyone (Editor 0.7.0)</a>


+ 162
- 0
en/news/memory-logic.html Переглянути файл

@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="../../style.css">
</head>
<body>
<script data-goatcounter="https://services.opengamestudio.org:443/count" async src="//services.opengamestudio.org:443/count.js"></script>
<div id="header">
<div>
<strong id="title">Open Game Studio</strong>
<div id="lang">
<a href="../../en/news/memory-logic.html">EN</a>
<a href="../../ru/news/memory-logic.html">RU</a>
</div>
</div>
<div class="header2">
<div class="menu">
<a href="../../en/news/index.html">News</a>
<a href="../../en/game/index.html">Games</a>
<a href="../../en/tool/index.html">Tools</a>
<a href="../../en/page/about.html">About</a>
</div>
<a class="discord" href="https://discord.gg/3A6THQabNf">
<img src="../../images/discord.png"></img>
</a>
<div class="clear"></div>
</div>
</div>
<h3 class="left_item_title">In the news...</h3>
<center>
<div class="news_item">
<h2 class="news_item_title">
<a href="memory-logic.html">"Memory" game logic</a>
</h2>
<p class="news_item_date">
2024-05-03 00:00
</p>
<div class="news_item_contents">
<h1 id="memorygamelogic">"Memory" game logic</h1>
<p>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.</p>
<p>Limited language model assumes the following architecture of two parts:</p>
<ol>
<li>state context</li>
<li>pure functions without side effects working only with the context</li>
</ol>
<p>Game logic state context in Python currently looks like this (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h">C++</a>):</p>
<pre><code class="python language-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
</code></pre>
<p>Since the instrument only works with functions at the moment, I had to write C++ context code manually.</p>
<p>Functions look like this (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory.cpp#L29">C++</a>):</p>
<pre><code class="python language-python"># Select item
@llm_by_value
def memory_selectItem(
c: memory_Context
) -&gt; memory_Context:
if (
len(c.selectedItems) == 2
):
c.selectedItems.clear()
#}
c.selectedItems.append(c.selectedId)
c.recentField = "selectedItems"
return c
#}
</code></pre>
<p>Limited language model functions have the following features:</p>
<ul>
<li><code>@llm_by_value</code> Python decorator is used to pass arguments by value instead of by reference (which is default in Python)</li>
<li>passing arguments by value is mandatory to limit function scope to only single context field, it's formalized Single Responsibility Principle</li>
<li>context contains <code>recentField</code> representing a stored "event"; this allows functions to run only when necessary field changes</li>
<li>function must use <code>recentField</code> to specify which field it changed or provide <code>none</code> if no action was performed</li>
<li>function takes only context as an input and only returns (an updated) context as an output</li>
</ul>
<p>"Memory" game logic has the following functions:</p>
<table>
<thead>
<tr>
<th>№</th>
<th>Function</th>
<th>Caller</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><code>memory_generateConstPlayfield</code></td>
<td>User</td>
<td>Generate simplified playfield with items of the same group following each other sequentially</td>
</tr>
<tr>
<td>2</td>
<td><code>memory_selectItem</code></td>
<td>User</td>
<td>Select playfield item</td>
</tr>
<tr>
<td>3</td>
<td><code>memory_shouldDeselectMismatchedItems</code></td>
<td>System</td>
<td>Reaction to deselect a pair of the selected items of different groups</td>
</tr>
<tr>
<td>4</td>
<td><code>memory_shouldDetectVictory</code></td>
<td>System</td>
<td>Reaction to detect victory when all items got hidden</td>
</tr>
<tr>
<td>5</td>
<td><code>memory_shouldHideMatchingItems</code></td>
<td>System</td>
<td>Reaction to hide a pair of the selected items of the same group</td>
</tr>
</tbody>
</table>
<p>To verify functions work identically in both Python and C++, I cover each function with at least one test:</p>
<ul>
<li><code>memory_test_generateConstPlayfield</code></li>
<li><code>memory_test_selectItem_1x</code></li>
<li><code>memory_test_selectItem_2x</code></li>
<li><code>memory_test_selectItem_3x</code></li>
<li><code>memory_test_shouldDeselectMismatchedItems</code></li>
<li><code>memory_test_shouldDeselectMismatchedItems_itemTwice</code></li>
<li><code>memory_test_shouldDetectVictory</code></li>
<li><code>memory_test_shouldHideMatchingItems</code></li>
</ul>
<h1 id="mayplans">May plans</h1>
<p>I'll make a text UI for "Memory" game.</p>
</div>
</div>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = "https://opengamestudio.org/en/news/memory-logic.html";
this.page.identifier = "memory-logic.html";
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://opengamestudio.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<div id="footer">
The site has been generated by <a href="http://opengamestudio.org/pskov">PSKOV</a>
from <a href="http://github.com/ogstudio/site-opengamestudio">this source code</a>.
</div>
</center>
</body>
</html>

+ 86
- 0
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

+ 26
- 17
ru/news/index.html Переглянути файл

@@ -30,6 +30,32 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="memory-logic.html">Игровая логика «Памяти»</a>
</h2>
<p class="news_item_date">
2024-05-03 00:00
</p>
<div class="news_item_contents">
<h1 id="">Игровая логика «Памяти»</h1>
<p>В апреле реализовал игровую логику игры «Память» на Python в виде модели ограниченного языка и успешно перевёл её инструментом в C++.</p>
<p>Модель ограниченного языка предполагает следующую архитектуру из двух частей:</p>
<ol>
<li>контекст состояния</li>
<li>чистые функции без побочных эффектов, работающие лишь с контекстом</li>
</ol>
<p>Контекст состояния игровой логики на Python получился следующим (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h">C++</a>):</p>
<p>```python
class memory_Context:
def <strong>init</strong>(self):
self.hiddenItems = []
self.mismatchedItems = []. . .</p>
</div>
<div class="news_item_more">
<a href="memory-logic.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="llm-first-py-cxx.html">Первый пример портируемого кода</a>
@@ -203,23 +229,6 @@ Ubuntu Edge</a>. Особенностью продукта должна была
<a href="the-pros-and-cons-of-restarting-from-scratch.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="on-the-way-to-durable-applications.html">На пути к долговечным приложениям</a>
</h2>
<p class="news_item_date">
2019-08-05 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2019-08-05_on-the-way-to-durable-applications.jpg" alt="Псковское вече" /></p>
<p>В этой статье мы расскажем о нашем первом долговечном приложении для настольных ПК - генераторе статических сайтов ПСКОВ.</p>
<p><strong>Долговечность</strong></p>
<p>Под долговечным приложением мы понимаем такое приложение, которое работает без единого изменения на операционных системах, выпущенных в период 2010-2030 годов. Иными словами, долговечное приложение обладает 10-летней обратной совместимостью и 10-летней прочностью. Впрочем, <a href="http://opengamestudio.org/pskov/ru">ПСКОВ</a> работает даже на Windows 2000, так что у него 19-летняя обратная совместимость.. . .</p>
</div>
<div class="news_item_more">
<a href="on-the-way-to-durable-applications.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 1 из 7</p>
<p>


+ 17
- 24
ru/news/index2.html Переглянути файл

@@ -30,6 +30,23 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="on-the-way-to-durable-applications.html">На пути к долговечным приложениям</a>
</h2>
<p class="news_item_date">
2019-08-05 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2019-08-05_on-the-way-to-durable-applications.jpg" alt="Псковское вече" /></p>
<p>В этой статье мы расскажем о нашем первом долговечном приложении для настольных ПК - генераторе статических сайтов ПСКОВ.</p>
<p><strong>Долговечность</strong></p>
<p>Под долговечным приложением мы понимаем такое приложение, которое работает без единого изменения на операционных системах, выпущенных в период 2010-2030 годов. Иными словами, долговечное приложение обладает 10-летней обратной совместимостью и 10-летней прочностью. Впрочем, <a href="http://opengamestudio.org/pskov/ru">ПСКОВ</a> работает даже на Windows 2000, так что у него 19-летняя обратная совместимость.. . .</p>
</div>
<div class="news_item_more">
<a href="on-the-way-to-durable-applications.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="defending-availability.html">Защита доступности</a>
@@ -184,30 +201,6 @@
<a href="openscenegraph-examples.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-techdemo1-gameplay.html">Первая технодемка OGS Mahjong 2: Игровая механика</a>
</h2>
<p class="news_item_date">
2018-02-16 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2018-02-16-mahjong-techdemo1-gameplay.png" alt="Конец партии Маджонг" /></p>
<p>Мы ради сообщить о выпуске первой технической демонастрации OGS Mahjong 2. Её цель была в проверке игровой механики на всех поддерживаемых платформах.</p>
<p>Проверьте технодемку на своей платформе:</p>
<ul>
<li>Запустить <a href="https://ogstudio.github.io/game-mahjong/versions/013/mjin-player.html">версию для веба</a> в браузере</li>
<li>Получить <a href="https://drive.google.com/open?id=1KW8IEN8Dpz8ODeg8BctVSJyzj9-AL9hR">версию для Android</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1oj0-OXSmEatttzn86u2vgP9SRAIC0ozB">версию для Windows</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1EX7kLIThLiMz9_W7VmBPySms3mlrF-i6">версию для Linux</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1KWnvbHzan8MpMcZPG2QC-7KWoEYbqrM2">версию для macOS</a></li>
</ul>
<p>Замечания:. . .</p>
</div>
<div class="news_item_more">
<a href="mahjong-techdemo1-gameplay.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 2 из 7</p>
<p>


+ 24
- 16
ru/news/index3.html Переглянути файл

@@ -30,6 +30,30 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-techdemo1-gameplay.html">Первая технодемка OGS Mahjong 2: Игровая механика</a>
</h2>
<p class="news_item_date">
2018-02-16 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2018-02-16-mahjong-techdemo1-gameplay.png" alt="Конец партии Маджонг" /></p>
<p>Мы ради сообщить о выпуске первой технической демонастрации OGS Mahjong 2. Её цель была в проверке игровой механики на всех поддерживаемых платформах.</p>
<p>Проверьте технодемку на своей платформе:</p>
<ul>
<li>Запустить <a href="https://ogstudio.github.io/game-mahjong/versions/013/mjin-player.html">версию для веба</a> в браузере</li>
<li>Получить <a href="https://drive.google.com/open?id=1KW8IEN8Dpz8ODeg8BctVSJyzj9-AL9hR">версию для Android</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1oj0-OXSmEatttzn86u2vgP9SRAIC0ozB">версию для Windows</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1EX7kLIThLiMz9_W7VmBPySms3mlrF-i6">версию для Linux</a></li>
<li>Получить <a href="https://drive.google.com/open?id=1KWnvbHzan8MpMcZPG2QC-7KWoEYbqrM2">версию для macOS</a></li>
</ul>
<p>Замечания:. . .</p>
</div>
<div class="news_item_more">
<a href="mahjong-techdemo1-gameplay.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="mahjong-recreation-start.html">Начало воссоздания Маджонга</a>
@@ -177,22 +201,6 @@
<a href="ios-tutorial.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="osg-sample.html">Приложение OpenSceneGraph</a>
</h2>
<p class="news_item_date">
2017-05-12 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2017-05_osg-sample.png" alt="Ракета в дали" /></p>
<p>Эта статья описывает создание самоучителей по сборке приложения OpenSceneGraph на Linux, macOS, Windows и Android в апреле 2017.</p>
<p>Предыдущие самоучители описывали установку OpenSceneGraph на Linux, macOS, Windows и отображение модели с помощью стандартного инструмента <strong>osgviewer</strong>. На этот раз результатом нашей работы стало <a href="https://github.com/OGStudio/openscenegraph-cross-platform-guide-application">приложение OpenSceneGraph</a>, которое работает на Linux, macOS, Windows и Android.. . .</p>
</div>
<div class="news_item_more">
<a href="osg-sample.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 3 из 7</p>
<p>


+ 16
- 19
ru/news/index4.html Переглянути файл

@@ -30,6 +30,22 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="osg-sample.html">Приложение OpenSceneGraph</a>
</h2>
<p class="news_item_date">
2017-05-12 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2017-05_osg-sample.png" alt="Ракета в дали" /></p>
<p>Эта статья описывает создание самоучителей по сборке приложения OpenSceneGraph на Linux, macOS, Windows и Android в апреле 2017.</p>
<p>Предыдущие самоучители описывали установку OpenSceneGraph на Linux, macOS, Windows и отображение модели с помощью стандартного инструмента <strong>osgviewer</strong>. На этот раз результатом нашей работы стало <a href="https://github.com/OGStudio/openscenegraph-cross-platform-guide-application">приложение OpenSceneGraph</a>, которое работает на Linux, macOS, Windows и Android.. . .</p>
</div>
<div class="news_item_more">
<a href="osg-sample.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="its-all-fine.html">Всё проходит хорошо</a>
@@ -183,25 +199,6 @@
<a href="2016-september-recap.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="ogs-editor-0.10.html">OGS Editor 0.10 и материалы прямого эфира</a>
</h2>
<p class="news_item_date">
2016-10-03 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2016-10-03_ogs-editor-0.10.png" alt="Редактор с игрой Маджонг" /></p>
<p>Внимание: мы не выпустим версию 0.10 для macOS из-за технических проблем с системой сборки. Поддержку macOS вернём к 0.11.</p>
<ul>
<li><strong>OGS Editor 0.10</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Editor/jenkins/51_2016-10-01_06-39-48_0.10.0/">доступен на SourceForge</a>. Просто распакуйте архив и запустите скрипт run.</li>
<li><strong>Пасьянс маджонг</strong> тоже <a href="https://sourceforge.net/projects/osrpgcreation/files/Games/MahjongSolitaire/">доступен на SourceForge</a>. Просто распакуйте архив и запустите скрипт run.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="ogs-editor-0.10.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 4 из 7</p>
<p>


+ 19
- 18
ru/news/index5.html Переглянути файл

@@ -30,6 +30,25 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="ogs-editor-0.10.html">OGS Editor 0.10 и материалы прямого эфира</a>
</h2>
<p class="news_item_date">
2016-10-03 00:00
</p>
<div class="news_item_contents">
<p><img src="../../images/2016-10-03_ogs-editor-0.10.png" alt="Редактор с игрой Маджонг" /></p>
<p>Внимание: мы не выпустим версию 0.10 для macOS из-за технических проблем с системой сборки. Поддержку macOS вернём к 0.11.</p>
<ul>
<li><strong>OGS Editor 0.10</strong> <a href="https://sourceforge.net/projects/osrpgcreation/files/Editor/jenkins/51_2016-10-01_06-39-48_0.10.0/">доступен на SourceForge</a>. Просто распакуйте архив и запустите скрипт run.</li>
<li><strong>Пасьянс маджонг</strong> тоже <a href="https://sourceforge.net/projects/osrpgcreation/files/Games/MahjongSolitaire/">доступен на SourceForge</a>. Просто распакуйте архив и запустите скрипт run.. . .</li>
</ul>
</div>
<div class="news_item_more">
<a href="ogs-editor-0.10.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="yesterdays-live-session-short-overview.html">Пара слов о вчерашнем прямом эфире</a>
@@ -168,24 +187,6 @@
<a href="may-live-session-announcement.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="may-live-session-decision.html">Майский прямой эфир (Редактор 0.9)</a>
</h2>
<p class="news_item_date">
2016-04-24 00:00
</p>
<div class="news_item_contents">
<p>Как вы знаете, ранее опубликованная дорожная карта предполагала, что в апреле будет прямой эфир, в котором с помощью Редактора 0.9 мы создадим игру пинг-понг.</p>
<p>Мы должны признать, что наши способности к планированию всё ещё недостаточно высоки, поэтому следующий прямой эфир состоится в конце мая. Точную дату мы объявим позже.</p>
<p>Вот пара моментов из будущей игры:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/V3EvCVPc6kg" frameborder="0" allowfullscreen></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="may-live-session-decision.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 5 из 7</p>
<p>


+ 18
- 18
ru/news/index6.html Переглянути файл

@@ -30,6 +30,24 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="may-live-session-decision.html">Майский прямой эфир (Редактор 0.9)</a>
</h2>
<p class="news_item_date">
2016-04-24 00:00
</p>
<div class="news_item_contents">
<p>Как вы знаете, ранее опубликованная дорожная карта предполагала, что в апреле будет прямой эфир, в котором с помощью Редактора 0.9 мы создадим игру пинг-понг.</p>
<p>Мы должны признать, что наши способности к планированию всё ещё недостаточно высоки, поэтому следующий прямой эфир состоится в конце мая. Точную дату мы объявим позже.</p>
<p>Вот пара моментов из будущей игры:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/V3EvCVPc6kg" frameborder="0" allowfullscreen></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="may-live-session-decision.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="rolling-ball.html">Запись прямого эфира "Катящийся мяч" и материалы</a>
@@ -164,24 +182,6 @@
<a href="soon-game-creation-editor-07.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="bye-desura-hello-humblebundle.html">Прощай, Desura. Здравствуй, Humble Bundle Widget</a>
</h2>
<p class="news_item_date">
2015-07-23 00:00
</p>
<div class="news_item_contents">
<p>После недавнего банкротства родительской компании сервиса Desura мы пришли к выводу, что нам необходима новая площадка для распространения Deluxe-версии игры. Более современная, удобная, надежная.
Наш выбор пал на Humble Widget, благодаря которому вы можете приобрести Deluxe-версию игры прямо у нас на сайте.</p>
<p>Вот он:</p>
<iframe src="https://www.humblebundle.com/widget/v2/product/ogsmahjong/ySGF3h34?theme=transparent-light" width="526" height="325" style="border: none;" scrolling="no" frameborder="0"></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="bye-desura-hello-humblebundle.html">Читать далее</a>
</div>
</div>

<p class="pagination_title">Страница 6 из 7</p>
<p>


+ 18
- 0
ru/news/index7.html Переглянути файл

@@ -30,6 +30,24 @@
<center>
<h1>Новости</h1>

<div class="news_item">
<h2 class="news_item_title">
<a href="bye-desura-hello-humblebundle.html">Прощай, Desura. Здравствуй, Humble Bundle Widget</a>
</h2>
<p class="news_item_date">
2015-07-23 00:00
</p>
<div class="news_item_contents">
<p>После недавнего банкротства родительской компании сервиса Desura мы пришли к выводу, что нам необходима новая площадка для распространения Deluxe-версии игры. Более современная, удобная, надежная.
Наш выбор пал на Humble Widget, благодаря которому вы можете приобрести Deluxe-версию игры прямо у нас на сайте.</p>
<p>Вот он:</p>
<iframe src="https://www.humblebundle.com/widget/v2/product/ogsmahjong/ySGF3h34?theme=transparent-light" width="526" height="325" style="border: none;" scrolling="no" frameborder="0"></iframe>
<p>. . .</p>
</div>
<div class="news_item_more">
<a href="bye-desura-hello-humblebundle.html">Читать далее</a>
</div>
</div>
<div class="news_item">
<h2 class="news_item_title">
<a href="test-chamber-for-everyone.html">Тестовый цех каждому (Редактор 0.7.0)</a>


+ 162
- 0
ru/news/memory-logic.html Переглянути файл

@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="../../style.css">
</head>
<body>
<script data-goatcounter="https://services.opengamestudio.org:443/count" async src="//services.opengamestudio.org:443/count.js"></script>
<div id="header">
<div>
<strong id="title">Open Game Studio</strong>
<div id="lang">
<a href="../../en/news/memory-logic.html">EN</a>
<a href="../../ru/news/memory-logic.html">RU</a>
</div>
</div>
<div class="header2">
<div class="menu">
<a href="../../ru/news/index.html">Новости</a>
<a href="../../ru/game/index.html">Игры</a>
<a href="../../ru/tool/index.html">Инструменты</a>
<a href="../../ru/page/about.html">О нас</a>
</div>
<a class="discord" href="https://discord.gg/3A6THQabNf">
<img src="../../images/discord.png"></img>
</a>
<div class="clear"></div>
</div>
</div>
<h3 class="left_item_title">В новостях...</h3>
<center>
<div class="news_item">
<h2 class="news_item_title">
<a href="memory-logic.html">Игровая логика «Памяти»</a>
</h2>
<p class="news_item_date">
2024-05-03 00:00
</p>
<div class="news_item_contents">
<h1 id="">Игровая логика «Памяти»</h1>
<p>В апреле реализовал игровую логику игры «Память» на Python в виде модели ограниченного языка и успешно перевёл её инструментом в C++.</p>
<p>Модель ограниченного языка предполагает следующую архитектуру из двух частей:</p>
<ol>
<li>контекст состояния</li>
<li>чистые функции без побочных эффектов, работающие лишь с контекстом</li>
</ol>
<p>Контекст состояния игровой логики на Python получился следующим (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory_Context.h">C++</a>):</p>
<pre><code class="python language-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
</code></pre>
<p>Т.к. инструмент на текущий момент работает лишь с функциями, то контекст для Python и С++ пока пишем руками.</p>
<p>Функции получились примерно такими (<a href="https://git.opengamestudio.org/kornerr/research-portable-memory/src/commit/6fcd542daa6242c8c23dddb88d04cda74a730328/v3/memory.cpp#L29">C++</a>):</p>
<pre><code class="python language-python"># Select item
@llm_by_value
def memory_selectItem(
c: memory_Context
) -&gt; memory_Context:
if (
len(c.selectedItems) == 2
):
c.selectedItems.clear()
#}
c.selectedItems.append(c.selectedId)
c.recentField = "selectedItems"
return c
#}
</code></pre>
<p>Особенности функций для модели ограниченного языка:</p>
<ul>
<li>декоратор <code>@llm_by_value</code> в Python нужен для передачи аргументов по значению, а не по ссылке (по умолчанию - по ссылке)</li>
<li>передача по значению обязательна для ограничения сферы действия функции ровно одним исходящим полем контекста, т.е. это реализация Принципа Единственной Ответственности (Single Responsibility Principle)</li>
<li>контекст содержит поле <code>recentField</code>, представляющее собой хранимое «событие»; это поле позволяет функциям среагировать лишь в момент изменения значения интересующего поля</li>
<li>функция обязана в поле <code>recentField</code> указать изменённое поле контекста либо <code>none</code> в случае отсутствия изменений</li>
<li>функция принимает на вход контекст и выдаёт (изменённый) контекст на выход</li>
</ul>
<p>Полный список фукций игровой логики «Памяти»:</p>
<table>
<thead>
<tr>
<th>№</th>
<th>Функция</th>
<th>Инициатор вызова</th>
<th>Описание</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><code>memory_generateConstPlayfield</code></td>
<td>Пользователь</td>
<td>Генерируем упрощённое игровое поле, в котором последовательно парами идут элементы одной группы</td>
</tr>
<tr>
<td>2</td>
<td><code>memory_selectItem</code></td>
<td>Пользователь</td>
<td>Выбор элемента игрового поля</td>
</tr>
<tr>
<td>3</td>
<td><code>memory_shouldDeselectMismatchedItems</code></td>
<td>Система</td>
<td>Реакция снятия выделения с пары выбранных фишек различающихся групп</td>
</tr>
<tr>
<td>4</td>
<td><code>memory_shouldDetectVictory</code></td>
<td>Система</td>
<td>Реакция определения победы после скрытия всех фишек</td>
</tr>
<tr>
<td>5</td>
<td><code>memory_shouldHideMatchingItems</code></td>
<td>Система</td>
<td>Реакция скрытия пары выбранных фишек одной группы</td>
</tr>
</tbody>
</table>
<p>Для удостоверения работоспособности и идентичности работы этих функций как в Python, так и в C++, на каждую функцию ввёл минимум по одной функции проверки:</p>
<ul>
<li><code>memory_test_generateConstPlayfield</code></li>
<li><code>memory_test_selectItem_1x</code></li>
<li><code>memory_test_selectItem_2x</code></li>
<li><code>memory_test_selectItem_3x</code></li>
<li><code>memory_test_shouldDeselectMismatchedItems</code></li>
<li><code>memory_test_shouldDeselectMismatchedItems_itemTwice</code></li>
<li><code>memory_test_shouldDetectVictory</code></li>
<li><code>memory_test_shouldHideMatchingItems</code></li>
</ul>
<h1 id="-1">Планы на май</h1>
<p>Сделаю возможность сыграть одну партию игры «Память» в текстовом интерфейсе.</p>
</div>
</div>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = "https://opengamestudio.org/ru/news/memory-logic.html";
this.page.identifier = "memory-logic.html";
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://opengamestudio.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Пожалуйста, включите JavaScript для просмотра <a href="https://disqus.com/?ref_noscript">комментариев на платформе Disqus.</a></noscript>
<div id="footer">
Сайт сгенерирован <a href="http://opengamestudio.org/pskov/ru">ПСКОВОМ</a>
из <a href="http://github.com/ogstudio/site-opengamestudio">этого исходного кода</a>.
</div>
</center>
</body>
</html>

Завантаження…
Відмінити
Зберегти