MiniMato
- 📅 2021-08-21T13:09:40.000Z
- 👁️ 246 katselukertaa
- 🔓 Julkinen
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>MiniMato</title>
<style media="screen">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>MiniMato</h1><hr>
<span id="pisteet"></span><br>Pelaaja: <span id="xyz"></span><br>Omena: <span id="omppu"></span><br>
<canvas id="snake" width="180" height="70"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("snake");
var ctx = canvas.getContext("2d");
var score = 0
var omppux = 10
var omppuy = 10
var liike;
function omppu() {
ctx.beginPath();
ctx.rect(omppux, omppuy, 10, 10);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
}
var x = 10
var y = 30
function snake() {
ctx.beginPath();
ctx.rect(x, y, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
}
function onkopaalla() {
if (omppux == x && omppuy == y) {
score += 10;
omppux = Math.round(Math.floor(Math.random() * (canvas.width - 10)) / 10) * 10;
omppuy = Math.round(Math.floor(Math.random() * (canvas.height - 10)) / 10) * 10;
document.getElementById("omppu").innerHTML = " | X: " + omppux + "| Y: " + omppuy;
}
}
function onkoyli() {
if (y > canvas.height - 10) {
return true
} else if (x > canvas.width - 10) {
return true
} else if (x < 0) {
return true
} else if (y < 0) {
return true
} else {
return false
}
}
function jatkaliiketta() {
if (liike === "ylos") {
y -= 10
liike = "ylos"
if (onkoyli()) {
y += 10
}
} else if (liike === "alas") {
y += 10
if (onkoyli()) {
y -= 10
}
} else if (liike === "oikea") {
x += 10
if (onkoyli()) {
x -= 10
}
} else if (liike === "vasen") {
x -= 10
if (onkoyli()) {
x += 10
}
}
}
function pisteet() {
document.getElementById("pisteet").innerHTML = "Score: <span style='color: red;'>" + score + "</span>";
}
document.addEventListener('keyup', (e) => {
ctx.clearRect(x, y, canvas.width, canvas.height);
if (e.code === "ArrowUp") {
y -= 10
liike = "ylos"
if (onkoyli()) {
y += 10
}
} else if (e.code === "ArrowDown") {
y += 10
liike = "alas"
if (onkoyli()) {
y -= 10
}
} else if (e.code === "ArrowRight") {
x += 10
liike = "oikea"
if (onkoyli()) {
x -= 10
}
} else if (e.code === "ArrowLeft") {
x -= 10
liike = "vasen"
if (onkoyli()) {
x += 10
}
}
onkopaalla()
omppu()
pisteet()
snake()
document.getElementById("xyz").innerHTML = " | X: " + x + "| Y: " + y;
});
omppu()
snake()
setInterval(function(){
ctx.clearRect(x, y, canvas.width, canvas.height);
jatkaliiketta();
onkopaalla();
omppu();
pisteet();
snake();
}, 1000);
</script>
</body>
</html>