# Bounding Box Collision – python

A python program using PIL (pillow) to place a letter randomly on the canvas of fixed dimension. Uses AABB – AABB bounding box collision detection for letter-letter collision.
Ref: Real-time Collision Detection by Christer Ericson

``````"""
April 30, 2019
A program to palce letter a letter randomly on the canvas.
Letter Bounding Box Collision Test
Author: jithesh Kuyyalil https://jitheshkuyyalil.com
Date: April 26, 2019
"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from random import randint

img = Image.new("L", (500, 500))
word = "b"
font_size = 100
font_path = 'DroidSansMono.ttf'
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, font_size)
box_coord = []  # save bounding box co-ordinates [[(), ()], [(), ()]]
for i in range(100):
# x, y, where the word/letter is placed
x = randint(0, 500)  # 110 400
y = randint(0, 500)  # 110 400
print('xrand, yrand', x, y)
(x1, y1, x2, y2) = font.getmask(word).getbbox()
(width, baseline), (offset_x, offset_y) = font.font.getsize(word)
rect_1 = (x1 + x + offset_x, y1 + y + offset_y)   # top left corner
rect_2 = (x2 + x + offset_x -1, y2 + y + offset_y) # bottom right corner \
# don't know -1 ? \
# Rectangle fits well with -1.
intersect = False  # both letter-boundary, letter-letter collision
# boundary collision testing - boundary (0,0), (500,500)
if not (rect_2 < 500 and rect_2 < 500): # hitting the boundary
intersect = True
if intersect == False: # only if letter doesn't hit boundary
# checking for collision
if box_coord != []:
print(box_coord)
for box in box_coord:
if (rect_1 > box) or (rect_2 < box): # not \
# intersecting
continue
if (rect_1 > box) or (rect_2 < box): # not \
# interesecting
continue
intersect = True
break # interesecting; find new x, y

if not intersect :
#draw.rectangle([rect_1, rect_2], outline='white')
draw.text((x, y), word, fill='white', font=font) # 175, 90
box_coord.append([rect_1, rect_2])
img.show()
``````