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,8 +132,14 @@ function killCoin() {
coinCell.color = 'white'
}
const speed = computed(() => {
return 500 / (score.value + 1)
})
setInterval(() => {
let currentInterval = createInterval()
function createInterval() {
return setInterval(() => {
if (direction.value === undefined) {
return
@@ -155,19 +165,25 @@ setInterval(() => {
snake.value.length++
currentCoin.value = spawnCoin()
score.value++
}
}, 500);
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"