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

Method move_ant

cellular_automata/langtons_ant.py:37–84  ·  view source on GitHub ↗

Performs three tasks: 1. The ant turns either clockwise or anti-clockwise according to the colour of the square that it is currently on. If the square is white, the ant turns clockwise, and if the square is black the ant turns anti-clockwise 2

(self, axes: plt.Axes | None, display: bool, _frame: int)

Source from the content-addressed store, hash-verified

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]
75 self.ant_position = (x + move_x, y + move_y)
76
77 # Flip colour of square
78 self.board[x][y] = not self.board[x][y]
79
80 if display and axes:
81 # Display the board on the axes
82 axes.get_xaxis().set_ticks([])
83 axes.get_yaxis().set_ticks([])
84 axes.imshow(self.board, cmap="gray", interpolation="nearest")
85
86 def display(self, frames: int = 100_000) -> None:
87 """

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected