My students are trying to create a chess game. They want to be able to click on the piece and then click the square it moves to. I can’t figure out how to code that. This is what we started with. They are so excited to learn to code I want them to be successful. Can you help us get started with the block coding of it? Thanks.
Kia ora Mary Beth,
Here’s the way I think about it, in the most simple form:
- First, we need to detect the clicked piece - this is an event, so in the Events category
- We need to detect the clicked square
- We need to move the clicked piece to the clicked square:
The above code is not good for a number of reasons:
- It only works for 1 piece and 1 square - replicating this for all the possible pieces and squares would be incredibly inefficient.
- The piece doesn’t move on a fixed plane (the board) - this is trivial to fix though.
So, we need to be able to apply events and movement to multiple pieces/squares. By adding all squares and pawns to their own list, we can iterate over the list and apply the actions we want to each item:
Now we can iterate over first the pawns, then the squares, and apply actions:
You can see in the above code I’m using the variable created by the foreach loop in the actions - this applies the action to each item.
You can see this in action and remix the code at https://cospac.es/NIfk
Let me know if you have any questions.
Geoff @ TechLeap
Wow! Thank you so much for your help!!