Why I write games in C (yes, C). Game source texts (240) How to write games in C

Question: What advice do you have for creating games from scratch?


Good time. Recently he was inspired by toys like Papers, Please and Hotline Miami. I have my own idea for creating a game. But the thing is that I don’t know what’s better to write on. I planned the game with a top view, not 3D, for PC. For work I write in 1C, but not for games, although if you try really hard it’s possible, I also studied the very basics of Java. I understand that it's better to try something simple first, like tic-tac-toe or a snake, to gain basic knowledge.
On the Internet they suggest using C++, but they also suggest using C# + XNA. Anyone who has experience in creating games, please recommend literature or give some advice on programming games from scratch.

Answer:

Message from MonteKristo

recommend literature

Unfortunately, there is very little literature in Russian, especially of high quality. Not everything is translated, not immediately, and sometimes it’s not translated well. It happens that a book will be translated two years after the original was published, but a new version of the original has already been released and the first one is outdated. That's why I study English and translate current books using Lingvo and translate.google.com

You can search for books on creating games in different languages ​​and technologies here:

But under no circumstances start with books from the categories: Progressing and Mastering

You can find out what section means by clicking “i”. You can also download examples for free after registration. I showed this in the picture:

Question: Creating a game in C?

Answer: Added after 30 minutes

Message from HighPredator

In general, you can write everything in C. There would be desire, brains and time.

I have the desire, but no brains, I’ll look for the time >< Благодарю!

Message from McFair

You can also start learning Opengl yourself without an engine, create a couple of Tetris games, and you’ll see what’s what.

I feel like I'll have to write the engine myself

Message from McFair

7. It’s not entirely clear, should I cut out part of the picture and put it on the cube?

Yes, draw an object and texture it by overlaying an image.

Message from cyber-satyr

GTK, for example, is a cross. And so, for Venda, use winapi, it has a purely simple interface.

Thank you! That's what I meant

Message from McFair

8. It depends more on the game, goals and programming style, everything needs to be taken into account, if you take the same project in C and Sharp, then of course C will win a lot, but in Sharp the development speed will increase by 2/3 in my opinion.

A good choice would probably be to combine them. Write the basics in Sharp, and add features in C?)

Question: Creating an MMORPG game


Hello. I recently created a topic here where I learned about creating a 2D game.
Still, I decided to find out in which direction I should study.
Here are 2 screenshots:
http://kape.cc/uploads/posts/2011-05...a630f08343.jpg
http://mmohuts.com/wp-content/galler..._07.jpg?bb7a3b
And video:

I need to make a game like this. In general, the location is a grid system. The location is divided into some cubes
I understand that you need graphics, sounds, sound libraries, but first let’s take sound libraries.
Forget about graphics (let's say there are some), there are sounds.
I want to ask if the combination with ++ + OpenGL satisfies my requirements and the creation of a similar game, namely: moving an object through cells with animation, colliding objects, taking graphics from sprites + skeletal animation (naked character + binding objects - graphics, to the character's body (cloth)).

Answer: 8Observer8, I never liked physics until I realized that it was so necessary... But now, I realized that Box2D is definitely not needed for my planned game... I looked at the documentation on SFML, then today I poked around the previous work and was able to make it interacted with the walls, how much happiness there was)) It just took about 1-2 hours to understand how to do it, but it’s worth it.
By the way, I want to try to make at least the first level of Bomberman)

Added after 10 minutes
P.S. I'm learning C++ at the same time

Question: Recommend literature on creating games from start to finish


Recommend literature on creating games from start to finish. With all the elements, in C++ you can. Only a new book from the publishing house 2010-2015

Answer: What will you use for drawing: DirectX or OpenGL? I looked at there are general books on game theory --> . What kind of games will you write: 2D, 3D, RPG, shooting games, racing, chess, go? All these games have different specifics

Question: creating a game


Hello, I was planning to make a simple game (rpg). I’ll just do it “For myself.” The game will be static (bmb pictures of characters, objects, etc., possibly gif) When I started rummaging on the Internet in search of how this is generally done, I found a bunch of ready-made components for delphi (for example delphix) and therefore I had a question whether it is worth using something like? Or is it better to draw everything yourself on canvas?

Answer:

MrDmitry,
Static game? This is something new in the building program.
If she really is like that, then TImage is enough for you.
But if this is a dynamic game, then you will need TPaintBox.

Few people know, but in revenge Delphi comes with sample programs, including 3 mini-games!

In Windows 7, click Start | All programs | Embarcadero RAD Studio XE5 | Samples.

I have this folder
C:\Users\Public\Documents\RAD Studio\12.0\Samples\

As for components and engines.
Forget about the components right away. There is no component that will make the game for you. The game is written with hands and head.

As for the engines. The engine speeds up development.
In the engine you will find a bunch of ready-made code. The engine must be selected for the game.

From the engine, I advise you to look at the mathematical and geometric library. Library for working with the continent and multimedia. What file formats does the program support?
Camera support. Special effects support.

You didn't say 2D or 3D game.
Availability or absence of support for sprites and billboards. Text output.

Added after 14 minutes and 34 seconds
I think you will find it interesting. There is a site visited for creating games.

Here you can peek and borrow both ideas for the game and ideas for implementation.

Question: Creating your own language in Visual Studio


I'm looking for clear step-by-step examples/lessons on how to create your own language in Visual Studio.

I found an example of the language, but I need to understand what, how and why, because... my asm is not much like ook.

--
In general you need:
“cross-compiler” from your ASMA in the studio, with code hints, into codes for the Z80 processor (I haven’t figured out how to load it onto the hardware or into the emulator yet, this is the next step).

Requirements:
editor - Sun herself (2013);
assembler Z80 code on the screen, without unnecessary modules;
choosing a language when creating a project (where there is a list of languages ​​C#, F#, VB.NET and others).

Answer: but how to “tell” studio 2013 so that it highlights and prompts?

Question: Creating a game using the C++ engine


People, help me create a game using the C++ engine. Doodle jump, I would be grateful for the analogue. The problem is that I only started studying it not long ago. And I just can’t write the correct program. Apparently I'm still a specific noob. Thanks in advance!

Video games have been actively developing for more than 30 years, starting from gameplay and graphical capabilities, right up to advanced artificial intelligence systems and user perception of the material provided by the developers. E-sports, in turn, is a full-fledged sport with multi-million dollar prizes and billion-dollar turnover. And the video game industry itself is constantly gaining momentum, being one of the highest-grossing and popular branches of the entertainment sector. And humanity came to all this from the most primitive implementation of “tennis”, launched on an oscilloscope.


As a freshman, I decided, as part of studying the basic console capabilities of C/C++, it was possible to program a “classic” ASCII game that requires the player to think quickly, continuously interact with the game, and also have a simple graphic part that the player could interpret into some kind of three-dimensional image.


Despite the visual primitiveness of such solutions, they certainly evoke nostalgia for old-school games in players.

Inspiration

At the dawn of the appearance on the market of mobile phones with monochrome displays, the game “Space Impact”, which was firmware in Nokia devices, stood out. It fit perfectly into the limited capabilities of cell phones of that time. After the introduction of simple games into mobile phones, sales of devices increased sharply, and mobile gaming gradually became popular, and now competes with the industry of “adult” AAA projects.


“Space Impact” served as the basis for my first game due to its ease of execution and popularity in the early 2000s.

Features of "Space Invader"

First of all, the lightness of the program. The executable file takes up less than 100 kb and will work as intended on almost any computer running Windows OS with the Visual C++ package.


Secondly, portability - the source code can be remade for POSIX systems in a few minutes, thereby ensuring operability on UNIX and Mac operating systems, only by replacing several functions and rebuilding the program on the appropriate compiler.


The third advantage is that the program is portable and does not require any additional files. All additional files, if necessary, are created automatically in the directory where the executable file is located.


The simplest intuitive interface that does not require description or instructions for use.


  • Sub-item “New game” - starts a new game session.
  • Sub-item “Continue” - loads the last saved game from a binary file in the executable file directory and starts a game session using the received data.
  • “Help” item - instructions for working with the application and its description. Scroll by pressing the arrows on the keyboard.
  • The “Hall of Fame” item is a list of game session leaders, loaded from a binary file in the executable file directory and formatted output to the console.
  • Item “Exit” - exit the application.
  • The “world” shifting to the left with dynamic speed. “World” contains random fields at the top and bottom, 1 or 2 characters thick. Also, “space debris” appears randomly between the fields, displayed by the “¤” symbol, which is an obstacle for the player.
  • Pressed against the left edge of the window is a “spaceship”. The ship is moved using the up and down arrows on the keyboard, and by pressing the spacebar, it fires a projectile that destroys “space debris” upon touch.
  • A “dashboard” at the top of the console displays mileage traveled, current speed and number of attempts remaining.
  • How does Space Invader work?

    When the application starts, a splash animation appears. It consists of 6 pre-formatted character arrays, changing every 200ms.


    Start screen – final slide


    Next comes the call to the main menu function with parameter 1 (integer). The function displays a menu with the menu item highlighted in angle brackets, the number of which matches the input parameter. There are 4 items in the menu, respectively, the input parameter can vary from 1 to 4. When you press the down arrow, the incremented input parameter is recursively accessed if the input parameter is less than 4, with parameter 1 if the input parameter is equal to 4. When you press Space or Enter accesses the function corresponding to the highlighted menu item.


    void StartMenu(int switcher) ( system("cls"); switch (switcher) ( case 1: cout<< "\n\n\n << ИГРАТЬ! >> << "\n\n\n ИГРАТЬ!\n\n << ПОМОЩЬ! >> << "\n\n\n ИГРАТЬ!\n\n ПОМОЩЬ!\n\n << ЗАЛ СЛАВЫ >> << "\n\n\n ИГРАТЬ!\n\n ПОМОЩЬ!\n\n ЗАЛ СЛАВЫ\n\n << ВЫХОД >>"; break; ) int choice = _getch(); if (choice == 224) choice = _getch(); if (choice == 72) if (switcher != 1) StartMenu(switcher - 1); else StartMenu( 4); if (choice == 80) if (switcher != 4) StartMenu(switcher + 1); else StartMenu(1); if (choice == 13 || choice == 32) ( if (switcher == 1 ) GameMenu(1); if (switcher == 2) Help(0); if (switcher == 3) TopChart(); if (switcher == 4) _exit(0);


    Main menu (function entered with parameter 1)


    When you access the function corresponding to the “Game” item, a function similar in functionality is launched, but there is only a choice of 2 items. Accordingly, the input parameter will be 1 or 2, and when we press any of the arrows (up or down), we only need to change the number to the “opposite”. The most optimized option would be to subtract the input parameter from 3 (3 – 1 = 2, 3 – 2 = 1).


    void GameMenu(int switcher) ( system("cls"); if (switcher == 1) cout<< "\n\n\n\n\n << НОВАЯ ИГРА! >> << "\n\n\n\n\n НОВАЯ ИГРА!\n\n << ПРОДОЛЖИТЬ! >>"; int choice = _getch(); if (choice == 224) choice = _getch(); if (choice == 72 || choice == 80) GameMenu(3 - switcher); if (choice == 27) StartMenu(1); if (choice == 13 || choice == 32) Game(switcher)


    Additional menu (function entered with parameter 1)


    Now to the main thing - the game process. When you select the “New Game” sub-item, a new game session starts. A two-dimensional array is created with dimensions of 14 rows by 50 columns. The first line is allocated under the dashboard. The first device is the number of kilometers traveled, it is equal to the number of console updates (initially the console is updated once every 80ms, with each update this parameter is decremented until it reaches a value of 25).


    int odometerBuf = odometer, odometerDigitLength;

    for (odometerDigitLength = 0; odometerBuf != 0; odometerBuf /= 10, odometerDigitLength++);//calculating the number of digits on the odometer for (int i = odometerDigitLength, odometerBuf = odometer; i >= 0; i--, scr[i] = odometerBuf % 10 + "0", odometerBuf /= 10);//draw the odometer on the dashboard scr = "K"; scr = "M";//adding "KM" odometer++;//increasing the odometer


    The second device, the current speed, is a formula - 1000/console update speed. Speed ​​is measured in kilometers per second. Thus, initially the ship moves at a speed of 12 km/s, and after some time it reaches 40 km/s.

    speed = 1000 / timer;//speedometer update int speedBuf = speed;


    for (int i = 42; speed != 0; i--, scr[i] = speed % 10 + "0", speed /= 10);//drawing the speedometer on the dashboard scr = "K"; scr = "M"; scr = "/"; scr = "S";//adding "KM/S"


    The third device displays the number of remaining attempts, initially there are 3. Attempts are displayed with the “&” symbol.


    The next 2 lines, like the last 2, are the game fields. Field decorations are selected randomly and can consist of 3 characters or a space. The outermost lines are always completely filled, and the second and penultimate lines contain characters other than a space only in those places where these characters “grow” from others.


    char borderSymbols = ( "†", "‡", "¤", " " );< 50; aboveBelow++)//прорисовка верхнего и нижнего полей (2 + 2) { scr = borderSymbols; if (scr == "‡") scr = "¤"; scr = borderSymbols; if (scr == "‡") scr = "¤"; }


    for (int aboveBelow = 0; aboveBelow


    Dashboard and fields at the start of a game session


    In the central line of the playing space, pressed to the left edge, a spaceship is drawn, which the player will control.

    scr = "\\"; scr = "\\";//draw the ship scr = "3"; scr = "="; scr = "=";


    scr = "/"; scr = "/";<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); else { for (int i = 2; i < 13; i++)//корабль смещается на элемент выше for (int j = 0; j < 49; j++) if (scr[i][j] == "3" || scr[i][j] == "\\" || scr[i][j] == "=" || scr[i][j] == "/") { scr[j] = scr[i][j]; scr[i][j] = " "; } weaponPos--; } if (control == 80)//при движении корабля вниз if (scr == "/" || scr == "/" && scr == "¤" || scr == "/" && scr == "¤")//если корабль врезался в нижнее поле - игра окончена if (lifes >You can control it with the up and down arrows.<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); else { for (int i = 12; i > < 49; j++) if (scr[i][j] == "3" || scr[i][j] == "\\" || scr[i][j] == "=" || scr[i][j] == "/") { scr[j] = scr[i][j]; scr[i][j] = " "; } weaponPos++; }


    if (_kbhit())//if the key was pressed ( control = _getch();//the variable will take its value if (control == 224) control = _getch(); ) if (control == 72)//when moving ship up if (scr == "\\" || scr == "\\" && scr == "¤" || scr == "\\" && scr == "¤")//if the ship crashed into top field - game over if (lifes > 1) ( cout


    1) (cout


    Ship location when pressing up arrow twice


    Moving away from the visualization, it is worth noting that together with the ship we are moving up or down the array element responsible for the “barrel” of the ship. Accordingly, from which you can fire projectiles by pressing the spacebar.< 14; i++)//все "космические" элементы смещаются на элемент влево for (int j = 0; j < 49; j++) { if (scr[i][j] == "\\" && scr[i] == "¤" || scr[i][j] == "=" && scr[i] == "¤" || scr[i][j] == "/" && scr[i] == "¤") if (lifes >You can control it with the up and down arrows.<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); if (scr[i][j] != "3" && scr[i][j] != "\\" && scr[i][j] != "=" && scr[i][j] != "/" && scr[i][j] != "-" && scr[i] != "-") scr[i][j] = scr[i]; if (scr[i][j] == "¤") scr[i] = " "; } for (int i = 1; i < 14; i++)//все снаряды смещаются на элемент вправо for (int j = 48; j > < 12; i++)//рандомное появление космического мусора { if (rand() % 10 == 1) scr[i] = "¤"; }

    However, neither the field nor the projectiles move, therefore, in order to “revive” the gameplay, after the screen redraw timer expires, the “world” will move one column to the left, and the projectiles one column to the right. The ship remains in place until the player wants otherwise. But after redrawing, one empty column now appears - let’s fill it randomly with fields and “space debris” that can be shot down by projectiles or the ship’s side bumpers.



    for (int i = 1; i


    When the ship moves up or down at this moment, space debris will be destroyed without damage to the ship, all thanks to the bumpers


    However, although the fields consist of materials similar to space debris, they cannot be destroyed by impactors. Contact of any part of the ship with the fields leads to inevitable collapse. Just like space debris hitting the front of the ship. If at such moments there is an indication on the dashboard of at least one more “attempt”, the game seems to start over again, but with the score retained and one “attempt” lost. The speed is reset to the initial value of 12 km/s.


    If the player crashes and there are no attempts left, the game session ends, and the player is asked to enter his name in order to save his result in the “hall of fame.”



    Prompting the player to enter a name to save his result in the “hall of fame”


    The application processes 2 files:

    • "TopChart.bin" is a binary file for storing the leaderboard. The data is stored in structures (player nickname, score, end date of the gaming session). The data is written to the end of the file when the game ends. When you call up the “Hall of Fame” item, the file opens for reading with the ability to edit. Next, a dynamic array of structures is declared, into which the data from the file is rewritten, after which the array is sorted and formatted to the console (the maximum possible number of results is 12; if the array contains 13 results, the last one is discarded after sorting). Next, the file is overwritten with an array of result structures, after which the array is destroyed.
    • "CurrentSave.bin" is a binary file for storing a saved game. Called for reading when the “Continue” sub-item of the “Game” item is launched. May contain data for restoring one unfinished game session: the line number that contains the bow of the ship, the number of kilometers traveled, the number of remaining attempts, the location of objects on the screen. Using this data, a game session is formed that exactly repeats the unfinished one. To avoid unfair play, when loading a session from a file, the file is deleted. When you press Escape during the game, this file is created and all the necessary data is written to it for the successful continuation of the game session.

    The main menu item “Help” is a function that accepts a parameter from 0 to 22, displaying the next 12 lines of 50 characters from the input parameter. Control is done recursively using the up and down arrows.


    void Help(int switcher) ( system("cls"); cout<< "ПРОКРУТКА: СТРЕЛКИ ВВЕРХ/ВНИЗ | ВЕРНУТЬСЯ: ESCAPE\n"; char arr = { " УПРАВЛЕНИЕ В МЕНЮ Передвигаться по пунктам – СТРЕЛКИ ВВЕРХ/ВНИЗ Выбрать пункт – ПРОБЕЛ или ENTER Вернуться в предыдущее меню – ESCAPE УПРАВЛЕНИЕ В ИГРЕ Передвигаться вверх/вниз – СТРЕЛКИ ВВЕРХ/ВНИЗ Сделать выстрел – ПРОБЕЛ Вернуться в меню, сохранив игру – ESCAPE БРИФИНГ Вы – пилот космического корабля, попавшего в космическую бурю. Вам необходимо не разбиться и пролететь как можно большее расстояние. Корабль оборудован динамическим управлением. Чем быстрее вы летите – тем острее поворачивает судно. Корабльавтоматически постепенно разгоняется до 40 км/с. Вы можете сбивать космический мусор с помощью магнитной пушки, встроенной в судно, а также боковыми отбойниками. При управлении кораблем на щитке приборов отображается пройденная дистанция, текущая скорость и количество оставшихся «ячеек отката» (отображаются символом «&»), изначально их 3. Если решите прекратить игру – просто нажмите ESCAPE. Игра сохранится, и вы сможете ее продолжить даже после перезапуска приложения с помощью пункта «ПРОДОЛЖИТЬ!». В главном меню можно посмотреть таблицу почетных пилотов. Добейтесь своего права там оказаться! АВТОРСТВО Svjatoslav Laskov – AUTHOR Igor Marchenko – COACH National Technical University «Kharkiv Polytechnic Institute» 2016" }; for (int i = 0, buf = switcher; i < 13; i++) { for (int j = buf * 50; j < buf * 50 + 50; j++) cout << arr[j]; if (i != 12) cout << endl; buf++; } int controller = _getch();//получить значение нажатой клавиши if (controller == 224)//если была нажата стрелка controller = _getch();//то определить какая именно if (controller == 72)//если стрелка вверх if (switcher > < 22) Help(switcher + 1); else Help(22); if (controller == 27)//если Escape StartMenu(2); }

    Main menu item “Exit” - exits the application.


    User guide

    MENU CONTROLS
    o Move through items – UP/DOWN ARROW
    o Select item – SPACEBAR or ENTER
    o Return to previous menu – ESCAPE
    GAME CONTROLS
    o Move up/down – UP/DOWN ARROW
    o Take a shot – SPACEBAR
    o Return to the menu after saving the game – ESCAPE
    BRIEFING
    You are the pilot of a spaceship caught in a space storm. You need to avoid crashing and fly as far as possible.


    The ship is equipped with dynamic control. The faster you fly, the sharper the ship turns. The ship automatically gradually accelerates to 40 km/s.


    You can shoot down space debris using the magnetic gun built into the ship, as well as the side bumpers.
    When controlling the ship, the instrument panel displays the distance traveled, the current speed and the number of remaining “rollback cells” (displayed by the “&” symbol), initially there are 3.


    If you decide to stop playing, just press ESCAPE. The game will be saved, and you can continue it even after restarting the application using the “CONTINUE!” item.


    In the main menu you can see the table of honorary pilots. Achieve your right to be there!

    Bottom line

    Personally, I got a lot of pleasure from developing such a small project, especially since a standard console is designed for displaying information, and not for games. Because of this, the frame rate is very limited, regardless of the computer on which the application is running.


    I also wanted to divide the application into several threads for a more correct response to keystrokes by the user, but I will implement threads in the next project in C++.


    Source

    #include "conio.h" #include "windows.h" #include "ctime" #include using namespace std; struct player//definition of a structure that stores data about the results of any completed gaming session ( char name; int score; int mday; int mon; int year; ); struct save//definition of a structure storing data about an unfinished game session ( int weaponPos; int timer; int odometer; int lives; char scr; ); void ScreenOutput(char scr)//function of element-by-element output of an array to the console ( system("cls"); for (int i = 0; i< 14; i++) { for (int j = 0; j < 50; j++) cout << scr[i][j]; if (i != 13) cout << endl; } } //блок прототипов функций void StartMenu(int switcher);//функция, вызывающаяся из главного меню, содержит пункты "ИГРА" и "ПРОДОЛЖИТЬ" void GameMenu(int switcher);//функция главного меню void GameStart(char scr, int lifes, int *timer);//функция, определяющая начальный символьный массив при запуске нового игрового сеанса void Game(int var);//функция игровго сеанса void GameOver(int score);//функция, спрашивающая имя игрока, и записывающая его результат в бинарный файл void Help(int switcher);//функция помощи игроку void TopChart();//функция "ЗАЛ СЛАВЫ" - отображает список лидеров void Help(int switcher) { system("cls"); cout << "ПРОКРУТКА: СТРЕЛКИ ВВЕРХ/ВНИЗ | ВЕРНУТЬСЯ: ESCAPE\n"; char arr = { " УПРАВЛЕНИЕ В МЕНЮ Передвигаться по пунктам – СТРЕЛКИ ВВЕРХ/ВНИЗ Выбрать пункт – ПРОБЕЛ или ENTER Вернуться в предыдущее меню – ESCAPE УПРАВЛЕНИЕ В ИГРЕ Передвигаться вверх/вниз – СТРЕЛКИ ВВЕРХ/ВНИЗ Сделать выстрел – ПРОБЕЛ Вернуться в меню, сохранив игру – ESCAPE БРИФИНГ Вы – пилот космического корабля, попавшего в космическую бурю. Вам необходимо не разбиться и пролететь как можно большее расстояние. Корабль оборудован динамическим управлением. Чем быстрее вы летите – тем острее поворачивает судно. Корабльавтоматически постепенно разгоняется до 40 км/с. Вы можете сбивать космический мусор с помощью магнитной пушки, встроенной в судно, а также боковыми отбойниками. При управлении кораблем на щитке приборов отображается пройденная дистанция, текущая скорость и количество оставшихся «ячеек отката» (отображаются символом «&»), изначально их 3. Если решите прекратить игру – просто нажмите ESCAPE. Игра сохранится, и вы сможете ее продолжить даже после перезапуска приложения с помощью пункта «ПРОДОЛЖИТЬ!». В главном меню можно посмотреть таблицу почетных пилотов. Добейтесь своего права там оказаться! АВТОРСТВО Svjatoslav Laskov – AUTHOR Igor Marchenko – COACH National Technical University «Kharkiv Polytechnic Institute» 2016" }; for (int i = 0, buf = switcher; i < 13; i++) { for (int j = buf * 50; j < buf * 50 + 50; j++) cout << arr[j]; if (i != 12) cout << endl; buf++; } int controller = _getch();//получить значение надатой клавиши if (controller == 224)//если была нажата стрелка controller = _getch();//то определить какая именно if (controller == 72)//если стрелка вверх if (switcher >0) Help(switcher - 1);< 22) Help(switcher + 1); else Help(22); if (controller == 27)//если Escape StartMenu(2); } void StartMenu(int switcher) { system("cls"); switch (switcher) { case 1: cout << "\n\n\n << ИГРАТЬ! >else Help(0);<< "\n\n\n ИГРАТЬ!\n\n << ПОМОЩЬ! >if (controller == 80)//if down arrow if (switcher<< "\n\n\n ИГРАТЬ!\n\n ПОМОЩЬ!\n\n << ЗАЛ СЛАВЫ >>\n\nHELP!\n\nHALL OF FAME\n\nEXIT"; break; case 2: cout<< "\n\n\n ИГРАТЬ!\n\n ПОМОЩЬ!\n\n ЗАЛ СЛАВЫ\n\n << ВЫХОД >>"; break; ) int choice = _getch(); if (choice == 224) choice = _getch(); if (choice == 72) if (switcher != 1) StartMenu(switcher - 1); else StartMenu( 4); if (choice == 80) if (switcher != 4) StartMenu(switcher + 1); else StartMenu(1); if (choice == 13 || choice == 32) ( if (switcher == 1 ) GameMenu(1); if (switcher == 2) Help(0); if (switcher == 3) TopChart(); if (switcher == 4) _exit(0); system("cls"); if (switcher == 1) cout<< "\n\n\n\n\n << НОВАЯ ИГРА! >>\n\nCONTINUE!"; else cout<< "\n\n\n\n\n НОВАЯ ИГРА!\n\n << ПРОДОЛЖИТЬ! >>"; int choice = _getch(); if (choice == 224) choice = _getch(); if (choice == 72 || choice == 80) GameMenu(3 - switcher); if (choice == 27) StartMenu(1); if (choice == 13 || choice == 32) Game(switcher); void GameStart(char scr, int lives, int *timer) ( for (int i = 0; i< 14; i++)//очищение от мусора for (int j = 0; j < 50; j++) scr[i][j] = " "; for (int i = 50; lifes >0; i--, lives--, scr[i] = "&");< 50; aboveBelow++)//прорисовка верхнего и нижнего полей (2 + 2) { scr = borderSymbols; if (scr == "‡") scr = "¤"; scr = borderSymbols; if (scr == "‡") scr = "¤"; } scr = "\\"; scr = "\\";//прорисовка корабля scr = "3"; scr = "="; scr = "="; scr = "/"; scr = "/"; } void GameOver(int score) { system("cls"); player newPlayer;//объявляние структуры newPlayer.score = score;//инициализацие поля набранного счета cout << "Поздравляем Вас!\nВы продержались " << score << " километров.\n\n(Пожалуйста, не используйте кириллические символы)\n(Используйте не более 6 символов)\nОставьте свое имя и станьте примером\nдля подражания будущим игрокам: "; cin.getline(newPlayer.name, 7);//инициализацие поля имени time_t timeCur; time(&timeCur); struct tm * timeCurStruct = localtime(&timeCur); newPlayer.mday = timeCurStruct->*timer = 80;<< "Нет ни единого результата."; Sleep(1000); system("cls"); cout << "Нет ни единого результата.."; Sleep(1000); system("cls"); cout << "Нет ни единого результата..."; Sleep(1000); cout << "\nНажмите любую клавишу, чтобы вернуться."; _getch(); StartMenu(3); } fseek(topChart, 0L, SEEK_END); int playerAmount = ftell(topChart) / sizeof(player); player *temp = new player; fseek(topChart, 0L, SEEK_SET); for (int i = 0; i < playerAmount; i++)//копирование содержиомого файла в структкры fread(&temp[i], 1, sizeof(player), topChart); fclose(topChart); for (int i = 1; i < playerAmount; i++)//сортировка структур по спаданию итоговых счетов if (temp[i].score >char borderSymbols = ( "†", "‡", "¤", " " );<< "№ " << "Имя" << "\t" << "Счет" << "\t" << "Дата" << endl;//вывод таблицы лидеров в консоль for (int i = 0; i < playerAmount; i++) { cout << i + 1 << ")" << "\t" << temp[i].name << "\t" << temp[i].score << "\t"; if (temp[i].mday / 10 == 0) cout << "0" << temp[i].mday; else cout << temp[i].mday; cout << " "; switch (temp[i].mon) { case 0: cout << "января"; break; case 1: cout << "февраля"; break; case 2: cout << "марта"; break; case 3: cout << "апреля"; break; case 4: cout << "мая"; break; case 5: cout << "июня"; break; case 6: cout << "июля"; break; case 7: cout << "августа"; break; case 8: cout << "сентября"; break; case 9: cout << "октября"; break; case 10: cout << "ноября"; break; case 11: cout << "декабря"; break; } cout << " " << 1900 + temp[i].year << endl; } fopen_s(&topChart, "TopChart.bin", "wb+"); for (int i = 0; i < playerAmount; i++)//запись таблицы лидеров в бинарный файл fwrite(&temp[i], 1, sizeof(player), topChart); fclose(topChart); delete temp; _getch(); StartMenu(3); } int main() { setlocale(LC_ALL, "Rus");//задание кодировки system("mode con cols=51 lines=14");//задание размеров окна консоли system("title Space Invader");//задание описания окна консоли system("color 0A");//задание цвета консоли (0-задний фон; А-передний фон) HANDLE hCons = GetStdHandle(STD_OUTPUT_HANDLE);//получение хендла CONSOLE_CURSOR_INFO cursor = { 100, false };//число от 1 до 100 размер курсора в процентах; false\true - видимость SetConsoleCursorInfo(hCons, &cursor);//применение заданных параметров курсора int timer = 200; cout << " (____/(__) \\_/\\_/ \\___)(____)\n\n\n\n\n\n\n\n\n\n\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\";//вступительная заставка Sleep(timer); system("cls"); cout << " \\___ \\) __// \\((__) _)\n (____/(__) \\_/\\_/ \\___)(____)\n\n\n\n\n\n\n\n\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\\n)(/ /\\ \\/ // \\) D () _)) /";//вступительная заставка Sleep(timer); system("cls"); cout << " / ___)(_ \\ / _\\ / __)(__)\n \\___ \\) __// \\((__) _)\n (____/(__) \\_/\\_/ \\___)(____)\n\n\n\n\n\n\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\\n)(/ /\\ \\/ // \\) D () _)) /\n (__)\\_)__) \\__/ \\_/\\_/(____/(____)(__\\_)";//вступительная заставка Sleep(timer); system("cls"); cout << " ____ ____ __ ___ ____\n / ___)(_ \\ / _\\ / __)(__)\n \\___ \\) __// \\((__) _)\n (____/(__) \\_/\\_/ \\___)(____)\n\n\n\n\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\\n)(/ /\\ \\/ // \\) D () _)) /\n (__)\\_)__) \\__/ \\_/\\_/(____/(____)(__\\_)";//вступительная заставка Sleep(timer); system("cls"); cout << "\n ____ ____ __ ___ ____\n / ___)(_ \\ / _\\ / __)(__)\n \\___ \\) __// \\((__) _)\n (____/(__) \\_/\\_/ \\___)(____)\n\n\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\\n)(/ /\\ \\/ // \\) D () _)) /\n (__)\\_)__) \\__/ \\_/\\_/(____/(____)(__\\_)";//вступительная заставка Sleep(timer); system("cls"); cout << "\n\n ____ ____ __ ___ ____\n / ___)(_ \\ / _\\ / __)(__)\n \\___ \\) __// \\((__) _)\n (____/(__) \\_/\\_/ \\___)(____)\n __ __ _ _ _ __ ____ ____ ____\n ()((\\/)(\\ / _\\ (\\(__)(_ \\\n)(/ /\\ \\/ // \\) D () _)) /\n (__)\\_)__) \\__/ \\_/\\_/(____/(____)(__\\_)";//вступительная заставка cout << "\a"; Sleep(10 * timer);//задержка заставки StartMenu(1); return 0; } void Game(int var) { int weaponPos;//позиция строки дула в массиве int timer;//задержка между перерисовками экрана int odometer;//количество перерисовок экрана, они же итоговые очки int lifes;//количество жизней char control = "&";//переменная управления кораблем int shotPause = 4;//задержка между выстрелами (указывать на одну перерисовку больше) int speed;//скорость корабля char scr; if (var == 1) { weaponPos = 7;//позиция строки дула в массиве odometer = 1;//количество перерисовок экрана, они же итоговые очки lifes = 3;//количество жизней GameStart(scr, lifes, &timer); } else//при восстановлении игрового сеанса из сохранения { FILE *saveBin; fopen_s(&saveBin, "CurrentSave.bin", "rb"); if (!saveBin) { system("cls"); cout << "Нет сохранения."; Sleep(1000); system("cls"); cout << "Нет сохранения.."; Sleep(1000); system("cls"); cout << "Нет сохранения..."; Sleep(1000); Game(1); } fread(&weaponPos, 1, sizeof(int), saveBin); timer = 80; fread(&odometer, 1, sizeof(int), saveBin); fread(&lifes, 1, sizeof(int), saveBin); fread(&scr, 14 * 50, sizeof(char), saveBin); fclose(saveBin); remove("CurrentSave.bin"); } while (true) { int odometerBuf = odometer, odometerDigitLength; for (odometerDigitLength = 0; odometerBuf != 0; odometerBuf /= 10, odometerDigitLength++);//вычисление количества цифр на одометре for (int i = odometerDigitLength, odometerBuf = odometer; i >= 0; i--, scr[i] = odometerBuf % 10 + "0", odometerBuf /= 10);//drawing the odometer on the dashboard scr = "K"; scr = "M";//adding "KM" odometer++;//increasing the odometer speed = 1000 / timer;//updating the speedometer int speedBuf = speed;< 4)//перезарядка shotPause++; if (control == 27)//при выходе { FILE *saveBin; fopen_s(&saveBin, "CurrentSave.bin", "wb"); fwrite(&weaponPos, 1, sizeof(int), saveBin); fwrite(&odometer, 1, sizeof(int), saveBin); fwrite(&lifes, 1, sizeof(int), saveBin); fwrite(&scr, 14 * 50, sizeof(char), saveBin); fclose(saveBin); GameMenu(2); } if (control == 72)//при движении корабля вверх if (scr == "\\" || scr == "\\" && scr == "¤" || scr == "\\" && scr == "¤")//если корабль врезался в верхнее поле - игра окончена if (lifes >You can control it with the up and down arrows.<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); else { for (int i = 2; i < 13; i++)//корабль смещается на элемент выше for (int j = 0; j < 49; j++) if (scr[i][j] == "3" || scr[i][j] == "\\" || scr[i][j] == "=" || scr[i][j] == "/") { scr[j] = scr[i][j]; scr[i][j] = " "; } weaponPos--; } if (control == 80)//при движении корабля вниз if (scr == "/" || scr == "/" && scr == "¤" || scr == "/" && scr == "¤")//если корабль врезался в нижнее поле - игра окончена if (lifes >You can control it with the up and down arrows.<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); else { for (int i = 12; i >for (int i = 42; speed != 0; i--, scr[i] = speed % 10 + "0", speed /= 10);//drawing the speedometer on the dashboard scr = "K"; scr = "M"; scr = "/"; scr = "C";//adding "KM/S" if (_kbhit())//if the key was pressed ( control = _getch();//the variable will take its value if (control == 224) control = _getch( ); ) if (control == 13 && shotPause == 4 || control == 32 && shotPause == 4)//when the trigger is pressed if the gun is reloaded ( scr = "-"; shotPause = 0; ) if (shotPause< 49; j++) if (scr[i][j] == "3" || scr[i][j] == "\\" || scr[i][j] == "=" || scr[i][j] == "/") { scr[j] = scr[i][j]; scr[i][j] = " "; } weaponPos++; } for (int i = 1; i < 14; i++)//все "космические" элементы смещаются на элемент влево for (int j = 0; j < 49; j++) { if (scr[i][j] == "\\" && scr[i] == "¤" || scr[i][j] == "=" && scr[i] == "¤" || scr[i][j] == "/" && scr[i] == "¤") if (lifes >You can control it with the up and down arrows.<< "\a"; lifes--; weaponPos = 7; GameStart(scr, lifes, &timer); Sleep(1000); } else GameOver(odometer); if (scr[i][j] != "3" && scr[i][j] != "\\" && scr[i][j] != "=" && scr[i][j] != "/" && scr[i][j] != "-" && scr[i] != "-") scr[i][j] = scr[i]; if (scr[i][j] == "¤") scr[i] = " "; } for (int i = 1; i < 14; i++)//все снаряды смещаются на элемент вправо for (int j = 48; j >= 2; i--)//the ship is shifted down an element for (int j = 0; j< 12; i++)//рандомное появление космического мусора { if (rand() % 10 == 1) scr[i] = "¤"; } ScreenOutput(scr);//вывод экрана if (control != "&")//"обнуление" управляющей переменной control = "&"; if (timer >= 0; j--) if (scr[i][j] == "-") if (j != 48) ( scr[i] = "-"; scr[i][j] = " "; ) else scr [i][j] = " ";


    char borderSymbols = ( "†", "‡", "¤", " " );

    scr = " ";//random filling of new edge elements scr = borderSymbols;
    if (scr == "‡") scr = "¤"; scr = " ";.

    scr = borderSymbols;

    if (scr == "‡") scr = "¤";

    for (int i = 3; i

    25)//ship acceleration timer--;

    Sleep(timer);//redraw delay ) )

    The most important, but not mandatory, requirement is simplicity. I find studying the features of the language and its wonderful “smart” API incredibly boring. You can learn an ideal language once and never use its documentation again.

    Finding and fixing bugs drains creativity. I want to leave fewer bugs, so I want strong typing, high-quality error messages and static code analysis. I want to make it easier to find errors, and therefore good debugging tools and dynamic analysis.

    I'm not interested in a beautiful realistic picture, but I care about performance. Less resource requirements expand the range of possibilities available for implementation. It is especially interesting to observe what happens to modern powerful computers when the developer does not think about performance.

    I'm even more concerned about the speed of the compiler. I'm not some Buddhist master of concentration, and waiting more than 10 seconds is a waste. Worse, it takes you out of the flow. It seems like I just looked at Twitter, and 5 minutes disappeared somewhere.

    I'm not an OOP follower. Most of my time spent working with classes and objects. But the further I go, the less I understand why it is necessary to combine code and data so strictly. I want to work with data as data and write code that works best for a given situation.

    Alternatives

    C++ continues to be the most common language for game development, and for good reason. To this day, most of my custom projects are written in it, and I don't like it.

    C++ covers my needs, but doesn't meet my wants. It's wildly complex. Despite the availability of suitable tools, it is easy to make insidious mistakes. Also, compared to C, it compiles slowly. C++ has high performance and provides features that C doesn't have, but that's not what I want, and it comes at the cost of a lot of complexity.

    C# and Java have similar problems. These are verbose and complex monsters, but I need a small, simple animal. Both languages ​​send the programmer straight into the abyss of OOP, and I am against it. As with most high-level languages, a lot of the complex stuff is hidden away so you don't accidentally shoot yourself in the foot.

    I really like Go. In many ways, it's a reinvented C, albeit one that was several years in the making before it was released to the public. I would like to use Go, but there is one huge pitfall - garbage collection. Game development in Go is questionable because the garbage collector will pause the entire game world, which the developer cannot afford. Also, everything is not very good here with game libraries. And although you can always adapt a C library for this task, and without any problems, this still generates a lot of unnecessary work. Besides, I have doubts about the prospects. Go would be great for the web, but it's a rapidly changing environment. This was especially felt with the death of Flash.

    I don't like JavaScript at all. It provides so much freedom that I don’t understand how people manage to write any complex projects on it. And I don’t even want to try it.

    Haxe looks much more promising than other languages ​​on this list. He has no problems with libraries. If I start writing for the web again, I will definitely get to know it better. The relative youth of the language is somewhat concerning: will it survive? I have nothing more to add; I only managed to play around with Haxe a little without going deeper.

    Jonathan Blow writes his own language. The language he himself would want to use. I admire his decision, and sometimes I myself get excited about the idea of ​​doing the same. But don’t throw out all existing libraries. But achieving full compatibility with them is not so easy. And in general it’s difficult, I would prefer to continue writing games rather than programming languages.

    Why C is the best choice for me

    Although C is dangerous, it is reliable. This is a very sharp knife that can cut off fingers as easily as cutting vegetables. But it is simple, and learning how to use it correctly will not be difficult.

    Hi's fast. And when it comes to compilation, I can't imagine any language being able to do it faster.
    It is possible to write code so that it works everywhere. And it's usually relatively easy. It's hard to imagine that one day this will change.

    There is excellent support for libraries and tools.

    Although it makes me a little sad, C is still the best language for me.

    I don't really want to say something like, "Hey, you should write C too." I realize that my preferences are very specific. In addition, in terms of the amount of code I have written in different languages, “vanilla” C code occupies a leading position, so this is already part of my comfort zone.

    So yes, C is the best choice for me.

    From the translator

    The translation is quite free in places, but not to the detriment of meaning or content.

    I prepared the translation specifically for Friday, on this day it is especially appropriate, in my opinion. Although the author of the original text seems to write in all seriousness... you yourself understand everything if you read it. What you read should not be taken as truth.

    With suggestions, wishes and comments, as usual, in PM.

     
    Articles By topic:
    Pickled grapes: best recipes
    Pickled grapes are a wonderful dessert that can be prepared for the winter at home. There are many options for preparing berries, but several simple recipes are especially popular.
    Pickled grapes are a wonderful dessert.
    What does a new blue towel mean in a dream?
    Find out from the online dream book what the Towel is for in a dream by reading the answer below as interpreted by the interpretive authors.
    What does a towel mean in a dream? Dream Interpretation of the 21st Century Why do you dream about a Towel and what does it mean: Towel - Drying yourself with a towel in a dream is a sign that
    Purulent adnexitis symptoms and treatment
    (salpingoophoritis) is an inflammatory process with simultaneous involvement of the ovaries and fallopian tubes (uterine appendages). In the acute period, it is characterized by pain in the lower abdomen, more intense from inflammation, elevated temperature, and signs of intoxication. Mo