DEV/DEV4.1/tp1/modules/Ant.js

76 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-01-26 15:23:26 +01:00
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);
}
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() {
if(this.direction!=270)
{
this.direction += 90;
}
else{
this.direction = 0;
}
}
rotateLeft() {
if(this.direction!=0)
{
this.direction -= 90;
}
else{
this.direction = 270;
}
}
computeNextState()
{
2024-01-26 15:44:50 +01:00
if (this.tiles == 0) {
this.rotateRight();
this.tiles = 1;
}
else{
this.rotateLeft();
this.tiles = 0;
}
2024-01-26 15:23:26 +01:00
}
}
export default Ant;