How to resolve the algorithm Langton's ant step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Langton's ant step by step in the Python programming language

Table of Contents

Problem Statement

Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules: This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 cells wide.
Conceptually the ant can then walk infinitely far away.

Start the ant near the center of a 100x100 field of cells, which is about big enough to contain the initial chaotic part of the movement. Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind.

The problem has received some analysis; for more details, please take a look at the Wikipedia article   (a link is below)..

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Langton's ant step by step in the Python programming language

This code simulates the behaviour of an ant in a two-dimensional grid. The ant starts at the center of the grid and moves in one of the four cardinal directions: up, right, down, or left. At each step, the ant changes the color of the cell it is on from white to black or vice versa, and then turns either right or left according to the color of the cell it is on. If the cell is white, the ant turns right; if it is black, the ant turns left.

The code defines two enumerations, Dir and Color, which represent the possible directions and colors, respectively. The invert_color function takes a grid, an x coordinate, and a y coordinate as input and changes the color of the cell at that coordinate from white to black or vice versa. The next_direction function takes a grid, an x coordinate, a y coordinate, and a direction as input and returns the next direction the ant will move in. The next_position function takes an x coordinate, a y coordinate, and a direction as input and returns the next position the ant will move to. The print_grid function takes a grid as input and prints it to the console.

The ant function takes a width, a height, and a maximum number of steps as input and simulates the behaviour of an ant in a grid of the given width and height for the given number of steps. The ant function initializes a grid of the given width and height with all cells set to white and starts the ant at the center of the grid. At each step, the ant changes the color of the cell it is on, turns either right or left, and moves to the next cell in the grid. The print_grid function is called after each step to display the grid to the console.

The if __name__ == "__main__" block calls the ant function with a width of 75, a height of 52, and a maximum number of steps of 12000. This will simulate the behaviour of an ant in a grid of size 75x52 for 12000 steps and display the progression of the grid to the console.

Source code in the python programming language

"""Langton's ant implementation."""
from enum import Enum, IntEnum


class Dir(IntEnum):
    """Possible directions."""

    UP = 0
    RIGHT = 1
    DOWN = 2
    LEFT = 3


class Color(Enum):
    """Possible colors."""

    WHITE = " "
    BLACK = "#"


def invert_color(grid, x, y):
    """Invert the color of grid at x, y coordinate."""
    if grid[y][x] == Color.BLACK:
        grid[y][x] = Color.WHITE
    else:
        grid[y][x] = Color.BLACK


def next_direction(grid, x, y, direction):
    """Compute next direction according to current position and direction."""
    if grid[y][x] == Color.BLACK:
        turn_right = False
    else:
        turn_right = True
    direction_index = direction.value
    if turn_right:
        direction_index = (direction_index + 1) % 4
    else:
        direction_index = (direction_index - 1) % 4
    directions = [Dir.UP, Dir.RIGHT, Dir.DOWN, Dir.LEFT]
    direction = directions[direction_index]
    return direction


def next_position(x, y, direction):
    """Compute next position according to direction."""
    if direction == Dir.UP:
        y -= 1
    elif direction == Dir.RIGHT:
        x -= 1
    elif direction == Dir.DOWN:
        y += 1
    elif direction == Dir.LEFT:
        x += 1
    return x, y


def print_grid(grid):
    """Display grid."""
    print(80 * "#")
    print("\n".join("".join(v.value for v in row) for row in grid))


def ant(width, height, max_nb_steps):
    """Langton's ant."""
    grid = [[Color.WHITE] * width for _ in range(height)]
    x = width // 2
    y = height // 2
    direction = Dir.UP

    i = 0
    while i < max_nb_steps and 0 <= x < width and 0 <= y < height:
        invert_color(grid, x, y)
        direction = next_direction(grid, x, y, direction)
        x, y = next_position(x, y, direction)
        print_grid(grid)
        i += 1


if __name__ == "__main__":
    ant(width=75, height=52, max_nb_steps=12000)


  

You may also check:How to resolve the algorithm Longest increasing subsequence step by step in the Julia programming language
You may also check:How to resolve the algorithm Parallel calculations step by step in the Swift programming language
You may also check:How to resolve the algorithm Smith numbers step by step in the Julia programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the K programming language
You may also check:How to resolve the algorithm Exponentiation operator step by step in the Modula-3 programming language