C# Tutorial - Create a Classic Snakes Game in Visual Studio with Windows Forms [UPDATED]

  Рет қаралды 75,846

Moo ICT

Moo ICT

Күн бұрын

Пікірлер: 136
@agdcodera3603
@agdcodera3603 2 жыл бұрын
Form - 3:48 Button - 4:52 Text Box - 5:23 Labels - 6:04 Timer - 6:55 Class - 7:24 Circle - 10:40 Settings - 11:59 Form Events - 8:14 Methods/Functions - 9:59 Form Codes - 13:30 KeyDown - 16:01 RestartGame - 18:27 UpdatePictureBoxGraphics - 23:49 GameTimer - 28:31 EatFood - 37:13 Gameover - 41.34 TakeSnapShot - 44:57 Increase speed of the snake - 56:05
@mooict
@mooict 2 жыл бұрын
Thank you 😊
@nishr.exe11
@nishr.exe11 Жыл бұрын
the goat
@0peter897
@0peter897 2 жыл бұрын
Thank You Very Much!!! I used c# before for one of my exams and i hated it. But now after this project I feel that it is fun to code in this language.
@lil_fanera
@lil_fanera 2 ай бұрын
Thanks for your video, I'm learning programming in C# and it's really helping me. I repeated after you, and then I analyzed the code that you wrote.
@mooict
@mooict Ай бұрын
Great job!
@simonwong7969
@simonwong7969 2 жыл бұрын
Hi ICT. Can i ask u about why my following step by step but my array is not functioning?
@keivvy3269
@keivvy3269 Жыл бұрын
hi, when i try to press the keys to change the directions of the snake, the keys do not work, may i ask know why?
@reyniercastano625
@reyniercastano625 Ай бұрын
That happens when the focus is on another control, key events might not be captured by the form. Go to Form properties and set KeyPreview to true, when done, you ensure that the form receives key events before they are passed to other controls. This allows you to handle key presses even if another control has focus
@yardleighLanthony
@yardleighLanthony 3 жыл бұрын
I had one last question as well, the in Settings.cs. What is the field directions = "Left" for? I was also confused about that as well. Thank you and have a great day.
@mooict
@mooict 3 жыл бұрын
Direction == "Left" is the default direction of the snake. You can change it to any of the other directions and it will run in those direction when the game loads up first.
@yardleighLanthony
@yardleighLanthony 3 жыл бұрын
@@mooict Oh okay, that also makes a lot of sense, many thanks :D. Have a great day
@Veshy
@Veshy 2 жыл бұрын
@@mooict how do I make it stay still and wait for input
@defaultyboi3189
@defaultyboi3189 3 жыл бұрын
hello Moo can you help me to fix something, apparently when I start the game I cannot control the snake. Thankyou in advance
@omegafala720
@omegafala720 2 жыл бұрын
36:30 Put X++ in Left
@MarcusAlsterfjord
@MarcusAlsterfjord 3 жыл бұрын
Thanks for this tutorial. Made me inspired to learn more about coding games.
@johncarmelosaloritos5086
@johncarmelosaloritos5086 3 жыл бұрын
Thanks for the tutorial Moo, I just wanted to ask how can I reduce the length of the snake?
@tyshoe
@tyshoe 2 жыл бұрын
If you are talking about the default length of the snake, he set his length to 10 by default at 23:31 on line 116. if you wanted to reduce the starting length, thats where you'd do it.
@bencabilete6408
@bencabilete6408 Жыл бұрын
Where parts of event arguments to move upward, the snake stop when i press up arrow keys
@iScreens
@iScreens 3 жыл бұрын
What keyboard switches do you have?
@mooict
@mooict 3 жыл бұрын
Gateron Yellows I use mainly.
@Soax-GameCenter
@Soax-GameCenter 7 ай бұрын
When I was starting the game for you the snake moved and you could control it but for me the snake did not pop on the screen when i clicked start. Plz help and explain why it is not working
@ledschmidt1441
@ledschmidt1441 9 ай бұрын
Hope you still check out the channel..... What is NUTs is, when the game starts, it flips the panel 90 so the snake is running vertical!! I checked all out and nothing... the canvas and panel when viewed from the form window is right, game starts and it flips it 90degrees AND i have no control of the snake unless I hold down two buttons at a time??? Nuts
@oli9944
@oli9944 3 жыл бұрын
Hello moo. Could you make a tutorial for a grid type of game in windows forms c#? For example, think Zelda 3 (link to the past) but with a grid, so we could later customize it to make turn based games, grid dungeons exploration, grid war strategic fighting, things like chess, etc. Just a simple grid in windows forms which we can then use to make our own customized games!
@mooict
@mooict 3 жыл бұрын
I've done a snakes and ladders game using a image grid may be that will help you. It's also a turn based game 👍
@oli9944
@oli9944 3 жыл бұрын
@@mooict I’ll check it out, thank you!
@yardleighLanthony
@yardleighLanthony 3 жыл бұрын
Good day :), I find your videos really helpful and fun, thank you for that. I just had a question regarding why you named one of the methods "KeyIsUp" and "KeyIsDown"? I am confused about the naming. I am a first-year student and just learning about programming in c# and I apologise if my questions sound dumb but why did you not make a method as well that is called "KeyIsRight" and "KeyIsleft", if I may ask?, and the "e.KeyCode" is a built-in function? for when you press a key if I am not mistaken? Thank you and have a great day.
@mooict
@mooict 3 жыл бұрын
Hi, key is down and key is up is created not for their direction but for the process. So the reason is called key is down in this example is because this event will trigger when the keys pressed down and. The key is up will trigger when the keys are released. We can access up down left right and all the other keys on the keyboard from inside of those events and we won't need to make the key is right or left extra events there. Hope this helps you
@yardleighLanthony
@yardleighLanthony 3 жыл бұрын
@@mooict Thank you so much for replying :), this is such a big help, it makes a lot of sense, thank you! Have a great day.
@israelblanco7490
@israelblanco7490 3 жыл бұрын
This was really fun to do, nice tutorial man :D
@your_daily_duas
@your_daily_duas 2 жыл бұрын
Amazing Video!! (I am just at 36:10) but i got an error and my snake won't move The Error is in Snake[i].X = Snake[i - 1].X; The Error says : System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Another point to ask could these problems happen because of Format Errors The Details (if you need them) System.ArgumentOutOfRangeException HResult=0x80131502 Message=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Source=mscorlib StackTrace: at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) at System.Collections.Generic.List`1.get_Item(Int32 index) at Snake_Game.Form1.GameTimerEvent(Object sender, EventArgs e) in C:\Users\acer\Downloads\Snake Game\Snake Game\Form1.cs:line 168 at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Snake_Game.Program.Main() in C:\Users\acer\Downloads\Snake Game\Snake Game\Program.cs:line 19 - Qanith (Don't Forget The tutorial was amazing looking forward to more :) )
@haovothanh5167
@haovothanh5167 3 жыл бұрын
Is there any way to adjust snake's speed ?
@mooict
@mooict 3 жыл бұрын
Yes, change the timer interval in the properties window to speed it up or down
@haovothanh5167
@haovothanh5167 3 жыл бұрын
@@mooict tks
@user-defined52
@user-defined52 8 ай бұрын
What if we add stop button to stop the game for a temporary period What is the code for that???
@yazanjordan3103
@yazanjordan3103 3 жыл бұрын
Please i need help i am Stuck in 39:14 i typed this code exactly as it is but it showing me an error Says ( Error CS0019 Operator '&&' cannot be applied to operands of type 'bool' and 'int') Why it that !!!??? Please help i need to finish this project it took me 3 days to reach here
@mooict
@mooict 3 жыл бұрын
Hi Yazan, this error is stating that the if statement is trying to compare a boolean with an integer. Is it the part when snake eats the food? If so both the snake[i].x == food.x are integer values in the game, check if this statement is the same on yours.
@yazanjordan3103
@yazanjordan3103 3 жыл бұрын
@@mooict yes thank you for ur answer !! saved me
@mrdummy_nl
@mrdummy_nl 3 жыл бұрын
Why is my VS 2019 showing in Size with semicolon and yours is with comma? Explain why there are differences, which can confuse some users. And also, mine might have some mods installed, cause the change. Somebody can explain it?
@mooict
@mooict 3 жыл бұрын
Which line is this in?
@guineapigtaco288
@guineapigtaco288 Жыл бұрын
Hi. Is there a way not to write full lanes of code in one file (form) ?
@dmmsdramamoviesmusicshows2390
@dmmsdramamoviesmusicshows2390 2 жыл бұрын
Please solve my problem.... The snake moves left and then when i press right arrow the game stops why......? How to solve this error
@mohammadd7811
@mohammadd7811 3 жыл бұрын
Thank you for this tutorial , i have question here " canvas.FillEllipse(snackColor, new Rectangle( Snake[i].x * Settings.weight, " why did we multiply Snake[i].x with Settings.weight ?I'm not understanding what this is for
@mataszelvys111
@mataszelvys111 2 жыл бұрын
I have a problem when i type Settings.directions it shows that were is an error and error says 'Settings' does not contain a definition for 'directions'
@mooict
@mooict 2 жыл бұрын
You will need to add the directions enum to the settings class. It’s explained in the tutorial.
@wolfsbane8904
@wolfsbane8904 3 жыл бұрын
yet another question from me, and i am so so sorry to bother you this much: When i am at that part where we are adding "if (Snake[i].X == Snake[j].X && Snake[i].Y == Snake[j].Y)" { GameOver();} " [this is at 43:10 in video] i get following code: System.ArgumentOutOfRangeException: 'intex was out of range.Must be non-negative and less than the size of collection. Parameter name:index'. Thank you in advance, and i love how helpful you are, needless to say you have new sub.
@reyniercastano625
@reyniercastano625 Ай бұрын
That happen when the for loop is assigning values to either X or Y that don’t exist in your snake. Try using the debugging tool to identify exactly where things are going wrong
@maneharutyunian7430
@maneharutyunian7430 2 жыл бұрын
I want to write the game with levels and in each level the speed of the game is going to be changed and some obstacles is going to be appeared. I think that there is no need to create new forms for each level, but the modification can be done in general form. Could you help me with that task?
@nxkes3208
@nxkes3208 2 жыл бұрын
how to get your solution explorer on the side
@tranduykhanh2451
@tranduykhanh2451 Жыл бұрын
How can I reduce the snake's speed?
@Realv311
@Realv311 2 жыл бұрын
Why I have to clicks the start button forever if didn’t snake don’t go and if I clicks 1 time it will go 1 time so is that any with random could u reply plz🙏🏻
@yuno9848
@yuno9848 7 ай бұрын
Can I use the same code for C++?`
@Pilgrim182
@Pilgrim182 3 жыл бұрын
Can I make this on VisualStudio 2013?
@mooict
@mooict 3 жыл бұрын
Yes
@flashbackcat4664
@flashbackcat4664 2 жыл бұрын
I got a problem in food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight)}; when i run it says System.ArgumentOutOfRangeException: ''minValue' cannot be greater than maxValue. Parameter name: minValue' any solutions?
@adityapratapsingh2373
@adityapratapsingh2373 2 жыл бұрын
Same here How did you solve it?
@arhamkhan7424
@arhamkhan7424 2 жыл бұрын
What Extensions do i need to install??
@haovothanh5167
@haovothanh5167 3 жыл бұрын
what is picCanvas ? my VS notified me " the name "picCanvas" does not exist in the current context"
@mooict
@mooict 3 жыл бұрын
Change the picture box name to picCanvas in the properties window. That will solve the error.
@haovothanh5167
@haovothanh5167 3 жыл бұрын
@@mooict tks much
@snizel8
@snizel8 5 ай бұрын
Thanks for this tutorial.
@mooict
@mooict 5 ай бұрын
Glad you liked it
@miruna3465
@miruna3465 9 ай бұрын
Hi there! Thank you so much for posting this tutorial, the game works great for me and i’m pretty much a beginner. I was wondering what i would have to do to add obstacles for the snake to avoid, would it require another private void? Or what about adding a border for the snake to avoid?
@kentmetante7238
@kentmetante7238 Жыл бұрын
how can i slow it down mine is way too fast
@cameron7757
@cameron7757 3 жыл бұрын
This tutorial was awesome! Thanks a ton
@whallieoo
@whallieoo 3 жыл бұрын
In the "private void button1_Click(object sender, EventArgs e)" section the "KeyCode" command doesn't work for me. Any ideas of whats wrong?
@mooict
@mooict 3 жыл бұрын
It's the wrong event for key code. You are doing keyboard event code inside of the mouse click event. Do the keycode inside of the keydown function.
@whallieoo
@whallieoo 3 жыл бұрын
Got ya, thx!
@julitawojcik9994
@julitawojcik9994 2 жыл бұрын
Hi! Thanks for your amazing job. I am thinking of adding a pause button to the program, but the active button is blocking the movement of the snake. Could you give me any tips how to do it?
@mooict
@mooict 2 жыл бұрын
Having a pause button will take the focus away from the form. I think it will be better for you to have the pause function linked to a key down event. For example press p to pauses.
@joaosantos1582
@joaosantos1582 2 жыл бұрын
Hey Moo! When I start the project, it gives me back an error in the "private void RestartGame() maxHeight.Height/Settings.Height - 1;" saying System.DivideByZeroException.....What does that mean??? Because I can't start running the game! But when I look down to the errors area, it tells me that I don't have any errors...
@adityapratapsingh2373
@adityapratapsingh2373 2 жыл бұрын
Same here How did you solve it... Please tell. Ms
@deadropfurman1694
@deadropfurman1694 Жыл бұрын
Hey mate, i just wanted to know, why doesnt the Timer do anything? I expected that after 40 second the game would be over, but it play indefinitely, or did i mistake about what the timer actually does?
@mooict
@mooict Жыл бұрын
Hi the timer acts as the main game loop, it runs the entire game including the move Kent of the snake, updating the body of the snake, spawning the food and finally the user controls. The value 49 used in the timer properties is to set an interval so it ticks every 40 milliseconds and each time it will run the timer event. Hope this helps
@deadropfurman1694
@deadropfurman1694 Жыл бұрын
@@mooict Oh, thanks, it actually does help, i thought about expanding the game (cause my course project demands inheritance), one of the things i thought about was making certain foods that increase movement speed (i suppose the interval will affect that), but if i wanted to add a timer, like a real one for the game duration, where would i put it? Thanks!
@srilekhagr1147
@srilekhagr1147 Жыл бұрын
What is the front end and back end
@mooict
@mooict Жыл бұрын
Both
@niamacb8271
@niamacb8271 3 жыл бұрын
Hello, your video really helps me a lot. Just a little question here, is there any way to prevent the overlapping of food on the snake body when the food spawn on the map?
@comebackguy8892
@comebackguy8892 2 жыл бұрын
Use a while or do-while loop that loops if the food intersects with snake. The food will in other words continue to try and randomize a spawn until it does not touch the snake.
@laytonyeow1029
@laytonyeow1029 2 жыл бұрын
Hi, is there anyone that can fix this for me. "my snake body was stacking on each other" although my code is totally the same as the video. Thus, you only can see two circles moving around. @Moo ICT.
@christiandominicbaran
@christiandominicbaran Жыл бұрын
Thankyou so much for this new subscribers here from Philippines ❤❤❤
@mooict
@mooict Жыл бұрын
Hello 👋 and welcome 🤗
@wolfsbane8904
@wolfsbane8904 3 жыл бұрын
Hello, first of all thank you so much, but i have two problems, first at 35:18 when you attempt to press start, i followed your every step but i get error "Cannot impicityl convert type 'int' to 'bool' " error line is this one :"if (Snake[i].Y = maxHeight)" Second problem is , when i attempt to press start, it says it cannot find "mygame".exe within debug subfolder also "please build te project and retry, or set the output path and assemblyname properties appropriately to point at correct location for target assembly. I am sorry for my ignorancy, i am VERY new to any of this, and i thank you greately in advance.
@wolfsbane8904
@wolfsbane8904 3 жыл бұрын
Never mind, i instantly figured out after i posted. i placed same code twice, instead Snake[i].Y > maxHeight [not equal to but bigger than] and it also fixed other issue
@mooict
@mooict 3 жыл бұрын
Good job 👍
@umeshchaudhary4395
@umeshchaudhary4395 2 жыл бұрын
I try this tutorial but i get error how i can learn
@kriskata7653
@kriskata7653 3 жыл бұрын
19:03 Hey can someone please explain me with simple words what these 2 lines of code does. Why do we divide the picCanva's width and height by the settings's width and height -1 ?
@MarcusAlsterfjord
@MarcusAlsterfjord 3 жыл бұрын
It is to calculate number of parts that fit in the canvas. In my case maxWidth 442 / 16 and maxHeight 563 / 16. You can think like a grid divided in parts of 16 pixels.
@kriskata7653
@kriskata7653 3 жыл бұрын
@@MarcusAlsterfjord Thanks
@TheRocketTurtle
@TheRocketTurtle 2 жыл бұрын
how did you get the toolbox
@campbellardern9710
@campbellardern9710 3 жыл бұрын
Does this work in Visual Studio 2017?
@mooict
@mooict 3 жыл бұрын
Yes
@davidvarga9872
@davidvarga9872 2 жыл бұрын
Hey! Your code is very good but there are 2 Errors for me that doesn't appear in your code but I don't know how to fix it, however I have the same code as yours. Cannot assign to 'KeyDown' because it is a 'method group' and there is another for the KeyUp. What could be the solution here?
@mooict
@mooict 2 жыл бұрын
Delete the existing keydown and key up event from the code and try adding them again. If the designer gives an error you may need to delete them from the designer code as well.
@davidvarga9872
@davidvarga9872 2 жыл бұрын
@@mooict Thanks it worked
@mataszelvys111
@mataszelvys111 2 жыл бұрын
@@mooict i have problem too when i type directions it shows that this command dosent exist
@hichemebengaied4394
@hichemebengaied4394 2 жыл бұрын
Hi ! I have a little question, how do we decrease the speed of the snake ? :)
@ghostnoodle9721
@ghostnoodle9721 2 жыл бұрын
One way to do it with almost no effort and little repercussions is to increase the gametimer (6:48) from his recommended "40" to a slower "55"
@noreenmorrisfalk8074
@noreenmorrisfalk8074 2 жыл бұрын
Hi, can anyone help with adding code so that the snake gets quicker as time expires or after it has "eaten" x amount of food?
@VoxelStudios1093
@VoxelStudios1093 Жыл бұрын
In EatFood() Put This: gameTimer.Interval -= (How Much Faster You Want it to go)
@xucxichuc325
@xucxichuc325 2 жыл бұрын
You're a hero! Thank you so much
@mooict
@mooict 2 жыл бұрын
You're welcome!
@miszellleq
@miszellleq 2 жыл бұрын
does size of form1 have to be 764; 764?
@mooict
@mooict 2 жыл бұрын
No, it doesn’t have to be that size.
@yusuftopcu7426
@yusuftopcu7426 2 жыл бұрын
Can I also use the same Code for WPF?
@mooict
@mooict 2 жыл бұрын
I haven't tried it for WPF. It could be used for that.
@cryxalys7985
@cryxalys7985 2 жыл бұрын
can you make this game into .exe?
@lilkano4271
@lilkano4271 2 жыл бұрын
If the snake eat the food. he is not becoming biger pls help
@mooict
@mooict 2 жыл бұрын
Inside of the EatFood() function there should be a new circle created for the snake body and added to the existing snake as the body. First check if have those two instructions in the function, second does the food appear again on another location after its been eaten?
@lilkano4271
@lilkano4271 2 жыл бұрын
@@mooict Yes i have the new circle create for the snake body. And yes the food appears on a another location. But the snake will not becoming biger. also there are some points under snake.count in the code.
@lilkano4271
@lilkano4271 2 жыл бұрын
I fixed everthing the only problem is that If i make a snapshot Its all black if I open it
@chrisrodriguezm13
@chrisrodriguezm13 2 жыл бұрын
When I was coding something, my UI randomly disappeared because there were unknown errors but then I fixed it
@prhman1498
@prhman1498 3 жыл бұрын
I find your videos really helpful and fun, thank you for that
@lillyafton8147
@lillyafton8147 2 жыл бұрын
when i put else it puts 6 errors
@mooict
@mooict 2 жыл бұрын
What type of errors are you getting?
@اختراقوفضائحالعرب
@اختراقوفضائحالعرب 3 жыл бұрын
how to decrease speed of snack
@alexalexsandrovi4754
@alexalexsandrovi4754 2 жыл бұрын
Thank u! This tutorial helped me a lot.🙂🙂🙂
@mooict
@mooict 2 жыл бұрын
Glad it helped!
@chrisrodriguezm13
@chrisrodriguezm13 2 жыл бұрын
For me, the graphics just showed up NOTHING
@orytzhakian9326
@orytzhakian9326 Жыл бұрын
hi thank you so much for this tutorial i have a quick question can i insted of no boarders on the edges can make it finish the game??
@Countex21
@Countex21 Жыл бұрын
Perfect video
@mooict
@mooict Жыл бұрын
Glad you think so!
@GablameH
@GablameH 2 жыл бұрын
Perfect 🥰💝
@antonioaguilar2246
@antonioaguilar2246 2 жыл бұрын
Thanks bro Uwu
@DaveLight395
@DaveLight395 3 жыл бұрын
There should be a protection against spawning food in your body. Otherwise nice tutorial :)
@shibainuxdogocrash1260
@shibainuxdogocrash1260 3 жыл бұрын
I CAN'T EXPALAIN IN WORD WHEN MY HALF GAME WAS RUN😊😊
@МаркоШћекић-я3ы
@МаркоШћекић-я3ы 2 жыл бұрын
We will not change you
@mooict
@mooict 2 жыл бұрын
Haha thanks
@stephenhenderson7546
@stephenhenderson7546 3 жыл бұрын
nice
@mooict
@mooict 3 жыл бұрын
Thank you ☺️
@actionreactions6667
@actionreactions6667 2 жыл бұрын
lol funny now can u actually show how to make a snake game?
@Jde-xv5oz
@Jde-xv5oz 3 жыл бұрын
First
@mooict
@mooict 3 жыл бұрын
Nice 👍
@ralphplays1601
@ralphplays1601 2 жыл бұрын
System.DivideByZeroException: 'Attempted to divide by zero.' whyy
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН
C# Tutorial - Make a flappy bird game in windows form
26:20
Moo ICT
Рет қаралды 317 М.
Intro to WPF: Learn the basics and best practices of WPF for C#
1:10:34
Programming a Snake Game in C# - Full Guide
1:22:02
OttoBotCode
Рет қаралды 174 М.
C# Events - Creating and Consuming Events in Your Application
1:09:13
Intro to Windows Forms (WinForms) in .NET 6
1:35:50
IAmTimCorey
Рет қаралды 241 М.
C# Змейка в консоли / .NET Console Snake Game
29:06
Dmitry Stopkevich
Рет қаралды 31 М.
10. Memory Game with Windows Forms! | Intro To C# Programming
36:02
Michael Hicks
Рет қаралды 114 М.
Programming a Tetris Game in C# - Full Guide
39:34
OttoBotCode
Рет қаралды 212 М.
Creating a C# Application: From idea to finished product
2:01:33
IAmTimCorey
Рет қаралды 824 М.
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН