Resetting a variable increases it instead of resetting it - Tkinter - python

I am creating a game of Pong using tkinter as a small project. I have written the game and it works fully. However I have encountered a weird bug where upon the game ending, when one player reaches a score of 3, when the game is restarted the velocity of the ball appears to double, and this happens every time the game is reset. the startgame function should set the variable dx (x movement of the ball) to 2 when it is called, so I am not sure why it appears to get faster by 2 everytime, as there are no additions present.
I have posted the whole code block below and am completely lost as to why this happens, any help would be much appreciated!
from tkinter import *
root = Tk()
#size of window
w = 600
h = 400
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
#playing frame, with Canvas inside
canvframe = Frame(relief=SUNKEN, width=600, height = 350, background="black")
canvframe.pack()
canv = Canvas(canvframe, background="black", width=600, height = 350)
canv.pack(fill=NONE)
# Objects in canvas
ball = canv.create_oval(300,160,310,170, outline="white", fill="white", width=2, tags=('ball'))
paddle1 = canv.create_rectangle(0,200,10,120, outline="white", fill="white", width=2, tags=('paddle1'))
paddle2 = canv.create_rectangle(590,200,600,120, outline="white", fill="white", width=2)
#Paddle movement
def moveUp1(event):
canv.move(paddle1, 0, -10)
pass
def moveUp2(event):
canv.move(paddle2, 0, -10)
pass
def moveDown1(event):
canv.move(paddle1, 0, 10)
pass
def moveDown2(event):
canv.move(paddle2, 0, 10)
pass
#InitialVelocity
dx = 0
dy = 0
#initial score
Player1score = 0
Player2score = 0
#start game - what happens when you push start button (reset velocity and scores)
def startgame():
global dy, dx, Player1score, Player2score
canv.coords(paddle1, 0,200,10,120)
canv.coords(paddle2, 590,200,600,120)
dx = 2
dy = 0
Player1score = 0
Player2score = 0
Player1scoreLabel.configure(text="Score: "+ str(Player1score))
Player2scoreLabel.configure(text="Score: "+ str(Player2score))
moveBall()
#Ball Movement
def moveBall():
global dy, dx, Player1score, Player2score
# to make ball bounce off paddle 1
if canv.coords(ball)[0]<=canv.coords(paddle1)[2] and canv.coords(paddle1)[1]<= canv.coords(ball)[1] <= canv.coords(paddle1)[3]:
dx = -dx
if canv.coords(paddle1)[1] <= canv.coords(ball)[1] <= (int((canv.coords(paddle1)[1] + canv.coords(paddle1)[3])) / 2 ):
dy -=1
canv.move(ball, dx, dy)
elif (int(canv.coords(paddle1)[1] + canv.coords(paddle1)[3]) / 2 ) <= canv.coords(ball)[3] <= canv.coords(paddle1)[3]:
dy += 1
canv.move(ball, dx, dy)
else:
canv.move(ball, dx, dy)
# to make ball bounce off paddle 2
elif canv.coords(ball)[2]>=canv.coords(paddle2)[0] and canv.coords(paddle2)[1]<= canv.coords(ball)[3] <= canv.coords(paddle2)[3]:
dx = -dx
if canv.coords(paddle2)[1] <= canv.coords(ball)[1] <= (int((canv.coords(paddle2)[1] + canv.coords(paddle2)[3])) / 2 ):
dy -= 1
canv.move(ball, dx, dy)
elif (int(canv.coords(paddle2)[1] + canv.coords(paddle2)[3])/ 2 ) <= canv.coords(ball)[3] <= canv.coords(paddle2)[3]:
dy += 1
canv.move(ball, dx, dy)
else:
canv.move(ball, dx, dy)
# to make ball bounce off roof
elif canv.coords(ball)[1]<=0:
dy = -dy
canv.move(ball, dx, dy)
# to mkae ball bounce of floor
elif canv.coords(ball)[1]>=325:
dy = -dy
canv.move(ball, dx, dy)
# if player 2 scores
elif canv.coords(ball)[2]<=0:
Player2score += 1
Player2scoreLabel.configure(text="Score: "+ str(Player2score))
canv.coords(ball, 300,160,310,170)
canv.coords(paddle1, 0,200,10,120)
canv.coords(paddle2, 590,200,600,120)
dx=2
dy=0
# if player1 scores
elif canv.coords(ball)[0]>=600:
Player1score += 1
Player1scoreLabel.configure(text="Score: "+ str(Player1score))
canv.coords(ball, 300,160,310,170)
canv.coords(paddle1, 0,200,10,120)
canv.coords(paddle2, 590,200,600,120)
dx=-2
dy=0
# end game if player 1 wins
elif Player1score==3:
dx=0
dy=0
# end game if player 2 wins
elif Player2score==3:
dx=0
dy=0
# move ball if nothign happens
else:
canv.move(ball, dx, dy)
canv.after(10, moveBall)
#buttons
Butframe = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Butframe.pack()
startButton = Button(Butframe, text="Start", command = startgame)
startButton.pack(side=LEFT)
quitButton = Button(Butframe, text="Quit", command=root.destroy)
quitButton.pack(side=LEFT)
#scores
Score1frame = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Score1frame.pack(side=LEFT)
Player1scoreLabel = Label(Score1frame, text="Score: "+ str(Player1score), background="green")
Player1scoreLabel.pack()
Score2frame = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Score2frame.pack(side=RIGHT)
Player2scoreLabel = Label(Score2frame, text="Score: "+ str(Player2score), background="green")
Player2scoreLabel.pack()
#binding of movement keys
root.bind("<Up>", moveUp2)
root.bind("<w>", moveUp1)
root.bind("<Down>", moveDown2)
root.bind("<s>", moveDown1)
root.mainloop()

Your apparent speed increase is due to overlapping calls to the .after() method.
When one of the players wins, you should stop the loop in moveBall(), for example using a global variable called gameover like below:
# Initialize gameover variable
gameover = False
# (...) (Reset gameover to False in startgame() as well)
def moveBall():
global dy, dx, Player1score, Player2score, gameover
# (...)
# end game if player 1 or 2 wins
elif Player1score==3 or Player2score==3:
dx=0
dy=0
gameover = True
# move ball if nothing happens
else:
canv.move(ball, dx, dy)
# Repeat until game is over
if not gameover:
canv.after(10, moveBall)

Related

why am i getting a trace back in my code for my move ball command as it is stopping the rest of my code from running

i am making a pong game
i managed to code the ball to bounce around the window
but it seems that the code, for using user input to get the rectangles to move isn't working.
when i run the code i have been getting a traceback to my move.ball command relating to making the ball bounce, and i believe that may be stopping the rest of the code from running. I have included the full code in case any errors can be spotted in it.
from tkinter import *
import tkinter as tkr
import time
tk = tkr.Tk()
Canvas = tkr.Canvas(tk, width=300, height=400)
Canvas.grid()
ball = Canvas.create_oval(3,3,40,40,fill="light blue")
player1 = Canvas.create_rectangle(20,5,90,30,fill="black")
Canvas.moveto(player1, 120, 380)
player2 = Canvas.create_rectangle(20,5,90,30,fill="black")
Canvas.moveto(player2, 120, -5)
x = 1
y = 3
while True:
Canvas.move(ball,x,y)
pos = Canvas.coords(ball)
if pos[3] >= 400 or pos[1] <= 0:
y = -y
if pos[2] >= 300 or pos[0] <= 0:
x = -x
tk.update()
time.sleep(0.025)
pass
tk.mainloop()
def left(event):
x == -10
y == 0
Canvas.move(player1, x, y)
def right(event):
x == 10
y == 0
Canvas.move(player1, x, y)
def up(event):
x == 0
y == -10
Canvas.move(player1, x, y)
def down(event):
x == -10
y == 0
Canvas.move(player1, x, y)
root.bind("<Left>", left)
root.bind("<Right>", right)
root.bind("<Up>", up)
root.bind("<Down>", down)
tk.mainloop()
i am getting this trace back-
Traceback (most recent call last):
File "C:/Users/amarb/Desktop/code/pong.py", line 15, in <module>
Canvas.move(ball,x,y)
File "C:\Users\amarb\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2949, in move
self.tk.call((self._w, 'move') + args)
_tkinter.TclError: invalid command name ".!canvas"
.!canvas is the internal identifier of the canvas widget that you created. This error is happening because you try to run code after mainloop() returns, which is after the window being destroyed. You can't interact with widgets after they have been destroyed.
Edit: New. How to get the paddle moving and hit the paddle. I only used one player at a time. You will do the rest. I had to modify some and add some new functions. I am using new python 3.11.0b3.
from tkinter import *
import tkinter as tkr
import time
import random
tk = tkr.Tk()
width=300
height=400
Canvas = tkr.Canvas(tk, width=width, height=height)
Canvas.pack()
tk.update()
ball = Canvas.create_oval(3,3,25,25,fill="red")
Canvas.move(ball, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
ball_x = starts[0]
ball_y = 3
player1 = Canvas.create_rectangle(20,5,90,30,fill="black")
Canvas.moveto(player1, 180, 380)
player2 = Canvas.create_rectangle(20,5,90,30,fill="blue")
Canvas.move(player2, 120, -5)
paddle_x = 0
def hit_bat(pos):
bat_pos = Canvas.coords(player1) #retrieve the coordinates of the bat position - note the ball coordinates are being passed
if pos[2] >= bat_pos[0] and pos[0] <= bat_pos[2]: #if the right side of the ball (that is the x right hand coordinate) is greater than the left side of the bat, AND the left side of the ball is less than the right side of the bat ....move etc
if pos[3]>= bat_pos[1] and pos[3] <= bat_pos[3]: #if the bottom of the ball (pos[3]) is between the paddle's top [bat pos[1]) and bottom (pos[3])
return True
return False
def draw_ball():
global ball_x, ball_y
Canvas.move(ball, ball_x, ball_y)
pos = Canvas.coords(ball)
if pos[1] <= 0:
ball_y = 6
if pos[3] >= height:
ball_y = -6
#Call the hit_bat function
if hit_bat(pos) == True: #if the hit_bat function returns a value of True, the direction of the ball is changed
ball_y = -6 #if the ball hits the bat, then send the ball flying up at a rate of -6 (higher the number the faster the fly!)
if pos[0] <= 0:
ball_x = 6
if pos[2]>= width:
ball_x = -6
tk.update()
def hit_paddle(pos):
paddle_pos = Canvas.coords(ball)
if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
return True
return False
def draw_paddle():
global paddle_x
Canvas.move(player1, paddle_x, 0)
pos = Canvas.coords(player1)
if pos[0] <= 0:
paddle_x = 0
elif pos[2] >= width:
paddle_x = 0
time.sleep(0.02)
tk.update()
def move_left(event):
global paddle_x
paddle_x = -2
def move_right(event):
global paddle_x
paddle_x = 2
Canvas.bind_all("<KeyPress-Left>", move_left)
Canvas.bind_all("<KeyPress-Right>", move_right)
while True:
draw_ball()
draw_paddle()
New image:

python tkinter bouncing ball game

I'm making a basic game. I want the ball to bounce back up ONLY when it hits the platform. So far, I've written code that will make the ball bounce off the top and bottom screen, but I'm having trouble with getting the ball to bounce off the platform.
from tkinter import *
import time
import tkinter
tk = Tk()
canvas = Canvas(tk, bg="white",width=(900),height=(500))
canvas.pack()
platform = canvas.create_rectangle(400,400,500,410)
def ball():
xspeed = 2
yspeed = 2
ball = canvas.create_oval(430,10,470,50)
while True:
canvas.move(ball, xspeed, yspeed)
pos = canvas.coords(ball)
if pos[2] >=900 or pos[0] <0:
xspeed = -xspeed
tk.update()
time.sleep(0.01)
def board():
board_right()
board_left()
def board_right(event):
xspeed = 5
yspeed = 0
canvas.move(platform,xspeed,yspeed)
tk.update
time.sleep(0.01)
def board_left(event):
xspeed = 5
yspeed = 0
canvas.move(platform,-xspeed,yspeed)
tk.update()
time.sleep(0.01)
canvas.bind_all("<Right>",board_right)
canvas.bind_all("<Left>",board_left)
ball()
tk.mainloop()
Do not use time.sleep() as it will block the tkinter mainloop, use after() instead.
To check whether the ball hits the platform, you need to get the center x of the ball and the lower y of the ball. If center x is within the left and right of platform and the ball lower y is the platform upper y, then reverse the ball y speed. Otherwise game over!
Below is sample code based on yours:
import tkinter as tk
root = tk.Tk()
width = 900
height = 500
canvas = tk.Canvas(root, bg='white', width=width, height=height)
canvas.pack()
ball = canvas.create_oval(430, 10, 470, 50, fill='green')
platform_y = height - 20
platform = canvas.create_rectangle(width//2-50, platform_y, width//2+50, platform_y+10, fill='black')
# ball moving speed
xspeed = yspeed = 2
def move_ball():
global xspeed, yspeed
x1, y1, x2, y2 = canvas.coords(ball)
if x1 <= 0 or x2 >= width:
# hit wall, reverse x speed
xspeed = -xspeed
if y1 <= 0:
# hit top wall
yspeed = 2
elif y2 >= platform_y:
# calculate center x of the ball
cx = (x1 + x2) // 2
# check whether platform is hit
px1, _, px2, _ = canvas.coords(platform)
if px1 <= cx <= px2:
yspeed = -2
else:
canvas.create_text(width//2, height//2, text='Game Over', font=('Arial Bold', 32), fill='red')
return
canvas.move(ball, xspeed, yspeed)
canvas.after(20, move_ball)
def board_right(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond right wall
if x2 < width:
dx = min(width-x2, 10)
canvas.move(platform, dx, 0)
def board_left(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond left wall
if x1 > 0:
dx = min(x1, 10)
canvas.move(platform, -dx, 0)
canvas.bind_all('<Right>', board_right)
canvas.bind_all('<Left>', board_left)
move_ball()
root.mainloop()

moving circle using tkinter

i am new to programming and am currently trying to get a chemistry stimulation with beaker which produces bubbles. after a lot of research I have managed to get a circle moving and also created a rectangle representing a beaker. however I would like the circles to be formed at the top of the beaker and move upwards in random and destroy itself when it meets the top which I just cant figure out. I would be very grateful if anyone can help me. thank you in advance.
my code is:
from tkinter import *
x = 10
y = 10
a = 50
b = 50
x_vel = 5
y_vel = 5
def move():
global x
global y
global x_vel
global y_vel
if x < 0:
x_vel = 5
if x > 350:
x_vel = -5
if y < 0:
y_vel = 5
if y > 150:
y_vel = -5
canvas1.move(circle, x_vel, y_vel)
coordinates = canvas1.coords(circle)
x = coordinates[0]
y = coordinates[1]
window.after(33, move)
window = Tk()
window.geometry("1000x1000")
canvas1=Canvas(window, height = 1000, width= 1000)
canvas1.grid (row=0, column=0, sticky=W)
coord = [x, y, a, b ]
circle = canvas1.create_oval(coord, outline="red", fill="red")
coord = [230, 270, 270, 310]
rect2 = canvas1.create_rectangle(coord, outline="Blue", fill="Blue")
move()
window.mainloop ()
Using random you can move it randomly.
If y < -height then object left screen and you can move it to start position.
import tkinter as tk
import random
def move():
global x
global y
global x_vel
global y_vel
# get random move
x_vel = random.randint(-5, 5)
y_vel = -5
canvas1.move(circle, x_vel, y_vel)
coordinates = canvas1.coords(circle)
x = coordinates[0]
y = coordinates[1]
# if outside screen move to start position
if y < -height:
x = start_x
y = start_y
canvas1.coords(circle, x, y, x+width, y+height)
window.after(33, move)
# --- main ---
start_x = 230
start_y = 270
x = start_x
y = start_y
width = 50
height = 50
x_vel = 5
y_vel = 5
window = tk.Tk()
window.geometry("1000x1000")
canvas1 = tk.Canvas(window, height=1000, width=1000)
canvas1.grid(row=0, column=0, sticky='w')
coord = [x, y, x+width, y+height]
circle = canvas1.create_oval(coord, outline="red", fill="red")
coord = [x, y, x+40, y+40]
rect2 = canvas1.create_rectangle(coord, outline="Blue", fill="Blue")
move()
window.mainloop ()
EDIT: using class you can easily have many items
import tkinter as tk
import random
class Bubble():
def __init__(self, canvas, x, y, size, color='red'):
self.canvas = canvas
self.x = x
self.y = y
self.start_x = x
self.start_y = y
self.size = size
self.color = color
self.circle = canvas.create_oval([x, y, x+size, y+size], outline=color, fill=color)
def move(self):
x_vel = random.randint(-5, 5)
y_vel = -5
self.canvas.move(self.circle, x_vel, y_vel)
coordinates = self.canvas.coords(self.circle)
self.x = coordinates[0]
self.y = coordinates[1]
# if outside screen move to start position
if self.y < -self.size:
self.x = self.start_x
self.y = self.start_y
self.canvas.coords(self.circle, self.x, self.y, self.x + self.size, self.y + self.size)
def move():
for item in bubbles:
item.move()
window.after(33, move)
# --- main ---
start_x = 230
start_y = 270
window = tk.Tk()
window.geometry("1000x1000")
canvas = tk.Canvas(window, height=1000, width=1000)
canvas.grid(row=0, column=0, sticky='w')
bubbles = []
for i in range(5):
offset = random.randint(10, 20)
b = Bubble(canvas, start_x+10, start_y-offset, 20, 'red')
bubbles.append(b)
for i in range(5):
offset = random.randint(0, 10)
b = Bubble(canvas, start_x+10, start_y-offset, 20, 'green')
bubbles.append(b)
coord = [start_x, start_y, start_x+40, start_y+40]
rect = canvas.create_rectangle(coord, outline="Blue", fill="Blue")
move()
window.mainloop ()

How do I get a ball to glide in python tkinter?

I have this program that I tried to make in python tkinter. A ball would appear on screen and every time I click I want the ball to glide to the point at which I clicked. The x and y locations of the ball changed but the ball only redraws after the ball is finished "moving." Can someone tell me what I am doing wrong.
from tkinter import *
import time
width = 1280
height = 700
ballRadius = 10
iterations = 100
mouseLocation = [width/2, height/2]
ballLocation = [width/2, height/2]
root = Tk()
def drawBall(x, y):
canvas.delete(ALL)
canvas.create_oval(x - ballRadius, y - ballRadius, x + ballRadius, y + ballRadius, fill="blue")
print(x, y)
def getBallLocation(event):
mouseLocation[0] = event.x
mouseLocation[1] = event.y
dx = (ballLocation[0] - mouseLocation[0]) / iterations
dy = (ballLocation[1] - mouseLocation[1]) / iterations
for i in range(iterations):
ballLocation[0] -= dx
ballLocation[1] -= dy
drawBall(round(ballLocation[0]), round(ballLocation[1]))
time.sleep(0.02)
ballLocation[0] = event.x
ballLocation[1] = event.y
canvas = Canvas(root, width=width, height=height, bg="black")
canvas.pack()
canvas.create_oval(width/2-ballRadius, height/2-ballRadius, width/2+ballRadius, height/2+ballRadius, fill="blue")
canvas.bind("<Button-1>", getBallLocation)
root.mainloop()
In your code time.sleep pauses the entire GUI, that's why you don't see the intermediate locations of the ball. Instead you can construct a function with widget.after method. Try the following:
print(x, y)
dx = 0
dy = 0
def getBallLocation(event):
canvas.unbind("<Button-1>")
global dx, dy
mouseLocation[0] = event.x
mouseLocation[1] = event.y
dx = (ballLocation[0] - mouseLocation[0]) / iterations
dy = (ballLocation[1] - mouseLocation[1]) / iterations
draw()
i = 0
def draw():
global i
ballLocation[0] -= dx
ballLocation[1] -= dy
drawBall(round(ballLocation[0]), round(ballLocation[1]))
if i < iterations-1:
canvas.after(20, draw)
i += 1
else:
canvas.bind("<Button-1>", getBallLocation)
i = 0
canvas = Canvas(root, width=width, height=height, bg="black")

Pong with Python(Tkinter) paddle not working

So I'm new to GUI and Tkinter. I'm working on a one paddle pong game using Tkinter and I need the paddle to act like a paddle and bounce the disk off when the disk hits the paddle from the right or the left. The current code I have does bounce the disk of the paddles location on the x axis but it doesn't let the disk get past the line_x. Am I thinking in the right direction? or am I way off? It would be awesome if someone can fix my code so it works. This is probably very easy for someone that's been working with GUI's a while but I'm stomped. Please help.
from tkinter import *
import random
class ControlAnimation:
def __init__(self):
my_window = Tk() # create a window
my_window.title("Control Animation Demo")
self.width = 400
self.height = 200
self.line_x = 350
self.line_top = 75
self.line_bot = 125
self.paddle_width = 10
self.dy = 5
self.sleep_time = 50
self.is_stopped = False
self.my_canvas = Canvas(my_window, bg = 'white', \
width = self.width, height = self.height)
self.my_canvas.pack()
frm_control = Frame(my_window) # for comand buttons below canvas
frm_control.pack()
btn_stop = Button(frm_control, text = 'Stop', \
command = self.stop)
btn_stop.pack(side = LEFT)
btn_resume = Button(frm_control, text = 'Resume', \
command = self.resume)
btn_resume.pack(side = LEFT)
btn_faster = Button(frm_control, text = 'Faster', \
command = self.faster)
btn_faster.pack(side = LEFT)
btn_slower = Button(frm_control, text = 'Slower', \
command = self.slower)
btn_slower.pack(side = LEFT)
self.radius = 20
self.x = self.radius # just to start; y is at canvas center
self.y = self.height/2
# (x, y) is center of disk for this program, but ...
# recall: x1,y1 and x2,y2 form a bounding box for disk
self.my_canvas.create_oval(\
self.x - self.radius, self.height/2 + self.radius,\
self.x + self.radius, self.height/2 - self.radius,\
fill = "red", tags = "disk")
self.my_canvas.create_line(self.line_x, self.line_top, \
self.line_x, self.line_bot, \
width = self.paddle_width, fill = "blue", tags = "paddle")
self.my_canvas.bind("<KeyPress-Up>", self.move_paddle)
self.my_canvas.bind("<KeyPress-Down>", self.move_paddle)
self.my_canvas.bind("<B1-Motion>", self.left_click_paddle)
self.my_canvas.bind("<B3-Motion>", self.right_click_paddle)
self.animate()
self.my_canvas.focus_set()
my_window.mainloop()
def stop(self):
self.is_stopped = True
def resume(self):
self.is_stopped = False
self.animate()
def faster(self):
if self.sleep_time > 5:
self.sleep_time -= 15
def slower(self):
self.sleep_time += 15
def animate(self):
dx = 3
dy = 2
while not self.is_stopped :
self.my_canvas.move("disk", dx, dy) # move right
self.my_canvas.after(self.sleep_time) # sleep for a few ms
# redraw/update the canvas w/ new oval position
self.my_canvas.update()
# increment x to set up for next re-draw
r = random.randint(-1, 1)
self.x += dx # moves the disk
if self.x + self.radius > self.width: # hit right boundary
dx = -dx + r # add randomness
elif self.x - self.radius <= 0: # hit left boundary
dx = -dx + r # add randomness
elif self.x + self.radius > self.line_x and self.x + self.radius <= self.line_top:
dx = -dx + r
#elif self.x - self.radius <= self.line_x:
#dx = -dx + r
# increment y to set up for next re-draw
self.y += dy
if self.y + self.radius > self.height: # hit bottom boundary
dy = -dy
elif self.y - self.radius <= 0: # hit top boundary
dy = -dy
def left_click_paddle(self, event):
print(" clicked at =", event.x, event.y)
print("-"*30)
self.move_paddle( -self.dy)
def right_click_paddle(self, event):
print(" clicked at =", event.x, event.y)
print("-"*30)
self.move_paddle( self.dy)
def move_paddle(self, increment):
self.line_top += increment
self.line_bot += increment
self.my_canvas.delete("paddle")
self.my_canvas.create_line(self.line_x, self.line_top, \
self.line_x, self.line_bot, \
width = 10, fill = "blue", tags = "paddle")
ControlAnimation() # create instance of the GUI
In your movement loop, the logic to check whether to trigger a direction change in x is not complete. It should be something like this:
# new disk x, y positions
self.x += dx
self.y += dy
# Change "dx" sign if the ball hit something horizontally
if self.x + self.radius > self.width-1:
# ball hit right frame boundary
dx = -dx + r
elif self.x - self.radius <= 1:
# ball hit left frame boundary
dx = -dx + r
elif ( self.line_x <= self.x+self.radius <= self.line_x + 2*dx
and self.line_top <= self.y <= self.line_bot ):
# ball hit paddle from the left
dx = -dx + r
elif ( self.line_x + 2*dx <= self.x-self.radius <= self.line_x
and self.line_top <= self.y <= self.line_bot ):
# ball hit paddle from the right
dx = -dx + r

Categories

Resources