Как написать змейку на c

от admin

Своя змейка, или пишем первый проект. Часть 0

Привет Хабр! Меня зовут Евгений «Nage», и я начал заниматься программированием около года назад, в свободное от работы время. Просмотрев множество различных туториалов по программированию задаешься вопросом «а что же делать дальше?», ведь в основном все рассказывают про самые основы и дальше как правило не заходят. Вот после продолжительного времени за просмотром разных роликов про одно и тоже я решил что стоит двигаться дальше, и браться за первый проект. И так, сейчас мы разберем как можно написать игру «Змейка» в консоли со своими начальными знаниями.

Глава 1. Итак, с чего начнем?

Для начала нам ничего лишнего не понадобится, только блокнот (или ваш любимый редактор), и компилятор C#, он присутствует по умолчанию в Windows, находится он в С:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe. Можно использовать компилятор последней версии который поставляется с visual studio, он находится Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\csc.exe.

Создадим файл для быстрой компиляции нашего кода, сохранил файл с расширением .bat со следующим содержимым:

«@echo off» отключает отображение команд в консоли. С помощью команды goto получаем бесконечный цикл. Задаем переменную name, а с модификатором /p в переменную записывается значение введенное пользователем в консоль. «echo.» просто оставляет пустую строчку в консоли. Далее вызываем компилятор и передаем ему файл нашего кода, который он скомпилирует.

Таким способом мы можем скомпилировать только один файл, поэтому мы будем писать все классы в одном документе (я не разобрался еще как компилировать несколько файлов в один .exe через консоль, да и это не тема нашей статьи, может кто нибудь расскажет в комментариях).

Для тех кто сразу хочет увидеть весь код.

Глава 2. Первые шаги

Подготовим поле нашей игры, начиная с точки входа в нашу программу. Задаем переменные X и Y, размер и буфер окна консоли, и скроем отображение курсора.

Для вывода на экран нашей «графики» создадим свой тип данных — точка. Он будет содержать координаты и символ, который будет выводится на экран. Также сделаем методы для вывода на экран точки и ее «стирания».

Это интересно!
Оператор => называется лямбда-оператор, он используется в качестве определения анонимных лямбда выражений, и в качестве тела, состоящего из одного выражения, синтаксический сахар, заменяющий оператор return. Приведенный выше метод переопределения оператора (про его назначение чуть ниже) можно переписать так:

Создадим класс стен, границы игрового поля. Напишем 2 метода на создание вертикальных и горизонтальных линий, и в конструкторе вызываем отрисовку всех 4х сторон заданным символом. Список всех точек в стенке нам пригодится позже.

Как вы могли заметить для инициализации типа данных Point используется форма Point p = (x, y, ch); как и у встроенных типов, это становится возможным при переопределении оператора implicit, в котором описывается как задаются переменные.

Конструкция (int, int, char) называется кортежем, и работает только с .net 4.7+, по этому если у вас не установлен visual studio, то в вашем распоряжении только компилятор v4.0.30319 и нужно использовать стандартную инициализацию через оператор new.

Вернемся к классу Game и объявим поле walls, а в методе Main инициализируем ее.

Все! Можно скомпилировать код и посмотреть, что наше поле построилось, и самая легкая часть позади.

Глава 3. А что сегодня на завтрак?

Добавим генерацию еды на нашем поле, для этого создадим класс FoodFactory, который и будет заниматься созданием еды внутри границ.

Добавляем инициализацию фабрики и создадим еду на поле

Глава 4. Время главного героя

Перейдем к созданию самой змеи, и для начала определим перечисление направления движения змейки.

Теперь можем создать класс змейки, где опишем как она будет ползать, поворачивать. Определим список точек змеи, наше перечисление, шаг на сколько будет перемещаться за ход, и ссылки на хвостовую и головную точки, и конструктор, в котором рисуем змею в заданных координатах и заданной длинны при старте игры.

В методе поворота, что бы избежать возможности повернуть сразу на 180 градусов, просто указываем, что в каждом направлении мы можем повернуть только в 2 стороны. А проблему поворота на 180 градусов двумя нажатиями — поставив «переключатель», отключаем возможность поворачивать после первого нажатия, и включаем после очередного хода.

Осталось вывести ее на экран.

Готово! теперь у нас есть все что нужно, поле огороженное стенами, рандомно появляющаяся еда, и змейка. Пришла пора заставить все это взаимодействовать друг с другом.

Глава 5. Л-логика

Заставим нашу змейку двигаться, напишем бесконечный цикл для считывания клавиш нажатых на клавиатуре, и передаем клавишу в метод поворота змеи

для движения змеи воспользуемся классом .net который будет запускать метод Loop через определенные промежутки времени.

Теперь, перед тем как написать метод движения змейки, надо реализовать взаимодействие головы с едой, стенками и хвостом змеи. Для этого надо написать метод, позволяющий сравнивать две точки на совпадение координат. Переопределим оператор равенства и не равенства, их обязательно нужно переопределять в паре.

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

И похожий метод проверяющий не совпадает ли точка с хвостом.

И методом проверки съела ли еду наша змейка, и сразу делаем ее длиннее.

теперь можно написать метод движения, со всеми нужными проверками.

Вот и все! Наша змейка в консоли закончена и можно поиграть.

Заключение

Мы посмотрели как можно реализовать первую простенькую игру с небольшим использованием ООП, научились перегружать операторы, посмотрели на кортежи и лямбда оператор, надеюсь это было полезно!

Это была пилотная статья, и если вам понравилось, я напишу про реализацию змейки на Unity.
Всем удачи!

Как написать змейку на c

In this article, the task is to implement a basic Snake Game. Below given some functionalities of this game:

  • The snake is represented with a 0(zero) symbol.
  • The fruit is represented with an *(asterisk) symbol.
  • The snake can move in any direction according to the user with the help of the keyboard (W, A, S, D keys).
  • When the snake eats a fruit the score will increase by 10 points.
  • The fruit will generate automatically within the boundaries.
  • Whenever the snake will touch the boundary the game is over.

Steps to create this game:

  • There will be four user-defined functions.
  • Build a boundary within which the game will be played.
  • The fruits are generated randomly.
  • Then increase the score whenever the snake eats a fruit.

The user-defined functions created in this program are given below:

  • Draw(): This function creates the boundary in which the game will be played.
  • Setup(): This function will set the position of the fruit within the boundary.
  • Input(): This function will take the input from the keyboard.
  • Logic(): This function will set the movement of the snake.

Built-in functions used:

  • kbhit(): This function in C is used to determine if a key has been pressed or not. To use this function in a program include the header file conio.h. If a key has been pressed, then it returns a non-zero value otherwise it returns zero.
  • rand(): The rand() function is declared in stdlib.h. It returns a random integer value every time it is called.

Header files and variables:

  • The header files and variables used in this program are:

  • Here include the <unistd.h>header file for the sleep() function.

Draw(): This function is responsible to build the boundary within which the game will be played.

Below is the C program to build the outline boundary using draw():

setup():nThisbfunction is used to write the code to generate the fruit within the boundary using rand() function.

  • Using rand()%20 because the size of the boundary is length = 20 and width = 20 so the fruit will generate within the boundary.

Input(): In this function, the programmer writes the code to take the input from the keyboard (W, A, S, D, X keys).

logic(): Here, write all the logic for this program like for the movement of the snake, for increasing the score, when the snake will touch the boundary the game will be over, to exit the game and the random generation of the fruit once the snake will eat the fruit.

sleep(): This function in C is a function that delays the program execution for the given number of seconds. In this code sleep() is used to slow down the movement of the snake so it will be easy for the user to play.

main(): From the main() function the execution of the program starts. It calls all the functions.

C# Tutorial – Create a Classic Snake Game in Visual Studio

In this tutorial, we will take a look at how to create a super fun classic snake game in visual studio using C# programming language. I still remember this game from my old NOKIA phones, this game has gone through lots of different iterations over the years but the game is still lots of fun. We will be creating this awesome game in Visual Studio using the Windows Form Application template. We wont be using any game engines or external libraries to make this game. All you need is any version of visual studio and you can simply follow the tutorial through.

C# Flappy Bird Hunting Game MasterClass

Create a interactive shooting game with Flappy Birds

  • Use OOP to make the game
  • Backgrounds and Play Music
  • Work with Multiple Forms
  • & Much more ..

In this new course we will recreate the very popular game with a twist. We will create this game from an empty project to a fully compiled EXE file using Visual Studio. Click here to see the full course details.

This tutorial is based on a game created by Michiel Wouters @ https://www.youtube.com/watch?v=i6W-aGhlq7M. He made this awesome game and we have found it to be a very effective tool to teach coding. Therefore we are going to create a text-based tutorial around it. Michiel has a lot more online tutorials and you should check them out.

  • To create a snake game in visual studio
  • To create and manage an array of snake parts in the game
  • To spawn and respawn food across the screen
  • To detect hit test with the border and snakes own body
  • Start and restart the game
  • Keep score in the game
  • Manage the project and follow good programming practice by using comments and indentation
  • Using different OOP (object-oriented programming) classes to allocate the snake body and game controls
  • Using the system PAINT event to draw and animate SNAKE parts across the screen
  • Using Keyboard events and optimising the events to respond to up, down, left and right keys

New Updated Tutorial –

Written Tutorial –

Start a new project in Visual Studio. We will call this project SnakeGame. This project will be saved under the Documents folder / Visual Studio 2017 / Snake Game folder.

Click OK for the project to be created in Visual Studio.

Right click on the SnakeGame inside the Solutions Explorer, hover over Add, click on Class. We will need add a few classes for our game. Let’s set it up and then we can start adding the components for the game on Windows Form.

In the name box type Circle (Capital C) and Click add. Make sure the CLASS object is highlighted in the list not anything else.

The circle class has been added to the program. Visual Studio will also open the class file for us in the code editor. Let’s add the remaining classes for the game.

Add the following 2 classes now –

  1. Settings
  2. Input

Now we have all our classes added to the project.

This is a simple practice of Object Oriented Programming. We have created 3 classes for this project that can be imported or removed from the game dynamically, this process allows us to compartmentalize the programming therefore we will not be required to code everything in one file.

Now lets go in to the Design view for the form and change some property settings

Now we have our main game screen set, time to start adding the components to the game screen. In this game we will need the following

1 Picture box – which will be used as the main game area.

3 Labels – for various information to be shown on about the game.

1 Timer Object – This timer will be used as the main game engine

Drag and drop a picture box component from the toolbox to the form.

This what the picture box looks like now. This is an empty picture box added to the form.

Now change the following in the picture boxes properties. (When you select the picture box in the form it will allow you to change several options in the properties window. The Properties window is located right under the Solutions Explorer, if for some reason you cannot find it then right click on the picture box and select properties it will show up.)

Читать:
Io agora rtc что это за папка

This is the picture boxes properties window. Make the following changes to it in the properties window.

Name pbCanvas
Back Color Grey
Location 13, 13
Size 541, 560

This is what the picture box looks like after the changes we made to its properties.

Lets go back to the ToolBox and get some labels for the game.

Now add 3 labels to the form

In the properties for label 1 change the following

Font Bold, Size 14
Text Score:

Note to change the font in the properties window click on the three dotted … button in the properties window

In the properties for label 2 change the following

Font Bold, Size 14
Text 00

In the properties window for label 3 change the following

Font Bold, Size 14
Back Color Black
Fore Color Yellow
Location 215, 226
Text End Text

The main purpose for Label 3 is to show up when the game has ended and give some information. We will be changing the text dynamically using C#, so the End Text is only a place holder for now.

This is what the form looks like, now you can see that we have out Score text and a 00 text also we have the End Text in middle of the picture box.

Now let’s add a Timer to the form

In the Timer’s properties window make the following changes

Name gameTimer

You only need to change the of the Timer, the rest of the settings we need we can import them through the code later on. Nice Right!

We need several different types of Events to make this game work. We need a Key down, Key Up for the form and we also need a paint event for the picture box we added earlier.

Lets click on the form and make sure you haven’t clicked on anything else just the form and click on that little lightning bolt icon in the properties window to take you to the events window.

From the list lets find the Key Down and Key Up event

For key down type keyisdown and press and for key up type keyisup and press enter. They will take you to the code view but come back to the design view for one more event we need to add before going for the codes.

Click on the grey picture box on the form and in the events window find the Paint event and type updateGraphics

See the screen shot above.

Now with all the GUI components in place, lets start coding the game.

As you have followed thus far we have 3 different classes inserted in the game

Circle – This will be used to calculate the snakes head and body

Settings – This class will be used to check the height, width, speed and other default set ups for the game

Input – This class will be linked to the user input for example up, down, left or right

Lets start with Circle First

Double Click On the circle class and open in from the solutions explorer

Add the highlighted code from above. We are adding two different public INT classes in this Circle Class and then we have public circle function. The main purpose for this class is to give us the X and Y location of the snake object.

Since there might be a lot of back and forth between the code, it will be best if we explain the code in the comments.

// everything after the slash and colored green is a comment and we will be using this to explain the code for you.

The green text doesn’t affect the game in any way and is ignored by the compiler when the game is built so its ok to explain this here

Open the Input Class from the solutions explorer

Now to the Settings class

Now its time to look at the Form1.cs file. This is where we added the key down and key up event earlier.

This is the empty section now. These events don’t have anything in them to run the game for us. So we are going to add the contents to make this whole game work. Along with the empty events we have above we will be adding our own to make the game work as it should. So make sure you are following this part of the tutorial as close as you can. If you made any mistakes and visual studio throws an error at you come back and recheck the code.

We also need to the add some more functions to this game to make it work properly. We need to have another function called start game, move player, eat, generate food and die.

Lets take a look below

As you can see above we have added 4 empty functions for this game, all of this functions will complete a specific task for this game and we will be covering what goes inside of them in this tutorial. Make sure you pay extra attention to the open and closed curly brackets for this game as there are lots of them.

In the highlighted lines above we are adding two different variables but of the same class. This is a major benefit of using object oriented programming, we are able create two different objects by using the same class. Later in the program you will see how we can get them both to interact with each other.

Make the sure the lines are entered above the Form1() line. This means that both are Global Variables and they can be accessed from any function in this program. Although they both have the private initial in front they can be accessed from any function only from within this program. We cannot access them from outside the class.

Inside the Form1 function add the codes. This function runs when the form is loaded to the memory. In this function we have the initialize component function and we are also going to add our own instructions. We are creating a new settings instance and then we are adding the new values for the game timer object. The interval is like frames per second, in this case 1000 will be divided by the settings speed that was declared in the settings class. Then we are using a += to assign an EVENT to this timer tick. This EVENT will run each time the interval happens on the timer. We then start the game timer and run the start game function.

In MOOICT you have seen how to add an event from the events window, but this is a way to add an event to a component through pure code. Its much more effective to do it this way and sometimes it can save lots of time to implement.

Note – This event below has not been added through the designer so this will need to be added manually, because we are manually calling it so we will need to start with the private void again and type the whole thing over, or you can copy paste the even from below.

Above is update screen event that’s linked to our timer object. In the event first we are checking if the game is over then we ask the player to press the enter key to restart and then start the game again. However, if the game is not over then we can do more in this function. First we check the input of the player in up, down, left and right direction. We are running the move player function that’s defined later and then we are invoking the pbsCanvas (the picture box) invalidate function. This function allows us to refresh the picture box in milliseconds, so it looks like the snake is moving in the game area. If we don’t use this invalidate function then the snake will leave a trail of dots where it moves, this way we are going to clear any non-used graphics by the snake’s movements.

Above is the move player function. Since the snake has multiple parts or it can have once it starts eating. We have to ensure that the body parts of the snake follows it head. In this function we have also given it a limit of the games area where the snake can and cannot move to. We are also declaring when the snake collides with food then we can run the eat function.

Above is the key is down and up event we added to the form earlier. In both of them we are linking the input class’s change state function which will go through the hash table and return the keys back to us.

Above is the update graphics event we added to the Paint option for the picture box. As you probably have guessed we are painting all the graphics and then clearing it from the picture box. Therefore, we have used the pbCanvas.Invalidate() function in the timer event. This way we make it look like the player is moving the snake in the game smoothly. In this function we are setting the colours for head, body and food also we are setting up what happens when the game is over. If the game is over, we will show the label 3 on screen with the required information.

Above is the start game function. This function will run when the game actually starts. We are setting the default value for the game when it starts including setting up the head and adding it to the array.

Above is the generate food function. This function will generate the food icon on a random location in the game area.

Above is the eat function. This function will evoke when the snake and food collide. We are also going to add another sector to the snakes body and add it to the snake array.

Above is the die function. It does what it says, it will set the game over when it runs. Usually when the snake will either hit the borders or collide with the snakes body parts.

Now lets summaries what we done

  1. We have added the GUI components for this game
  2. We have added the events for this game
  3. We have created 3 external classes Settings, Input and Circle
  4. We have added custom events to the Form1.CS file
  5. We have created custom functions eat(), die(), movePlayer(), generateFood() and startGame().

Now debug the program either by pressing F5 or by clicking on the start button from tool bar

Final Game screens

If you encountered an error during this time, don’t be discouraged but come back here and try to find where the error is. Usually Visual Studio does an excellent job of tracking down the line number where the error has happened and then you can see what’s wrong with it. Most of the time it will be wrong name or spelling kind of stuff, but you can always come back here and check against the code.

Урок №14. Создание игры «Змейка» на C++/Qt5

Сегодня мы создадим аналог популярной игры «Змейка» на С++/Qt5.

Игра «Змейка»

Игра «Змейка» — это старая классическая видеоигра. Впервые она была создана в конце 70-х годов для использования на игровых автоматах, а затем в 1979 году её перенесли и на ПК. В этой игре игрок управляет тонким существом, похожим на змею, которое перемещается по игровому полю без остановки. Цель состоит в том, чтобы съесть как можно больше яблок, появляющихся в процессе игры. Каждый раз, когда змея съедает яблоко, она становится длиннее, что усложняет дальнейший процесс игры. Змея при этом должна избегать столкновений со стенами и собственным телом.

Разработка игры «Змейка»

Размер каждой отдельной «части» тела змеи составляет 10 пикселей. Управляется она с клавиатуры при помощи стрелочек: ← , → , ↑ , ↓ . Изначально тело змеи состоит из трех «частей». Если игра завершилась, то в центре игрового поля отображается сообщение «Game Over» .

Похожие статьи