Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Помогите решить задачу (https://javascript.ru/forum/events/77521-pomogite-reshit-zadachu.html)

fillika 16.05.2019 09:29

Помогите решить задачу
 
Ребята, привет. Я новичок в JavaScript, помогите найти решение, нужно создать поле ввода и кнопку. В поле нужно ввести позицию из шахматной доски, а клик по кнопке должен вывести все возможные ходы коня из данной позиции.
Например, ввожу в поле D4 и он выдает мне результаты:
b3 b5 c6 c2 e6 e2 f3 f5.
Как можно было бы решить задачу?
Заранее спасибо

Malleys 16.05.2019 11:12

<form id="knight-moves">
  <input name="position">
  <button>Найти ходы</button>
  <output></output>
</form>
<script>
function getPossibleMovesOfKnight(p) {
	class Position {
		constructor(position) {
			Object.assign(this, position);
		}

		get isValid() {
			return this[0] >= "A" && this[0] <= "H" && this[1] >= "1" && this[1] <= "8";
		}

		moveBy([x, y]) {
			const position = new Position([
				String.fromCodePoint(this[0].codePointAt() + x),
				String.fromCodePoint(this[1].codePointAt() + y)
			]);

			return position.isValid ? position : null;
		}

		toString() {
			return `${this[0]}${this[1]}`;
		}
	}

	const position = new Position(p.toUpperCase());
	const directions = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];

	if(!position.isValid) throw new Error(`Invalid position '${p}'`);

	return directions.map(direction => position.moveBy(direction)).filter(position => position).map(String);
}

document.getElementById("knight-moves").addEventListener("submit", event => {
  event.preventDefault();
  const moves = getPossibleMovesOfKnight(event.target.position.value);
  
  event.target.querySelector("output").innerHTML = `<b>Ходы</b>: ${moves.join(", ")}`;
});
</script>


UPD Добавлена обработка ошибки в случае ввода неправильной начальной позиции, Position теперь наследует от String
<form id="knight-moves">
  <input name="position">
  <button>Найти ходы</button>
  <output></output>
</form>
<script>
function getPossibleMovesOfKnight(p) {
	class Position extends String {
		get isValid() {
			return this.length === 2 && this[0] >= "A" && this[0] <= "H" && this[1] >= "1" && this[1] <= "8";
		}

		moveBy([x, y]) {
			const position = new Position(
				String.fromCodePoint(this[0].codePointAt() + x) +
				String.fromCodePoint(this[1].codePointAt() + y)
			);

			return position.isValid ? position : null;
		}
	}

	const position = new Position(p.toUpperCase());
	const directions = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];

	if(!position.isValid) throw new Error(`Invalid position '${p}'`);

	return directions.map(direction => position.moveBy(direction)).filter(position => position);
}

document.getElementById("knight-moves").addEventListener("submit", event => {
  event.preventDefault();
  var html;
  
  try {
    const moves = getPossibleMovesOfKnight(event.target.position.value);
    html = `<b>Ходы</b>: ${moves.join(", ")}`;
  } catch(error) {
    html = "Невозможно вычислить ходы, неверная начальная позиция!";
  }
  
  event.target.querySelector("output").innerHTML = html;
});
</script>

fillika 16.05.2019 11:39

Боже, как все просто выглядит. Тупо копировать не буду, обещаю, сегодня вечером разберу полностью код, чтобы в будущем самостоятельно все решать. Спасибо вам огромное!!!


Часовой пояс GMT +3, время: 13:52.