Help with javascript array [Snakegame.js]

Asked

Viewed 50 times

1

I have a question about Arrays in javascript using P5.js library, I want to make a coral snake, but for this I need to assign the value of the color for each element of the array, for example:

  • [First element, color:black]
  • [secondElement, orange color]

How could I do it in the best way?`

class Cobra{

    constructor(){
        //tamanho de cada parte
        this.tam = 10;
        //cores da cobra
        this.cor = [
            {_corMargin:'#FFFFFF'},
            {_corUm: '#1B1B1B'},
            {_corDois:'#FFA500'}
        ];
        //parte da cobra
        this.corpo = [
            {_x: 200, _y:200},
            {_x: 190, _y:200},
            {_x: 180, _y:200}
        ];

    }

    desenharCobra() {
        //colocarCores
        stroke(this.cor[0]._corMargin)
        fill(this.cor[1]._corUm)
        
        //colocar corpo pra c/array
        function desenharCorpo(parte){
            rect(parte._x, parte._y,10,10)
        }

        this.corpo.forEach(desenharCorpo)

    }
}

1 answer

0

I did,I executed the foreach method itself parameter that checks the index.

class Cobra {
constructor(){
    this.corpo = {
        cores: ['black','orange'],
        tamanho: 10,
        posicao: [
            {_x: 50, _y:200},
            {_x: 40, _y:200},
            {_x: 30, _y:200},
            {_x: 20, _y:200}
        ]
    }
    this.cauda = []
    this.cabecaCobra = this.corpo.posicao[0]; 
}
desenhoCobra(){
    this.corpo.posicao.forEach(
        function (pos,lugar){
            rect(pos._x, pos._y, 10, 10)
            if (lugar % 2){
                console.log('par')
                fill('black')
            }else{
                console.log('impar')
                fill('orange')
            }
        },
    );
    
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.