- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
import tkinter
import random
# constants
WIDTH = 540
HEIGHT = 480
BG_COLOR = 'white'
MAIN_BALL_COLOR = 'blue'
MAIN_BALL_RADIUS = 25
COLORS = ['aqua', 'fuchsia', 'pink', 'yellow', 'gold', 'chartreuse']
NUM_OF_BALLS = 9
MAX_RADIUS = 35
MIN_RADIUS = 15
DELAY = 8
INIT_DX = 1
INIT_DY = 1
ZERO = 0
# ball class
class Ball():
def __init__(self, x, y, r, color, dx=0, dy=0):
self.x = x
self.y = y
self.r = r
self.color = color
self.dx = dx
self.dy = dy
def draw(self):
canvas.create_oval(self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r, fill=self.color,
outline=self.color)
def hide(self):
canvas.create_oval(self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r, fill=BG_COLOR,
outline=BG_COLOR)
def is_collision(self, ball):
a = abs(self.x + self.dx - ball.x)
b = abs(self.y + self.dy - ball.y)
return (a * a + b * b) ** 0.5 <= self.r + ball.r
def move(self):
# collision with the walls
if (self.x + self.r + self.dx >= WIDTH) or (self.x - self.r + self.dx <= ZERO):
self.dx = -self.dx
if (self.y + self.r + self.dy >= HEIGHT) or (self.y - self.r + self.dy <= ZERO):
self.dy = -self.dy
self.hide()
self.x += self.dx
self.y += self.dy
if self.dx * self.dy != 0:
self.draw()
# process the mouse events
def mouse_click(event):
global main_ball
if event.num == 1: # left mouse button
if 'main_ball' not in globals(): # старт
main_ball = Ball(event.x, event.y, MAIN_BALL_RADIUS, MAIN_BALL_COLOR, INIT_DX, INIT_DY)
if main_ball.x > WIDTH / 2:
main_ball.dx = -main_ball.dx
if main_ball.y > HEIGHT / 2:
main_ball.dy = -main_ball.dy
main_ball.draw()
# create a list of objects-balls
def create_list_of_balls(number):
lst = []
return lst
# games main loop
def main():
if 'main_ball' in globals():
main_ball.move()
root.after(DELAY, main)
# create a window, the canvas and start game
root = tkinter.Tk()
root.title("Colliding Balls")
canvas = tkinter.Canvas(root, width=WIDTH, height=HEIGHT, bg=BG_COLOR)
canvas.pack()
canvas.bind('<Button-1>', mouse_click)
canvas.bind('<Button-2>', mouse_click, '+')
canvas.bind('<Button-3>', mouse_click, '+')
balls = create_list_of_balls(NUM_OF_BALLS)
if 'main_ball' in globals(): # for restarts
del main_ball
main()
root.mainloop()