Skip to content

Instantly share code, notes, and snippets.

@ales
Created June 14, 2023 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ales/1cb5086fe7b9dcb3d05963b4992ac5c9 to your computer and use it in GitHub Desktop.
Save ales/1cb5086fe7b9dcb3d05963b4992ac5c9 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Had ~~</title>
<style>
body {
margin: 0
}
section {
background-color: rgb(16, 188, 88);
width: 20em;
height: 20em;
}
b {
background-color: black;
}
b, i {
width: 1em;
height: 1em;
display: block;
position: absolute;
}
</style>
</head>
<body>
<section>
<div id="had">
<b>a</b>
<b>b</b>
<b>c</b>
</div>
<i id="apple">🍎</i>
</section>
<script>
const areaSize = 20
let position = [0, 0] // x, y souradnice hada
let direction = [1, 0] // vpravo
let applePosition = [10,10]
const setApple = () => {
apple.style.left = applePosition[0] + "em"
apple.style.top = applePosition[1] + "em"
}
setApple()
const setDirection = (event) => {
const key = event.key
if (key == 'ArrowLeft') {
direction = [-1, 0]
} else if (key == 'ArrowRight') {
direction = [1, 0]
} else if (key == 'ArrowUp') {
direction = [0, -1]
} else if (key == 'ArrowDown') {
direction = [0, 1]
}
}
window.onkeydown = setDirection
const moveToDirection = (e, i) => {
const location = (e + direction[i]) % areaSize
return location < 0 ? areaSize - 1 : location
}
const step = () => {
const tail = had.children[0]
const newTail = tail.cloneNode()
position = position.map(moveToDirection)
tail.style.left = position[0] + "em";
tail.style.top = position[1] + "em";
had.append(tail)
if (Math.random() > 0.9) {
had.prepend(newTail)
}
}
setInterval(step, 200)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment