*Source code* If you don't want to write the code yourself, it's available here for 3$ (and free for Patreon supporters): www.patreon.com/OttoBotCode/shop/78661 Your support would be a massive help for me and my channel! 😊
I have a snake game project, but my language is C++. I am just a first-semester student, and I don't know much about C++. 😢 Can you create a video, similar to how you do in C#, or guide me on how to convert this code into C++? I have only 10 days left for project submission, and my project is still pending.
I'm not done watching the tutorial yet! But I'm really appreciated it, that you've invested so much time and effort into making these Tutorial. Thank you so much for that! You're a real hero
I've been staring at this without doing it for so long, but today's the day! Thanks for making it - teachers like you make starting the journey for people who want to do this sort of thing so much better.
Hi Otto, I would like to say this tutorial is absolutely the best ever. Thanks and well done! I have modified my version to include a pause/resume feature and currently playing on a 32 x 32 grid. The longest snake I have to date is 176 cells. This took several minutes to construct but with the pause feature I was able to stop for a tea break halfway through. :)
Hi @@M-G112 Sorry I couldn't respond sooner. Maybe you have found a way to implement pause/resume in the meantime. But my approach was to introduce a new enum to track game mode (distinct from GameState): public enum GameMode { NotStarted, Started, Paused, Resuming, Over } The code looks for the space bar key press to enter 'Paused' mode if (gameState.Mode == GameMode.Started && e.Key == Key.Space) { mediaPlayer.Open(new Uri("Assets/intermission.wav", UriKind.Relative)); mediaPlayer.Play(); gameState.Mode = GameMode.Paused; return; } And another press of the space bar will enter 'Resuming' mode briefly before returning to 'Started' where the game play will continue from where it was interrupted. if (gameState.Mode == GameMode.Paused && e.Key == Key.Space) { gameState.Mode = GameMode.Resuming; return; } There are other code changes too but hopefully you get the idea. You can see them all in this github repo: github.com/rroostan/Snake/
Thats a nice Tutorial! One Tip: you can double a row of text by using ctrl+D. This speeds up code like: public readonly static Direction Left = new Direction(0, -1); public readonly static Direction Right = new Direction(0, 1); public readonly static Direction Up = new Direction(1, 0); public readonly static Direction Down = new Direction(-1, 0);
Just finished the tutorial today. Thank you so much for explaining each step and for making this video. It helps immensely in seeing what I still need to revise in my own understanding of the language and building confidence in seeing the bits and pieces coming together. I am a huge fan!! Thanks a lot and I will be going through the other tuts on your channel as well.
Man!! Thank you a lot! My first fream was write a game using C# and today I made it!!) I spend 4,5 hours watching you, but I did it!! Thanks a lot. I have then looked your videolist. And have seen, that you made my second dream. Write the chess!!! AAAAAA!! I am so happy right now! I will thank a world for your existance!) Good luck in your life and etc.)) Thanks a lot again
Dear OttoBotCode, Thank you so much for the video. You are explaining very well and the temp is good. I am still newbie in programming, but you are explaining in very understandable and helpful way. Before I started with the learning to code in c#, friend of mind recommended me to start to work under some projects following a step by step the professionalist. I am very glad that I found that your video. Thank you again for doing all this hard work. I followed all of your steps and I (thought I did the codes the same like you). Of course it is not the same because I have an issue for solving. Everything at the game goes at the way you did ( the colors, the snake, the food, the dead body snake, the counter from 3 to 1, the welcome text) except the important thing - the game it is not working prorerly(after the back counting the snake just dying and the game is restarting). It is not giving me any opportunity to move it. That was even when I wrote the codes with you. You showed that your game is working (I think may be from the 20min in the video) but mine did not moved at all. I reviewed and compared mine and your code tripple and everything seems the same as your. Of course I am sure I have missed someting😢. (By the way the 3 watching of the full video helped me to understand a lot of things). I decided to write you an comment, because I didn't find similar issue at the comments I read. The other think that I wanted to ask is - what I have to do to send the game to my friend to try it out? I tried, but on my computer is opening just on visual studio. Is it possible to set a instalation file, because I did not found it at the saved folder? I will be very glad if I receive your back comment. Thank you again for all your hard work under this project and thank you for sharing and helping people with it. Wish you many luck.
Thanks for the kind words! I cannot figure out what the problem is without seeing your code. If you are interested, you can send me your entire project to ottobotcodehelp@gmail.com (either as a github link or a zip). Then I'll take a look and see what I can find. When your game works, I can show you how to send it to a friend 😉
thank youu for this a great application. i made a few changes like, different types of obstacles, foods, health bar, game duration, pause/stop menu and notification bar. + snake can move from outside Movement: Use keys A, W, S, D for movement. Also, consider arrow keys (arrays) and the number pad if available. Special Movements: X Movement: Q: Move above-left. E: Move above-right. Z: Move below-left. C: Move below-right. Scoring: Animals: Bird: 1 point per second. Rabbit: 3 points per 3 seconds. Frog: 5 points per 5 seconds. Total hearts: 3. Wood obstacles deduct 1 heart, metal obstacles deduct 2 hearts. Game duration: 60 seconds. Mystery Box and Chances: If total second is less than 30 seconds: Either +10 seconds or -5 seconds. Else total second is greater than 30: 1. Increase total obstacles. 2. Decrease total obstacles. 3. Additional Hearth Notification Bar: Located above the game arena. Displays important information. Pause/Resume: Open/close the resume menu by clicking the Space key.
Thank you so much 🤩 I know it has been a little slow (lot's of things going on these past few months) BUT I am not stopping don't worry. I am working on the next video 😉
I think the glossing over nullables is probably a little bad for newer developers. Why did you disable it? Nullables are super useful, those warnings should be handled correctly - even if you don't anticipate nullref.
Hi OttoBotCode, thanks a lot. it is very good tutorial. i followed through with good understanding. 2 suggestions, 1) can you see some sound to it, when eat food, turn and die? as a next level tutorial. 2) consider teaching use how to make it an web app to put in online thanks anyway
Thanks for the suggestions 😊 Playing sounds is very easy. Just add an mp3 file to the assets folder. You have to set "Build Action" to "Content" and "Copy to Output Directory" to "Copy always". You can play the sound with the MediaPlayer class. MediaPlayer player = new MediaPlayer(); player.Open(new Uri("Assets/your_sound.mp3", UriKind.Relative)); player.Play();
HELP! At 19:48 it when you did the HeadPosition, TailPosition and also the SnakePositions I get the ERROR Code CS0050 (Inconsistent accessibility: return type 'type' is less accessible than method 'method'). And I did not know what do do so I put it to private for then but at 1:14:40 when you used the HeadPosition again I got the ERROR Code CS0122 ('member' is inaccessible due to its protection level) because it was private. I really need help because I am completely stuck. Thank you!
You need a special Tail .png or .svg for the End of the snake… maybe a triangle shape. A bit more work (especially changing direction of that Tail), but would be much more real.
Hey, I really love your content so far very high quality and informative. I unfortunately have been running into a problem for quite sometime now and can't seem to figure it out. At 44:34 is where I first start to have problems. Everything works up until then but, unlike you, when I run the program the empty grid image that is in the assets folder does not show up. I decided to continue till about 53:00 and the same issue still persits, none of the ImageSource images that are shown when you run it, show up for me. The images are indeed marked as "resource" and i have checked over most of the code. Any Ideas? Thanks
Thanks for the kind words! Perhaps you are loading your assets from the wrong path (in Images.cs). I am of course just guessing here. If you want me to take a look, then send your project to me at ottobotcodehelp@gmail.com. I'll see if I can find the issue! ☺
Great tutorial! My first time monkeying with WPF, I learned a lot. I thought of using the same system to display an old console app game of mine, but it's slow as molasses (and before making my own, I tested your game with a field as large as 120x70 and it was pretty fast). Any suggestion? Can I write you in private?
This game is optimized more for simplicity than for speed, but it's good to hear that it works okay for larger grid sizes. How big is the grid in your game? You can contact me at ottobotcodehelp@gmail.com 😊
I know the basics of C++ and C#, I've programmed applications like to-do, the hanged man, a textual game using classes, objects, pointers etc... and still I'm having a lot of difficulties understanding this code. Even if I searched it yet I don't understand what is an hashcode for example
Excellent course although I think it would be more instructive if various game elements e.g. adding head, removing tail, were implemented a bit later, during debugging. It's a bit overwhelming to implement all logic at the beginning for a beginner audience. Still, great content.
can somebody give me some advice? Mine works great but one error msg "System.NullReferenceException: Object reference not set to an instance of an object" on method named GetLastDirection
Anything is possible! Both ideas sound like a fun additions to the game. I think different types of food would be easy to implement. How would multiple snakes work? Will all snakes be controlled by the user? 😉
hello OttoBotCode ! I would like to say that your tutorial is amazing to understand C# syntaxt and principles. Although, I have a question : In the Direction Class, won't the lines where you initialize LEFT, RIGHT, DOWN, UP create a spiral and themselves create a Direction class that will repeat these lines etc? because you used "new Direction(0, -1)" won't this create a new Direction class? Thanks. PS : I'm french so my question could be badly formulated
The new keyword creates an instance of the given class and calls it's constructor. "Normal" class variables are instance variables, which means they belong to an instance (or object) of a class. Left, Right, Down and Up are static variables. Static variables belong to the class itself, so they will only be initialized once. There are simply 4 predefined instances of the Direction class. It is not the case that each Direction instance contains 4 other Direction instances. That would indeed be really bad! Thanks for the kind words ☺
@OttoBotCode in 50 min mark how did you auto generate the Window_Loaded and Window_KeyDown methods? It gives me an error once I try to make them my self, and I cant see where in the code you wrote them. Thanks in advance :)
Let's say you want to create an event handler for the KeyDown event. Type in KeyDown="", then the text should show up. When it does, simple hit return and the method will be generated for you 😊
Do you have the final project on Github? I have gone wrong somewhere and want to compare your code to mine. This will help to see where I have gone wrong
Everything was good until 44:00 minutes, the grids won't show. I still followed thru until the snake and food being draw, and nothing was there. I did it exactly like you, maybe something broke in these 2 years.
No it's working just fine for other people. The most common mistake is not marking your assets as resources - then they won't show up. In the assets folder, select all the images, right click and choose properties, then set "Build Action" to "Resource" (I show this around 2:40 in the video). Let me know if that solves the issue! 😉
@@alessandroesofago1837 The other problem is see quite often is people spell "Assets" wrong. Make sure that the folder is indeed called "Assets" and that the path in Images.cs is also correct. If that doesn't work, you can send your project to ottobotcodehelp@gmail.com and I'll find the problem for you 😊
Hello!!! you just gain a new subscriber here!!! I just wanted to ask a question on can you write a code so that every 10 food eaten the snake will get faster and faster? thank you!!!
Awesome, thank you 👍 You can create a variable for the delay in the gameLoop, which you change depending on the current score. For a concrete example, check out my Tetris tutorial. I do something very similar in the game loop for that project! 😊
At this part in the code under the gamestate class i am getting an error saying inconsistent accessibility for headposition, tailposition, and snakeposition. I have went over everything even rewatched your video up til this point to make sure everything was correct and it is and I can not figure out what is going on. Any ideas? public Position HeadPosition() { return snakePositions.First.Value; } public Position TailPosition() { return snakePositions.Last.Value; } public IEnumerable SnakePositions() { return snakePositions;
Hi Otto, Thank you so much for the tutorial. This helped me learn a lot about creating things in C#. I was using this to try and learn how to create windows and games in C#, however, what I want to do will need a lot larger grid then the 15x15 for snake. I was wondering if this method of creating and drawing the grid is scalable to something like H:350xW:1000? When I try to use large numbers with the code of the snake game (i.e H:200xW:400) the game window doesn't open.
Although it is convenient to use a UniformGrid filled with Image Controls, it's not great for performance. For very large grids, it won't work (at least not well). You need to find a different way of drawing the GameState if you want to use a large grid. I don't know what options are available for fast 2D drawing in C#, but I'm sure something exists.
Tutorial is fine, the animations are so helpful. However imo many things are maked so complicated. For exaple in part "Changing Direction Properly" you maked a few method and it could have been done like this: public void ChangeDirection(Direction direction) { if (direction != Dir.Oposite()) { Dir = direction; } }
That actually doesn't work. I try to explain why in the video. Let's say the snake is moving DOWN and I quickly press LEFT and UP. With your code both changes are accepted (neither one is an opposite). The snake will change direction to LEFT and then to UP before it moves. The result is that the game just ends 😉 I hope that makes sense. Try to use your code and replicate the scenario I just described.
@@OttoBotCode I didnt think about this i that way. Ok so we can wait for move and then Switch dir again. I Missed this info in video, sorry for confusion
HI! I got an error in the switch (e.Key). There is an error on the word key saying 'RoutedEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'RoutedEventArgs' could be found. What might be the problem? I'm not sure what I'm doing wrong so a help would be much appreciated!
Hi there, I’ve just emailed you again regarding my code. When I press any key to start the game the snake doesn’t move and dies on the spot. Do you know what I’ve done wrong?
I am completely lost :) My Snake turns dead just after one step. Can you share the source code? P.S. Step 1 - I've found an error, I just missed the loop in the GameLoop :). Step 2 - now I don't have a snake's head texture - I've just missed DrawSnakeHead() in drawGrid. Step 3 - snake's head not turning rightfully when moving to the left - Direction Left = 2700 instead of 270. Step 4 - score not updates at all - changed DrawGrid to Draw in MainLoop. Now all working perfectly :) I know how to add sound, but how to add background music in the loop?
Sorry for the late reply. Glad you made it work! 😊 It looks like you can do add background music using a "MediaTimeline". Check out the answer here: stackoverflow.com/questions/3148965/how-to-do-background-music-for-my-wpf-application
@@OttoBotCode It would be nice if you could cover some more comples sizers (like gridbag sizer and flexgrid sizer) and the wxGLCanvas widget. That would be awesome.
So far I am really enjoying this tutorial! However I have run into a problem that probably has a super easy fix but I just can't figure it out. At roughly 43:00 you input the code "GameGrid.Row = rows" and the same for column. My problem is it keeps saying that "GameGrid" doesn't exist. it is possible I missed where you created that, but I can't find where you did that.
GameGrid is the name we give the Uniform Grid in MainWindow.xaml. Make sure that your UniformGrid has the attribute x:Name="GameGrid" (I write it around 39:45). Hope this helps and good luck with the rest of the tutorial 😊
@@OttoBotCode Thank you for replying! It turns out I actually did name the Uniform Grid that, but after closing it and opening it, it seems visual studio has registered it properly now, so its all working now. Thanks again!
@@OttoBotCode Hey again, so I've run into another problem. for some reason, when you write the switch statement at 50:27 my one has a problem with the (e.Key) it keeps saying: " 'RoutedEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'RoutedEventArgs' could be found (are you missing a using directive or an assembly reference?)"
Excuse me, i to write your code and everything runs except my snake. It doesn't move anywhere. Can you help me please? I've looked at it several times but can't find any mistakes.
I Wrote all the codes right but when i want to run or debug the game the bar at bottom turns red and seems like freeze or stop the process and i cant play the game whats the solution?
Im having issues around 45:00 - 55:00 somewhere inbetween my code doesnt do the same as yours anymore since when i load the game nothing gets loaded anymore, i got the grid to work before but when i add the snake and the food and give the grid values it just opens the program with nothing, like no program opens at all
Never mind I got it to work but ill keep this here incase anyone has a similar issue so you don't have to respond as often, i solved my issue going back to the gamestate code and finding an issue i wrote there. In my case i had put: for (int c = 0; c
Hello Otto, I would like to thank you from the bottom of my heart about this guide but i would like to ask you if you can help me with a problem i got. Right now i am at 49:51 of the video and when i run the program it says Exceptions Unhandled in a small box, and behind a new screen pops up with the title Symbol Loading Skipped. Can you please help ?
You're very welcome 😊 I can try to help, but I need to see your code to figure out what's going on. Can you send your entire project to ottobotcodehelp@gmail.com? It can be as a GitHub link or a zip.
it is teling me Error CS1061 'KeyboardEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'KeyboardEventArgs' could be found (are you missing a using directive or an assembly reference?) Can you help thanks
@@OttoBotCode tks for the fast response..was because i didnt have the xaml designer..i close it i still dont know how to open...started a new project and its fine ! i finished the tutorial amazing !!!
Hello, i'm at 52:55, when i run the application sometimes the key presses do not work. And when they do, after i change the direction 3 times it stops working completely. Then the game "pauses"/freezes, not sure where i went wrong though.
The grid is made by displaying the empty squares next to each other. If it doesn't show up, it's most likely because your assets are not loading correctly. Double check that they are marked as resources and that you've typed their paths correctly in Images.cs 😊
Hello. Thank you for lesson. I started to learn c# 3moth ago. I did what you did until 1:00:00, but wheh I start project i see only square and inscription SCORE 0 from above. Maybe I don't tied up grid with main document or what can it be. In class Direction and Position i see ??? like :operator ==(Position? left, Position? ...) public override bool Equals(object? obj), maybe problem tied up with this?
The ? after the types indicates that they are "nullable". You can turn off the "nullable" feature (I show how to do it in the beginning of this video). Try turning it off and then generate Equals, GetHashCode, etc. again. That will get rid of those strange question marks. I'm not sure if this will fix your problem, if it doesn't just let me know 😁
Maybe the Window_KeyDown method in MainWindow.xaml.cs is not called. Try setting a breakpoint in that method and see if it's hit when you press a key. If the method is never called you are probably missing KeyDown="Window_KeyDown" in MainWindow.xaml (at 46:18 in the video). Hope this helps! If not you can send your code to ottobotcodehelp@gmail.com. Then I'll take a look and find the problem 😊
I've just updated my installation of VS 2022 and WPF is available! Open the "Visual Studio Installer" and "Modify" your installation. Under "Desktop and Mobile" make sure you have ".NET desktop development" installed.
That doesn't happen in my game. Maybe you have written something wrong in "AddFood" or "EmptyPositions" in GameState.cs? AddFood should only be able to pick a position which contains nothing
*Source code*
If you don't want to write the code yourself, it's available here for 3$ (and free for Patreon supporters):
www.patreon.com/OttoBotCode/shop/78661
Your support would be a massive help for me and my channel! 😊
private readonly Image[,] in mainwindow.xaml is not working on my project. It says that the type or namespace Image could not be found
I have a snake game project, but my language is C++. I am just a first-semester student, and I don't know much about C++. 😢 Can you create a video, similar to how you do in C#, or guide me on how to convert this code into C++? I have only 10 days left for project submission, and my project is still pending.
@@hamnaic good luck ... people are not here to do your homework.
@@jamesross3939Real
I'm not done watching the tutorial yet! But I'm really appreciated it, that you've invested so much time and effort into making these Tutorial. Thank you so much for that! You're a real hero
Thank you for the kind comment! ☺
I followed this guide as an intro to WPF during my studies.
Tempo was great, explainations were great. Overall a pretty fun video!
Great to hear, thank you!
I've been staring at this without doing it for so long, but today's the day! Thanks for making it - teachers like you make starting the journey for people who want to do this sort of thing so much better.
My first C# project!
Thanks @OttoBotCode!
Hi Otto, I would like to say this tutorial is absolutely the best ever. Thanks and well done!
I have modified my version to include a pause/resume feature and currently playing on a 32 x 32 grid. The longest snake I have to date is 176 cells. This took several minutes to construct but with the pause feature I was able to stop for a tea break halfway through. :)
You've made my day 🤩 Thanks for your comment and well done on the pause/resume feature!
Would you be willing to share pause implementation?
Hi @@M-G112
Sorry I couldn't respond sooner. Maybe you have found a way to implement pause/resume in the meantime.
But my approach was to introduce a new enum to track game mode (distinct from GameState):
public enum GameMode
{
NotStarted,
Started,
Paused,
Resuming,
Over
}
The code looks for the space bar key press to enter 'Paused' mode
if (gameState.Mode == GameMode.Started && e.Key == Key.Space)
{
mediaPlayer.Open(new Uri("Assets/intermission.wav", UriKind.Relative));
mediaPlayer.Play();
gameState.Mode = GameMode.Paused;
return;
}
And another press of the space bar will enter 'Resuming' mode briefly before returning to 'Started' where the game play will continue from where it was interrupted.
if (gameState.Mode == GameMode.Paused && e.Key == Key.Space)
{
gameState.Mode = GameMode.Resuming;
return;
}
There are other code changes too but hopefully you get the idea. You can see them all in this github repo:
github.com/rroostan/Snake/
@@RonRoostan thank you for the reply, I allready implemented the pause but it is nice to see how you went about it.
Thats a nice Tutorial! One Tip: you can double a row of text by using ctrl+D. This speeds up code like:
public readonly static Direction Left = new Direction(0, -1);
public readonly static Direction Right = new Direction(0, 1);
public readonly static Direction Up = new Direction(1, 0);
public readonly static Direction Down = new Direction(-1, 0);
Thanks for the comment and the tip! 😊
Thank you for listening to me!
And thank you for the suggestion 😀
Now you code in a much better speed. I only had to pause a few times. The flow is much better when I code along. Great video...thanks.
Super! Thank you for that comment 🤩
Just finished the tutorial today. Thank you so much for explaining each step and for making this video. It helps immensely in seeing what I still need to revise in my own understanding of the language and building confidence in seeing the bits and pieces coming together. I am a huge fan!! Thanks a lot and I will be going through the other tuts on your channel as well.
I'm so glad to hear that! Thanks for your comment 😊
Man!! Thank you a lot!
My first fream was write a game using C# and today I made it!!)
I spend 4,5 hours watching you, but I did it!!
Thanks a lot.
I have then looked your videolist. And have seen, that you made my second dream. Write the chess!!!
AAAAAA!! I am so happy right now! I will thank a world for your existance!)
Good luck in your life and etc.))
Thanks a lot again
Thank you so much! Glad you enjoy the videos 😊
Dear OttoBotCode,
Thank you so much for the video. You are explaining very well and the temp is good. I am still newbie in programming, but you are explaining in very understandable and helpful way.
Before I started with the learning to code in c#, friend of mind recommended me to start to work under some projects following a step by step the professionalist. I am very glad that I found that your video. Thank you again for doing all this hard work.
I followed all of your steps and I (thought I did the codes the same like you). Of course it is not the same because I have an issue for solving.
Everything at the game goes at the way you did ( the colors, the snake, the food, the dead body snake, the counter from 3 to 1, the welcome text) except the important thing - the game it is not working prorerly(after the back counting the snake just dying and the game is restarting). It is not giving me any opportunity to move it.
That was even when I wrote the codes with you. You showed that your game is working (I think may be from the 20min in the video) but mine did not moved at all. I reviewed and compared mine and your code tripple and everything seems the same as your. Of course I am sure I have missed someting😢.
(By the way the 3 watching of the full video helped me to understand a lot of things).
I decided to write you an comment, because I didn't find similar issue at the comments I read.
The other think that I wanted to ask is - what I have to do to send the game to my friend to try it out?
I tried, but on my computer is opening just on visual studio.
Is it possible to set a instalation file, because I did not found it at the saved folder?
I will be very glad if I receive your back comment.
Thank you again for all your hard work under this project and thank you for sharing and helping people with it. Wish you many luck.
Thanks for the kind words! I cannot figure out what the problem is without seeing your code. If you are interested, you can send me your entire project to ottobotcodehelp@gmail.com (either as a github link or a zip). Then I'll take a look and see what I can find. When your game works, I can show you how to send it to a friend 😉
لدي نفس المشكلة هل توصلتي الي حل؟
great video otto!! i havent watched more than 2 min but i can tell you but alot of hard work into this, great work luv from india!!!
Thank you! 😊
Just finished the project. Thanks for the tutorial, this was also a cool introduction to WPF.
Awesome! Thanks for your comment 😊
really good tutorial! helped me with my college project!!
thank youu for this a great application. i made a few changes like, different types of obstacles, foods, health bar, game duration, pause/stop menu and notification bar. + snake can move from outside
Movement:
Use keys A, W, S, D for movement.
Also, consider arrow keys (arrays) and the number pad if available.
Special Movements:
X Movement:
Q: Move above-left.
E: Move above-right.
Z: Move below-left.
C: Move below-right.
Scoring:
Animals:
Bird: 1 point per second.
Rabbit: 3 points per 3 seconds.
Frog: 5 points per 5 seconds.
Total hearts: 3.
Wood obstacles deduct 1 heart, metal obstacles deduct 2 hearts.
Game duration: 60 seconds.
Mystery Box and Chances:
If total second is less than 30 seconds:
Either +10 seconds or -5 seconds.
Else total second is greater than 30:
1. Increase total obstacles.
2. Decrease total obstacles.
3. Additional Hearth
Notification Bar:
Located above the game arena.
Displays important information.
Pause/Resume:
Open/close the resume menu by clicking the Space key.
I'm glad you enjoyed the tutorial. Well done on all the extra features, it's sounds like a really fun Snake game! 😁
@@OttoBotCode yeah it's. your role is undeniable
Thanks a Lot for this, I needed one project to complete personally in C# and that was my first one, thank you.
I'm glad you like it. Thanks for your comment!
Finally this type of videos return
You re the best bro , don t stop here. Tell us all you know, GOAT!
Thank you so much 🤩 I know it has been a little slow (lot's of things going on these past few months) BUT I am not stopping don't worry. I am working on the next video 😉
Thanks for this and the chess game tutorial. Added to my library.
Great tutorial, thank you so much!
This video is really great
Hope you will continue making games with c#
Thanks! There's a big project on the way 😉
appreciate the work you put into this
Awesome, greetings from France ! Thank you !
Idk why but I can’t get the snake to move but the code is the same
I think the glossing over nullables is probably a little bad for newer developers. Why did you disable it? Nullables are super useful, those warnings should be handled correctly - even if you don't anticipate nullref.
Great job. This would have been awesome if you did it using Avalonia UI which is very close to WPF and is cross-platform. This is just an idea.
I like this. Finally a real person. I'm so tired of the stupid AI voices and videos.
Glad you like it! Thanks for your comment 😊
Best video of making snake games
I will Like and Subscribe in my 10 devices
Very good video and easy way of coding
thanks a lot , i hope you will be doing such good coding videos
Thank you very much! 😊
Hi OttoBotCode, thanks a lot. it is very good tutorial. i followed through with good understanding. 2 suggestions, 1) can you see some sound to it, when eat food, turn and die? as a next level tutorial. 2) consider teaching use how to make it an web app to put in online thanks anyway
Thanks for the suggestions 😊
Playing sounds is very easy.
Just add an mp3 file to the assets folder.
You have to set "Build Action" to "Content" and "Copy to Output Directory" to "Copy always".
You can play the sound with the MediaPlayer class.
MediaPlayer player = new MediaPlayer();
player.Open(new Uri("Assets/your_sound.mp3", UriKind.Relative));
player.Play();
@@OttoBotCode awesome thanks! I was looking for that! Can you please explain why we use "content" in that case and not "Resource"?
HELP!
At 19:48 it when you did the HeadPosition, TailPosition and also the SnakePositions I get the ERROR Code CS0050 (Inconsistent accessibility: return type 'type' is less accessible than method 'method'). And I did not know what do do so I put it to private for then but at 1:14:40 when you used the HeadPosition again I got the ERROR Code CS0122 ('member' is inaccessible due to its protection level) because it was private. I really need help because I am completely stuck.
Thank you!
The properties have to public like you said. You are probably getting errors because your Position class is "internal" instead of "public" 😉
@@OttoBotCode Yep, That was the solution! Thank you very much, This deserves to subscribe
Hello can i get the whole copy of this game?
You need a special Tail .png or .svg for the End of the snake… maybe a triangle shape. A bit more work (especially changing direction of that Tail), but would be much more real.
Hey, I really love your content so far very high quality and informative. I unfortunately have been running into a problem for quite sometime now and can't seem to figure it out. At 44:34 is where I first start to have problems. Everything works up until then but, unlike you, when I run the program the empty grid image that is in the assets folder does not show up. I decided to continue till about 53:00 and the same issue still persits, none of the ImageSource images that are shown when you run it, show up for me. The images are indeed marked as "resource" and i have checked over most of the code. Any Ideas? Thanks
Thanks for the kind words! Perhaps you are loading your assets from the wrong path (in Images.cs). I am of course just guessing here. If you want me to take a look, then send your project to me at ottobotcodehelp@gmail.com. I'll see if I can find the issue! ☺
@@OttoBotCode Nvm fixed the issue, turns out i spelt "assets" wrong lmao
Great tutorial! My first time monkeying with WPF, I learned a lot.
I thought of using the same system to display an old console app game of mine, but it's slow as molasses (and before making my own, I tested your game with a field as large as 120x70 and it was pretty fast). Any suggestion? Can I write you in private?
This game is optimized more for simplicity than for speed, but it's good to hear that it works okay for larger grid sizes. How big is the grid in your game? You can contact me at ottobotcodehelp@gmail.com 😊
I know the basics of C++ and C#, I've programmed applications like to-do, the hanged man, a textual game using classes, objects, pointers etc... and still I'm having a lot of difficulties understanding this code. Even if I searched it yet I don't understand what is an hashcode for example
awesome stuff bro !!
Excellent course although I think it would be more instructive if various game elements e.g. adding head, removing tail, were implemented a bit later, during debugging. It's a bit overwhelming to implement all logic at the beginning for a beginner audience. Still, great content.
where is the right place to call SnackPositions() ?
this is very good
many thanks for your great effort
I'm glad you like it!
Amazing tutorial!
can somebody give me some advice? Mine works great but one error msg "System.NullReferenceException: Object reference not set to an instance of an object" on method named GetLastDirection
Thank you very much! This is awesome! May I ask you how can I save the score with a nickname?
thanks my brother 💙
thank you sir, it's very helpful
I'm glad you like it! Thanks for the comment 😉
Thanks a lot! you are awesome!
At 43:22 I Wrote GameGrid and a error appears it says does not exist in the current context
Would one be able to add one or two more snakes to the game, and also add different type of foods to make the game more dynamic?
Anything is possible! Both ideas sound like a fun additions to the game. I think different types of food would be easy to implement. How would multiple snakes work? Will all snakes be controlled by the user? 😉
@@OttoBotCode possibly multiplayer
really nice video! thank you
Thanks 😁 I appreciate it!
Could you please make tutorial about how to add a high score on the snake thank you.
Great Job! Thank you
Thanks for your comment 😀
Where is the part where the Food does not get placed on the Snake?
hello OttoBotCode ! I would like to say that your tutorial is amazing to understand C# syntaxt and principles. Although, I have a question : In the Direction Class, won't the lines where you initialize LEFT, RIGHT, DOWN, UP create a spiral and themselves create a Direction class that will repeat these lines etc? because you used "new Direction(0, -1)" won't this create a new Direction class?
Thanks.
PS : I'm french so my question could be badly formulated
The new keyword creates an instance of the given class and calls it's constructor.
"Normal" class variables are instance variables, which means they belong to an instance (or object) of a class.
Left, Right, Down and Up are static variables. Static variables belong to the class itself, so they will only be initialized once.
There are simply 4 predefined instances of the Direction class. It is not the case that each Direction instance contains 4 other Direction instances. That would indeed be really bad!
Thanks for the kind words ☺
hey! great video, im having trouble since this is kind of an old version , can u help and create an updated version? thanks!
I believe everything should work even with the newest version of C#. What kind of issues are you having?
@OttoBotCode in 50 min mark how did you auto generate the Window_Loaded and Window_KeyDown methods? It gives me an error once I try to make them my self, and I cant see where in the code you wrote them.
Thanks in advance :)
Let's say you want to create an event handler for the KeyDown event.
Type in KeyDown="", then the text should show up.
When it does, simple hit return and the method will be generated for you 😊
@@OttoBotCode Sweet thanks for the fast help, that fixed it :)
@@OttoBotCode Thanks, I was looking for that!
hey how could one make an 'easy gamemode' and once the snake hits the edge of the board it reapears on the other side?
Do you have the final project on Github? I have gone wrong somewhere and want to compare your code to mine. This will help to see where I have gone wrong
Everything was good until 44:00 minutes, the grids won't show. I still followed thru until the snake and food being draw, and nothing was there.
I did it exactly like you, maybe something broke in these 2 years.
No it's working just fine for other people. The most common mistake is not marking your assets as resources - then they won't show up. In the assets folder, select all the images, right click and choose properties, then set "Build Action" to "Resource" (I show this around 2:40 in the video). Let me know if that solves the issue! 😉
@@OttoBotCodei'm having the same problem, all the assets are marked as resources.
@@alessandroesofago1837 The other problem is see quite often is people spell "Assets" wrong. Make sure that the folder is indeed called "Assets" and that the path in Images.cs is also correct. If that doesn't work, you can send your project to ottobotcodehelp@gmail.com and I'll find the problem for you 😊
Scratch my last comment I figured it out. Thank you for this tutorial it is helping me alot!
Awesome! Thank you ☺
Hello!!! you just gain a new subscriber here!!!
I just wanted to ask a question on can you write a code so that every 10 food eaten the snake will get faster and faster? thank you!!!
Awesome, thank you 👍
You can create a variable for the delay in the gameLoop, which you change depending on the current score.
For a concrete example, check out my Tetris tutorial. I do something very similar in the game loop for that project! 😊
At this part in the code under the gamestate class i am getting an error saying inconsistent accessibility for headposition, tailposition, and snakeposition. I have went over everything even rewatched your video up til this point to make sure everything was correct and it is and I can not figure out what is going on. Any ideas?
public Position HeadPosition()
{
return snakePositions.First.Value;
}
public Position TailPosition()
{
return snakePositions.Last.Value;
}
public IEnumerable SnakePositions()
{
return snakePositions;
Hi Otto, Thank you so much for the tutorial. This helped me learn a lot about creating things in C#. I was using this to try and learn how to create windows and games in C#, however, what I want to do will need a lot larger grid then the 15x15 for snake. I was wondering if this method of creating and drawing the grid is scalable to something like H:350xW:1000? When I try to use large numbers with the code of the snake game (i.e H:200xW:400) the game window doesn't open.
Although it is convenient to use a UniformGrid filled with Image Controls, it's not great for performance. For very large grids, it won't work (at least not well). You need to find a different way of drawing the GameState if you want to use a large grid. I don't know what options are available for fast 2D drawing in C#, but I'm sure something exists.
Tutorial is fine, the animations are so helpful. However imo many things are maked so complicated. For exaple in part "Changing Direction Properly" you maked a few method and it could have been done like this:
public void ChangeDirection(Direction direction)
{
if (direction != Dir.Oposite())
{
Dir = direction;
}
}
That actually doesn't work. I try to explain why in the video. Let's say the snake is moving DOWN and I quickly press LEFT and UP. With your code both changes are accepted (neither one is an opposite). The snake will change direction to LEFT and then to UP before it moves. The result is that the game just ends 😉
I hope that makes sense. Try to use your code and replicate the scenario I just described.
@@OttoBotCode I didnt think about this i that way. Ok so we can wait for move and then Switch dir again. I Missed this info in video, sorry for confusion
@@OttoBotCode I found other solution for this. How can I contack with you to show code?
@@El_kammex You can send it to me at OttoBotCodeHelp@gmail.com. I'll take a look when I have the time 😉
If I buy full code via patreon for 3$ can I open it with SharpDevelop 4.4?
HI! I got an error in the switch (e.Key). There is an error on the word key saying 'RoutedEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'RoutedEventArgs' could be found. What might be the problem?
I'm not sure what I'm doing wrong so a help would be much appreciated!
i need help but must send photo to see the problem where can send photo and you see
Can i write this game in code blox? I use normal c language.
Hi there, I’ve just emailed you again regarding my code. When I press any key to start the game the snake doesn’t move and dies on the spot. Do you know what I’ve done wrong?
where is source code
Nice !
The code link no longer works, could you provide it?
Hey. May you tell which patterns of OOP do you use here, please?
Ocaml
what did you say in the first 10 min video about the key, the key is cntrl + ...... please tell me
dot/period "."
I am completely lost :) My Snake turns dead just after one step. Can you share the source code? P.S. Step 1 - I've found an error, I just missed the loop in the GameLoop :). Step 2 - now I don't have a snake's head texture - I've just missed DrawSnakeHead() in drawGrid. Step 3 - snake's head not turning rightfully when moving to the left - Direction Left = 2700 instead of 270. Step 4 - score not updates at all - changed DrawGrid to Draw in MainLoop. Now all working perfectly :)
I know how to add sound, but how to add background music in the loop?
Sorry for the late reply. Glad you made it work! 😊
It looks like you can do add background music using a "MediaTimeline". Check out the answer here:
stackoverflow.com/questions/3148965/how-to-do-background-music-for-my-wpf-application
Hello, can you give an example of components that we need to run this program. I mean processor, video card, RAM. I will very much appreciate it.
This little game should run on the cheapest hardware you can get your hands on. You need very little RAM and no dedicated video card is necessary 😊
Do you have any plans for videos MAUI? Looking forward for that
Potentially, yes! But first I have to learn about it myself 😉
@@OttoBotCode ♥
Still looking forward to see the upcoming C++ videos...
It will come! 😉
@@OttoBotCode It would be nice if you could cover some more comples sizers (like gridbag sizer and flexgrid sizer) and the wxGLCanvas widget. That would be awesome.
So far I am really enjoying this tutorial! However I have run into a problem that probably has a super easy fix but I just can't figure it out. At roughly 43:00 you input the code "GameGrid.Row = rows" and the same for column. My problem is it keeps saying that "GameGrid" doesn't exist. it is possible I missed where you created that, but I can't find where you did that.
GameGrid is the name we give the Uniform Grid in MainWindow.xaml. Make sure that your UniformGrid has the attribute x:Name="GameGrid" (I write it around 39:45). Hope this helps and good luck with the rest of the tutorial 😊
@@OttoBotCode Thank you for replying! It turns out I actually did name the Uniform Grid that, but after closing it and opening it, it seems visual studio has registered it properly now, so its all working now. Thanks again!
@@SarcasticCupcake223 You're welcome. "Bugs" like that seem to be a little too common in Visual Studio 😅
@@OttoBotCode Hey again, so I've run into another problem. for some reason, when you write the switch statement at 50:27 my one has a problem with the (e.Key) it keeps saying:
" 'RoutedEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'RoutedEventArgs' could be found (are you missing a using directive or an assembly reference?)"
@@SarcasticCupcake223 I probably need a bit more information to find the problem. If you send your code to ottobotcodehelp@gmail.com I'll take a look!
Excuse me, i to write your code and everything runs except my snake. It doesn't move anywhere. Can you help me please? I've looked at it several times but can't find any mistakes.
Send your project to ottobotcodehelp@gmail.com. I'll take a look 😉
Can I have the full code of the 3 classes plz
Hi,
Can someone please explain to me why we override equals?
I Wrote all the codes right but when i want to run or debug the game the bar at bottom turns red and seems like freeze or stop the process and i cant play the game whats the solution?
Do you get some kind of error message in the output window?
Awesome Project! 😎💪💪 Thank You so much!
Glad you like it and thanks for your comment!
gj you are great thx ;)
Is it possible to do the same things you did with xaml just using the editor tools and properties?
Thank you 😀 I'm not sure - I prefer to type in the code myself 😉
Can u share link of this projects guthub repo pls?
@OttoBotCode im having problem with this line "List empty = new List(Convert.ToInt32(EmptyPositions()));" in the AddFood() method
The line is:
List empty = new List(EmptyPositions());
Do you get an error when you use that?
Im having issues around 45:00 - 55:00 somewhere inbetween my code doesnt do the same as yours anymore since when i load the game nothing gets loaded anymore, i got the grid to work before but when i add the snake and the food and give the grid values it just opens the program with nothing, like no program opens at all
Never mind I got it to work but ill keep this here incase anyone has a similar issue so you don't have to respond as often, i solved my issue going back to the gamestate code and finding an issue i wrote there. In my case i had put: for (int c = 0; c
Hello Otto,
I would like to thank you from the bottom of my heart about this guide but i would like to ask you if you can help me with a problem i got. Right now i am at 49:51 of the video and when i run the program it says Exceptions Unhandled in a small box, and behind a new screen pops up with the title Symbol Loading Skipped. Can you please help ?
You're very welcome 😊
I can try to help, but I need to see your code to figure out what's going on. Can you send your entire project to ottobotcodehelp@gmail.com? It can be as a GitHub link or a zip.
it is teling me Error CS1061 'KeyboardEventArgs' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'KeyboardEventArgs' could be found (are you missing a using directive or an assembly reference?) Can you help thanks
Do you get this error in the event handler for the key down event? The argument should be"KeyEventArgs" not "KeyboardEventArgs".
Amazing Tutorial by the way !!!! Can anyone help me with this : The tag 'ViewBox' does not exist in XML namespace ???
Thank you 😃
It's Viewbox (with a lowercase b), maybe that's the problem.
@@OttoBotCode tks for the fast response..was because i didnt have the xaml designer..i close it i still dont know how to open...started a new project and its fine ! i finished the tutorial amazing !!!
Hello, i'm at 52:55, when i run the application sometimes the key presses do not work. And when they do, after i change the direction 3 times it stops working completely. Then the game "pauses"/freezes, not sure where i went wrong though.
You can send your entire project to me at ottobotcodehelp@gmail.com. I'll take a look and see if I can spot the problem 😊
for some reason the grid is not showing up when i run the code what exactly makes the grid and how do i fix it.
The grid is made by displaying the empty squares next to each other. If it doesn't show up, it's most likely because your assets are not loading correctly. Double check that they are marked as resources and that you've typed their paths correctly in Images.cs 😊
yes i forgot to set the build action to resource
@@OttoBotCode
Hello. Thank you for lesson. I started to learn c# 3moth ago. I did what you did until 1:00:00, but wheh I start project i see only square and inscription SCORE 0 from above. Maybe I don't tied up grid with main document or what can it be. In class Direction and Position i see ??? like :operator ==(Position? left, Position? ...) public override bool Equals(object? obj), maybe problem tied up with this?
The ? after the types indicates that they are "nullable". You can turn off the "nullable" feature (I show how to do it in the beginning of this video). Try turning it off and then generate Equals, GetHashCode, etc. again. That will get rid of those strange question marks.
I'm not sure if this will fix your problem, if it doesn't just let me know 😁
@@OttoBotCode I just did't do assets like resourse. I think, programing is not mine, I even can't repeat that have already been done(
im new to coding. but why cant i make the snake move? everything else is working but the snake wont move, it just goes straight and dies. pls help aha
Maybe the Window_KeyDown method in MainWindow.xaml.cs is not called. Try setting a breakpoint in that method and see if it's hit when you press a key. If the method is never called you are probably missing KeyDown="Window_KeyDown" in MainWindow.xaml (at 46:18 in the video).
Hope this helps! If not you can send your code to ottobotcodehelp@gmail.com. Then I'll take a look and find the problem 😊
Visual Studio 2022 has deadlined WPF. It's not available in Visual Studio anymore. Is there an alternative way to set up the project in VS 2022?
I've just updated my installation of VS 2022 and WPF is available! Open the "Visual Studio Installer" and "Modify" your installation. Under "Desktop and Mobile" make sure you have ".NET desktop development" installed.
@@OttoBotCode Thank you!!! :)
By the way i found a bug...sometimes food appears on snake body...did you notice ?
That doesn't happen in my game. Maybe you have written something wrong in "AddFood" or "EmptyPositions" in GameState.cs?
AddFood should only be able to pick a position which contains nothing
@@OttoBotCode yes i found it was missing IF condition GameGrid empty :) !! I will now try to implement new things then i share ! tks a lot
How to App.xaml add Snake proje?
47:43 i dont get what i have to do if it doesnt work