Advertisement
Josif_tepe

Untitled

May 19th, 2023
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const canvas = document.getElementById("game")
  2. const context = canvas.getContext('2d');
  3.  
  4. const tileCount = 20
  5. const tileSize = 18
  6. let headX = 10
  7. let headY = 10
  8. let appleX = 0
  9. let appleY = 0
  10. let xVelocity = 0
  11. let yVelocity = 0
  12. function clearScreen() {
  13.     context.fillStyle = "black"
  14.     context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight)
  15. }
  16. function drawGame() {
  17.     if(isGameOver() == true) {
  18.         return
  19.     }
  20.     changeSnakePosition()
  21.     clearScreen()
  22.     drawSnake()
  23.     drawApple()
  24.     setTimeout(drawGame, 1000 / 7)
  25. }
  26. function drawSnake() {
  27.     context.fillStyle = "green"
  28.     context.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize)
  29. }
  30. // drawSnake()
  31.  
  32. function keyPressed() {
  33.     if(event.keyCode == 87) { // W
  34.         if(yVelocity == 1) {
  35.             return
  36.         }
  37.  
  38.         xVelocity = 0
  39.         yVelocity = -1
  40.     }
  41.     if(event.keyCode == 83) { // S
  42.  
  43.         if(yVelocity == -1) {
  44.             return
  45.         }
  46.  
  47.         xVelocity = 0
  48.         yVelocity = 1
  49.     }
  50.     if(event.keyCode == 65) { // A
  51.         if(xVelocity == 1) {
  52.             return
  53.         }
  54.  
  55.         xVelocity = -1
  56.         yVelocity = 0
  57.     }
  58.     if(event.keyCode == 68) { // D
  59.         if(xVelocity == -1) {
  60.             return
  61.         }
  62.  
  63.         xVelocity = 1
  64.         yVelocity = 0
  65.     }
  66.  
  67. }
  68. function changeSnakePosition() {
  69.     headX += xVelocity
  70.     headY += yVelocity
  71.  
  72.    
  73.  
  74. }
  75. function drawApple() {
  76.     context.fillStyle = "red"
  77.     context.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize)
  78. }
  79. function collisionDetection() {
  80.     if(appleX == headX && appleY == headY) {
  81.        appleX = Math.floor(Math.random() * tileCount)
  82.        appleY = Math.floor(Math.random() * tileCount)
  83.     }
  84. }
  85. function isGameOver() {
  86.     let over = false
  87.     if(xVelocity == 0 && yVelocity == 0) {
  88.         return false
  89.     }
  90.     if(headX < 0) {
  91.         over = true
  92.     }
  93.     if(headX >= tileCount) {
  94.         over = true
  95.     }
  96.     if(headY < 0) {
  97.         over = true
  98.     }
  99.     if(headY >= tileCount) {
  100.         over = true
  101.     }
  102.     return over
  103. }
  104. document.addEventListener('keydown', keyPressed)
  105. drawGame()
  106.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement