Guest User

Untitled

a guest
Aug 15th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. from tkinter import *
  2. from random import randint, choice
  3.  
  4.  
  5. class Ball:
  6.     def __init__(self):
  7.         self.R = randint(30, 60)
  8.         self.x = randint(self.R, WIDTH - self.R)
  9.         self.y = randint((self.R + 50), HEIGHT - self.R)
  10.         self.colors = ['red', 'orange', 'yellow', 'green', 'blue']
  11.         self.dx, self.dy = +4, +5
  12.         self.ball_id = canv.create_oval(self.x - self.R, self.y - self.R,
  13.                                         self.x + self.R, self.y + self.R,
  14.                                         fill=choice(self.colors), width=0)
  15.  
  16.     def move(self):
  17.         global R, x, y
  18.         self.x += self.dx
  19.         self.y += self.dy
  20.         if self.x + self.R > WIDTH or self.x - self.R <= 0:
  21.             self.dx = -self.dx
  22.         if self.y + self.R > HEIGHT or (self.y - self.R - 50) <= 0:
  23.             self.dy = -self.dy
  24.         R = self.R
  25.         x = self.x
  26.         y = self.y
  27.  
  28.     def show(self):
  29.         canv.move(self.ball_id, self.dx, self.dy)
  30.  
  31.  
  32. def tick():
  33.     ball1.move()
  34.     ball2.move()
  35.     ball1.show()
  36.     ball2.show()
  37.     root.after(20, tick)
  38.  
  39.  
  40. def new_score(event):
  41.     global global_score
  42.     goal = ((event.x - x) ** 2 + (event.y - y) ** 2) ** 0.5
  43.     if goal <= R:
  44.         score_label['text'] = 'Total score: ' + str(global_score)
  45.         global_score += 1
  46.  
  47.  
  48. def main():
  49.     global root, canv, WIDTH, HEIGHT, score_label, global_score, ball1, ball2
  50.     root = Tk()
  51.     WIDTH = 800
  52.     HEIGHT = 600
  53.     global_score = 1
  54.     root.geometry(str(WIDTH) + 'x' + str(HEIGHT) + '+500+50')
  55.     root.title('Catch the ball')
  56.  
  57.     canv = Canvas(root, bg='white')
  58.     canv.pack(fill=BOTH, expand=1)
  59.     score_label = Label(canv, text='Total score: 0', font='Arial 20', bg='blue', fg='white', width=90, bd=5)
  60.     score_label.pack()
  61.  
  62.     ball1 = Ball()
  63.     ball2 = Ball()
  64.     tick()
  65.  
  66.     canv.bind('<Button-1>', new_score)
  67.     root.mainloop()
  68.  
  69.  
  70. if __name__ == '__main__':
  71.     main()
  72.  
Advertisement
Add Comment
Please, Sign In to add comment