snake can now die, score is available

This commit is contained in:
2024-01-27 22:40:35 +01:00
parent 37197c3596
commit d9638f714d

View File

@@ -1,11 +1,11 @@
<script setup lang="ts">
import { Ref, ref } from 'vue';
const grid = ref(genGrid(30, 30))
const currentCoin = ref(spawnCoin())
const direction: Ref<'left' | 'right' | 'top' | 'bottom' | undefined> = ref('right')
const direction: Ref<'left' | 'right' | 'top' | 'bottom' | undefined> = ref(undefined)
const snake = ref(spawnSnake())
const score = ref(0)
interface Cell {
x: number
@@ -67,18 +67,22 @@ function randomCell() {
const randomRow = random(grid.value)
const randomCell = random(randomRow)
return randomCell
return randomCell
}
function moveSnake(x: number, y: number) {
const current = snake.value.cell
const newCell = grid.value[current.x + x][current.y + y]
const newCell = getCell(current.x + x, current.y + y);
if (newCell === undefined || newCell.color === 'green') {
death()
return;
}
newCell.color = 'green'
snake.value.cell = newCell
snake.value.history.push(newCell)
if (snake.value.history.length > length) {
const currentLength = snake.value.history.length
const allowedLength = snake.value.length
@@ -90,6 +94,36 @@ function moveSnake(x: number, y: number) {
}
function getCell(x: number, y: number) {
try {
return grid.value[x][y]
} catch {
return undefined
}
}
function death() {
killSnake()
killCoin()
currentCoin.value = spawnCoin()
snake.value = spawnSnake()
direction.value = undefined;
score.value = 0
}
function killSnake() {
snake.value.history
for (const cell of snake.value.history) {
cell.color = 'white'
}
}
function killCoin() {
const coinCell = grid.value[currentCoin.value.x][currentCoin.value.y]
coinCell.color = 'white'
}
setInterval(() => {
if (direction.value === undefined) {
@@ -115,8 +149,8 @@ setInterval(() => {
if (currentCoin.value.x === snake.value.cell.x && currentCoin.value.y === snake.value.cell.y) {
snake.value.length++
currentCoin.value = spawnCoin()
score.value++
}
}, 500);
@@ -138,6 +172,7 @@ window.addEventListener('keydown', keydown)
</script>
<template>
<h1>Score {{ score }}</h1>
<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"
@@ -168,4 +203,4 @@ window.addEventListener('keydown', keydown)
width: 10px;
overflow: hidden;
}
</style>
</style>