Advertisement
hang0l

Ball_game

Jun 22nd, 2020
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. from tkinter import *
  2. from random import randrange as rnd, choice
  3.  
  4. root = Tk()
  5. root.geometry('800x600')
  6. canv = Canvas(root, bg = 'white')
  7. canv.pack(fill = BOTH, expand = 1)
  8.  
  9. colors = ['red', 'orange', 'yellow', 'green', 'blue']
  10. i = 0
  11.  
  12.  
  13. class Ball():
  14. def __init__(self):
  15. root.update_idletasks()
  16. size = root.geometry()
  17. x_ball = size.split('x')[0]
  18. size2 = size.split('x')[1]
  19. y_ball = size2.split('+')[0]
  20. self.r = rnd(20, 50)
  21. self.x = rnd(self.r, (int(x_ball) - self.r))
  22. self.y = rnd(self.r, (int(y_ball) - self.r))
  23. self.color = choice(colors)
  24. self.ball = canv.create_oval(self.x - self.r, self.y - self.r,
  25. self.x + self.r, self.y + self.r,
  26. fill = self.color)
  27. self.dx = choice((-5, -4, -3, 3, 4, 5))
  28. self.dy = choice((self.dx, -(self.dx)))
  29.  
  30. def mirror(self):
  31. root.update_idletasks()
  32. size = root.geometry()
  33. x_ball = size.split('x')[0]
  34. size2 = size.split('x')[1]
  35. y_ball = size2.split('+')[0]
  36. self.x += self.dx
  37. self.y += self.dy
  38. if canv.coords(self.ball)[0] <= 0:
  39. self.dx = - (self.dx)
  40. if canv.coords(self.ball)[1] <= 0:
  41. self.dy = - (self.dy)
  42. if canv.coords(self.ball)[2] >= int(x_ball):
  43. self.dx = - (self.dx)
  44. if canv.coords(self.ball)[3] >= int(y_ball):
  45. self.dy = - (self.dy)
  46.  
  47. def move(self):
  48. canv.move(self.ball, self.dx, self.dy)
  49.  
  50. def click(self, event):
  51. global i
  52. if self.x > event.x:
  53. if self.y > event.y:
  54. if self.x - event.x <= self.r and self.y - event.y <= self.r:
  55. print(True)
  56. i += 1
  57. print(i)
  58. elif self.y < event.y:
  59. if self.x - event.x <= self.r and event.y - self.y <= self.r:
  60. print(True)
  61. i += 1
  62. print(i)
  63. elif self.x < event.x:
  64. if self.y > event.y:
  65. if event.x - self.x <= self.r and self.y - event.y <= self.r:
  66. print(True)
  67. i += 1
  68. print(i)
  69. elif self.y < event.y:
  70. if event.x - self.x <= self.r and event.y - self.r <= self.r:
  71. print(True)
  72. i += 1
  73. print(i)
  74.  
  75. balls = [Ball() for ball in range(3)]
  76.  
  77.  
  78. def tick():
  79. for ball in balls:
  80. ball.mirror()
  81. ball.move()
  82. root.bind('<Button-1>', ball.click)
  83. root.after(10, tick)
  84.  
  85. tick()
  86. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement