speeeeeeed and score and no bugs

This commit is contained in:
2024-01-29 11:26:36 +01:00
parent 4ae67b1e08
commit e01c060671

View File

@@ -1,11 +1,12 @@
<script setup lang="ts">
import { Ref, ref } from 'vue';
import { Ref, computed, ref } from 'vue';
const grid = ref(genGrid(30, 30))
const currentCoin = ref(spawnCoin())
const direction: Ref<'left' | 'right' | 'top' | 'bottom' | undefined> = ref(undefined)
const snake = ref(spawnSnake())
const score = ref(0)
const lastScore: Ref<undefined | number> = ref(undefined)
interface Cell {
x: number
@@ -113,7 +114,10 @@ function death() {
currentCoin.value = spawnCoin()
snake.value = spawnSnake()
direction.value = undefined;
lastScore.value = score.value
score.value = 0
clearInterval(currentInterval)
currentInterval = createInterval()
}
function killSnake() {
@@ -128,46 +132,58 @@ function killCoin() {
coinCell.color = 'white'
}
const speed = computed(() => {
return 500 / (score.value + 1)
})
setInterval(() => {
let currentInterval = createInterval()
if (direction.value === undefined) {
return
}
function createInterval() {
return setInterval(() => {
switch (direction.value) {
case 'left':
moveSnake(-1, 0)
break
case 'right':
moveSnake(1, 0)
break
case 'top':
moveSnake(0, -1)
break
case 'bottom':
moveSnake(0, 1)
break
}
if (direction.value === undefined) {
return
}
switch (direction.value) {
case 'left':
moveSnake(-1, 0)
break
case 'right':
moveSnake(1, 0)
break
case 'top':
moveSnake(0, -1)
break
case 'bottom':
moveSnake(0, 1)
break
}
if (currentCoin.value.x === snake.value.cell.x && currentCoin.value.y === snake.value.cell.y) {
snake.value.length++
currentCoin.value = spawnCoin()
score.value++
}
}, 500);
if (currentCoin.value.x === snake.value.cell.x && currentCoin.value.y === snake.value.cell.y) {
snake.value.length++
currentCoin.value = spawnCoin()
score.value++
if (currentInterval) {
clearInterval(currentInterval)
currentInterval = createInterval()
}
}
}, speed.value);
}
function keydown(event: KeyboardEvent) {
switch (event.key) {
case 'ArrowRight': direction.value = 'right'
case 'ArrowRight': direction.value = direction.value !== 'left' ? 'right' : 'left'
break
case 'ArrowLeft': direction.value = 'left'
case 'ArrowLeft': direction.value = direction.value !== 'right' ? 'left' : 'right'
break
case 'ArrowUp': direction.value = 'top'
case 'ArrowUp': direction.value = direction.value !== 'bottom' ? 'top' : 'bottom'
break
case 'ArrowDown': direction.value = 'bottom'
case 'ArrowDown': direction.value = direction.value !== 'top' ? 'bottom' : 'top'
break
}
}
@@ -178,6 +194,7 @@ window.addEventListener('keydown', keydown)
<template>
<h1>Score {{ score }}</h1>
<h2 v-if="lastScore">Last Score {{ lastScore}}</h2>
<div class="grid" @keyup="keydown($event)">
<div class="row" v-for="row in grid">
<div class="cell" :class="`cell-${cell.y}-${cell.x}`" v-for="cell in row"