Files
klienckie_mendela/Lekcja_04/index.html
T

537 lines
17 KiB
HTML

<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Saperrro</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
background-color: darkslategray;
}
.container {
display: flex;
justify-content: center;
}
main {
margin: 1em;
width: fit-content;
padding: 1em;
background-color: rgb(40, 40, 45);
color: white;
}
aside {
margin: 1em;
width: 20rem;
padding: 1em;
background-color: rgb(40, 40, 45);
color: white;
}
hr {
margin: .5em 0;
}
.settings>p {
font-weight: bold;
}
.setting {
display: flex;
justify-content: space-between;
margin-top: .5em;
}
.setting>input {
margin-left: 8em;
}
#start {
border: none;
width: 100%;
padding: .5em;
}
#start:hover {
background-color: darkslateblue;
cursor: pointer;
color: white;
}
table {
border-collapse: collapse;
}
td {
width: 40px;
height: 40px;
margin: 0;
border: 1px solid white;
text-align: center;
font-family: monospace;
user-select: none;
}
.nieodkryte-pole {
background-color: gray;
}
.nieodkryte-pole:hover {
cursor: pointer;
background-color: darkslateblue;
}
.odkryte-pole {
background-color: darkgray;
font-weight: bold;
}
#message {
text-align: center;
}
.timer {
display: flex;
justify-content: space-between;
margin-bottom: 1rem;
}
.timer>p {
font-size: 1.5em;
}
.timer>p:last-child {
font-weight: bold;
}
ol {
margin-top: .5rem;
margin-left: 1.5rem;
}
ol>li:nth-child(1) {
color: gold;
font-size: 1.5rem;
}
ol>li:nth-child(2) {
color: silver;
font-size: 1.25rem;
}
ol>li:nth-child(3) {
color: burlywood;
font-size: 1.125rem;
}
</style>
</head>
<body>
<div class="container">
<main>
<h1>Saperrro</h1>
<div class="settings">
<hr>
<p>Ustawienia</p>
<div class="setting">
<label for="width">Szerokość planszy</label>
<input type="number" name="width" id="width" size="2" value="10">
</div>
<div class="setting">
<label for="height">Wysokość planszy</label>
<input type="number" name="height" id="height" size="2" value="10">
</div>
<div class="setting">
<label for="mines">Ilość min</label>
<input type="number" name="mines" id="mines" size="2" value="10">
</div>
<div class="setting">
<button id="start">Graj</button>
</div>
<hr style="margin-bottom: 1.5rem;">
</div>
<div class="timer" id="timer-wrapper">
<p>Twój czas:</p>
<p id="timer-time">0:00</p>
</div>
<div class="timer" id="nickname-wrapper">
<p>Twój nick:</p>
<input type="text" name="nickname" id="nickname-box" style="text-align: right;">
</div>
<div class="game">
<table id="plansza">
</table>
</div>
<div class="messages">
<hr>
<p id="message">Podaj wymiary planszy i rozpocznij grę.</p>
</div>
</main>
<aside>
<h2>Rekordy dla <span id="mode-name"></span></h2>
<ol id="leaderboard"></ol>
</aside>
</div>
<script>
function get_cookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
let cookie_string = c.substring(name.length, c.length);
let cookie_array = cookie_string.split(" ");
if (cookie_array.length < 2) { return [] }
if (cookie_array.length % 2 != 0) { return [] }
let arr = [];
let obj = {};
for (let i = 0; i < cookie_array.length; i += 2) {
obj = {
nickname: decodeURIComponent(cookie_array[i]),
score: decodeURIComponent(cookie_array[i + 1])
};
arr.push(obj);
}
return arr;
}
}
return [];
}
function set_cookie(name, nickname_array, time_array) {
let cookie_string = '';
let len = Math.min(nickname_array.length, time_array.length);
for (let i = 0; i < len; i++) {
cookie_string += encodeURIComponent(nickname_array[i]) + ' ' + encodeURIComponent(time_array[i]) + ' ';
}
cookie_string = cookie_string.trim();
document.cookie = name + "=" + cookie_string + ";";
}
function read_settings() {
// później: funkcja posłuży do zapamiętania ustawień rozgrywki (wysokość, szerokość, ilość min, nick)
}
function update_leaderboard() {
let w = document.getElementById('width').value;
let h = document.getElementById('height').value;
let m = document.getElementById('mines').value;
document.getElementById('mode-name').innerText = `${w}x${h}:${m}`;
let lb = get_cookie(`R-${w}-${h}-${m}`);
let html = '';
if (lb.length < 1) {
html = 'Nikt jeszcze w to nie grał!';
document.getElementById('leaderboard').innerHTML = html;
return;
}
for (let i = 0; i < lb.length; i++) {
html += `<li>${lb[i].score}: ${lb[i].nickname}</li>`;
}
document.getElementById('leaderboard').innerHTML = html;
}
update_leaderboard();
document.getElementById('width').onchange = update_leaderboard;
document.getElementById('height').onchange = update_leaderboard;
document.getElementById('mines').onchange = update_leaderboard;
function leaderboard_candidate(w, h, m, n, t) { // width, height, mines, nick, time
let lb = get_cookie(`R-${w}-${h}-${m}`);
lb.push({ nickname: n, score: t });
if (lb.length > 1) {
lb = lb.sort(function (a, b) {
let a_split = a.score.split(":");
let b_split = b.score.split(":");
a_split[0] = parseInt(a_split[0]);
a_split[1] = parseInt(a_split[1]);
b_split[0] = parseInt(b_split[0]);
b_split[1] = parseInt(b_split[1]);
if (a_split[0] > b_split[0]) {
return 1;
} else if (a_split[0] < b_split[0]) {
return -1;
} else if (a_split[0] == b_split[0]) {
if (a_split[1] > b_split[1]) {
return 1;
} else {
return -1;
}
}
});
}
let nickname_array = [];
let time_array = [];
let best_of_me = Math.min(lb.length, 10);
for (let i = 0; i < best_of_me; i++) {
nickname_array.push(lb[i].nickname);
time_array.push(lb[i].score);
}
set_cookie(`R-${w}-${h}-${m}`, nickname_array, time_array);
update_leaderboard();
}
</script>
<script>
// wymiary gry
let w = 0
let h = 0
let m = 0
let gra = true
let polozono_miny = false
let odkryte_pola = 0
let czas_startu;
let czas_obecny;
let ms_gry;
let interwal;
// tablica z polami
let plansza = [] // tablice obiektów (pól) { x: int, y: int, mina: true/false, sasiednie_miny: int }
const kolorki = ["red", "green", "blue", "darkseagreen", "cornflowerblue", "beige", "orange", "navy"]
function flaga(btn) {
let x = btn.dataset.x
let y = btn.dataset.y
if (!gra) { return }
event.preventDefault()
if (btn.classList.contains("nieodkryte-pole")) {
plansza[y][x].flaga = !plansza[y][x].flaga;
plansza[y][x].flaga ? btn.innerHTML = '&#128681;' : btn.innerHTML = '';
}
}
function klik(btn) {
let x = btn.dataset.x
let y = btn.dataset.y
if (!polozono_miny) {
czas_startu = new Date();
if (interwal != undefined) { clearInterval(interwal); }
interwal = setInterval(() => {
czas_obecny = new Date();
ms_gry = czas_obecny.getTime() - czas_startu.getTime();
let min = Math.floor(ms_gry / (60000));
let sec = Math.floor((ms_gry % 60000) / 1000);
let piekny_string = min + ":" + (sec > 9 ? sec : `0${sec}`);
document.getElementById("timer-time").innerText = piekny_string;
}, 500); // mniej niż sekunda bo moze sie zdarzyć, że interwał potrwa więcej niż sekundę
// i wtedy zegar nam przeskoczy o dwie sekundy i to by było brzydkie dość
losuj_miny(x, y)
polozono_miny = true
}
if (!gra) { return }
if (plansza[y][x].flaga) { return }
if (document.getElementById(`p${x}-${y}`).classList.contains("odkryte-pole")) { return }
if (plansza[y][x].mina) {
document.getElementById('message').innerText = "Koniec gry, przegrana!";
document.getElementById(`p${x}-${y}`).style.backgroundColor = "red";
gra = false
clearInterval(interwal);
let pola = plansza.flat();
pola.forEach(pole => {
if (pole.mina) {
document.getElementById(`p${pole.x}-${pole.y}`).style.backgroundColor = 'red';
}
});
} else {
btn.classList.remove("nieodkryte-pole")
btn.classList.add("odkryte-pole")
if (plansza[y][x].sasiednie_miny != 0) {
btn.innerText = plansza[y][x].sasiednie_miny
btn.style.color = kolorki[plansza[y][x].sasiednie_miny - 1]
}
odkryte_pola++
if (odkryte_pola == (w * h) - m) {
document.getElementById('message').innerText = "Koniec gry, wygrana!";
leaderboard_candidate(w, h, m, document.getElementById("nickname-box").value, document.getElementById("timer-time").innerText);
gra = false
clearInterval(interwal);
let pola = plansza.flat();
pola.forEach(pole => {
if (pole.mina) {
document.getElementById(`p${pole.x}-${pole.y}`).style.backgroundColor = 'red';
}
});
}
}
// jeśli nie ma min dookoła to odkryj pola sąsiednie
if (plansza[y][x].sasiednie_miny == 0) {
let i = y;
let j = x - 1;
if (i >= 0 && i < h && j >= 0 && j < w) {
if (document.getElementById(`p${j}-${i}`).classList.contains("nieodkryte-pole")) {
klik(document.getElementById(`p${j}-${i}`))
}
}
j += 2;
if (i >= 0 && i < h && j >= 0 && j < w) {
if (document.getElementById(`p${j}-${i}`).classList.contains("nieodkryte-pole")) {
klik(document.getElementById(`p${j}-${i}`))
}
}
j = x;
i = y - 1;
if (i >= 0 && i < h && j >= 0 && j < w) {
if (document.getElementById(`p${j}-${i}`).classList.contains("nieodkryte-pole")) {
klik(document.getElementById(`p${j}-${i}`))
}
}
i += 2;
if (i >= 0 && i < h && j >= 0 && j < w) {
if (document.getElementById(`p${j}-${i}`).classList.contains("nieodkryte-pole")) {
klik(document.getElementById(`p${j}-${i}`))
}
}
}
}
function przygotuj() {
plansza = []
const plansza_table = document.getElementById("plansza")
plansza_table.innerHTML = ''
// wypełnij planszę na razie bez min
let n_html = ''
for (let i = 0; i < h; i++) {
plansza.push([])
n_html += '<tr>'
for (let j = 0; j < w; j++) {
plansza[i].push({ x: j, y: i, mina: false, sasiednie_miny: 0, flaga: false })
n_html += `<td class="nieodkryte-pole" id="p${j}-${i}" onclick="klik(this)" oncontextmenu="flaga(this)" oncontextmenu="flaga" data-x="${j}" data-y="${i}"></td>`
}
n_html += '</tr>'
}
plansza_table.innerHTML += n_html
document.getElementById("timer-wrapper").style.marginBottom = ".5em";
document.getElementById("timer-time").innerText = "0:00";
}
function losuj_miny(unikaj_x = 0, unikaj_y = 0) {
let wspolrzedne_min = []
while (wspolrzedne_min.length < m) {
let random_x = Math.floor(Math.random() * w)
let random_y = Math.floor(Math.random() * h)
if (!wspolrzedne_min.find(wspolrzedna => (wspolrzedna.x == random_x && wspolrzedna.y == random_y))) {
if (!(random_x == unikaj_x && random_y == unikaj_y)) {
wspolrzedne_min.push({ x: random_x, y: random_y })
}
}
}
wspolrzedne_min.forEach(wspolrzedna => {
// znajdz pole
plansza[wspolrzedna.y][wspolrzedna.x].mina = true
// znajdz pola sasiadujace
for (let i = wspolrzedna.y - 1; i <= wspolrzedna.y + 1; i++) {
if (i < 0) { continue }
if (i >= h) { continue }
for (let j = wspolrzedna.x - 1; j <= wspolrzedna.x + 1; j++) {
if (j < 0) { continue }
if (j >= w) { continue }
if (j == wspolrzedna.x && i == wspolrzedna.y) { continue }
plansza[i][j].sasiednie_miny += 1
}
}
})
}
// funkcja startu gry
document.getElementById("start").onclick = function () {
if (document.getElementById("nickname-box").value == '') {
document.getElementById('message').innerText = 'Wprowadź nick!';
return;
}
let w_t = parseInt(document.getElementById("width").value);
let h_t = parseInt(document.getElementById("height").value);
let m_t = parseInt(document.getElementById("mines").value);
// walidacja
if (
isNaN(w_t) |
isNaN(h_t) |
isNaN(m_t)
) {
document.getElementById("message").innerText = "Podaj właściwe wymiary!"
return
}
gra = true
polozono_miny = false
odkryte_pola = 0
w = w_t
h = h_t
m = m_t
document.getElementById('message').innerText = 'Powodzenia!';
przygotuj()
}
</script>
</body>
</html>