0

I am trying to build a chess game using Javascript(ES 6) and Canvas. I have built a basic chessboard and also rendered pawns on top of it. Now I intend to either click on the pawn or drag it to make a move.

document.addEventListener('click',board_click)

or

canvas.addEventListener('click', board_click, false);

is the way I manage to listen to these events.

Now how would I know where I have clicked? I figured I can try to get the current position of the click, but how will I know what item is there at the present location. Any libraries or already implemented logics will also be helpful

I have rendered my pawns like this

const drawPawns = (white, black, ctx, boardDimension, allPieces) => {
  const rows = [0, 1, 2, 3, 4, 5, 6, 7];
  const cols = [1, 6];
  let pawn;
  let side;
  // boardDimension  = 90;
  cols.forEach((col) => {
    rows.forEach((row) => {
      // pawn = Pawn.call(this, 'black');
      side = col === 1 ? 'black' : 'white';
      // That little tinkering is to center align the Pawn in the tile
      pawn = new Pawn(side, row * boardDimension + 30, col * boardDimension + 5, true);
      spriteImage.draw(ctx, pawn.canvasPosition, pawn.x, pawn.y);
      allPieces.push(pawn);
    });
  });
};

The pawn.canvasPostion is to draw the image(using Sprite), whereas x and y are the places where its coordinates are. Now how would I get this particular Coor ordinates?

Varun G
  • 44
  • 8

1 Answers1

2

The listener callback (your board_click function) gets the browser event as an argument. This event object contains a bunch of data, including the clicked element and the coordinates of the click.

Since you are using canvas, you should attach the click listener on the canvas element. Canvas does not have a state graph, which means it has no concept of objects in the canvas - it is just a bunch of pixels. This means it is your responsibility to keep track of which piece is where.

Since you are already placing the pieces on the board, you know exactly where they are!

The normal way to do this is to get the click position, map that to a grid cell on the board, and then check whether anything was on that cell. How exactly this will happen depends on the data structure that describes your game.

For illustrative purposes let's assume that the chess pieces reside in an array, and each piece knows its cell coordinates (for chess it probably makes sense to do the opposite - each cell would know whether it has a piece on it, but bear with me).

var cellSize = 16; // let's assume a cell on your board is 16x16 pixels
var pieces = []; // this keeps all chess pieces

function board_click(evt) {
    // get cell coordinates
    var cellX = Math.floor(evt.clientX/cellSize);
    var cellY = Math.floor(evt.clientY/cellSize);

    var piece = pieces.find((p) => {
        return p.x == cellX && p.y == cellY;
    });

    if (piece) {
        // a piece was clicked
    } else {
        // an empty cell was clicked
    }
}

I hope this is enough to get you started.

Edit: had forgotten to divide the mouse coordinates by the cell size...

RecencyEffect
  • 736
  • 7
  • 18
  • Great! I have implemented this but have one issue. – Varun G Apr 15 '17 at 07:22
  • imo it makes most sense to just store the cell coordinates. Whenever you need the screen coordinates you can easily convert to/from them. If you are worried about too many conversions (which doesn't really matter in chess), then you could store both - e.g. Pawn(side, cellCoords, screenCoords). Or am I misunderstanding the question? – RecencyEffect Apr 16 '17 at 07:59
  • The prob is since I'm using Canvas..the screen coordinates got nothing to do with canvas coordinates. I need to get the canvas coordinates and that I'm not able to figure out how – Varun G Apr 16 '17 at 11:39
  • Ah, I see. Check for example the third answer here http://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element - use canvasEl.getBoundingClientRect(), and then subtract these coordinates from the mouse event's clientX and clientY to get the click offset relative to the canvas origin. – RecencyEffect Apr 16 '17 at 14:39