Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_shape_detection.py
- import tkinter as tk
- from PIL import Image, ImageDraw, ImageFont, ImageTk
- import random
- ww = 500
- hh = 500
- root = tk.Tk()
- root.title("tk_shape_detection")
- root.geometry(f"{ww}x{hh}+10+10")
- canvas = tk.Canvas(root, width=ww, height=hh, bg="black")
- canvas.pack()
- font_size = 500
- font = ImageFont.truetype("times.ttf", font_size)
- text = "S"
- image_mask = Image.new('RGB', (ww, hh), (0, 0, 0))
- draw_mask = ImageDraw.Draw(image_mask)
- bbox = draw_mask.textbbox((0, 0), text, font=font)
- textwidth = bbox[2] - bbox[0]
- textheight = bbox[3] - bbox[1]
- x = (ww - textwidth) // 2 - bbox[0]
- y = (hh - textheight) // 2 - bbox[1]
- draw_mask.text((x, y), text, font=font, fill=(255, 255, 255))
- soldier_mask = image_mask.convert('L')
- soldier = Image.new('RGB', (ww, hh), (0, 0, 0))
- draw = ImageDraw.Draw(soldier)
- draw.text((x, y), text, font=font, fill=(255, 255, 255))
- color_palette = [(255, 255, 0), (0, 0, 255), (128, 0, 128), (255, 165, 0), (0, 165, 255)]
- colors = []
- xy = set()
- for i in range(soldier.height):
- for j in range(soldier.width):
- if soldier_mask.getpixel((j, i)) != 0:
- xy.add((j, i))
- color = color_palette[-1]
- colors.append(color)
- soldier.putpixel((j, i), color)
- color_palette.append(color_palette.pop(j % 3))
- color_palette.append(color_palette.pop(j % 2))
- soldier_tk = ImageTk.PhotoImage(soldier)
- soldier_id = canvas.create_image(ww//2, hh//2, image=soldier_tk)
- bullet = canvas.create_rectangle(0, 0, 10, 10, outline="")
- def shuffle_colors():
- pixels = colors[:]
- random.shuffle(pixels)
- temp_soldier = soldier.copy()
- for (i, j), color in zip(xy, pixels):
- temp_soldier.putpixel((i, j), color)
- temp_soldier_tk = ImageTk.PhotoImage(temp_soldier)
- canvas.itemconfig(soldier_id, image=temp_soldier_tk)
- return temp_soldier_tk
- def move_bullet(event):
- canvas.coords(bullet, event.x - 5, event.y - 5, event.x + 5, event.y + 5)
- def check_collision():
- bullet_coords = canvas.coords(bullet)
- bx1, by1, bx2, by2 = map(int, bullet_coords)
- points_to_check = [
- (bx1, by1), (bx2, by1), (bx1, by2), (bx2, by2),
- ((bx1 + bx2) // 2, (by1 + by2) // 2)
- ]
- for x, y in points_to_check:
- if 0 < x < ww and 0 < y < hh:
- if soldier_mask.getpixel((x, y)) != 0:
- return True
- return False
- canvas.bind("<Motion>", move_bullet)
- def toggle_text():
- global soldier_tk
- if canvas.itemcget(soldier_id, 'state') == 'normal':
- canvas.itemconfig(soldier_id, state='hidden')
- else:
- canvas.itemconfig(soldier_id, state='normal')
- root.after(1500, toggle_text)
- toggle_text()
- while True:
- if check_collision():
- canvas.itemconfig(bullet, fill="red")
- else:
- canvas.itemconfig(bullet, fill="green")
- soldier_tk = shuffle_colors()
- root.update_idletasks()
- root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement