Please don't get aghast of TypeScript. It's just js with types.
I'm making a chess game and I've reached the part of validating the movements. My Tile class is as follows:
class Tile {
x: number;
y: number;
tile: Element;
team: string;
piece: string;
constructor(i: number, j: number, tile: Element, team: string) {
this.x = i;
this.y = j;
this.tile = tile;
this.piece = "none";
this.team = team;
}
}
As you can see I have control of the x and y position of any given tile in my 2D array.
I have the following function that returns an array with the total movement that each piece has made in its y and x coordinates. It receives 2 Tile
objects as parameters. The first one is the initial click, and the last one is the ending click (where the user wants to move the piece).
function getVectorComponents(start: Tile, end: Tile) {
return [Math.abs(start.x - end.x), Math.abs(start.y - end.y)];
//getVectorComponents(start_position, end_position)[0] returns the movement in the y axis
//getVectorComponents(start_position, end_position)[1] returns the movement in the x axis
}
I have managed to validate the movement of the rook ♜ with the following:
if (
(getVectorComponents(start, end)[0] <= 7 &&
getVectorComponents(start, end)[1] == 0) ||
(getVectorComponents(start, end)[0] == 0 &&
getVectorComponents(start, end)[1] <= 7)
) {
//This is an available move for the rook
}
My problem comes when I try to validate the movement of a pawn ♟️. Since my getVectorComponents()
returns the absolute value of the movement, I don't know the direction of this movement.
I have the following validation algorithm for the pawn:
if (start.x == 6 || start.x == 1) {
//Check if the pawn hasn't moved, if not: it has 2 available moves
if (
getVectorComponents(start, end)[0] <= 2 &&
getVectorComponents(start, end)[1] == 0
) {
//This is an available move for the pawn
}
} else {
//The pawn only has 1 move available
if (
getVectorComponents(start, end)[0] <= 1 &&
getVectorComponents(start, end)[1] == 0
) {
//This is an available move for the pawn
}
}
This algorithm leads to the following problem:
In a chess game, the pawn can't move backwards. But, the algorithm that I have returns this movement as valid.
Is there a nice way to restrict the movement of the pawns, so that they can only move forwards? This needs to take into consideration the white and black team.
More information:
a8 = [0][0]
h1 = [7][7]
team: string
, you would get ateam: Team
that would hold adirection
property somehow (e.g.UP
orDOWN
, or even1
and-1
which might simplify the calculations down the route). The key is that the authorised movements from a tile depend on the owner of that tile, which makes me thinkstring
isn't expressive enough.getVectorComponents
once and storing the result in a variable. It probably doesn't make much of a difference right now with the simple calculation, but generally, you don't want to run something that gives you the same answer multiple times if you don't have to (DRY).