CHESS! // Code Review
Vložit
- čas přidán 27. 07. 2024
- The first 1,000 people to use this link will get a 1 month free trial of Skillshare: skl.sh/thecherno11211
Patreon ► / thecherno
Instagram ► / thecherno
Twitter ► / thecherno
Discord ► / discord
Code ► github.com/JuUnland/Chess
Send an email to chernoreview@gmail.com with your source code, a brief explanation, and what you need help with/want me to review and you could be in the next episode of my Code Review series! Also let me know if you would like to remain anonymous.
Chapters:
----------------
0:00 - What we're looking at today
5:11 - Playing chess (testing the game)
8:13 - Initial look at the code
12:48 - Allocating and using class objects better
16:20 - Event-driven application design
17:16 - The performance issue with the main loop
19:57 - Examining more code
24:05 - Why I like to avoid tuples
27:15 - Blurry chess pieces
28:48 - More code
34:53 - Chess piece class hierarchy
38:50 - Calculating possible moves
43:15 - How I would calculate possible moves
46:18 - More thoughts and code
47:57 - Creating and handling pieces better
50:08 - Outro
This video is sponsored by Skillshare.
#CodeReview
Thanks for watching! Code Review album drops next summer 😎 Don't forget that the first 1,000 people to use this link will get a 1 month free trial of Skillshare: skl.sh/thecherno11211
Couple things I missed in the video:
- The king and queen positions are flipped! Not sure how I managed to not notice…
- Castling _does_ actually work, but you have to drag the king onto the rook - I’m used to castling by dragging the king two spaces over, which doesn’t work in this game
Ready enjoyed the song lol
Слушай, как насчёт рассказать как ты переехал в Австралию?
I believe I'm owed some royalties. Sunglasses McCoolguyface is _my_ thing!😡... 🤪 😎😎😎
Btw, I need that compressor in my life. Where can I get one?! If you don't know what the hell I'm talking about, just point me to your audio person. Thx in advance.
Oop is not the only way... It's just the only way that is _correct!_ again, 😂... No more, I promise.
Okay I didn't expect you to go this HARD on singing
It was so good as well!
@@Keregosh Did he use autotune?
@@emty5526 I have no idea xD
It was great! Except for the last bit
i sang along, it made my day!
When my man played the bong cloud I knew he was a man of culture ♟️
I'm into chess and programming and now I like him even more.
Cue Hikaru bongcloud speedrun intro.
Hahaha
"What are we thinking... like, Bongcloud opening, probably?"
Ah, I see you are a man of culture as well.
Next video: How to build C++ projects and setup a git repo
(Best clip btw: czcams.com/users/clipUgkxtL5J8amsZAOkbza7ucYwc6EDEAQEaEQ7 )
This would be so important!
would be cool
Yes
Create new repo, clone locally. Create cpp project in another directory. Then copy entire project to the repo dir. Done.
I want this
Hey, did you try clicking on the king and then on the rook? I think that might trigger castling, since when you clicked the king, it showed the rook square as a possible option.
We do see a MoveType CASTLE so I also guess it's there somewhere (haven't finished watching.. just noticed it now and ran to comments :P )
This annoyed me so much xD. Cherno bashing so hard on not being able to Castle. It's more an intuitive problem than it not being there. But ah well.
@@AgentM124 I think moving two squares with the King is like the fundamental principle of castling and “moving to the rook” is more of a quality of life improvement. Which is probably why Cherno’s assumption that castling didn’t exist is a valid one.
@@blablabla7796 the fundamentals of castling isn't to put your king behind the pawns in the corner and your rook into play?
@@AgentM124 the concept of castling is moving your King by two squares in one move provided the following conditions are met:…. The same as moving your pawn from the 2nd or 7th rank to the 4th or 5th which is two squares in a single move given the following conditions … respectively. The idea is that they are special moves that typically involve multiple moves but only take a single move if certain conditions are met. The king swapping positions with the rook somewhere in the middle is more of a derivative idea based on the previously mentioned underlying concept as a way to better visualize the move.
SVG (Vector) Images are perfect for these kind of simple textures, small filesize and scalable and supported in SDL
I like how he never realized that the queens and kings were placed incorrectly on the board.
Would really love to see Chess made in Hazel2D!
@@J3ekir Same lol
I too saw that.
Its not, its just turned around
@@kalilinuxuser972 king and queen need to swap or the colors need to flip
I literally thought you were trying to castle with the queen, because it was in that position 😂
I'm about 8 minutes into the video and I just couldn't hold back. How did no one notice that the kings and queens starting positions are switched. I wouldn't have noticed until the Cherno started playing. Maybe you'll point that out later in the video but ahhhh.
Haha lol good point! I totally missed that! I guess I didn’t notice because it changes depending on which side you play, and I must not have paid too much attention to the colours since I was playing myself here
Actually the pieces are on the correct coordinate but the color of the squares are "wrong".
If you imagine the coordinates, White's King is on e1 and Black's King is on e8 which is correct. Changing places would make kings start on the D-file which would be completely wrong.
The rule "White's queen on white square and Black's queen on black square" can't overrule the coords, in order to make it right, black pieces should be arranged on top of that board and white pieces on the bottom of it.
@@ScorpionG4merBr I'm not quite sure I understand what you mean by the coordinates. Currently the kings are on the D file. The only problem with the layout is that the respective kings and queens need to be switched around.
I don't remember exactly my line of thought but you're right.
Sorry for the confusion.
I love how he just instantly understands every function/class, tears it down and reduces the CPU usage by 99% in the first 5 mins of seeing the code 😂
Pretty sure he did castling but you need to drag the king to the rook..
Ya I saw the rook light up so it seemed like it was working.
I was so annoyed by this hahaha
Well, that would be misleading interface...
if he played chess often he'd realize absolutely no chess clone does that, you have to drag the king two squares (3 squares if it's on queen side) close to the rook to trigger castling
As a full time C++ dev i can only say excellent code review! You pointed out all of the major pinpoints with an easy to understand explanation on why and how to improve it without going into any super advanced C++ topics that would easily confuse & overwhelm a beginner programmer. Great Job! I wish i had someone like you when i was first getting into C++.
I think one of the biggest design problems in the code that you missed is that they didn't decouple the rendering stuff from the actual chess engine
Exactly what I thought
A video on building c++ code and about build systems will be great. The main problem for people is that they don't understand how compilation and linking works. And how to deal with libraries.
Btw loved your voice 😋
I second this so much. I really wanna learn CMake as a linux user but it's just so complicated and there are pretty much no tutorials that go beyond the very basics
YESYESYES
Yes would love to see that too!
Yes this would be very helpful
Build systems would be extremely helpful. I never understood it.
Another vote for a video on build and distribution processes.
I also like how you separate your own opinions on code from actual issues in the code.
Very tough to see king and queen in the wrong place at the start of every game. Otherwise very cool project and great review!
Lets be fair, most of the projects on github (including big name ones) have many of the same issues - missing files or the expectation that the person building the code has just the right version of python / ninja / environment paths / ceiling cat set up. A huge amount of pain and wasted time would go away if we could solve this. My steps when I'm about to put anything out public is to take a totally fresh windows/linux/mac install as necessary (a vm is fine) and then see what it takes to build / run the thing I'm putting out. I document everything needed at that point and either "fix" stupid requirements and start again or ensure all steps are clearly documented.
Docker is the way
@@sebastianmorris5394 It's really not though, I've had just as many issues trying to install docker versions of things as non docker versions. It just adds yet another layer of potentially broken stuff. The few times I have deployed something docker based that worked right away broke within a few weeks after an update was required and pushing that update either to docker or to the thing itself left it so broken I had to start back from scratch.
@@Ken-Creates you're probably not being specific enough with your yaml file container versions
@@sebastianmorris5394 Haha, I'll take that as agreement that it's not the way. 😆
@@Ken-Creates ok kiddo
I just want to say, that seeing the way you go through the code, how quick you are and all looks so damn cool holy shit-
I love you videos
This is what I'm looking for on CZcams. Really learned a lot on writing clean codes. Thx!
This is so entertaining to watch as a programming student. I'm looking forward watching more code reviews 🧐
Please more singing, I love it 😂
18:15
Everyone chilling while cpu7 is dying
18:33
Cpu7: my suffering is finally over, i am out of event polling hell
😅
I just checked the github repo, and dude didn't even made that fix. wtf. Why send code for review and then not listen to the recommendations. 🤦♂️
The build system in C++ is one of the reason I moved to Rust. Everybody does things differently and it's so hard to put the pieces together. Most of the people uses CMake, so it makes things just a little bit easier, but it's always terrible =/
Backend eng here, which uses python, cpp, dotnet, and rust. I love cpp, but not the build system lol. I don't know why no one in 20+ years streamlined this process with a standard. If anyone is interested I created some cmake templates for sdl2 and sfml which can make life easier for simple game dev projects. Is a work in progress. Would love feedback, so far every template works on windows and Linux. Need to write docs for running.
autotools is also fairly common. its amazing once it gets working (it can make porting things into an almost trivial task in some cases), but having to mess with it is an absolute pain.
Best code review to date. Thanks!
I like how he never realised that he could castle the king because in the MoveType there was castle in the list, probably when he tried the game he couldn't castle because he had to drag the piece on top of the rook, but this is irrelevant, beautiful video!!!
Even if you have a constant (like 8 tiles per row), it's good to use a constant instead if you're gonna type if more than once so that you know exactly what that 8 is. Maybe there are other things that also have the value 8. It will help you understand your code.
That's true a lot of the times, but in a situation where you are writing something like:
for (int row_number = 0; row_number < 8; ++row_number) {}
I think it's obvious from context what that 8 means and if you accidentally type 9 instead, you will catch that mistake immediately from context. If you write a lot of words, instead of numbers, it can infact confuse you because you need to spend some mental energy deciphering what the words mean. If you see 8, you know the loop will iterate 8 times, if you see BOARD_SIZE, you first have to find out what BOARD_SIZE is - is it 8, is it the number of pixels in one dimension, .... My point is, you have to think more when you are using words instead of numbers. In cases where it may not be clear from context what the 8 means I agree with you fully, but considering this is a chess application and the person reading your code, be it you, or someone else, is most likely not stupid, it's a reasonanble thing to assume that they know what the 8 means.
@@stewartzayat7526Literal numbers are always bad:
- Forbids you to ever change. Otherwise you'll have to go replacing the entire project.
- May mistake their meaning.
- Words can always describe better. If the number "is obvious", the word could has it: BOARD_SIZE_8.
- ~100% chance of a word typo resulting in compile error.
- C++ Core Guidelines says to always avoid them.
Erstmal, Yan, cooles Video! I just keep learning from every video that you post. German game engine programmer here.
when he clicked the king, the rook was highlighted, suggesting that he could've castled.
With the Hello Again song you literally had me crying LOOOOL
came here for the code review and now I am waiting for your debut album.
It's fun to see that how you quickly tested checks, castling, checkmate and prise en-passant (and later promotion), but failed to notice that the king and queen's position were inverted in the initial position, which striked me the second I saw the board :P.
It perfectly illustates why it's so important to have experienced alpha/beta testers (and sometimes a few team advisers familiar with the game genre during the design and early development) when developping games.
he probably just didn't wanna spend too long on it, cuz he didnt test promotion, playing an actual game of chess or a few would have definitely been enough to make one realise
Awesome glimpse into the mind of a professional. Thanks for the opportunity.
Subscribed after the singing🤣🤣🤣. I love this channel already
One thing to add (months later), try not to hard code values everywhere. You could calculate the division value for example as a global. So if you change the resolution, the division values also change. You could still leave them const manual updates as well, but it would be better if they were all together in one place. Not spread out through the code.
Edit: Nvm, just saw he mentions it later haha
Useful video, thanks man!
I remember the first chess game I programed with my dad, well he did all the programing as I was like 8. Done in BASIC on an old IBM computer with no hard drive and 5 1/4" floppies! It was written such that you gave the coordinate position of the piece, then named the piece and then gave the coordinate position that you wanted to move too and the name of the piece. I think most of you can guess the bug.
...
As long as the move was a legal move for the piece you were moving (at the start of the movie), you could rename the piece in the destination field and promote it to anything you wanted
I think you can castle is you click on the rook after selecting the king.. the rook square is highlighted as a valid king move bro, you missed that
OMG, the singing!! 😂😂 Epic!
I need a full cover of hello right now Cherno!
His best album yet, the code review
Why is no one talking about the fact the King and Queen are literally in the wrong squares
very very educational! thank you
Thank you Cherno. I learned a lot.
love your videos
Really Enjoyed your singing.
Learnt a lot from this review.
Lol the singing at 2:27 was so cool and funny
Great review and great Code overall!
I want to deepen my C/C++ knowledge and was wondering about the tuple thing. I really like to use tuples (C#) when readability is given since you can name your tuple values, kinda sad about that
I've seen some versions of online chess where if you click the king, you have to click the corresponding rook, and when you clicked the king, the corresponding rook highlighted, so that would likely have worked.
that performance brought a tear to my eye. what a truly angelic voice. adele ain't shit.
Cherno lowkey flexing his singing skills 😂
Thanks for an interesting code review, and nice polling fix!
From a readability standpoint (and to some degree safety) I would have expected more feedback on the code duplication -- I like what you did for the knight moves loop, but would have taken it further, e.g. all of the x + dx > 7 && ... that is, you should do that once (x_new = x + dx) (even better with a point class) and then (OnBoard(p) && Free(p)).
I think a bit more of an investigation into how you want to handle the polymorphism would have been interesting too.
Singing was amazing! :D
There is a cool wiki on chess programming of situations that could happen. Like en passant and ending up in check etc. There are a few cases that are difficult. Also some cool books on using bit fields to get the best speed.
do you happen to have a link for the wiki (is it on wikipedia or something else?) im curious lol
he also needs to get rid of that class hierarchy
Hi Yan! Thanks for this video. I would love to see one for organizing a c/c++ project with source control. I have a little bit of experience with cmake but... yeah it's cmake
very good code review
LOL that Hello rendition was bomb
that cpu core usage hack was cool !
2:27 That was amazing!
Would love to see how you set up your build tools!
I would love to see a video on building C++ code :)
Yess. Plzz make a video for building c++ projects
YES, please make the video on how to properly make a project on git.
God when you broke into Hello I died.
3 move draw rule, 50 move without a capture rule, stalemate, insufficient material, draw offer, resigning, plenty of other test cases to deal with that are probably not implemented but more time consuming to test. It doesn't show the moves, who is to move or offer PGNs to clipboard which also is not great.
Did he test for discovered check?
What a coincidence, I was looking for graphical libraries to make a chess game right as this video dropped.
great singing
I would be super interested in a video about distributing c++ code, getting it to build. This has been my biggest pain point with getting into c++.
I've personally been struggling with static linking libcurl the last few days.. in a previous video you said you will create a separate project for static dependencies that builds into a .lib and then reference them in your main project.... And that you will create a video in the future on how to do that (I don't think you did) so yeah, make how to build videos!!! :D
And now I just got to the part of the video that said you do that in other code review videos... Looks like I need to watch more of these 😅
31:46 "Ok. So back to blur town" DAAAAAAMN LMAO
A video on how to make a project would be really useful honestly
31:19 didn't expect to see cyrillic here
He speaks Russian
Code Review Musical is awesome!
One thing you did not say but is something I heard as a point of graphics... If you need a texture at 80*80 and you can scale the textures... Always go larger than what you want and never smaller unless you are mapping and applying to a model. With 2d at least... Always scale down or match scale. It avoids the graphics blurring.
he did castles hahaha
You have to click the rook! :)
That singing was pretty good actually
sauber julian!
"Quelle" also means source, which kind of makes sense for the water thing too since thats where the water comes from
This man's commenting in the code is on another level 😆 🤣
Instead of using std::pair for points he could have just used SDL_Point provided by SDL. This would then also be compatible with some other SDL functions as they only accept SDL_Points.
Waiting for that build video
haha, I feel off the chair when you started singing ...
bro were you in a band? If that wasn't autotuned your voice is incredible. would def want to hear you release a single or something
I don't even do game programming; but I love your videos!
Dang! The singing tho!!
Thanks for this Interesting and good code review on code, application design and architecture!
If you want to build and test a real chess game engine, you will need to add many specific rules, that are not obvious at first sight.
It’s not only about adding castling and en-passant, you will also have to test and prepare specific little rules like drawing rules
(draw after three-time-repetition, 50-moves-rule and draw through lack of material, even depending on who was to move at the given position, …).
Properly implementing and testing these things can become challenging soon, as many of these constellations are not so easy to test and detect and might require specific knowledge, e.g. can you theoretically force a checkmate in a position like king and bishop vs king and knight.
If you made that building tutorial, i'd be forever greatful
Cherno is a genious.
17:42
Electricity bills go brrrrrr
I'm sure you will find this out later in the video, but castling seems to be possible by dragging the king to the rook rather than the square next to it. (:
You reffer to the fact that he couldn't castle there in the first minutes of the video?
@@alexandrucalitescu5822 Yeah. I didn't have time to watch the whole thing, but i thought i would point it out anyways.
@@Katt1n Well there, he couldn't castle because you can't castle trough a line of check. The bishop was up there. And it was implemented in the game I think, it even lighted that line of check in order to show why the castle is not possible there.
@@alexandrucalitescu5822 I understand the rules of chess, for the first few minutes of the video he implied that castling was not implemented which is not true.
Hey Cherno, please make a video dedicated to a polymorphism in cpp.
finally a video hehe
6:04 I'm pretty sure you can, it's just not standard, the rook is highlighted as a possible move
34:30 isMyPiece() or canMovePiece()
36:00 still doesn't notice you can castle :)
49:50 Or create once then copy construct the rest? (not sure what the non default copy constructor did, why it set texture to null)
One thing ive noticed is that the board is not actually reversed when the white is on the top side, it's always the white king should be on a black square.
I am new to opengl and GLFW so the first project that I have done in C with openGL was a tic tac toe project, I put nothing on the heap there. OK, tic tac toe is a lot simpler than a chess app (I have made a chess app in Java), but I think that even if I were to make a chess app in C with opengl and GLFW I could just initialize all the objects for chess pieces in the function which contains the main loop (while (! glfwWindowShouldClose(window) loop) and I would put all the chess piece objects on the stack frame of this function which runs in its own thread (I would put it in a different thread). The stack frame of this function lasts as long as the window lasts. I don't think I need to put anything on the heap whatsoever. Even when dealing with promotion when a pawn becomes a queen/rook/knight/Bishop, I can still put that queen on the stack frame of the promotion function and then use memcpy to copy it into where the pawn used to be and that should work correctly as long as the size of the pawn object is bigger or equal to the size of the queen/rook/knight/Bishop object.
My variables on the stack will last as long as the window of their chess board exists, their stack frame will exist as long as the main loop of their chess game exists, only after the main loop of that chess game is over, that function is over and leaveq CPU instruction is executed (leaveq is basically the same as add numberOfBytesInThisStackFrame, %rsp and then pop %rbp, I am talking about x86-64 architecture here)
the stack frame of that function no longer exists.
Great singing bro! Music channel coming!?!? 2:45
I didn't know he could sing this well lol 😂😂
Nice video
16:26, sure. It's less energy spent, less thing to write, read and think, since it has the same syntax as a pointer or class object evaluated against bool. Plus, if the boolean variable ever changes to a pointer by design, no refactoring will be needed here.
23:45, since this pointer is not meant to move, it'd be better as a reference: safer, less typing and a visual hint.
24:53, struct has better performance than tupple, because it doesn't get members by number. Generates much less bytecode too.
30:45, literal numbers are dangerous due to this kind of thing. Right thing to do would be to has it attached to the screen size, either at compile time, like a global constant, or at runtime (in case of user being allowed to change it) as information from a class, calculated together with the screen size.
36:25, bold security flaw here: this f() should not be public. If a piece goes to a wrong place, he'll has to look the entire project for calls to it. Fix: remove it from public domain, get a compile error, mark the f() who is calling it as 'friend', and only if it's actually 1 of the few that should be allowed to change piece location.
38:40, a good design choice is to separate the character logic from its multimedia resources, so that its logic may go to the CPU caches, becoming much faster.
I remember 3 months ago watching this and not being able to understand a lot of things, now I watched this and I understood almost everything Cherno said in this video. I studied Java and C in the meantime, I guess that helped for C++ understanding as well. Still, it is not quite clear to me what tulp is and some usages of :: I don't understand.
I even get the frustration of cherno that this guy didn't put more things on the stack, if I were making a chess game in C I would put everything on the stack, I don't think I would call malloc even once. As long as I put my chess pieces in the same stack frame where the game loop is, I will not get a seg fault, because that stack frame is alive as long as the game is alive.
I wish you would make a video on how to build and distribute it, Because I too am having problems with that part of it...