0

Essentially I'm trying to create the game reversi. To cut it short if you don't know what it is, I have a 8x8 board of squares. There are 2 coordinates and I need to determine all the squares that are between the two coordinates and fill them in. The 2 coordinates are either on the same y, same x or diagonal to each other.

Can someone explain the logic behind how I would go about doing something like this? How can I determine the coordinates of all the elements between the 2 coordinates.

Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
  • 1
    Are you working with JavaScript or Java? They're two very different languages. – Andy Apr 30 '21 at 15:20
  • so, you have the 8x8 matrix.. and then you have one position of that matrix, lets say the (1,4) meaning x=1, y=4. What do you want to get? All the diagonally reachable positions in the matrix? – Uriel Chami Apr 30 '21 at 15:21
  • I have 2 points on a 2d array. For example 1,1 and 3,3. How can I generate an algorithm that finds the elements inbetween? In this example, it would be 2,2 Thank you for replying! – acc4232111 Apr 30 '21 at 15:24
  • 1
    Look for resources on the Digital Differential Analyzer (DDA) algorithm. Here's a simple Javascript [implementation](https://gist.github.com/rilut/8eb8c76c85f00477329c). However, there can be rounding issues with this simple approach - you may want to look into using fixed point arithmetic. – RaffleBuffle Apr 30 '21 at 17:09
  • FYI: Reversi is also known as Othello. – RBarryYoung Apr 30 '21 at 17:36
  • By diagonal do you mean 45%? Or, in other words, are you saying that every pair of coordinates: `{ (x1,y1), (x2,y2) }` will have either `x1=x2` or `y1=y2` or `|x1-x2| = |y1-y2|`? – RBarryYoung Apr 30 '21 at 17:40

1 Answers1

2

You need a simple for loop, starting at one of the coordinates and moving towards the other.

let connect = (c1, c2) => {
  // Determine the distance between c1 & c2
  let delta = c1.map((v, i) => c2[i] - v);
  let distance = Math.max(...delta.map(v => Math.abs(v)));
  
  // Determine the unit vector (e.g. [1, -1]) to move each iteration
  let direction = delta.map(v => v / distance);
  
  // Starting at `c1`, iterate for `distance` iterations, moving in `direction` each iteration.
  return [...Array(distance + 1)].map((_, i) => c1.map((v, j) => v + direction[j] * i));
  
  // Same as above, but exclude `c1` and `c2` from the return array.
  // return [...Array(distance - 1)].map((_, i) => c1.map((v, j) => v + direction[j] * (i + 1)));
};

let c1 = [3, 6];
let c2 = [8, 1];
console.log(connect(c1, c2));
junvar
  • 11,151
  • 2
  • 30
  • 46
  • 1
    I personally think this is a very clean solution. Are you willing to post this as answer to https://stackoverflow.com/questions/4672279/bresenham-algorithm-in-javascript and https://stackoverflow.com/questions/13491676/get-all-pixel-coordinates-between-2-points ? Bet you earn quite some well deserved credits there – Piemol Jan 20 '23 at 09:10