Python Forum

Full Version: make it to move to mouse
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import tkinter,random,time
class game():
	def __init__(self):

		self.canvas= tkinter.Canvas(
			width=500,
			height=700,
			bg='white'
			)
		self.canvas.pack()

		self.x=250
		self.y=400
		self.interval=0.01

		self.z=800

		self.x1=random.randint(0, 500)
		self.y1=random.randint(0, 800)
		self.r=random.randint(5, 16)

		self.canvas.bind_all('<Left>',self.moveleft)
		self.canvas.bind_all('<Right>',self.moveright)
		self.canvas.bind_all('<Up>',self.moveup)
		self.canvas.bind_all('<Down>',self.movedown)

		self.canvas.create_oval(self.x-7,self.y+300,self.x+7,self.y+270,tags='plane')
		self.canvas.create_oval(self.x-14,self.y+280,self.x+14,self.y+290,tags='plane')

		self.obstacles()

		self.cycle()
		self.canvas.mainloop()

	def obstacles(self):

		self.x2=random.randint(0, 500)
		self.y2=random.randint(0, 800)
		self.r1=random.randint(5, 16)
		self.canvas.create_rectangle(self.x2-self.r1,self.y2-self.z-self.r1,self.x2+self.r1,self.y2-self.z+self.r1,fill='red',tags='obs')
		self.canvas.after(200,self.obstacles)

	def cycle (self) :
		while True:
			time.sleep(self.interval)
			self.canvas.move('obs', 0, +2)

			tagged_objects = self.canvas.find_withtag('obs')
			overlapping_objects = self.canvas.find_overlapping(*self.canvas.coords('plane'))
			
			for item in overlapping_objects:
				if item in tagged_objects:
					return False

			self.canvas.update()

	def moveleft(self,event):
		self.canvas.move('plane', -15, 0)
	def moveright(self,event):
		self.canvas.move('plane', 15, 0)
	def movedown(self,event):
		self.canvas.move('plane', 0, 15)
	def moveup(self,event):
		self.canvas.move('plane', 0, -15)
game()
can u remake this so it will move to my mouse?
Im not sure why people insist on making games in tkinter when pygame was made specifically for things like this?

here is a pygame example in a tutorial format
https://python-forum.io/Thread-PyGame-En...ion-part-6

But you basically need to create a vector between the object moving and the target. And then start moving the object. In something like pygame this is easier as there are built in functions like pygame.mouse.get_pos() that returns the mouse position on every frame.

Quote:can u remake this so it will move to my mouse?
That would be your job, especially since you chose tkinter. But you have to make the effort
Metulburr is right, tkinter is the wrong tool.

This is wrong:
           #for item in overlapping_objects:
           #    if item in tagged_objects:
           #        return False
yeah i know doing it like this is wrong but I'm doing it for class so i need it to be it in python and not in pygame.
tkinter is not apart of the python standard library either. It is packaged alongside python in windows only.

But that makes sense....if your doing it for a class, there is no choice then.