Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99994 > unrolled thread

How to bounce the ball forever around the screen

Started byphamtony33@gmail.com
First post2015-12-03 20:19 -0800
Last post2015-12-04 09:09 +0100
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  How to bounce the ball forever around the screen phamtony33@gmail.com - 2015-12-03 20:19 -0800
    Re: How to bounce the ball forever around the screen Peter Otten <__peter__@web.de> - 2015-12-04 09:09 +0100

#99994 — How to bounce the ball forever around the screen

Fromphamtony33@gmail.com
Date2015-12-03 20:19 -0800
SubjectHow to bounce the ball forever around the screen
Message-ID<ee38a39b-5d03-4715-b9d8-23ca24e91866@googlegroups.com>
from Tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=500, background="green")
canvas.pack()

def move_ball(speed_x, speed_y):
	box = canvas.bbox("ball")
	x1 = box[0]
	y1 = box[1]
	x2 = box[2]
	y2 = box[3]
	
	if x1 <= 0:
		speed_x = 0
		speed_y = 0
		
	canvas.move("ball", speed_x, speed_y)
	canvas.after(30, move_ball, speed_x, speed_y)
	
canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball")

move_ball(-10, 7)

mainloop()

 where in the code should i change to make the ball bounce around forever. is it the x and y?

[toc] | [next] | [standalone]


#99996

FromPeter Otten <__peter__@web.de>
Date2015-12-04 09:09 +0100
Message-ID<mailman.190.1449216556.14615.python-list@python.org>
In reply to#99994
phamtony33@gmail.com wrote:

> from Tkinter import *
> window = Tk()
> canvas = Canvas(window, width=500, height=500, background="green")
> canvas.pack()
> 
> def move_ball(speed_x, speed_y):
>         box = canvas.bbox("ball")
>         x1 = box[0]
>         y1 = box[1]
>         x2 = box[2]
>         y2 = box[3]
>         
>         if x1 <= 0:
>                 speed_x = 0
>                 speed_y = 0
>                 
>         canvas.move("ball", speed_x, speed_y)
>         canvas.after(30, move_ball, speed_x, speed_y)
>         
> canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball")
> 
> move_ball(-10, 7)
> 
> mainloop()
> 
>  where in the code should i change to make the ball bounce around forever. 
is it the x and y?

When the ball hits a wall you have to "reflect" it; for a vertical wall 
speed_x has to change:

    if x1 <= 0: # ball hits left wall
        speed_x = -speed_x
    elif ... # ball hits right wall
        speed_x = -speed_x

Can you come up with the correct check for the right wall?
To try if this part works correctly temporarily change

> move_ball(-10, 7)

to

move_ball(-10, 0)

so that the ball only moves in horizontal direction. Once this works handle 
the vertical walls and speed_y the same way.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web