Advertisement
gorskaja2019

Untitled

May 1st, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 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. global score
  30. (x1, y1, x2, y2) = self.canvas.coords(self.id)
  31. (A1, B1, A2, B2) = self.canvas.coords(self.paddle.id)
  32. if x1 >= A1 and x2 <= A2 and y2 >= B1 and y2 <= B2 - 5:
  33. score += 1
  34. self.canvas.itemconfigure(score_text, text = 'Счет: '+str(score))
  35. return True
  36.  
  37. class Paddle:
  38. def __init__(self, canvas, color):
  39. self.canvas = canvas
  40. self.id = canvas.create_rectangle(0, 0, 100, 15, fill = color)
  41. self.canvas.move(self.id, 200, 300)
  42. self.x = 0
  43. self.canvas.bind_all('<Left>', self.move_left)
  44. self.canvas.bind_all('<Right>', self.move_right)
  45.  
  46. def draw(self):
  47. self.canvas.move(self.id, self.x, 0)
  48. (x1, y1, x2, y2) = self.canvas.coords(self.id)
  49. if x1 <= 0 or x2 >= 500:
  50. self.x *= -1
  51. self.canvas.move(self.id, 5*self.x, 0)
  52.  
  53.  
  54. def move_left(self, event):
  55. self.x = -2
  56. #self.canvas.move(self.id, -2, 0)
  57.  
  58. def move_right(self, event):
  59. self.x = 2
  60. #self.canvas.move(self.id, 2, 0)
  61.  
  62.  
  63. root = Tk()
  64. root.title('Пинг-понг')
  65. canvas = Canvas(width = 500, height = 400, bg = 'deepskyblue')
  66. canvas.pack()
  67. score = 0
  68. lives = 3
  69. score_text = canvas.create_text(10,10,anchor = 'nw', font = 'Verdana 18', fill = 'darkblue', text = 'Счет: '+str(score))
  70. lives_text = canvas.create_text(500-10,10,anchor = 'ne', font = 'Verdana 18', fill = 'darkblue', text = 'Жизней: '+str(lives))
  71.  
  72. HarryPotter = Paddle(canvas, 'orange')
  73.  
  74. balls = []
  75. for i in range(lives):
  76. R = '%02x'%randint(0,255)
  77. G = '%02x'%randint(0,255)
  78. B = '%02x'%randint(0,255)
  79. color = '#'+R+G+B
  80. ball = Ball(canvas, HarryPotter, color)
  81. balls.append(ball)
  82.  
  83. while True:
  84. for ball in balls:
  85. ball.draw()
  86. HarryPotter.draw()
  87. root.update_idletasks()
  88. root.update()
  89. sleep(0.01)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement