Python Forum
How to make ball stay within frame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make ball stay within frame
#1
I want to be able to bounce the ball on the screen but when I run the code the ball moves of frame. I have attached a file of the code down below. Here's the code I have so far:
import time import random from graphics import * def main(): window_width=600 window_length=700 dx= int(1) dy= int(1) win= GraphWin("shapes", window_width, window_length) center= Point(dx,dy) circ= Circle(center, 30) circ.setFill('red') circ.draw(win) for i in range(100): dx1=random.randint(1,155) dy2=random.randint(1,155) dx+=dx1 dy+=dy2 if dx > window_width or dx <0: dx =1 if dy > window_length or dy<0: dy=1 circ.move(dx,dy) time.sleep(3)
buran write Nov-15-2025, 07:23 AM:
Please, use proper tags when post code, traceback, output, etc.
See BBcode help for more info.

Attached Files

Thumbnail(s)
   
Reply
#2
I think the main issue is you're updating dx and dy as positions, but then you're also using them as movement speeds. So the ball basically keeps jumping off screen because the random values get added to its coords every loop. For bouncing, you want to keep position and velocity separate.

So here's an example that actually keeps the ball inside the window:

from graphics import * import time def main(): window_width = 600 window_height = 700 win = GraphWin("shapes", window_width, window_height) # starting position x = 100 y = 100 # velocity (keeps ball moving slowly) vx = 3 vy = 3 radius = 30 circ = Circle(Point(x, y), radius) circ.setFill("red") circ.draw(win) while True: # bounce logic if x - radius <= 0 or x + radius >= window_width: vx = -vx if y - radius <= 0 or y + radius >= window_height: vy = -vy # update position x += vx y += vy circ.move(vx, vy) time.sleep(0.01) main()
our gaming project:- TAG game
Reply
#3
What you are trying to do is difficult. The only way to "move" a circle is to use the move() command, which moves relative from the current position. To ensure that the circle remains inside the window you need to bound the "new" position and compute the move from the current position to the new position.
import time import random from graphics import Circle, GraphWin, Point def main(): window_width = 600 window_height = 700 win = GraphWin("shapes", window_width, window_height) x = window_width // 2 y = window_height // 2 circ = Circle(Point(x, y), 30) circ.setFill('red') circ.draw(win) for i in range(100): # Compute new x and y positions that stay inside the window. new_x = min(window_width, max(1, x + random.randint(-75, 75))) new_y = min(window_height, max(1, y + random.randint(-75, 75))) # Move from old x, y to new x, y circ.move(new_x - x, new_y - y) # Update the x, y x = new_x y = new_y time.sleep(0.25)
It would be nice if the Circle class had a way to move the circle to a specific location. A beauty of python is it is easy to add new features to existing code. In the code below I add a moveTo method to the Circle class by subclassing. MyCircle can do everything Circle can do. In addition it has a moveTo(x, y) method and properties for getting the x and y coordinates of the circle center.
import time from random import randint from graphics import Circle, GraphWin, Point class MyCircle(Circle): """Circle with additional features.""" @property def x(self): return self.getCenter().getX() @property def y(self): return self.getCenter().getY() def moveTo(self, x, y): dx = x - self.x dy = y - self.y self.move(dx, dy) def clip(value, vmin, vmax): """Clip value to be in range vmin..vmax.""" return max(vmin, min(vmax, value)) def main(): window_width = 600 window_height = 700 win = GraphWin("shapes", window_width, window_height) circles = [] for color in ('black', 'red', 'green', 'blue', 'yellow'): circle = MyCircle( Point(randint(0, window_width), randint(0, window_height)), 30 ) circle.setFill(color) circle.draw(win) circles.append(circle) for i in range(100): for c in circles: c.moveTo( clip(c.x + randint(-75, 75), 0, window_width), clip(c.y + randint(-75, 75), 0, window_height) ) time.sleep(0.25) main()
The new features make it so easy to write your program that I had to add 4 more circles.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need help with tracking a tennis ball in a video gqdeep01 1 2,197 Sep-11-2025, 12:35 AM
Last Post: wabbity
  Make these LEDs stay on duckredbeard 5 5,160 Apr-08-2021, 10:26 PM
Last Post: duckredbeard
Question How to make a button always stay on a point when resizing the window? _ShevaKadu 5 8,163 Nov-04-2020, 03:59 PM
Last Post: deanhystad
  bouncing ball with variable collision points (in time) Zhaleh 1 3,873 Jul-24-2020, 02:54 PM
Last Post: Marbelous
  How can i change the direction of the ball based on player's xcor and ycor collisions MohammedSohail 0 2,770 May-25-2020, 08:39 AM
Last Post: MohammedSohail
  How to iterate over some characters in a string and the others will stay as it is. ? sodmzs 9 7,600 Jun-17-2019, 06:45 PM
Last Post: perfringo
  AttributeError: 'Ball' object has no attribute 'hit_paddle' meza1123 1 4,879 Jan-30-2019, 07:25 PM
Last Post: buran
  Could not build the ssl module while installing python3.7 from tar ball badfish 1 9,339 Dec-11-2018, 04:33 AM
Last Post: badfish
  Robot Stay Inside Circular Ring webmanoffesto 4 8,827 Dec-07-2016, 06:57 PM
Last Post: micseydel

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.