Legal movements of the chess pieces

Recently, I developed a chess game using vue.js and have successfully implemented legal move validation for the knight, pawn, and bishop pieces.

However, while working on the bishop validation, I encountered a challenge. It involves determining if there is a piece obstructing the path of the bishop.

For better clarity, please refer to the image linked below.

https://i.sstatic.net/Nyy4e.png

In the image, you can see how the red figures move past pawns and continue upwards instead of stopping at the pawn piece as intended.

Below is the code snippet related to bishop movement calculation. Additionally, any guidance on implementing validations for the queen and other pieces would be highly appreciated.

    var el = {  };
    // sample Data
    // Code snippets go here...
  

Answer №1

Your for loop lacks code for collision detection, allowing the piece to move all the way to the edge of the board unchecked. One solution is to break the loop into four separate for loops, each ending at the board's edge or upon detecting a collision. Collisions must be handled differently based on whether it's with a piece of the same color (illegal move) or the opposite color (capture).

var dx = +1, dy = +1;
do {
  x += dx;
  y += dy;

  // A color piece collision stops the loop.
  // If encountering an opposite color piece, one last move is added.
  var onBoard = (x >= 0) && (x < 8) && (y >= 0) && (y < 8);
  var samePiece = onBoard ? (detect_collision_with_same_color_piece) : false;
  var oppPiece = onBoard ? (detect_collision_with_opp_color_piece) : false;

  if (onBoard && !samePiece) {
    offSet.push({ x: x, y: y });
  }
} while (onBoard && !samePiece && !oppPiece);

Please note that placeholders were left in the collision detection logic. Here are some additional considerations:

  1. Parameterize dx and dy to iterate over all combinations of +1 and -1 to avoid repeating code.
  2. If memory allows, padding the matrix with special values on all sides eliminates the need to continuously check the correctness of x and y. For instance, padding with white pawns could simplify the logic, removing the need for the onBoard condition.
  3. Explore faster move generation techniques like rotated bitboards, which offer a different approach for improving performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

Transmitting Various Static Files via Express Router

I am currently utilizing the Express router to serve static .html files based on the URL specified in router.get. For example, this code snippet sends the homepage: router.get('/', function(req, res, next) { res.sendFile('index.html&ap ...

Vercel and Firebase Realtime Database causing snapshot.val() to return null during build deployment

Creating a blog application using Next.js, Firebase Realtime Database, and Vercel for hosting has been seamless on my local machine. Even after running npm run build, everything functions perfectly. However, when deployed to Netlify in production, the snap ...

What is the solution for resolving a 404 error when making a POST request using Axios in a

I am encountering a 404 error when trying to send a request to an API, and I can't find any leads in the network. Can anyone assist me with this issue? Here is my code: loginMethod() { const config = { userName: "<a href="/cdn-cgi/l/ ...

Is it possible to use AngularJS to show additional information between rows when a table row is clicked in HTML

I'm currently working on an html table where the <tbody> is generated using angular's ng-repeat. Take a look at my html: <tbody ng-repeat="car in carList | filter:tableFilter"> <tr> <td><a target="_blank" h ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

submit django form when a checkbox is checked

tml: <div id="report-liveonly"> <form action="." id="status" method="POST">{% csrf_token %} <p>{{SearchKeywordForm.status}}Only display LIVE reports</p> </form> </div> I am facing an issue while trying to submit ...

Positioning of the dropdown in Material UI Autocomplete

Can the Material UI Autocomplete be customized easily to position the Popper dropdown relative to the text cursor, similar to the VS Code Intellisense dropdown? The input field is a multiline Textfield component. The code snippet below demonstrates: impor ...

Peer dependency conflict detected: [email protected]

Encountering a conflicting peer dependency error: [email protected] while attempting to build/deploy my Vue CLI application using Heroku: npm ERR! Could not resolve dependency: npm ERR! peer eslint-plugin-vue@"^7.0.0" from @vue ...

Move the placement of a slice on a pie chart using Three.js

I have successfully created a pie chart object using 3js ExtrudeGeometry. However, my current goal is to move out a slice from the piechart object, similar to the illustration in the image below. https://i.sstatic.net/DRx7M.jpg Below is the code snippet ...

End the setInterval() function when a particular class is displayed

My current challenge involves creating a function that checks for the visibility of the #discountbox element and then clones it to be placed after the .pricebox. However, I am encountering an issue where the cloning process continues indefinitely. Any sug ...

Popovers in Bootstrap 4 do not have clickable Custom Forms

I find it strange that in Bootstrap 4, only custom forms are not clickable in the Bootstrap popover. It's interesting how default forms in Bootstrap 4 work just fine. Any suggestions on how to resolve this issue? Below is my code. Thank you for you ...

A tutorial on implementing dynamic imports within a series of routes in Next.js

When dealing with a specific set of data (JSON, TS) within a dynamically changing group like app/(blog-articles)/first.ts, you may encounter issues when trying to import it dynamically using useEffect. In this case, Next.js might throw an error. I attempt ...

Is it possible to determine the data type of a constant without having to widen

Is there a way to perform type checking on the value assigned to a variable without changing or widening its type? For instance, const a = {foo: "hi"} as const; // typeof = {foo: "hi"} type THasFoo = {foo: string}; const b: THasFoo = ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Retrieve vue environment variables within a template

I am trying to figure out how to access my environment variables directly from the template of Vue single file components. When attempting to do so like this: <img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt=" ...

Gather information from various mongodb collections and consolidate them into a single array using Javascript

Is there a way to retrieve the most recent item from multiple collections and store them in an array based on the collection name and newest item? How can I accomplish this either sequentially or asynchronously? let dat = ["test", "test2"]; ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

Different ways to use jquery to move to the top of an overflow div

$('.lb').click(function() { $('#modal').hide(); var id = $(this).attr('id'); var dir = '/lightbox/' + id + '.php'; $('#lightbox').find('#modal').load(dir, function() { ...

error occurred while looping through json array

i am encountering an issue with a code that keeps returning an "undefined" message instead of the expected HTML output. Purpose of function: the aim of the following function is to display notifications in a manner similar to those on Facebook. The code se ...