My goal is to make sort of a chess game where you can place multiple towers or rooks, and the game is supposed to check if the chess pieces can hit each other or not, so far I have made the code you can see under, but I am stuck on the loop that checks if one rook can hit another rook. I am quite confused on how to check this. If anyone could help me or give me any hints on how to make the loop it would mean a lot! (Sorry for the norwegian variable names, if you need a translation or anything I will gladly help with it!!!)
Thanks in advance!!!
<!doctype html>
<html lang="no">
<head>
<title> Standardoppsett </title>
<meta charset="utf-8">
</head>
<style>
body{
font-size: 25px;
}
.board {
width: 360px;
height: 360px;
border: 32px solid;
border-color: darkslategray;
border-radius: 5px;
}
.firkant {
height:calc(100% / 8);
width: calc(100% / 8);
text-align: center;
border: 1px black solid;
}
.hvit{
background:white;
}
.svart{
background:grey;
}
td:hover {
background: lightgreen;
cursor: pointer
}
</style>
<body>
<table class="board"></table>
<script>
let tableEl = document.querySelector("table")
let liste = []
for(let i = 1; i < 9; i++) {
let trEl = document.createElement('tr');
for(let j = 1; j < 9; j++) {
let tdEl = document.createElement('td');
tdEl.setAttribute("id","rute"+i+j)
tdEl.addEventListener("click",plasserTårn)
trEl.appendChild(tdEl);
// Bare på grunn av css
tdEl.className = (i%2 === j%2) ? "hvit firkant" : "svart firkant";
}
tableEl.appendChild(trEl);
}
function plasserTårn(e){
let trykketFirkant = e.target
let plassertBrikke = {rad:trykketFirkant.id.substring(5,4), kolonne:trykketFirkant.id.substring(6,5)}
liste.push(plassertBrikke)
console.log(liste)
console.log(plassertBrikke)
for(let i = 0;i<liste.length;i++){
let rekkefolgehusker = i
for (let k = rekkefolgehusker;k<liste.length;k++) {
if(liste[i].rad == liste.rad[k]) {
console.log("tårn blir slott");
}
}
}
}
</script>
</body>
</html>
I'm not 100% sure what you want, but before pushing plassertBrikke to liste, you can do something like this to see if plassertBrikke can take any of the rooks already on the board.
const piecesUpForGrabs = liste.filter(rook => {
return plassertBrikke.rad === rook.rad || plassertBrikke.kolonne === rook.kolonne;
})
console.log('plassertBrikke can take these pieces:', piecesUpForGrabs);