<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>