♟️ Code CHESS in JavaScript (Super simple!)
HTML-код
- Опубликовано: 17 май 2023
- Found this hard? Learn the fundamentals of JavaScript here: www.codewithania.com
🚀 Sign up to www.codewithania.com to receive access for the final code.
____
⭐ Check out my IDE here and get 1 month free: jb.gg/get_webstorm
⭐ New to code and none of this is making sense? Watch my '12hr+ RUclips Coding Bootcamp' in which you will learn HTML, CSS and JavaScript Fundamentals completely from scratch. It's on my channel and its 100% free.
⭐ In most videos I use Tabnine as my A.I autocompletion tool. You can download it for free here (I get no commission from this link, but am in a partnership): bit.ly/tabnine-top-tool
⭐ You can get a blockchain domain with my affiliate link here: bit.ly/get-a-crypto-domain
⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : www.buymeacoffee.com/aniakubow
⭐ Sign up for weekly coding tips from my newsletter partnership: bit.ly/JS-tips
You can also find me on:
Twitter: / ania_kubow
Instagram: / aniakubow - Развлечения
Thank you so much Ania! this is one of the most insightful and advanced tutorials I've seen
00:04 Build a working game of chess using JavaScript without canvas
05:26 Define constants for chess pieces and use them in the app.js file.
18:15 Create a chessboard with black and white squares
24:01 Add drag and drop functionality to the squares on the board.
35:54 Check if something is taken and change player turn
41:50 Drag and drop function for checking the correct player and if taken by the opponent
53:52 Validating pawn moves based on start and target ID using math.
1:00:04 Valid moves for the pieces discussed
1:13:07 The code checks for possible moves in a chess game
1:20:58 Check for a win by collecting all the kings and checking if any of them are missing the white king (indicating a black player win)
Thank you for all your great courses !
Thanks Ania, I was just thinking about how chess works in coding and your video popped up on RUclips. I'll subscribe and save it for my next project
i appreciate people using more and more javascript, keep up the good work!
Ania another great tut - thank you, I am learning so much from you.
I've just found one gem of a playlist. Very thankful!
Really good job, I enjoyed the process and refreshed a lot of my JavaScript. Thank you for the content!
Done! It was so cool Ania.... I'll make other stuff from your channel!! thank you!
Did you ever do a follow up for check logic? I was thinking of making chess in something (JS made sense so I'd have a GUI), but the thing I was finding the most difficult was determining what moves were legal, mainly due to stuff like pins on the king.
Thanks a lot.... i followed along it was great... lots of conditional statements
The javascript vanilla with html and css will always be your mark for me, cant belive the day I saw you coding packman, told everyone
Fantastic tutorial! i only had one issue with pawn taking an opponent piece by moving forward which can easily be rectified by adding "&& !document.querySelector(`[square-id="${startId + width}"]`).firstChild" on line 106 before the or statement
beautiful tutorial you are an excellent teacher
This is a really great exercise, thanks!
Thanks for the tutorial!
42:23 a suggestion for reversing id's with just one function. Grab Id value and parse it to integer then subtract from 63 which gives you new ID, set the ID. It's gonna work for both the players.
is there a specific need to reverse the id of all squares in chess?
Excellent Video. Very nice explanation. Learned a lot. Nice application design.
Thank you loved this lesson
evey single time i watch your video I feel professional
Great Stuff! Thanks for sharing - keep it up! 💯🔥
Thank you Ania. it is great. I wish you could see my version of this chess.
Impressive Ania,
Could you make them into all in one game zone including the admin dashboard?
Thanks for the interesting video. In VSCode there are multicursors, very handy thing.
This is so valuable!
Thank you Madam !! i was dreaming with this chess program !! i will do it !!
Thanks mam you are really working hard 💪 keep doing wish for your greater success
Great content ! thank you Ania ! I have an issue with piece background. When they are in start position it's transparent, but when I drag the piece it appear to have a white background, I've set position and z-index oof square, svg and piece as in tutorial. Please any idea how can I change it ?
for those on Firefox having issues with the dragDrop grabbing the path and svg you can add pointer-events to none in the css classes for those two
that did not help for me but I'm not very smart.
it usually takes me a while
I don't know why it doesn't work for me I've followed the code step by step, and it doesn't work as it should, can anyone please share with me the final code so that I can see where I've made a mistake, because it's really frustrating...
I don't know if you read the comment section, but as you recommended finding any bug in the code, I found out that when you move a pawn vertically into a square where there already is an opponent piece, it rakes it out! to debug it you need to add a " !document.querySelector().firstChild " part to the first two lines of "pawn condition" snippet, to make sure the square is empty and you can move your pawn into it. I changed it up that way and worked fine for me.
here is how i changed the code :
case "pawn":
const starterRow = [8, 9, 10, 11, 12, 13, 14, 15];
if (
(starterRow.includes(startId) &&
startId + width * 2 === targetId &&
!document.querySelector(`[square-id="${startId + width * 2}"]`)
.firstChild) ||
(startId + width === targetId &&
!document.querySelector(`[square-id="${startId + width}"]`)
.firstChild) ||
(startId + width - 1 === targetId &&
document.querySelector(`[square-id="${startId + width - 1}"]`)
.firstChild) ||
(startId + width + 1 === targetId &&
document.querySelector(`[square-id="${startId + width + 1}"]`)
.firstChild)
) {
return true;
}
break;
Hi there!, I'm having some bugs in my code
Can you please share your code to fix the bugs ?
It a nice coding journey filled with logic and conditions ! Thank you so much !
Where can I find the source code to follow through. Thank you Ania!
Ever since I took C++ courses I was curious about coding the rules for Chess. It's such a great example of coding a game with all the complexity. How did you learn Web Development?
Very nice Keep it good work with JavaScript
Sorry just wanted to add some rules there the game does not end when the king is eaten..... the king never gets eaten... it ends when the king closed every where when you about to eat the black king you must say check..... white is the one that starts in the game not black...... ya and another condition is the one for castling where by you can move both king and the queen at the same time😁.... but other wise i really followed along the entire video my app is working thanks a lot
Thank you for sharing :) Great job! Greetings from PL :)
You should definitely go further with this add in some form of login support and allow players to chat and join rooms!
you can weirdly move the pieces along the board if they are near the border because the border was never respected in any movement code. e.g: the king is on h1, you could move him to a1 to the other side of the board because the tile is still only "+1" because the game doesnt know borders. besides this weird error the tutorial is very nice and simple
I'm glad I found this. I understand chess but suck at JavaScript.
Suggestion for future video: booking calendar with stripe integration. Haven’t found any videos on making a booking/appointment website for like a yoga studio with their classes or even a hair salon with available appointments.
Thank you for Code CHESS in JavaScript.
thanks again eres lo maximo!!!
Awesome 🎉 love ❤ from India 🇮🇳 😊
How I not find this before?! Thanks, very interesting, manly for understand drag and drop.
Thanks so much!
Thank you !!
Thank you!
Everything you provide our community is pure gold!Thank you Ania!!!
i followed along to everything and when i finished, my pieces arent moving anymore. anyone know what the issue could be and where?
I don't know if anyone ca answer me immediately, I really like this video, but one problem I am facing is the drag and drop function not working when i run it on live server on my chrome
I have a question ,how can I hide the sign next to the cursor that appears when I drag a piece
CAN u make a video on employee management system or gym management using mern stack?
Great video..I'm following it now...just so you know in the future..as a chess player, white always goes first
Nice tutorial. What is the name of the font used?
it seems like you can for exemple with the knights jump from one edge to another (like jumping from g8 to a6) wich in the logic of your approch is "correct", we start from square 6 to go to square 16 ( 6 + 8 * 2 + 1) but is not correct in chess rules. How to correct this ?
Appreciate how your camera doesnt take up half the screen, incredibly professional! 😊
Thank YOU
Thank you too!
Thank you.
why does firstChild work for you but not me? My code works if I remove firstChild in most of your code, but breaks if I don't. Some of the parentNode and firstChilds just return null.
I kinda hard time to push tru my code at draggable function and I can't figure it out why console.log(e) is isn't working.
using webpack js
Maybe the next episode of refining this chess?
This is really impressive!
Do programmers usually get that fluent at the point of making everything at once with no tests and mistakes or you got prepared for the video?
I struggle a lot and you just flow so easily and always know what is needed to get the result you're looking for. Congrats
Gabriel, as every performance, it takes a lot of rehearsing, and of course, Ania did all the analysis previous to making the video. It's a lot of effort to show people like you and me how to make a chess game, and more effort to put everything in just an hour and a half, that's amazing! Thanks Ania!
Any time Juan :) so kind of you to say!!
@@JuanCarlosAlvezBalbastro Thanks
Competitive programmer here: after reusing the basic methods of a language hundreds of times in a row you just memorize the basic usage by heart and can indeed not look online for documentation or test small features.
As you become better and better you can abstract more things.
On a side note, most strictly typed languages (C#,Typescript,...) have very good linting (error troubleshooting directly in your code instead of waiting for compiling) that will allow you to not even have to launch the app to manage coding related problems.
One of the reasons people often hate to code in native JS.
plus plus plus plus minus minus minus but this was great to follow ! Thanks Ania
I believe there might be an issue with this if I haven't made a mistake on my part:
For the rook (and by extension, the queen), the code for moving left and right in a straight line is:
startId + 1 === targetId ||
startId + 2 === targetId ||
startId + 3 === targetId ||
startId + 4 === targetId ||
startId + 5 === targetId ||
startId + 6 === targetId ||
startId + 7 === targetId ||
//--
startId - 1 === targetId ||
startId - 2 === targetId ||
startId - 3 === targetId ||
startId - 4 === targetId ||
startId - 5 === targetId ||
startId - 6 === targetId ||
startId - 7 === targetId ||
So if rook/queen is standing in for example position 5 it as possible to move it 1 row ahead and 2/3/4/5 positions to the side to positions 11/10/9/8 as it falls in the code of being +- 7 positions, which is of course an illegal move,.
I solved it by in the createBoard function adding:
square.setAttribute('row', row)
Creating a variable:
let startPositionRow
in dragStart function:
startPositionRow = e.target.parentNode.getAttribute('row')
in checkIfValid function:
const targetRow = Number(target.getAttribute('row'))
const startRow = Number(startPositionRow)
if(
startId + 1 === targetId && startRow === targetRow ||
startId + 2 === targetId && startRow === targetRow ||
startId + 3 === targetId && startRow === targetRow ||
startId + 4 === targetId && startRow === targetRow ||
startId + 5 === targetId && startRow === targetRow ||
startId + 6 === targetId && startRow === targetRow ||
startId + 7 === targetId && startRow === targetRow ||
startId - 1 === targetId && startRow === targetRow ||
startId - 2 === targetId && startRow === targetRow ||
startId - 3 === targetId && startRow === targetRow ||
startId - 4 === targetId && startRow === targetRow ||
startId - 5 === targetId && startRow === targetRow ||
startId - 6 === targetId && startRow === targetRow ||
startId - 7 === targetId && startRow === targetRow ||
)
hellooo, for some reason i can only drop onto other pieces, and not squares,,, how would i fix this?
how many day did it take for u to finish the source code?...please reply
So beautiful lady tutor and best Tutor for Javascript your Efforts are appreciated to the self taught software Enginners . Thank you 💖
Quick question. If i wanted the pieces to be randomized, what would the command be for that? As where you were working on const startPieces. Instead of rook, what could i to do call up a random piece?
Thank you.
you could create an array with the different pieces and a function that calls a random number from 0 to 5 (as there are 6 different pieces) and then enter the array[randomnumber] instead of the pieces. not sure if this works but i would try this way
Ania! bella, ma soprattutto brava!
check for win function can be more straightforward like :
function checkForWin(){
const both_kings = Array.from(document.querySelectorAll("#king"));
console.log(both_kings)
if(both_kings.length === 1)
{
let winner = both_kings[0].firstChild.className;
console.log("winner ",winner.baseVal);
info.textContent = `${winner.baseVal} wins`
}
}
I started similar as you did and finished with TypeScript instead of pure JS and a deep Object Oriented Programming approach. I really recommend people to try it out the code is way more easy to maintain, read and develop. At the same time I manipulated the DOM mostly directly with JS/TypeScript and I learned a lot about it. Very fun project and an amazing way to learn. Now I will extend this to a Fullstack application with database because why not?
is there any reference that will do in the angular chess game UI
Sorry for the trivial question, but what do you use as a project editor or IDE?
I use webstorm for my videos :) but this will work with any code editor
Awesome! The only thing I didn't like was the verbosity to validate if there were pieces between. We could create a function iterating through the path of start and target only checking first the direction of the movement. Greetings!
so u do and show that !
@@triggeredprogrammer name checks out
I believe there is a bug that involves moving pieces from left to right or vice versa off of the edge of the board which mathematically satisfies your algorithm but physically should be impossible. For example, you could move the knight from a6 to g4. In code, this is square 16 to 31. This would satisfy the equation width * 2 -1. However, it is an illegal knight move. This is a well-known chess programming problem which can be resolved by adding 2 virtual columns and rows all around the outside of the "real" board. Thus, making a 12x12 board instead of an 8x8 board. Nonetheless, thanks for the impressive starting point for a javascript chess program.
Can u plz share your coding journey ???l where u start something like that....that would be great to hear ...🥰
That is the weirdest brown I ever seen
You mean blonde?
@@Sharonli23345you didn’t saw the video did you
You really should not code logic for figures in that way it is obvious that it is too repetitive and redundant and hard to debug, and when there is repeating you should be using loops.
example for bishop :
case 'bishop':
// Calculate the difference between the target and start squares
const diff = Math.abs(targetId - startId);
// Check if the move is along a diagonal (difference is a multiple of width + 1 or width - 1)
if (diff % (width + 1) === 0 || diff % (width - 1) === 0) {
const step = diff % (width + 1) === 0 ? (width + 1) : (width - 1);
// Determine the direction of the step (positive or negative)
const direction = targetId > startId ? 1 : -1;
// Loop through each square along the diagonal to check for blocking pieces
for (let i = startId + step * direction; i !== targetId; i += step * direction) {
const square = document.querySelector(`[square-id="${i}"]`);
// If a square contains a piece, the path is blocked
if (square.firstChild) {
return false;
}
}
return true;
}
return false;
Love from 🇧🇩
32:11 Chrome Dev Tools is on the FRITZ
Nice video, very nice mastery of the languages but the logic could be really improved.
For example, I'd have used way more OOP, define classes for the Game/Player/Piece.
Having the ids reverted through some logic hidden in the functional part of the code is a very bad habit and makes code hardly maintainable if you do this 20x-50x-100x in a more complex project, instead we could have defined the direction pieces move depending on the color of the player or such directly in a class.
Pls Check your 'bishop' code, the other wont move...
I add a way to check the move of the knight is valid in two rows const movesKnight = [-15, -6, 10, 17, 15, 6, -10,-17] return movesKnight.includes(startId-targetId) I calculate the difference between startId and targetId
As a chess player the fact that the black starts hurt my deep inside ahahah. Good Video
🙃! Hahah oops! Thanks for watching
Github link ??
Very good, its code great
where is the source code? mine doesnt show biege brown :(
I am waiting for your video
I found a problem in the pawn's movement. If you position a black pawn on h5 and a white piece on a3 you can capture it.
Basically if the black pawn is in the 31 square (at the edge of the board) and there is a white piece in the square 40 (in the other side of the board) you can capture it.
Same for the knight's. There should be a check for the edges of the board. (also pawn should not be able to eat pieces in front of them)
why you don't use new design in webstorm ?
Great 👍👍
@Code with Ania Kubów
Hello! Before I get into this I want to ask, can I use VS Code for this project? Or do I have to download webstorm? Also is there any preperation that I need to do before that? Like donwloading the languages and what not?
Thanks in advance :)
I add a way to check the move of the rook with two rows const movesRook = [1, 2, 3, 4, 5, 6, 7, 8, 16, 24,32, 40, 48, 56, 64] return movesRook.includes(Math.abs(startId-targetId)) I subtract startId and targetId and I take the Math.abs
Oi será possivel você criar um App usando Ionic + Angular
Can you build in react js that
10:25 or use back ticks ``
Need help.
For some reason the firstchild function doesn’t work on mine, even though my container contains a child element. Whenever I use firstchild function it shows an error ( “firstchild is not defined” ). Does anyone have a solution for that
same with me
The pieces would still have pacman powers. Math doesn't know that the next field could be on the other side of the board
The pawn also moves En passant.
Hey Ania Kubóv, Great Content💌, thanks for sharing it!