63 lines
1.8 KiB
JavaScript
63 lines
1.8 KiB
JavaScript
class Ant {
|
|
constructor(grid, startX, startY, transitionTable) {
|
|
this.grid = grid;
|
|
this.x = startX;
|
|
this.y = startY;
|
|
this.direction = 90; // 0: N, 90: E, 180: S, 270: W
|
|
this.antState = 0;
|
|
this.transitionTable = transitionTable;
|
|
this.numAntStates = transitionTable.length;
|
|
this.numTileStates = transitionTable[0].length;
|
|
}
|
|
|
|
step() {
|
|
const tileState = this.grid[this.y][this.x];
|
|
const transition = this.transitionTable[this.antState][tileState];
|
|
|
|
const [antStateChange, directionChange, tileStateChange] = transition;
|
|
|
|
// Appliquer les changements
|
|
this.antState = (this.antState + antStateChange) % this.numAntStates;
|
|
this.direction = (this.direction + directionChange + 360) % 360;
|
|
this.grid[this.y][this.x] = (tileState + tileStateChange) % this.numTileStates;
|
|
|
|
// Déplacer la fourmi
|
|
switch (this.direction) {
|
|
case 0: this.y--; break;
|
|
case 90: this.x++; break;
|
|
case 180: this.y++; break;
|
|
case 270: this.x--; break;
|
|
}
|
|
|
|
// Gérer les bords de la grille
|
|
const gridSize = this.grid.length;
|
|
this.x = (this.x + gridSize) % gridSize;
|
|
this.y = (this.y + gridSize) % gridSize;
|
|
}
|
|
|
|
reset() {
|
|
const gridSize = this.grid.length;
|
|
for (let y = 0; y < gridSize; y++) {
|
|
for (let x = 0; x < gridSize; x++) {
|
|
this.grid[y][x] = 0;
|
|
}
|
|
}
|
|
this.x = Math.floor(gridSize / 2);
|
|
this.y = Math.floor(gridSize / 2);
|
|
this.direction = 90;
|
|
this.antState = 0;
|
|
}
|
|
}
|
|
|
|
// Exemple d'utilisation dans app.js
|
|
// const langtonTable = [
|
|
// [[0, 90, 1], [0, -90, 0]]
|
|
// ];
|
|
// ant = new Ant(grid, Math.floor(gridSize / 2), Math.floor(gridSize / 2), langtonTable);
|
|
|
|
// Exemple de la table du TP
|
|
const tpTable = [
|
|
// Tuile 0 Tuile 1
|
|
[[1, 0, 1], [0, 90, 1]], // Fourmi 0
|
|
[[0, -90, 1], [1, 0, 1]] // Fourmi 1
|
|
]; |