farry

tkinter-moves-collisions.py

Mar 30th, 2020
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # Requires Python 3.6+
  3.  
  4. import tkinter as tk
  5. from random import randint
  6.  
  7. w, h = 800, 600
  8. s = 80              # size of disk
  9. root = tk.Tk()
  10. canvas = tk.Canvas(root, width=w, height=h, bg="black")
  11. canvas.pack()
  12.  
  13. player = canvas.create_oval(0, 0, s, s, fill='white')
  14. canvas.move(player, w // 2 -15, h // 2 -15)
  15.  
  16. arrows = {"Up":(0,-5), "Down":(0,5), "Left":(-5,0), "Right":(5,0)}
  17. for key in arrows:
  18.     moves = lambda _, key=key: canvas.move(player, *arrows[key])
  19.     canvas.bind_all(f'<KeyPress-{key}>', moves)
  20.  
  21. def collisions():
  22.     px, py = canvas.bbox(player)[0:2]
  23.     if not 0 <= px + 1 <= w - s or not 0 <= py + 1 <= h - s:
  24.         canvas.itemconfig(player, fill='red')
  25.         return False
  26.     for enemy in enemies:
  27.         canvas.move(enemy, randint(-1, 1), randint(-1, 1))
  28.         ex, ey = canvas.bbox(enemy)[0:2]
  29.         dist = ((px - ex) ** 2 + (py - ey) ** 2) ** 0.5
  30.         if dist < s:
  31.             canvas.itemconfig(enemy, fill='red')
  32.             return False
  33.     return True
  34.  
  35. def spawn():
  36.     if randint(0, 5) == 0:
  37.         px, py = canvas.bbox(player)[0:2]
  38.         enemy = canvas.create_oval(-s, -s, 0, 0, fill="green")
  39.         ex, ey = randint(0, w - s), randint(0, h - s)
  40.         dist = ((px - ex) ** 2 + (py - ey) ** 2) ** 0.5
  41.         if dist > s * 1.1:
  42.             canvas.move(enemy, ex + 1 + s, ey + 1 + s)
  43.             enemies.append(enemy)
  44.         else:
  45.             del enemy
  46.     if collisions():
  47.         root.after(50, spawn)
  48.  
  49. enemies = []
  50. spawn()
  51. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment