import random
def display_grid(grid):
for row in grid:
print(' '.join(row))
print()
def move_titanic(grid, row, col):
# Check if Titanic is at the western edge
if col == 0:
return True, row, col
# Check for iceberg to the west
if grid[row][col - 1] == 'I':
# Try to move north or south to avoid iceberg
if row > 0 and grid[row - 1][col] == '.':
return False, row - 1, col
elif row < len(grid) - 1 and grid[row + 1][col] == '.':
return False, row + 1, col
else:
# Move west
return False, row, col - 1
def place_icebergs(grid, num_icebergs):
rows = len(grid)
cols = len(grid[0])
for _ in range(num_icebergs):
row, col = random.randint(0, rows - 1), random.randint(1, cols - 1)
grid[row][col] = 'I'
def titanic_simulation(rows, columns, num_icebergs):
# Initialize the grid
grid = [['.' for _ in range(columns)] for _ in range(rows)]
# Place the Titanic
titanic_row, titanic_col = random.randint(0, rows - 1), columns - 1
grid[titanic_row][titanic_col] = 'T'
# Place icebergs
place_icebergs(grid, num_icebergs)
# Run the simulation
display_grid(grid)
safe_landing = False
while not safe_landing:
safe_landing, titanic_row, titanic_col = move_titanic(grid, titanic_row, titanic_col)
grid[titanic_row][titanic_col] = 'T'
display_grid(grid)
print("Titanic has landed safely!")
# Example usage
titanic_simulation(10, 15, 10)