Files
klienckie_mendela/Lekcja_07/index.html
T
2026-11-10 08:37:30 +01:00

135 lines
3.4 KiB
HTML

<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Statki</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#start {
margin: 1rem;
}
table {
margin: 1rem;
border-collapse: collapse;
}
td {
border: 1px solid black;
width: 40px;
height: 40px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="start">Wylosuj statki</button>
<table id="plansza"></table>
</body>
<script>
let size = 10;
let board = [];
function drawHTML() {
const table = document.getElementById("plansza");
table.innerHTML = '';
for (let h = 0; h < size; h++) {
table.append(document.createElement("tr"));
for (let w = 0; w < size; w++) {
table.lastChild.append(board[h][w].element());
}
}
}
function zero() {
for (let h = 0; h < size; h++) {
board.push([]);
for (let w = 0; w < size; w++) {
board[h].push({
w,
h,
has_ship: false,
element: function () {
let el = document.createElement("td");
if (this.has_ship) { el.style.backgroundColor = 'gray'; }
el.onclick = function () {
// procesuj kliknięcie...
console.log(this.h, this.w);
}.bind(this)
return el;
}
});
}
}
drawHTML();
}
zero();
let placed = 0;
const ships = [4, 3, 3, 2, 2, 2, 1, 1, 1, 1];
function place() {
const length = ships[placed];
const horizontal = Math.random() < 0.5 ? true : false; // idziemy w prawo i w dół
let is_placed = false;
let min = 0;
let max_w = 0;
let max_h = 0;
// z tego można zrobić jedną logikę
if (horizontal) {
max_w = size - length;
max_h = size;
// sprawdzić czy start stop nie kolidują z innymi statkami, jeśli tak to ponowić losowanie
// zrobić tablicę surroundings ze współrzędnymi, jeśli wszystkie mają has_ship == false to kontynuujemy, jeśli nie to losujemy nowe miejsca
let h = Math.floor(Math.random() * (max_h));
let start = Math.floor(Math.random() * (max_w + 1));
let stop = start + length - 1;
for (let i = start; i <= stop; i++) {
board[h][i].has_ship = true;
}
} else {
max_h = size - length;
max_w = size;
// sprawdzić czy start stop nie kolidują z innymi statkami, jeśli tak to ponowić losowanie
let w = Math.floor(Math.random() * (max_w));
let start = Math.floor(Math.random() * (max_h + 1));
let stop = start + length - 1;
for (let i = start; i <= stop; i++) {
board[i][w].has_ship = true;
}
}
placed += 1;
drawHTML();
}
document.getElementById("start").onclick = place;
</script>
</html>