Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import*
- from random import *
- from time import *
- class Ball:
- def __init__(self, canvas, paddle, color):
- self.canvas = canvas
- self.paddle = paddle
- self.id = canvas.create_oval(10,10,25,25,fill=color)
- self.canvas.move(self.id, 225, 180)
- starts = [-3, -2, -1, 1, 2, 3]
- shuffle(starts)
- self.x = choice(starts)
- self.y = choice(starts)
- self.hit_bottom = False
- def draw(self):
- global lives
- self.canvas.move(self.id, self.x, self.y)
- (x1, y1, x2, y2) = self.canvas.coords(self.id)
- if x2 >= self.canvas.winfo_width() or x1 <= 0:
- self.x *= -1
- if y1 <= 0:
- self.y *= -1
- if y2 >= self.canvas.winfo_height():
- self.hit_bottom = True
- lives -= 1
- self.canvas.itemconfigure(lives_text, text = 'Жизней: '+str(lives))
- if self.hit_paddle():
- self.y *= -1
- def hit_paddle(self):
- global score
- (x1, y1, x2, y2) = self.canvas.coords(self.id)
- (A1, B1, A2, B2) = self.canvas.coords(self.paddle.id)
- if x1 >= A1 and x2 <= A2 and y2 >= B1 and y2 <= B2 - 5:
- score += 1
- self.canvas.itemconfigure(score_text, text = 'Счет: '+str(score))
- return True
- class Paddle:
- def __init__(self, canvas, color):
- self.canvas = canvas
- self.id = canvas.create_rectangle(0, 0, 100, 15, fill = color)
- self.canvas.move(self.id, 200, 300)
- self.x = 0
- self.canvas.bind_all('<Left>', self.move_left)
- self.canvas.bind_all('<Right>', self.move_right)
- def draw(self):
- self.canvas.move(self.id, self.x, 0)
- (x1, y1, x2, y2) = self.canvas.coords(self.id)
- if x1 <= 0 or x2 >= 500:
- self.x *= -1
- self.canvas.move(self.id, 5*self.x, 0)
- def move_left(self, event):
- self.x = -2
- #self.canvas.move(self.id, -2, 0)
- def move_right(self, event):
- self.x = 2
- #self.canvas.move(self.id, 2, 0)
- root = Tk()
- root.title('Пинг-понг')
- canvas = Canvas(width = 500, height = 400, bg = 'deepskyblue')
- canvas.pack()
- score = 0
- lives = 3
- score_text = canvas.create_text(10,10,anchor = 'nw', font = 'Verdana 18', fill = 'darkblue', text = 'Счет: '+str(score))
- lives_text = canvas.create_text(500-10,10,anchor = 'ne', font = 'Verdana 18', fill = 'darkblue', text = 'Жизней: '+str(lives))
- HarryPotter = Paddle(canvas, 'orange')
- root.update()
- balls = []
- for i in range(lives):
- R = '%02x'%randint(0,255)
- G = '%02x'%randint(0,255)
- B = '%02x'%randint(0,255)
- color = '#'+R+G+B
- ball = Ball(canvas, HarryPotter, color)
- balls.append(ball)
- def on_click(event):
- while True:
- if lives > 0:
- for ball in balls:
- if ball.hit_bottom == False:
- ball.draw()
- HarryPotter.draw()
- else:
- canvas.create_text(220,200,anchor = 'c', font = 'Verdana 36', fill = 'red', text = 'Конец игры!')
- root.update_idletasks()
- root.update()
- sleep(0.01)
- canvas.bind('<Button-1>', on_click)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement