uloha:had_class

Toto je starší verze dokumentu!


class Snake {
    bodyParts = []
    direction = 'north'
    alive = true
 
    constructor(startX, startY) {
        this.bodyParts.push([startX, startY])
    }
 
    /*
    * Udela jeden krok hada
    * */
    step() {
        if (!this.alive) {
            return false
        }
        const headPosition = this.bodyParts[0]
        const newPosition = [headPosition[0], headPosition[1]]
        if (direction == 'north') {
            newPosition[1]--
        } else if (direction == 'south') {
            newPosition[1]++
        } else if (direction == 'west') {
            newPosition[0]--
        } else if (direction == 'east') {
            newPosition[0]++
        } else {
            throw "Unknown snake direction"
        }
        if (this.collides(newPosition)) {
            // had narazil
            this.alive = false
            return
        }
 
        let snakeHasEaten = false
        // todo: pokud je na newPosition jablicko, rekni ze se had nakrmil
 
        // pridani noveho prvku zleva = vytvoreni "nove" hlavy hada
        this.bodyParts.unshift(newPosition)
        if (!snakeHasEaten) {
            // odebrani posledniho prvku tela ("posun" ocasu)
            this.bodyParts.pop()
        }
    }
 
    setDirection(direction) {
        if (['north', 'east', 'south', 'west'].includes(direction)) {
            this.direction = direction
        } else {
            throw "Unknown direction in setDirection"
        }
    }
 
    collides(position) {
        for (let i = 0; i < this.bodyParts.length; i++) {
            if (position[0] == this.bodyParts[i][0] && position[1] == this.bodyParts[i][1]) {
                return true
            }
        }
        // jinak
        return false
    }
 
    draw(paintFunction){
        for(let i = 0; i < this.bodyParts.length; i++){
            paintFunction(this.bodyParts[i][0], this.bodyParts[i][1], 'green')
        }
    }
}
  • uloha/had_class.1675876241.txt.gz
  • Poslední úprava: 2023/11/15 20:54
  • (upraveno mimo DokuWiki)