Issue
I am trying to make pong, I want my paddle to follow the x position of the mouse. I just had the x position of the mouse assigned to a variable and it would add to itself every time I moved the mouse then just go off the screen. I now changed it a little bit but I just cannot get it to work
ERRORS:
Traceback (most recent call last):
File "Tkinter.py", line 1536, in __call__
return self.func(*args)
File "animationTest.py", line 51, in motion
self.diff = self.x - canvas.coords(self.paddle)
TypeError: unsupported operand type(s) for -: 'int' and 'list'
CODE:
from Tkinter import *
import time
HEIGHT = 500
WIDTH = 800
COLOR = 'blue'
SIZE = 50
root = Tk()
canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg=COLOR)
canvas.pack()
class Ball:
def __init__(self, canvas):
self.ball = canvas.create_oval(0, 0, SIZE, SIZE, fill='black')
self.speedx = 6
self.speedy = 6
self.active = True
self.move_active()
def ball_update(self):
canvas.move(self.ball, self.speedx, self.speedy)
pos = canvas.coords(self.ball)
if pos[2] >= WIDTH or pos[0] <= 0:
self.speedx *= -1
if pos[3] >= HEIGHT or pos[1] <= 0:
self.speedy *= -1
def move_active(self):
if self.active:
self.ball_update()
root.after(1, self.move_active)
class Paddle:
def __init__(self, canvas):
self.paddle = canvas.create_rectangle(0,0,100,10, fill='red')
canvas.bind('<Motion>', self.motion)
self.active = True
self.move_active
def motion(self, event):
self.x = event.x
self.diff = self.x - canvas.coords(self.paddle)
print('the diff is:' ,self.diff)
print('the click is at: {}'.format(self.x))
def move_active(self):
if self.active:
self.motion()
root.after(1, self.move_active)
run = Ball(canvas)
run2 = Paddle(canvas)
root.mainloop()
Solution
There's no reason to read the current coordinates. You can use the event.x
to calculate the new coordinates without knowing what the current coordinates are.
def motion(self, event):
'''update paddle coordinates using current mouse position'''
canvas.coords(self.paddle, event.x-50, 0, event.x+50, 10)
This simply overrides the coordinates 0,0,100,10 that you set in the __init__
method with new ones based on the mouse position.
Answered By - Novel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.