JS/TP01/EX1/modules/Ant.js

87 lines
1.5 KiB
JavaScript

class Ant {
x = 0; // position
y = 0;
move = 0;
w = 0; // universe dimensions
h = 0;
direction = 0; // 0 90 180 270
state = 0;
tiles = null;
constructor (w,h)
{
this.tiles = new Array(w).fill(null);
this.tiles.forEach((el,i) => this.tiles[i] = new Array(h).fill(0));
this.w = w;
this.h = h;
this.x = Math.floor(w/2);
this.y = Math.floor(h/2);
}
reset() {
this.direction = 0;
this.x = Math.floor(this.w/2);
this.y = Math.floor(this.h/2);
this.state = 0;
this.tiles.forEach(el=>el.fill(0));
}
moveForward()
{
switch (this.direction) {
case 0:
this.x = ((this.x + 1) + this.w) % this.w;
break
case 90:
this.y = ((this.y + 1) + this.h) % this.h;
break
case 180:
this.x = ((this.x - 1) + this.w) % this.w;
break
case 270:
this.y = ((this.y - 1) + this.h) % this.h;
break
}
this.move ++;
this.computeNextState();
}
rotateRight() {
// TODO
this.direction = (this.direction+90)%360;
}
rotateLeft() {
// TODO
this.direction = (this.direction+270)%360;
}
computeNextState()
{
// TODO
if (this.tiles[this.x][this.y]===1){ //noir
if (this.state ===1){
this.state = 0;
this.tiles[this.x][this.y] = 0;
}
else{
this.rotateLeft();
this.tiles[this.x][this.y] = 0;
}
}
else{ // blanc
if (this.state ===1){
this.rotateRight();
this.tiles[this.x][this.y] = 1;
}
else{
this.state = 1;
this.tiles[this.x][this.y] = 1;
}
}
}
}
export default Ant;