♟️ Code CHESS in JavaScript (Super simple!)
Вставка
- Опубліковано 10 вер 2024
- Found this hard? Learn the fundamentals of JavaScript here: www.codewithan...
🚀 Sign up to www.codewithan... to receive access for the final code.
____
⭐ Check out my IDE here and get 1 month free: jb.gg/get_webs...
⭐ New to code and none of this is making sense? Watch my '12hr+ UA-cam 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-...
⭐ You can get a blockchain domain with my affiliate link here: bit.ly/get-a-cr...
⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : www.buymeacoff...
⭐ 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
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 ?
nice catch! I noticed this myself and was wondering if i'd missed something.
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
Thanks Ania, I was just thinking about how chess works in coding and your video popped up on UA-cam. I'll subscribe and save it for my next project
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)
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?
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
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
Thank you for all your great courses !
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...
Done! It was so cool Ania.... I'll make other stuff from your channel!! thank you!
i appreciate people using more and more javascript, keep up the good work!
I've just found one gem of a playlist. Very thankful!
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?
Imagine using DOM manipulation instead of using JSX/TSX
I'm glad I found this. I understand chess but suck at JavaScript.
Really good job, I enjoyed the process and refreshed a lot of my JavaScript. Thank you for the content!
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
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`
}
}
Thank you so much Ania! this is one of the most insightful and advanced tutorials I've seen
As a chess player the fact that the black starts hurt my deep inside ahahah. Good Video
🙃! Hahah oops! Thanks for watching
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
Hey Ania Kubóv, Great Content💌, thanks for sharing it!
evey single time i watch your video I feel professional
Where can I find the source code to follow through. Thank you Ania!
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;
i followed along to everything and when i finished, my pieces arent moving anymore. anyone know what the issue could be and where?
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
I am facing the same problem, but it isn't getting resolved . Can you please guide me where exactly should I make the change?
So beautiful lady tutor and best Tutor for Javascript your Efforts are appreciated to the self taught software Enginners . Thank you 💖
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.
Thank you for Code CHESS in JavaScript.
Ania another great tut - thank you, I am learning so much from you.
You should definitely go further with this add in some form of login support and allow players to chat and join rooms!
There are a few rules missing (pinned pieces, en Passant, moving when in check and the way checkmate is identified) that should be done first, but I think these are relatively small additions and tweaks to make the game adhere to the rules of chess
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.
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.
Great video..I'm following it now...just so you know in the future..as a chess player, white always goes first
beautiful tutorial you are an excellent teacher
Appreciate how your camera doesnt take up half the screen, incredibly professional! 😊
That is the weirdest brown I ever seen
You mean blonde?
@@Sharonli23345you didn’t saw the video did 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.
plus plus plus plus minus minus minus but this was great to follow ! Thanks Ania
How I not find this before?! Thanks, very interesting, manly for understand drag and drop.
Thanks so much!
Awesome 🎉 love ❤ from India 🇮🇳 😊
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?
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.
Thanks for the interesting video. In VSCode there are multicursors, very handy thing.
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
Thank you Madam !! i was dreaming with this chess program !! i will do it !!
how do u have multiple divs with the same id ?
It is not working for me
Thanks a lot.... i followed along it was great... lots of conditional statements
This is a really great exercise, thanks!
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 ||
)
Thanks mam you are really working hard 💪 keep doing wish for your greater success
where is the source code? mine doesnt show biege brown :(
same problem here
Github link ??
This is so valuable!
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
Great Stuff! Thanks for sharing - keep it up! 💯🔥
Thank YOU
Thank you too!
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.
Thank you Ania. it is great. I wish you could see my version of this chess.
Excellent Video. Very nice explanation. Learned a lot. Nice application design.
Thanks for the tutorial!
its great too see how the gui works and how you can drag and drop. but the gamelogic isn't good. it made me cry. i am missing rules and you can go to wierd places on the board. maybe it would be better if you define row's, column's and diagonals, then define your position and check only the rest in the array so you can't misplace them.
For some reason when I thought my code looked exactly like hers, I can’t see the chess board or pieces at all
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
I have a question ,how can I hide the sign next to the cursor that appears when I drag a piece
Impressive Ania,
Could you make them into all in one game zone including the admin dashboard?
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
how many day did it take for u to finish the source code?...please reply
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 ?
The first 2 seconds of the demo shows a pawn making an illegal move
🤣
Can u plz share your coding journey ???l where u start something like that....that would be great to hear ...🥰
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
When I was younger I had a beautiful teacher I’d flirt with I think I can follow these tutorials because I’ll actually focus on what you say.
I didn’t wanna be one of those cringe comments but it helps.
Hopefully I’ll be learning a lot here!
There is a lot that wasn’t covered here.. but that’s fine for a simple intro. Chess is a hard game to program.
Such features missing are:
- En passant
- Illegal move detection
- Checkmate detection rather than capturing the king
There’s a lot more…
For sure. It’s just a ‘super simple’ game of chess so I do not cover moves such as ‘en passant’ etc. however I do encourage people to take the logic I write for making valid moves and improve on the game to take it to the level they would like. Hope that makes sense.
@@aniakubow no offence Mrs but I can’t figure out en passant on a real life game let alone in Java Script.
I’m 7/8 through freeCodeCamp’s Baisic Java script and today I’m pretty sure this will teach me more, be more fun and stop me from trying to figure out the logic for a chess game for the last I don’t know how many years. En Passant be damned.
Thanks for everything
@@seanfaherty en passant needs 3 conditions that need to be satisfied at the same time in order to happen
1) you have a pawn somewhere and an enemy pawn performs a 2 square move (personally I call that a pawn special move, because it can only happen at any pawns first move)
2) that pawn lands adjacent to your pawn
3) That pawn crossed your pawns line of fire in order to do 1 and 2
This might be too much for regular chess, but in general it is how the move works and that is something that universally applies to other more complicated chess variants
So writing that code is useful if at any time you want to use it at some chess variant project with bigger than 8x8 board
@@-_Nuke_- thanks
I’m stuck on checkmate detection.😢
hellooo, for some reason i can only drop onto other pieces, and not squares,,, how would i fix this?
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 ?
Very nice Keep it good work with JavaScript
Thank you loved this lesson
The pawn also moves En passant.
The pieces would still have pacman powers. Math doesn't know that the next field could be on the other side of the board
Everything you provide our community is pure gold!Thank you Ania!!!
Pls Check your 'bishop' code, the other wont move...
Thank you for sharing :) Great job! Greetings from PL :)
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
Maybe the next episode of refining this chess?
I can’t add the svg into my JavaScript file
Love from 🇧🇩
32:11 Chrome Dev Tools is on the FRITZ
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
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 isnt mine working?
let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
event.preventDefault();
console.log("Clicked!")
})
document.body.append(element);
good but according to chess rules a king can not be killed a king can only be tapped or stopped from moving in no other square blocks then only a chess game is said to be as completed.
It a nice coding journey filled with logic and conditions ! Thank you so much !
I think a better approach would be to use cartesian coordinates for the board. Perhaps an array of arrays of length 8. The math for the move validation I feel would be easier.
Very nice job Ania, thank you for the video! 👍🏽
I am amazed Ania could work out the math. An 12x12 array (because the knights cannot jump of that board) makes it so much easier and faster for validation, display and AI.
Nevertheless it's a very good tuorial.
@@MrHerbalite why are you amazed that she could work out the math?
@@delphinelisabethwomen ☕
Can you tell me where to get those svg
CAN u make a video on employee management system or gym management using mern stack?
thanks again eres lo maximo!!!
Where is the full file of Icons?
Can we all just a take a moment and acknowledge her beauty and knowledge :)
Could you just take a moment and reflect on how lame and tacky it is to copy and paste comments from other videos?
I am waiting for your video