Advertisement
gorskaja2019

Untitled

May 1st, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. from tkinter import*
  2. from random import *
  3. from time import *
  4.  
  5. class Ball:
  6. def __init__(self, canvas, paddle, color):
  7. self.canvas = canvas
  8. self.paddle = paddle
  9. self.id = canvas.create_oval(10,10,25,25,fill=color)
  10. self.canvas.move(self.id, 225, 180)
  11. starts = [-3, -2, -1, 1, 2, 3]
  12. shuffle(starts)
  13. self.x = choice(starts)
  14. self.y = choice(starts)
  15.  
  16. def draw(self):
  17. self.canvas.move(self.id, self.x, self.y)
  18. (x1, y1, x2, y2) = self.canvas.coords(self.id)
  19. if x2 >= self.canvas.winfo_width() or x1 <= 0:
  20. self.x *= -1
  21. if y1 <= 0:
  22. self.y *= -1
  23. if y2 >= self.canvas.winfo_height():
  24. self.y *=-1
  25. if self.hit_paddle():
  26. self.y *= -1
  27.  
  28. def hit_paddle(self):
  29. (x1, y1, x2, y2) = self.canvas.coords(self.id)
  30. (A1, B1, A2, B2) = self.canvas.coords(self.paddle.id)
  31. if x1 >= A1 and x2 <= A2 and y2 >= B1 and y2 <= B2 - 5:
  32.  
  33. return True
  34.  
  35. class Paddle:
  36. def __init__(self, canvas, color):
  37. self.canvas = canvas
  38. self.id = canvas.create_rectangle(0, 0, 100, 15, fill = color)
  39. self.canvas.move(self.id, 200, 300)
  40. self.x = 0
  41. self.canvas.bind_all('<Left>', self.move_left)
  42. self.canvas.bind_all('<Right>', self.move_right)
  43.  
  44. def draw(self):
  45. self.canvas.move(self.id, self.x, 0)
  46. (x1, y1, x2, y2) = self.canvas.coords(self.id)
  47. if x1 <= 0 or x2 >= 500:
  48. self.x *= -1
  49. self.canvas.move(self.id, 5*self.x, 0)
  50.  
  51.  
  52. def move_left(self, event):
  53. self.x = -2
  54. #self.canvas.move(self.id, -2, 0)
  55.  
  56. def move_right(self, event):
  57. self.x = 2
  58. #self.canvas.move(self.id, 2, 0)
  59.  
  60.  
  61. root = Tk()
  62. root.title('Пинг-понг')
  63. canvas = Canvas(width = 500, height = 400, bg = 'deepskyblue')
  64. canvas.pack()
  65. score = 0
  66. lives = 3
  67. score_text = canvas.create_text(10,10,anchor = 'nw', font = 'Verdana 18', fill = 'darkblue', text = 'Счет: '+str(score))
  68.  
  69. HarryPotter = Paddle(canvas, 'orange')
  70.  
  71. balls = []
  72. for i in range(lives):
  73. R = '%02x'%randint(0,255)
  74. G = '%02x'%randint(0,255)
  75. B = '%02x'%randint(0,255)
  76. color = '#'+R+G+B
  77. ball = Ball(canvas, HarryPotter, color)
  78. balls.append(ball)
  79.  
  80. while True:
  81. for ball in balls:
  82. ball.draw()
  83. HarryPotter.draw()
  84. root.update_idletasks()
  85. root.update()
  86. sleep(0.01)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement