So I'm trying to make snake. The snake function is the green block that moves with the arrows, and I'm trying to make another block that will be the fruit. But at the moment I'm trying to make a button that is in the canvas, that when clicked will run all the functions for the game.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<link rel="stylesheet" href="snake.css">
</head>
<body>
<input type="button" value="Play Snake" onclick="play()" value="test">
<canvas class="canvas"></canvas>
<script src="snake.js"></script>
<script src="fruit.js"></script>
</body>
</html>
here is my javascript
const canvas = document.querySelector('canvas')
canvas.height = window.innerHeight
canvas.width = window.innerWidth
let x = 580
let y = 275
let dx = 0
let dy = 0
const c = canvas.getContext('2d')
function snake(){
requestAnimationFrame(snake)
c.clearRect(0,0, innerWidth,innerHeight)
c.beginPath()
c.fillStyle = 'rgb(0,128,0)'
c.fillRect(x, y ,20 ,20)
if (x > innerWidth - 20 || x < 0 ){
alert('You Lose!'),x = 580, y = 275, dx = 0, dy = 0}
if (y > innerHeight -20 || y < 0 ){
alert('You Lose!'),x = 580, y = 275, dx = 0, dy = 0}
x += dx
y += dy
document.onkeydown = function(e){
e = e || window.event;
var key = e.which || e.keyCode
if (key == 37){dx = -4, dy = 0}
if (key == 38){dy = -4, dx = 0}
if (key == 39){dx = 4, dy = 0}
if (key == 40){dy = 4, dx = 0}
}
}
function fruit(){
c.beginPath()
c.fillStyle = '#000'
c.fillRect(100,100,10,10)
}
function play(){
snake();
fruit()
}