Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const canvas = document.getElementById("game")
- const context = canvas.getContext('2d');
- const tileCount = 20
- const tileSize = 18
- let headX = 10
- let headY = 10
- let appleX = 0
- let appleY = 0
- let xVelocity = 0
- let yVelocity = 0
- function clearScreen() {
- context.fillStyle = "black"
- context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight)
- }
- function drawGame() {
- if(isGameOver() == true) {
- return
- }
- changeSnakePosition()
- clearScreen()
- drawSnake()
- drawApple()
- setTimeout(drawGame, 1000 / 7)
- }
- function drawSnake() {
- context.fillStyle = "green"
- context.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize)
- }
- // drawSnake()
- function keyPressed() {
- if(event.keyCode == 87) { // W
- if(yVelocity == 1) {
- return
- }
- xVelocity = 0
- yVelocity = -1
- }
- if(event.keyCode == 83) { // S
- if(yVelocity == -1) {
- return
- }
- xVelocity = 0
- yVelocity = 1
- }
- if(event.keyCode == 65) { // A
- if(xVelocity == 1) {
- return
- }
- xVelocity = -1
- yVelocity = 0
- }
- if(event.keyCode == 68) { // D
- if(xVelocity == -1) {
- return
- }
- xVelocity = 1
- yVelocity = 0
- }
- }
- function changeSnakePosition() {
- headX += xVelocity
- headY += yVelocity
- }
- function drawApple() {
- context.fillStyle = "red"
- context.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize)
- }
- function collisionDetection() {
- if(appleX == headX && appleY == headY) {
- appleX = Math.floor(Math.random() * tileCount)
- appleY = Math.floor(Math.random() * tileCount)
- }
- }
- function isGameOver() {
- let over = false
- if(xVelocity == 0 && yVelocity == 0) {
- return false
- }
- if(headX < 0) {
- over = true
- }
- if(headX >= tileCount) {
- over = true
- }
- if(headY < 0) {
- over = true
- }
- if(headY >= tileCount) {
- over = true
- }
- return over
- }
- document.addEventListener('keydown', keyPressed)
- drawGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement