Update from 12

This commit is contained in:
Administrator 2024-07-16 07:39:30 +00:00
parent e78f187cda
commit 8912bb7190
10 changed files with 130 additions and 130 deletions

View file

122
README.md
View file

@ -1,6 +1,8 @@
# BrickGame Tetris
Summary: In this project, you need to implement the Tetris game in the C programming language using a structural approach.
💡 [Tap here](https://new.oprosso.net/p/4cb31ec3f47a4596bc758ea1861fb624) **to leave your feedback on the project**. It's anonymous and will help our team make your educational experience better. We recommend completing the survey immediately after the project.
# Contents
- [BrickGameTetris](#brickgame-tetris)
@ -21,34 +23,34 @@ Summary: In this project, you need to implement the Tetris game in the C program
## Introduction
The project must consist of two parts for implementing the Tetris game: a library that implements the game's logic, which can be connected to various GUIs in the future, and a terminal interface. The logic of the library must be implemented using finite-state machines, one of the possible descriptions of which will be given below.
The project must consist of two parts to implement the Tetris game: a library that implements the logic of the game, which can be connected to different GUIs in the future, and a terminal interface. The logic of the library must be implemented using finite-state machines, one of the possible descriptions of which is given below.
## Chapter I <div id="chapter-i"></div>
# General information
### BrickGame
BrickGame is a popular handheld console from the 90s with several ~~thousands~~ of built-in games developed in China. Originally, it was a copy of Tetris, developed in the USSR and released by Nintendo as part of the GameBoy platform, but also included many other games that were added over time. The console had a small screen with a 10x20 size playing field, which was a matrix of "pixels". There was a scoreboard to the right of the field with a digital display of the current game status, records and other additional information. The most popular games on BrickGame were Tetris, Tanks, Racing, Frogger, and Snake.
BrickGame is a popular handheld console from the 90s with several ~~thousands~~ of built-in games developed in China. It was originally a copy of Tetris developed in the USSR and released by Nintendo as part of the GameBoy platform, but also included many other games that were added over time. The console had a small screen with a 10x20 playing field that was a matrix of "pixels". To the right of the field was a scoreboard with a digital display of the current game status, records, and other additional information. The most popular games on BrickGame were Tetris, Tanks, Racing, Frogger and Snake.
![BrickGameConsole](misc/images/brickgame-console.jpg)
### History
Tetris was created on an Electronica-60 computer by Alexey Pajitnov on June 6, 1984. The game was a puzzle based on the use of "tetraminoes" - shaped pieces consisting of four squares. The first commercial version of the game was released in America in 1987. In the following years, Tetris was ported to many different devices, including cell phones, calculators, and PDAs.
Tetris was created on an Electronica-60 computer by Alexey Pajitnov on June 6, 1984. The game was a puzzle based on the use of "tetraminoes" shaped pieces consisting of four squares. The first commercial version of the game was released in the United States in 1987. In the following years, Tetris was ported to many different devices, including mobile phones, pocket calculators and PDAs.
The most popular version of Tetris is the one for the Game Boy and NES consoles. But there are various versions of the game apart from it. For example, there's a version with three-dimensional pieces or a dueling version where two players get the same pieces and try to beat each other on points.
The most popular version of Tetris is the one for the Game Boy and NES consoles. But there are several other versions of the game. For example, there's a version with three-dimensional pieces, or a duel version where two players get the same pieces and try to beat each other in scoring.
### Finite-state machines
A finite-state machine (FSM) in the theory of algorithms is a mathematical abstraction, a model of a discrete device that has one entry, one exit and at each moment of time is in one state out of a set of possible states.
A finite-state machine (FSM) in algorithm theory is a mathematical abstraction, a model of a discrete device that has an input, an output, and is in one of a set of possible states at any given time.
During operation, the input of the FSM sequentially receives entry actions, and at the output the FSM generates exit signals. Transition from one internal state to another can occur not only from external action, but also spontaneously.
During operation, the input of the FSM receives input actions sequentially, and the output of the FSM generates output signals. Transition from one internal state to another can occur not only by external action, but also spontaneously.
FSM can be used to describe algorithms for solving certain problems, as well as for modeling almost any process. A few examples:
FSM can be used to describe algorithms for solving specific problems, as well as to model almost any process. Some examples:
- Artificial intelligence logic for games;
- Artificial intelligence game logic;
- Syntactic and lexical analysis;
- Complex application network protocols;
- Streaming data
- Streaming data.
Below are examples of using FSM to formalize the game logic of a few games from BrickGame.
@ -56,42 +58,42 @@ Below are examples of using FSM to formalize the game logic of a few games from
![Frogger](misc/images/frogger-game.png)
Frogger is one of the later games released on the Brickgame consoles. The game is a playing field on which the logs move, and by jumping over them, the player needs to direct the frog from one side to the other. If the player hits the water or the frog moves outside the playing field, the frog dies. The game ends when the player brings the frog to the other side or the last frog dies.
Frogger is one of the later games released for the Brickgame consoles. The game consists of a playing field on which logs move, and the player has to guide the frog from one side to the other by jumping over them. If the player hits the water or the frog moves outside the playing field, the frog dies. The game ends when the player gets the frog to the other side, or when the last frog dies.
In order to formalize the logic of this game, the following variant of a finite-state machine can be introduced:
To formalize the logic of this game, the following variant of a finite state machine can be introduced:
![Frogger's finite-state machine](misc/images/frogger.jpg)
This FSM has the following states:
- Start is the state in which the game waits for the player to press the ready to play button.
- Spawn is the state in which the next frog is created.
- Moving is the main game state with user input processing - moving the frog along the lane left/right or jumping forward/backward.
- Shifting is the state that occurs after the timer expires, which shifts all objects on the lanes to the right, along with the frog.
- Collision is a state that occurs if the frog hits the water after jumping, or if the frog is outside the playing field after shifting logs.
- Reached the other side is the state that occurs when a frog reaches the other side.
- Game over is the state that occurs after reaching the other side of the river or the last frog dies.
- Start is the state where the game is waiting for the player to press the ready button.
- Spawn is the state where the next frog is created.
- Moving is the main game state with user input processing — moving the frog left/right along the path or jumping forward/backward.
- Shift is the state that occurs after the timer runs out, where all objects on the paths are shifted to the right along with the frog.
- Collision is a state that occurs when the frog hits the water after jumping, or when the frog is outside the playing field after moving logs.
- Reached the other side is the state that occurs when a frog reaches the other side.
- Game over is the state that occurs after reaching the other side of the river, or when the last frog dies.
You can find an example of implementing a frogger using FSM in the `code-samples` folder.
An example of implementing a frogger using FSM can be found in the `code-samples` folder.
### Tetris
![Tetris](misc/images/tetris-game.png)
Tetris is probably one of the most popular games for the Brickgame console. It's not rare for the console itself to be referred to as Tetris. The goal of the game is to score points for building lines from the blocks generated by the game. The next block generated by the game starts moving down the playing field until it reaches the lower boundary or collides with another block. The user can rotate the pieces and move them horizontally, trying to make rows. Once filled, the row is destroyed, the player gets points, and the blocks above the filled row go down. The game ends when the next piece stops in the topmost row.
Tetris is probably one of the most popular games for the Brickgame console. It's not uncommon for the console itself to be called Tetris. The goal of the game is to score points by building lines of blocks generated by the game. The next block generated by the game starts moving down the board until it reaches the bottom border or collides with another block. The user can rotate the blocks and move them horizontally, trying to make rows. Once a row is filled, it is destroyed, the player scores points, and the blocks above the filled row fall down. The game ends when the next piece stops in the top row.
In order to formalize the logic of this game, the following variant of a finite-state machine can be introduced:
To formalize the logic of this game, the following variant of a finite state machine can be introduced:
![Tetriss finite-state machine](misc/images/tetris.png)
This FSM has the following states:
- Start is the state in which the game waits for the player to press the ready to play button.
- Spawn is the state the game enters when you create another block and choose the next block to spawn.
- Moving is the main game state with user input processing - rotating blocks/moving blocks horizontally.
- Shifting is the state the game enters after the timer expires. It moves the current block down one level.
- Attaching is the state the game enters after the current block "touches" the already fallen blocks or the ground. If filled rows are created, it is destroyed and the rest of the blocks are shifted down. If a block is stopped in the topmost row, the game enters the "game over" state.
- Game over is a game over.
- Start is the state in which the game waits for the player to press the ready button.
- Spawn is the state the game enters when you create another block and select the next block to spawn.
- Moving is the main game state with user input processing rotating blocks/moving blocks horizontally.
- Move is the state the game enters after the timer runs out. It moves the current block down one level.
- Attaching is the state the game enters after the current block "touches" the already fallen blocks or the ground. If full rows are created, it is destroyed and the remaining blocks are moved down. If a block is stopped in the top row, the game enters the "game over" state.
- Game over is the end of the game.
## Chapter II <div id="chapter-ii"></div>
## Project Requirements
@ -100,38 +102,38 @@ This FSM has the following states:
You need to implement the BrickGame v1.0 aka Tetris program:
- The program must be developed in C language of C11 standard using gcc compiler.
- The program must consist of two parts: a library implementing the logic of the tetris game, and a terminal interface using the `ncurses` library.
- A finite-state machine must be used to formalize the logic of the game.
- The library must have a function that accepts user input and a function that outputs a matrix that describes the current state of the playing field whenever it is changed.
- The program library code must be located in the `src/brick_game/tetris` folder.
- The program interface code must be located in the `src/gui/cli` folder
- The program must be built using a Makefile with the standard set of targets for GNU-programs: all, install, uninstall, clean, dvi, dist, test, gcov_report. Installation directory can be arbitrary
- The program must be developed in accordance with the principles of structured programming.
- Stick to Google Style when writing code.
- The program must be developed in C language of the C11 standard using the gcc compiler.
- The program must consist of two parts: a library implementing the logic of the Tetris game, and a terminal interface using the `ncurses` library.
- A finite state machine must be used to formalize the logic of the game.
- The library must have a function that accepts user input and a function that outputs a matrix describing the current state of the playing field whenever it is changed.
- The library code must be placed in the `src/brick_game/tetris` folder.
- The program interface code must be in the `src/gui/cli` folder.
- The program must be built using a Makefile with the standard set of targets for GNU programs: all, install, uninstall, clean, dvi, dist, test, gcov_report. The installation directory can be arbitrary.
- The program must be developed according to the principles of structured programming.
- Follow Google Style when writing code.
- Prepare full coverage of the library with unit tests, using the `check` library (tests must run on Darwin/Ubuntu OS). The coverage of the library with game logic with tests must be at least 80 percent.
- The following mechanics must be in the game:
- The following mechanics must be present in the game:
- Rotation of pieces;
- Moving pieces horizontally;
- Acceleration of the piece's fall (when the button is pressed, the figure moves all the way down);
- Display of the next piece;
- Destruction of filled raws;
- End of the game when the top border of the playing field is reached;
- All sorts of pieces shown in the picture below must be included in the game.
- Add support for all the buttons provided on the physical console for control:
- Horizontal movement of pieces;
- Acceleration of the piece's fall (when the button is pressed, the piece moves all the way down);
- Displaying the next piece;
- Destruction of filled rows;
- End of the game when the top of the board is reached;
- All types of pieces shown in the picture below must be included in the game.
- Add support for all buttons provided on the physical console for control:
- Start game,
- Pause,
- End game,
- Left arrow - movement of the piece to the left,
- Right arrow - movement of the piece to the right,
- Down arrow - piece falls,
- Left arrow — move the piece to the left,
- Right arrow — move piece to the right,
- Down arrow piece falls,
- Up arrow is not used in this game,
- Action (piece rotation).
- The playing field must match the dimensions of the console's playing field - ten "pixels" wide and twenty "pixels" high.
- After reaching the lower boundary of the field or contacting another figure, the figure must stop. After that, the next piece, shown in the preview, is generated.
- The library interface must correspond to the description found in materials/library-specification.md.
- The playing area must be the same size as the console's playing field — ten "pixels" wide and twenty "pixels" high.
- When the figure reaches the lower boundary of the board or touches another figure, it must stop. After that, the next piece, shown in the preview, is generated.
- The library interface must match the description in materials/library-specification.md.
- The UI must support rendering of the playing field and additional information.
- Prepare a diagram in any format describing the used FSM (its states and all possible transitions).
- Prepare a diagram in any format describing the FSM used (its states and all possible transitions).
Pieces used:
@ -139,24 +141,22 @@ Pieces used:
### Part 2. Bonus. Scoring and game record
Add the following mechanics to the game:
Add the following mechanics to the game
- scoring;
- storing maximum points.
- Scoring;
- Store maximum score.
This information must be passed and displayed by the user interface in the sidebar. The maximum number of points must be stored in a file or embedded DBMS and saved between program runs.
This information must be passed and displayed by the user interface in the sidebar. The maximum score must be stored in a file or an embedded DBMS and saved between program runs.
The maximum number of points must be changed during the game if the user exceeds the current maximum score.
The maximum score must be changed during the game if the user exceeds the current maximum score.
Points will be accrued as follows:
Points are accumulated as follows:
- 1 row is 100 points;
- 2 rows is 300 points;
- 3 rows is 700 points;
- 4 rows is 1500 points;
- 4 rows is 1500 points.
### Part 3. Bonus. Level mechanics
Add level mechanics to the game. Each time a player gains 600 points, the level increases by 1. Increasing the level boosts the speed at which the pieces move. The maximum number of levels is 10.
💡 [Press here](https://forms.yandex.ru/cloud/65d4a02673cee73bdc52da80/)**, to give us feedback on this project**. It's anonymous and will help our team make your learning process better.
Add level mechanics to the game. Each time a player earns 600 points, the level increases by 1. Increasing the level increases the speed at which the pieces move. The maximum number of levels is 10.

View file

@ -1,6 +1,8 @@
# BrickGame Тетрис
Резюме: в данном проекте тебе предстоит реализовать игру «Тетрис» на языке программирования С с использованием структурного подхода.
💡 [Нажми сюда](https://new.oprosso.net/p/4cb31ec3f47a4596bc758ea1861fb624), **чтобы поделиться с нами обратной связью на этот проект**. Это анонимно и поможет нашей команде сделать обучение лучше. Рекомендуем заполнить опрос сразу после выполнения проекта.
## Содержание
- [BrickGame Тетрис](#brickgame-тетрис)
@ -72,13 +74,13 @@ BrickGame — популярная портативная консоль 90-ых
- Достигнут другой берег — состояние, которое наступает при достижении лягушкой верхней другого берега.
- Игра окончена — состояние, которое наступает после достижения другого берега или смерти последней лягушки.
Пример реализации фроггера с использованием КА вы можете найти в папке `code-samples`.
Пример реализации фроггера с использованием КА ты можешь найти в папке `code-samples`.
### Тетрис
![Тетрис](misc/images/tetris-game.png)
«Тетрис», наверное, одна из самых популярных игр для консоли Brickgame. Нередко и саму консоль называют тетрисом. Цель игры — в наборе очков за построение линий из генерируемых игрой блоков. Очередной блок, сгенерированный игрой, начинает опускаться вниз по игровому полю, пока не достигнет нижней границы или не столкнется с другим блоком. Пользовать может поворачивать фигуры и перемещать их по горизонтали, стараясь составлять ряды. После заполнения ряд уничтожается, игрок получает очки, а блоки, находящиеся выше заполненного ряда опускаются вниз. Игра заканчивается, когда очередная фигура останавливается в самом верхнем ряду.
«Тетрис», наверное, одна из самых популярных игр для консоли Brickgame. Нередко и саму консоль называют тетрисом. Цель игры — в наборе очков за построение линий из генерируемых игрой блоков. Очередной блок, сгенерированный игрой, начинает опускаться вниз по игровому полю, пока не достигнет нижней границы или не столкнется с другим блоком. Пользователь может поворачивать фигуры и перемещать их по горизонтали, стараясь составлять ряды. После заполнения ряд уничтожается, игрок получает очки, а блоки, находящиеся выше заполненного ряда, опускаются вниз. Игра заканчивается, когда очередная фигура останавливается в самом верхнем ряду.
Для формализации логики данной игры можно представить следующий вариант конечного автомата:
@ -90,7 +92,7 @@ BrickGame — популярная портативная консоль 90-ых
- Спавн — состояние, в которое переходит игра при создании очередного блока и выбора следующего блока для спавна.
- Перемещение — основное игровое состояние с обработкой ввода от пользователя — поворот блоков/перемещение блоков по горизонтали.
- Сдвиг — состояние, в которое переходит игра после истечения таймера. В нем текущий блок перемещается вниз на один уровень.
- Соединение — состояние, в которое преходит игра после «соприкосновения» текущего блока с уже упавшими или с землей. Если образуются заполненные линии, то она уничтожается и остальные блоки смещаются вниз. Если блок остановился в самом верхнем ряду, то игра переходит в состояние «игра окончена».
- Соединение — состояние, в которое преходит игра после «соприкосновения» текущего блока с уже упавшими или с землей. Если образуются заполненные линии, то она уничтожается, и остальные блоки смещаются вниз. Если блок остановился в самом верхнем ряду, то игра переходит в состояние «игра окончена».
- Игра окончена — игра окончена.
## Chapter II <div id="chapter-ii"></div>
@ -103,13 +105,13 @@ BrickGame — популярная портативная консоль 90-ых
- Программа должна быть разработана на языке Си стандарта C11 с использованием компилятора gcc.
- Программа должна состоять из двух частей: библиотеки, реализующей логику игры тетрис, и терминального интерфейса с использованием библиотеки `ncurses`.
- Для формализации логики игры должен быть использован конечный автомат.
- Библиотека должна иметь функцию, принимающая на вход ввод пользователя, и функцию, выдающую матрицу, которая описывает текущее состояние игрового поля, при каждом ее изменении.
- Библиотека должна иметь функцию, принимающую на вход ввод пользователя, и функцию, выдающую матрицу, которая описывает текущее состояние игрового поля при каждом ее изменении.
- Код библиотеки программы должен находиться в папке `src/brick_game/tetris`.
- Код с интерфейсом программы должен находиться в папке `src/gui/cli`.
- Сборка программы должна быть настроена с помощью Makefile со стандартным набором целей для GNU-программ: all, install, uninstall, clean, dvi, dist, test, gcov_report. Установка должна вестись в любой другой произвольный каталог.
- Программа должна быть разработана в соответствии с принципами структурного программирования.
- При написании кода придерживайся Google Style.
- Должно быть обеспечено покрытие библиотеки unit-тестами, с помощью библиотеки `check` (тесты должны проходить на ОС Darwin/Ubuntu). Покрытие библиотеки с логикой игры тестами должно составлять не меньше 80 процентов.
- Должно быть обеспечено покрытие библиотеки unit-тестами с помощью библиотеки `check` (тесты должны проходить на ОС Darwin/Ubuntu). Покрытие библиотеки с логикой игры тестами должно составлять не меньше 80 процентов.
- В игре должны присутствовать следующие механики:
- Вращение фигур;
- Перемещение фигуры по горизонтали;
@ -158,5 +160,3 @@ BrickGame — популярная портативная консоль 90-ых
### Часть 3. Дополнительно. Механика уровней
Добавь в игру механику уровней. Каждый раз, когда игрок набирает 600 очков, уровень увеличивается на 1. Повышение уровня увеличивает скорость движения фигур. Максимальное количество уровней — 10.
💡 [Нажми сюда](https://forms.yandex.ru/cloud/65d4a02673cee73bdc52da80/)**, чтобы поделиться с нами обратной связью на этот проект**. Это анонимно и поможет нашей команде сделать твоё обучение лучше.

View file

@ -1,32 +1,32 @@
Message from developers:
Hello, dear friend!
Let's play a game.
Something like the good old text-based adventure games with elements of a puzzle.
Each Task is a challenge, usually some kind of a hurdle you need to overcome.
Only those who tackle them all will be able to move further.
Something like the good old text-based adventures with puzzle elements.
Each task is a challenge, usually some kind of hurdle you have to overcome.
Only those who complete them will be able to advance.
Below are several tips to help you find your way:
1. During the entire journey, you will be accompanied by the feeling of uncertainty and a severe shortage of information: THAT'S OK. It's a part of the game. Remember that the information in the repository and Google are always there for you. Just like other players. Communicate. Search. Collect. Do not be afraid to make a mistake.
2. There may be a game inside the game, and another game inside it. That's normal. Just like in real life. Recursion is beautiful.
3. Levels can be very different from one another. That's normal. It's a part of the game. You can't just learn one recipe and apply it everywhere. The only way to achieve the goal is by continuously learning and adapting.
4. It's a multiplayer game, even if it doesn't seem like it in the beginning.
5. You will, however, be able to get through most of it on your own.
6. Be careful with information sources. Check. Think. Analyze. Compare. Do not trust.
7. Pay attention to the text of the task. Think. Check.
8. If the task seems unclear or impossibleit only seems like it. Take your time, sit down in silence or with your favorite music. Get back to the task in 1015 minutes and read the entire text once again.
9. If tip #8 hasn't helpedsearch for a guide. You are surrounded by many wanderers just like you and they will be happy to help you find the exit.
10. Watch the time! It's deceitful. You have to complete at least one challenge a day!
11. Be attentive and do not miss important things. Check the repository carefully!
12. Always push only to the develop branch! The master branch will be ignored. Work in the src directory.
13. Remember that each task undergoes a series of checks: code style check, static analyzer check, check for correct work with memory, check with a set of autotests, check with a checklist. Be careful.
14. You will come across different tasks on your way. The tasks marked with the asterisk (*) are only for the most reckless ones. They are more difficult and not compulsory. But if you complete them, you will gain extra experience and knowledge.
15. Some things may seem important but they are actually not.
16. Remember that ultimately the fact of completing the challenge is not as important as HOW you complete it.
Here are some tips to help you find your way:
1. Throughout your journey, you will feel a sense of uncertainty and a severe lack of information: THAT'S OK. It's part of the game. Remember that the information in the repository and Google is always there for you. Just like other players. Communicate. Search. Collect. Do not be afraid to make mistakes.
2. There may be a game in the game and another game in the game. That's normal. Just like in real life. Recursion is beautiful.
3. Levels can be very different from each other. That's normal. It's part of the game. You can't just learn one recipe and apply it everywhere. The only way to get there is to keep learning and adapting.
4. It's a multiplayer game, even if it doesn't seem like it at first.
5. You can do most of it on your own.
6. Be careful with sources of information. Check. Think. Analyze. Compare. Do not trust.
7. Pay attention to the text of the problem. Think. Check.
8. If the task seems unclear or impossible — it only seems that way. Take your time, sit in silence or with your favorite music. In 10-15 minutes, return to the assignment and read the entire text again.
9. If tip #8 didn't help — find a guide. You are surrounded by many wanderers just like you and they will be happy to help you find your way out.
10. Watch the time! It's deceptive. You must complete at least one challenge per day!
11. Pay attention and do not miss important things. Check the repository carefully!
12. Always push to the develop branch only! The master branch will be ignored. Work in the src directory.
13. Remember that each task goes through a series of checks: code style check, static analyzer check, check for correct work with memory, check with a set of autotests, check with a checklist. Be careful.
14. You will encounter various tasks along the way. The tasks marked with an asterisk (*) are for the most foolhardy. They are more difficult and not mandatory. However, completing them will give you extra experience and knowledge.
15. Some things may seem important, but they are not.
16. Remember that in the end, the fact that you complete the challenge is not as important as HOW you complete it.
17. The main goal of our journey is to understand what "HOW" means.
18. Separate the wheat from the chaff.
19. Divide and rule. Decompose.
20. Think about the main thing (good code, obviously). Move from the general to the specific.
21. Do not cheat, do not try to deceive the system and others. First of all, you will deceive yourself.
22. Do not write off, but if you use help - always figure it out to the end. Otherwise, your journey will not make any sense.
23. Check "materials" folder often. There can be a lot of useful things there!
19. Divide and conquer. Decompose.
20. Think about the big picture (good code, obviously). Move from the general to the specific.
21. Do not cheat, do not try to deceive the system and others. You will fool yourself first.
22. Do not write off, but if you use help — always find it out to the end. Otherwise your journey will be meaningless.
23. Check the "materials" folder often. There can be a lot of useful stuff in there!
24. Reread these tips several times.

View file

@ -1,9 +1,9 @@
От разработчиков:
Здравствуй, дорогой друг!
Мы предлагаем сыграть тебе в игру.
Игру, в духе старых добрых текстовых квестовых игр-бродилок с элементами головоломки.
Каждый Task — это очередное испытание, обычно некоторое препятствие, которое необходимо преодолеть.
Лишь тот, кто пройдет все сможет двинуться дальше.
Мы предлагаем тебе сыграть в игру.
Игру в духе старых добрых текстовых квестовых игр-бродилок с элементами головоломки.
Каждый Task — это очередное испытание, обычно некоторое препятствие, которое необходимо преодолеть.
Лишь тот, кто пройдет все, сможет двинуться дальше.
Ниже приведено несколько напутствий, они помогут тебе найти свой путь:
1. Всю дорогу тебя будет сопровождать чувство неопределенности и острого дефицита информации: ЭТО НОРМАЛЬНО. Это часть игры. Не забывай, что информация в репозитории и Google — всегда с тобой. Как и другие игроки. Общайся. Ищи. Собирай. Не бойся ошибиться.
@ -19,15 +19,15 @@
11. Будь внимателен — и не упусти важное. Внимательно изучай репозиторий!
12. Всегда делай push только в ветку develop! Ветка master будет проигнорирована. Работай в директории src.
13. Помни, что каждое задание проходит ряд проверок: проверка на стиль кода, проверка статическим анализатором, проверка на корректную работу с памятью, проверка набором автотестов, проверка с помощью чеклиста. Будь внимателен.
14. На твоем пути тебе встретятся разные задания. Те, что помечены звездочкой (*) подходят только для самых отчаянных. Они с повышенной сложностью и в целом не являются обязательными к выполнению. Но если ты их сделаешь, то получишь дополнительный опыт и знания.
14. На твоем пути тебе встретятся разные задания. Те, что помечены звездочкой (*), подходят только для самых отчаянных. Они с повышенной сложностью и в целом не являются обязательными к выполнению. Но если ты их сделаешь, то получишь дополнительный опыт и знания.
15. Иногда то, что кажется важным — не есть важное.
16. Помни, в конечном счете, факт преодоления препятствия не так важен, как то, КАК ты его преодолел.
17. Главная цель нашего путешествия — осознать, что такое “КАК”.
17. Главная цель нашего путешествия — осознать, что такое «КАК».
18. Отделяй зерна от плевел.
19. Разделяй и властвуй. Декомпозируй.
20. Думай о главном (о хорошем коде, разумеется). Следуй от общего к частному.
21. Не жульничай, не пытайся обмануть систему и окружающих. В первую очередь ты обманешь себя.
22. Не списывай, а если пользуешься помощью - всегда разбирайся до конца, почему, как и зачем. Иначе твое путешествие не будет иметь никакого смысла.
22. Не списывай, а если пользуешься помощью всегда разбирайся до конца, почему, как и зачем. Иначе твое путешествие не будет иметь никакого смысла.
23. Почаще заглядывай в папку materials. Там может быть много полезного!
24. Перечитай напутствия несколько раз.

View file

@ -1,20 +1,20 @@
# Инструкция по запуску тестов.
Помимо тестов на корректные выходные данные система автотестирования будет проверять вашу программу и ее исходный код по
Помимо тестов на корректные выходные данные система автотестирования будет проверять твою программу и ее исходный код по
следующим пунктам:
* **Стилевые тесты.** Чтобы проверить, насколько красота вашего кода соответствует стандартам, вы можете протестировать
ваш код с помощью утилиты _clang-format_. В папке ```materials/linters``` лежит файл ```.clang-format```, который
* **Стилевые тесты.** Чтобы проверить, насколько красота твоего кода соответствует стандартам, ты можешь протестировать
свой код с помощью утилиты _clang-format_. В папке ```materials/linters``` лежит файл ```.clang-format```, который
содержит необходимые настройки для стилевого теста. Данный конфигурационный файл распространяет свое действие на все
файлы, которые лежат с ним в директории или в директориях ниже. Поэтому, чтобы данные настройки применились к вашим
файлам с исходным кодом, скопируйте ```.clang-format``` в папку ```src```. \
файлы, которые лежат с ним в директории или в директориях ниже. Поэтому, чтобы данные настройки применились к твоим
файлам с исходным кодом, скопируй ```.clang-format``` в папку ```src```. \
\
Чтобы запустить проверку на стиль, выполните следующую команду: \
Чтобы запустить проверку на стиль, выполни следующую команду: \
```clang-format -n src/sourcefile_name.c``` \
\
Чтобы скачать _clang-format_, введите в терминал одну из следующих команд: \
Чтобы скачать _clang-format_, введи в терминал одну из следующих команд: \
```brew install clang-format``` \
или, если у вас есть root-права (для Ubuntu / Linux Mint / Debian) \
или, если у тебя есть root-права (для Ubuntu / Linux Mint / Debian) \
```sudo apt install clang-format```
Необходимая версия clang-format: \
@ -27,41 +27,41 @@
* **Тест на корректную работу с памятью.** При написании C-программ очень важно следить за утечками памяти. Для этого в
Unix-подобных операционных системах довольно часто используют утилиту _valgrind_. Однако, на OS X имеются проблемы с
поддержкой _valgrind_, поэтому вместо нее можно использовать утилиту _leaks_. Вдаваться в механизм работы этих утилит
мы сейчас не будем — если интересно, можете почитать в гугле.
мы сейчас не будем — если интересно, можешь почитать в гугле.
**_LEAKS_**
Чтобы запустить ваш исполняемый файл с помощью этой утилиты, наберите в терминале: \
Чтобы запустить свой исполняемый файл с помощью этой утилиты, набери в терминале: \
```leaks -atExit -- ./main.out | grep LEAK:```
Обратите внимание на команду ```| grep LEAK:```. Мы используем ее для короткого вывода, чтобы видеть только линии с
утечками, если они есть. Если вы хотите увидеть весь вывод, просто удалите эту команду.
Обрати внимание на команду ```| grep LEAK:```. Мы используем ее для короткого вывода, чтобы видеть только линии с
утечками, если они есть. Если ты хочешь увидеть весь вывод, просто удали эту команду.
При запуске исполняемого файла с помощью _leaks_ может появиться сообщение об ошибке:
> dyld: could not load inserted library /usr/local/lib/libLeaksAtExit.dylib because image not found
Ошибка возникает из-за того, что _leaks_ не может найти библиотеку _libLeaksAtExit.dylib_. \
В этом случае вам необходимо ввести следующие команды:
В этом случае тебе необходимо ввести следующие команды:
```sh
cd /usr/local/lib
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib
```
ополнительно:_ \
Используйте флаг ```-exclude``` утилиты _leaks_ для того, чтобы отфильтровать утечки в функциях, где известно об
Используй флаг ```-exclude``` утилиты _leaks_ для того, чтобы отфильтровать утечки в функциях, где известно об
утечках памяти. Этот флаг позволяет уменьшить количество посторонней информации, сообщаемой _leaks_.
**_VALGRIND_**
Чтобы установить _valgrind_ на компьютер, введите одну из следующих команд: \
Чтобы установить _valgrind_ на компьютер, введи одну из следующих команд: \
```brew install valgrind``` \
или, если у вас есть root-права (для Ubuntu / Linux Mint / Debian) \
или, если у тебя есть root-права (для Ubuntu / Linux Mint / Debian) \
```sudo apt install valgrind``` \
Чтобы запустить ваш исполняемый файл с помощью этой утилиты, наберите в терминале: \
Чтобы запустить свой исполняемый файл с помощью этой утилиты, набери в терминале: \
```valgrind --tool=memcheck --leak-check=yes ./main.out```
Не рекомендуется использовать _valgrind_ на OS X, вместо нее лучше использовать _leaks_.
* **Тест сборки.** Программу можно проверить на корректность сборки на тестовой системе. Для этого потребуется
установленный _Docker_. Если на системе есть докер, то можно зайти в директорию `materials/build` и запустить оттуда
скрипт run.sh. Скрипт обернет ваше решение в докер и запустит его вместе с типовым сценарием сборки.
скрипт run.sh. Скрипт обернет твое решение в докер и запустит его вместе с типовым сценарием сборки.

View file

@ -2,7 +2,7 @@
This task is the first in the BrickGame series. There will be four projects, each with its own game and technology. But in addition to developing new projects, you will also need to support old games and add support for new games to old projects. This time the interface will be console, next time - desktop, and so on. In order to support old and new games, it is necessary to determine in advance how the API of interfaces and libraries will be organized, so that in the future you don't have to rewrite already completed projects.
The game field is a matrix of ten by twenty dimension. Each element of the matrix corresponds to a "pixel" of the game field and can be in one of two states: empty or filled. In addition to the game field, each game has additional information that is displayed in the sidebar to the right of the game field. Provide stubs for additional information that is not used during the game.
The game field is a matrix of ten by twenty dimensions. Each element of the matrix corresponds to a "pixel" of the playfield and can be in one of two states: empty or filled. In addition to the playfield, each game has additional information that is displayed in the sidebar to the right of the playfield. Provide stubs for additional information that is not used during the game.
Each game library must have a function that accepts user input. The console has eight physical buttons: start game, pause, end game, action, and four arrows.

View file

@ -1,8 +1,8 @@
# Спецификация для библиотеки игры из коллекции игр BrickGame
Это задание является первым из серии BrickGame. Всего будет четыре проекта, в каждой - своя игра и свои технологии. Но помимо разработки новых проектов, необходимо будет поддерживать и старые игры, и добавлять поддержку новых игр в старые проекты. В этот раз интерфейс будет консольным, в следующем - десктопный, и так далее. Для того чтобы поддерживать старые и новые игры необходимо заранее определиться как будет устроено АПИ интерфейсов и библиотек, чтобы в дальнейшем не приходилось переписывать уже сданные проекты.
Это задание является первым из серии BrickGame. Всего будет четыре проекта, в каждом — своя игра и свои технологии. Но помимо разработки новых проектов, необходимо будет поддерживать и старые игры, и добавлять поддержку новых игр в старые проекты. В этот раз интерфейс будет консольным, в следующем десктопный, и так далее. Для того чтобы поддерживать старые и новые игры, необходимо заранее определиться, как будет устроено АПИ интерфейсов и библиотек, чтобы в дальнейшем не приходилось переписывать уже сданные проекты.
Игровое поле представляется как матрица размерностью десять на двадцать. Каждый элемент матрицы соответствует "пикселю" игрового поля и может находится в одном из двух состояний: пустой и заполненный. Кроме игрового поля у каждой игры есть дополнительная информация, которая выводится в боковой панели справа от игрового поля. Для дополнительной информации, не используемой во время игры, предусмотреть заглушки.
Игровое поле представляется, как матрица размерностью десять на двадцать. Каждый элемент матрицы соответствует «пикселю» игрового поля и может находится в одном из двух состояний: пустой и заполненный. Кроме игрового поля, у каждой игры есть дополнительная информация, которая выводится в боковой панели справа от игрового поля. Для дополнительной информации, не используемой во время игры, предусмотреть заглушки.
Каждая библиотека с игрой должна иметь функцию, принимающую на вход пользовательский ввод. У консоли имеется восемь физических кнопок: начало игры, пауза, завершение игры, действие и четыре стрелочки.
@ -37,4 +37,4 @@ void userInput(UserAction_t action, bool hold);
GameInfo_t updateCurrentState();
```
Обратите внимание, что информация о текущем состоянии игры `GameInfo_t` может быть представлена внутри библиотеки игры статическим объектом.
Обрати внимание, что информация о текущем состоянии игры `GameInfo_t` может быть представлена внутри библиотеки игры статическим объектом.

View file

@ -1,14 +1,14 @@
# Topoics list
Hello, student of School21!😉
Hello, School21 student! 😉
To make it easier for you to navigate the material, we have prepared a list of topics that you will learn in this project.
To help you navigate through the material, we have prepared a list of topics that you will learn in this project.
We will study:
- finite-state machine;
- working with matrixes;
- finite state machines;
- working with matrices;
- working with files;
- working with GUI library.
- working with the GUI library.
Now, knowing what awaits you in this project, you can slowly begin to study the topics listed above.😇
Now that you know what awaits you in this project, you can slowly begin to study the topics listed above. 😇

View file

@ -1,6 +1,6 @@
# Topics list
Привет, участник Школы21!😉
Привет, участник «Школы 21»! 😉
Чтобы тебе было проще, мы подготовили список тем, на которые следует обратить особое внимание при выполнении данного проекта:
@ -9,4 +9,4 @@
- работа с файлами;
- работа с графическими интерфейсами.
Теперь, когда известен список тем, знания которых потребуются в проекте, можешь приступать к изучению.😇
Теперь, когда известен список тем, знания которых потребуются в проекте, можешь смело приступать к изучению. 😇