MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / LangtonsAnt

Class LangtonsAnt

cellular_automata/langtons_ant.py:17–98  ·  view source on GitHub ↗

Represents the main LangonsAnt algorithm. >>> la = LangtonsAnt(2, 2) >>> la.board [[True, True], [True, True]] >>> la.ant_position (1, 1)

Source from the content-addressed store, hash-verified

15
16
17class LangtonsAnt:
18 """
19 Represents the main LangonsAnt algorithm.
20
21 >>> la = LangtonsAnt(2, 2)
22 >>> la.board
23 [[True, True], [True, True]]
24 >>> la.ant_position
25 (1, 1)
26 """
27
28 def __init__(self, width: int, height: int) -> None:
29 # Each square is either True or False where True is white and False is black
30 self.board = [[True] * width for _ in range(height)]
31 self.ant_position: tuple[int, int] = (width // 2, height // 2)
32
33 # Initially pointing left (similar to the wikipedia image)
34 # (0 = 0° | 1 = 90° | 2 = 180 ° | 3 = 270°)
35 self.ant_direction: int = 3
36
37 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None:
38 """
39 Performs three tasks:
40 1. The ant turns either clockwise or anti-clockwise according to the colour
41 of the square that it is currently on. If the square is white, the ant
42 turns clockwise, and if the square is black the ant turns anti-clockwise
43 2. The ant moves one square in the direction that it is currently facing
44 3. The square the ant was previously on is inverted (White -> Black and
45 Black -> White)
46
47 If display is True, the board will also be displayed on the axes
48
49 >>> la = LangtonsAnt(2, 2)
50 >>> la.move_ant(None, True, 0)
51 >>> la.board
52 [[True, True], [True, False]]
53 >>> la.move_ant(None, True, 0)
54 >>> la.board
55 [[True, False], [True, False]]
56 """
57 directions = {
58 0: (-1, 0), # 0°
59 1: (0, 1), # 90°
60 2: (1, 0), # 180°
61 3: (0, -1), # 270°
62 }
63 x, y = self.ant_position
64
65 # Turn clockwise or anti-clockwise according to colour of square
66 if self.board[x][y] is True:
67 # The square is white so turn 90° clockwise
68 self.ant_direction = (self.ant_direction + 1) % 4
69 else:
70 # The square is black so turn 90° anti-clockwise
71 self.ant_direction = (self.ant_direction - 1) % 4
72
73 # Move ant
74 move_x, move_y = directions[self.ant_direction]

Callers 1

langtons_ant.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected