Случайное изменение фонового изображения еды в игре snake

#javascript #html

#javascript #HTML

Вопрос:

Моя идея состоит в том, чтобы изменить фоновое изображение только после того, как еда съедена. Однако он просто продолжает меняться взад и вперед между изображениями в моем списке. Я думаю, это из-за requestAnimationFrame, который я использовал в своем скрипте. Это script.js

 import { update as updateSnake, draw as drawSnake, getSnakeHead, snakeIntersection } from './snake.js'
import { update as updateFood, draw as drawFood} from './food.js'
import { outsideGrid } from './grid.js'
let lastRenderTime = 0
let gameOver = 0;
let modal = document.getElementById('modal')
let easy = document.getElementById('easy')
let normal = document.getElementById('normal')
let hard = document.getElementById('hard')
let SNAKE_SPEED
easy.onclick = function() {
    modal.style.display = "none"
    chooseDifficulty(easy)
}

normal.onclick = function() {
    modal.style.display = "none"
    chooseDifficulty(normal)
}

hard.onclick = function() {
    modal.style.display = "none"
    chooseDifficulty(hard)
}
const gameBoard = document.getElementById('game-board')

function chooseDifficulty(difficulty) {
    switch (difficulty) {
        case easy:
            SNAKE_SPEED = 5;
            break;
        case normal:
            SNAKE_SPEED = 8;
            break;
        case hard:
            SNAKE_SPEED = 12;
            break;
    }
    
}

function main(currentTime) {
    if (gameOver) {
        if (confirm('You lost. Press OK to restart')) {
            location.reload()
        }
        return
    }
    window.requestAnimationFrame(main)
    const secondsSinceLastRender = (currentTime - lastRenderTime) / 1000
    if (secondsSinceLastRender < 1 / SNAKE_SPEED) return

    lastRenderTime = currentTime;

    update()
    draw()
}
window.requestAnimationFrame(main)

function update() {
    updateSnake()
    updateFood()
    checkDeath()
}

function draw() {
    gameBoard.innerHTML = ''
    drawSnake(gameBoard)
    drawFood(gameBoard)
}
function checkDeath() {
    gameOver = outsideGrid(getSnakeHead()) || snakeIntersection()
}


  

Вот food.js

 import { onSnake, expandSnake } from './snake.js'
import { randomGridPosition } from './grid.js'
let food = getRandomPosition()
let foodList = ['assets/giraffe.png','assets/lion.png','assets/kangaroo.png'];
let foodImg
const EXPANSION_RATE = 1
export function update() {
    if (onSnake(food)) {
        expandSnake(EXPANSION_RATE)
        food = getRandomPosition()
    }
    
}

export function draw(gameBoard) {
        const foodElement = document.createElement("div")
        foodElement.style.gridRowStart = food.y
        foodElement.style.gridColumnStart = food.x
        foodElement.classList.add('food')
        foodImg = foodList[Math.floor(Math.random() * 3)]
        foodElement.style.backgroundImage = 'url('   foodImg   ')'
        gameBoard.appendChild(foodElement)
        
}

function getRandomPosition() {
    let newFoodPosition
    while (newFoodPosition == null || onSnake(newFoodPosition)) {
        newFoodPosition = randomGridPosition()
    }
    return newFoodPosition
}
  

Как мне изменить изображение еды только один раз после того, как она съедена?

Ответ №1:

Вы можете обновить свой foodImg в update функции в food.js .

Например: (food.js )

 import { onSnake, expandSnake } from './snake.js'
import { randomGridPosition } from './grid.js'
let food = getRandomPosition()
let foodList = ['assets/giraffe.png','assets/lion.png','assets/kangaroo.png'];
let foodImg = foodList[Math.floor(Math.random() * 3)]; // <---- here get random food image
const EXPANSION_RATE = 1
export function update() {
    if (onSnake(food)) {
        expandSnake(EXPANSION_RATE);
        foodImg = foodList[Math.floor(Math.random() * 3)]; // <-- here get new foodImg after food eaten.
        food = getRandomPosition();
    }
    
}

export function draw(gameBoard) {
        const foodElement = document.createElement("div")
        foodElement.style.gridRowStart = food.y
        foodElement.style.gridColumnStart = food.x
        foodElement.classList.add('food')
        // foodImg = foodList[Math.floor(Math.random() * 3)]
        foodElement.style.backgroundImage = 'url('   foodImg   ')'
        gameBoard.appendChild(foodElement)
        
}

function getRandomPosition() {
    let newFoodPosition
    while (newFoodPosition == null || onSnake(newFoodPosition)) {
        newFoodPosition = randomGridPosition()
    }
    return newFoodPosition
}