import tkinter as tk import random as rd class MC: def __init__(self): self.top = tk.Tk() self.top.geometry('700x500') self.top.title('keep the ball') self.ball = Ball(200, 200) self.top.after(1, self.animate) self.make_widgets() self.top.mainloop() def make_widgets(self): self.label = tk.Label(text='Keep the ball inside', font=('Avant Garde', 30)) self.label.pack(side='top') self.canvas = tk.Canvas(self.top, height=400, width=700, bg = '#104060') self.canvas.pack(side='bottom') self.canvas.bind("", lambda e: self.handler(e)) self.display_ball() self.button=tk.Button(self.top, text='reset', command=self.reset) self.button.pack(side='bottom') def reset(self): self.ball = Ball(350, 250) print('reset') def display_ball(self): x,y = int(round(self.ball.x)), int(round(self.ball.y)) self.canvas.delete('all') self.canvas.create_oval(x-5, y-5, x+5, y+5, fill='white') def animate(self): self.ball.move() self.display_ball() self.top.after(100, self.animate) def handler(self,e): self.ball.adjust(e.x, e.y) class Ball: max_speed = 10 def __init__(self, x, y): self.x, self.y = x, y self.dx, self.dy = rd.random()*10-5, rd.random()*10-5 def move(self): self.x += self.dx self.y += self.dy def __str__(self): return f"x={self.x}, y={self.y}, dx={self.dx}, dy={self.dy}" def adjust(self, a,b): deltax = a - self.x deltay = b - self.y distance = ((a-self.x)**2+(b-self.y)**2)**1/2 self.dx = 0.5 *self.dx + 0.5 * deltax self.dy = 0.5 *self.dy + 0.5 * deltay length = (self.dx**2+self.dy**2)**1/2 #self.dx *= Ball.max_speed / length #self.dy *= Ball.max_speed / length print(self.dx, self.dy) m=MC()