Advertisement
mikhail_dvorkin

Python multiple libraries showcase

Mar 26th, 2021
983
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. from PIL import Image, ImageDraw
  2. import imageio
  3. import math
  4. import scipy.optimize
  5. import matplotlib.pyplot as plt
  6.  
  7. n = 8
  8. image_size = 400
  9. gif_writer = imageio.get_writer('b.gif', mode='I')
  10.  
  11. def draw_board(y, obstacle=None):
  12.     image = Image.new('RGB', (image_size, image_size), color=(255, 255, 200))
  13.     draw = ImageDraw.Draw(image)
  14.     # 0..7  — удобные координаты → пиксельные
  15.     cell_size = image_size / n
  16.     if obstacle:
  17.         x_obstacle, y_obstacle, r_obstacle = obstacle
  18.         xc_pixel = (x_obstacle + 0.5) * cell_size
  19.         yc_pixel = (y_obstacle + 0.5) * cell_size
  20.         r_pixel = r_obstacle * cell_size
  21.         draw.ellipse((xc_pixel - r_pixel, yc_pixel - r_pixel, xc_pixel + r_pixel, yc_pixel + r_pixel), fill=(255, 0, 0))
  22.     for i in range(n):  # 0 .. n-1
  23.         xc_pixel = (i + 0.5) * cell_size
  24.         yc_pixel = (y[i] + 0.5) * cell_size
  25.         r_pixel = 0.3 * cell_size
  26.         draw.ellipse((xc_pixel - r_pixel, yc_pixel - r_pixel, xc_pixel + r_pixel, yc_pixel + r_pixel), fill=(0, 0, 240))
  27.     image.save('a.png')
  28.     gif_writer.append_data(imageio.imread('a.png'))
  29.  
  30.  
  31. def solve(obstacle):
  32.     def is_forbidden(x, y):
  33.         return math.hypot(x - obstacle[0], y - obstacle[1]) < obstacle[2]
  34.     penalty_matrix = [[is_forbidden(x, y) for y in range(n)] for x in range(n)]
  35.     assignment = list(scipy.optimize.linear_sum_assignment(penalty_matrix)[1])
  36.     draw_board(assignment, obstacle)
  37.     return sum([is_forbidden(x, assignment[x]) for x in range(n)])
  38.  
  39.  
  40. scores = []
  41. for frame in range(50):
  42.     score = solve((2 + frame * 0.1, 1 + frame * 0.05, 2 + frame * 0.05))
  43.     scores.append(score)
  44.  
  45. plt.plot(scores)
  46. plt.title('Lost rooks')
  47. plt.savefig('scores.svg')
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement