I have a program in Python for making one ball bounce off of all 4 sides of a window, but now I need to make 10 balls using an array. I'm still very new to this and confused on how to implement this. I'll post what I have so far below:
#create 10 balls bouncing off all 4 sides of the window (400 x 500)
#The ball must start moving after a click, then stop after a given amount of time
#After a second click, the program ends
#----Algorithm----#
#create screen 400 x 500
#create array of 10 circles in different starting points
#wait for click anywhere on screen
#click anywhere on screen
#all 10 balls move in different directions bouncing off all 4 walls
#if ball hits left or right wall
#dy=dy*-1
#if ball hits top or bottom
#dx=dx*-1
#ball moves for no more than 30 seconds
#ball stops
#wait for next click
#program ends
#----ProgramStarts----#
from graphics import *
import time, random
#create screen
winWidth = 400;
winHeight = 500;
win = GraphWin('Ball Bounce', winWidth, winHeight);
win.setBackground(color_rgb(255,255,255));
win.setCoords(0,0,winWidth, winHeight);
numBalls= 10;
#create 10 balls
def makeBall(center, radius, win):
balls=[];
radius=10;
for i in range (0,numBalls):
aBall=Circle(center, radius);
aBall.setFill("red");
aBall.draw(win);
balls.append(aBall);
#animate 10 balls bouncing off edges of window
def bounceInWin(shape, dx, dy, xLow, xHigh, yLow, yHigh):
clickPoint=win.getMouse();
delay = .005
for x in range(900):
shape.move(dx, dy)
center = shape.getCenter()
x = center.getX()
y = center.getY()
if x < xLow:
dx = -dx
if x > xHigh:
dx = -dx
if y < yLow:
dy = -dy
if y > yHigh:
dy = -dy
time.sleep(delay);
#get a random Point
def getRandomPoint(xLow, xHigh, yLow, yHigh):
x = random.randrange(xLow, xHigh+1)
y = random.randrange(yLow, yHigh+1)
return Point(x, y)
#make ball bounce
def bounceBall(dx, dy):
winWidth = 400
winHeight = 500
win = GraphWin('Ball Bounce', winWidth, winHeight);
win.setCoords(0,0,winWidth, winHeight);
radius = 10
xLow = radius
xHigh = winWidth - radius
yLow = radius
yHigh = winHeight - radius
center = getRandomPoint(xLow, xHigh, yLow, yHigh)
ball = makeBall(center, radius, win)
bounceInWin(ball, dx, dy, xLow, xHigh, yLow, yHigh)
bounceBall(3, 5);
#wait for another click to end program
win.getMouse(); #close doesn't work, tried putting in loop
win.close;
Specific problems with your code: makeBall() fails to return balls; makeBall() needs to generate random starting points, not all starting at the same place; bounceInWin() needs to have a separate, and separately updated, dx and dy for every ball, not just the one; the code creates the main window twice -- just once is fine; need to add time calculation to shut down motion instead of fixed number of iterations; win.close() is a method so it needs parentheses; avoid using semi-colon ";" in Python code.
Below is a rework of your code with the above changes and some style tweaks:
# Create 10 balls bouncing off all 4 sides of a window (400 x 500)
# The ball must start moving after a click, then stop after a given
# amount of time. After a second click, the program ends.
#----Algorithm----#
# create screen 400 x 500
# create array of 10 circles in different starting points
# wait for click anywhere on screen
# all 10 balls move in different directions bouncing off all 4 walls
# if ball hits left or right wall
# dx = -dx
# if ball hits top or bottom
# dy = -dy
# balls move for no more than 30 seconds
# balls stops
# wait for next click
# program ends
#----ProgramStarts----#
import time
import random
from graphics import *
winWidth, winHeight = 400, 500
ballRadius = 10
ballColor = 'red'
numBalls = 10
delay = .005
runFor = 30 # in seconds
# create 10 balls, randomly located
def makeBalls(xLow, xHigh, yLow, yHigh):
balls = []
for _ in range(numBalls):
center = getRandomPoint(xLow, xHigh, yLow, yHigh)
aBall = Circle(center, ballRadius)
aBall.setFill(ballColor)
aBall.draw(win)
balls.append(aBall)
return balls
# animate 10 balls bouncing off edges of window
def bounceInWin(shapes, dx, dy, xLow, xHigh, yLow, yHigh):
movedShapes = [(getRandomDirection(dx, dy), shape) for shape in shapes]
start_time = time.time()
while time.time() < start_time + runFor:
shapes = movedShapes
movedShapes = []
for (dx, dy), shape in shapes:
shape.move(dx, dy)
center = shape.getCenter()
x = center.getX()
if x < xLow or x > xHigh:
dx = -dx
y = center.getY()
if y < yLow or y > yHigh:
dy = -dy
# Could be so much simpler if Point had setX() and setY() methods
movedShapes.append(((dx, dy), shape))
time.sleep(delay)
# get a random direction
def getRandomDirection(dx, dy):
x = random.randrange(-dx, dx)
y = random.randrange(-dy, dy)
return x, y
# get a random Point
def getRandomPoint(xLow, xHigh, yLow, yHigh):
x = random.randrange(xLow, xHigh + 1)
y = random.randrange(yLow, yHigh + 1)
return Point(x, y)
# make balls bounce
def bounceBalls(dx, dy):
xLow = ballRadius * 2
xHigh = winWidth - ballRadius * 2
yLow = ballRadius * 2
yHigh = winHeight - ballRadius * 2
balls = makeBalls(xLow, xHigh, yLow, yHigh)
win.getMouse()
bounceInWin(balls, dx, dy, xLow, xHigh, yLow, yHigh)
# create screen
win = GraphWin('Ball Bounce', winWidth, winHeight)
bounceBalls(3, 5)
# wait for another click to end program
win.getMouse()
win.close()
Related
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
Hi sorry for the many questions but again I know python but am trying to learn pygame. In the game I'm making im trying to make it so when a block/image touches the sprite it goes back to the top of the screen. I have looked at many tutorials but can't seem to figure it our in a way that would work good. Any advice? Heres the code thanks!!!:
import pygame
import sys
from random import randint
import os
x = 250
y = 30
os.environ["SDL_VIDEO_WINDOW_POS"] = "%d,%d" % (x, y)
width = 1024
height = 768
icon1 = pygame.image.load("Firstpygamegame/santa-claus.png")
pygame.display.set_icon(icon1)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Gift Catcher")
background_image = pygame.image.load("Firstpygamegame/wintervillage.png")
sprite1 = pygame.image.load("Firstpygamegame/santabag2.png")
spriterect = sprite1.get_rect()
speed = 2.5
# 442 or 467
spriterect.x = 442
icon2 = pygame.image.load("Firstpygamegame/present1.png")
icon3 = pygame.image.load("Firstpygamegame/present2.png")
icon4 = pygame.image.load("Firstpygamegame/present3.png")
icon5 = pygame.image.load("Firstpygamegame/present4.png")
cubes = [[
randint(1, 1000), # X coordinate
randint(-1500, -350)] # Y coordinate, -Y is above screen (top of screen is zero)
for x in range(2)] # 20 cubes
cubes1 = [[
randint(1, 1000), # X coordinate
randint(-1500, -150)] # Y coordinate, -Y is above screen (top of screen is zero)
for x in range(2)] # 20 cubes
cubes2 = [[
randint(1, 1000), # X coordinate
randint(-1500, -550)] # Y coordinate, -Y is above screen (top of screen is zero)
for x in range(2)] # 20 cubes
cubes3 = [[
randint(1, 1000), # X coordinate
randint(-1500, -450)] # Y coordinate, -Y is above screen (top of screen is zero)
for x in range(2)] # 20 cubes
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
spriterect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
spriterect.y = 600
screen.blit(background_image, (0, 0))
screen.blit(sprite1, spriterect)
for cb in cubes:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon2, cb) # draw cube
if cb[1] > 800: # if cube passed bottom of screen
cb[1] = -100 # move to above screen
cb[0] = randint(1, 1000)
for cb in cubes1:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon3, cb) # draw cube
if cb[1] > 800: # if cube passed bottom of screen
cb[1] = -100 # move to above screen
cb[0] = randint(1, 1000) # random X position
for cb in cubes2:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon4, cb) # draw cube
if cb[1] > 800: # if cube passed bottom of screen
cb[1] = -100 # move to above screen
cb[0] = randint(1, 1000) # random X position
for cb in cubes3:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon5, cb) # draw cube
if cb[1] > 800: # if cube passed bottom of screen
cb[1] = -100 # move to above screen
cb[0] = randint(1, 1000) # random X position
pygame.display.flip()
Use a pygame.Rect object and colliderect() to find a collision between a rectangle and an object.
pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument:
while running:
# [...]
for cb in cubes:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon2, cb) # draw cube
icon_rect = icon2.get_rect(topleft = cb)
if cb[1] > 800 or icon_rect.colliderect(spriterect):
cb[1] = -100 # move to above screen
cb[0] = randint(1, 1000)
# [...]
However, you can simplify your code:
icon_list = [icon2, icon3, icon4, icon5]
cube_lists = [[[
randrange(screen.get_width() - icon.get_width()),
randint(-1500, -350)]
for x in range(2)]
for icon in icon_list]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
spriterect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
spriterect.y = 600
screen.blit(background_image, (0, 0))
screen.blit(sprite1, spriterect)
for icon, cubes in zip(icon_list, cube_lists):
for cb in cubes:
cb[1] += .25 # cube moves down 2 pixels
screen.blit(icon, cb) # draw cube
icon_rect = icon.get_rect(topleft = cb)
if cb[1] > screen.get_height() or icon_rect.colliderect(spriterect):
cb[:] = randrange(screen.get_width() - icon.get_width()), -800
pygame.display.flip()
pygame.quit()
sys.exit()
Please note, the application loop terminates if running is False. There is no point in setting running = False and to call pygame.quit() and sys.exit() in the event loop. Let the loop run to the end and call pygame.quit() and sys.exit() after the event loop.
I am a new coder and I am building a "Breakout" game in python and i got most of it to except getting the bricks to delete. *What is odd, is after the ball touches the bottom wall (out of bounds) and regenerates, the bricks are then able to be deleted by playing the game! Also, I need to stop the game after 3 chances. I'm stuck, with those 2 problems. Help please. Here is my code:
import tkinter
import time
# How big is the playing area?
CANVAS_WIDTH = 600 # Width of drawing canvas in pixels
CANVAS_HEIGHT = 800 # Height of drawing canvas in pixels
# Constants for the bricks
N_ROWS = 8 # How many rows of bricks are there?
N_COLS = 10 # How many columns of bricks are there?
SPACING = 5 # How much space is there between each brick?
BRICK_START_Y = 50 # The y coordinate of the top-most brick
BRICK_HEIGHT = 20 # How many pixels high is each brick
BRICK_WIDTH = (CANVAS_WIDTH - (N_COLS + 1) * SPACING) // N_COLS
# Constants for the ball and paddle
BALL_SIZE = 70
PADDLE_Y = CANVAS_HEIGHT - 40
PADDLE_WIDTH = 200
def main():
canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'Brick Breaker')
# Makes a ball
ball = canvas.create_oval(300, 300, 350, 350, fill="red", outline="red")
# Makes a paddle
paddle = canvas.create_rectangle(299, PADDLE_Y, PADDLE_WIDTH, CANVAS_HEIGHT - 20, fill="black")
# Change_X
dx = 6
# Change_Y
dy = 6
for row in range(N_ROWS):
# Draws columns of brick
for col in range(N_COLS):
draw_brick(canvas, row, col)
while True:
# Mouse location and respond to movement
mouse_x = canvas.winfo_pointerx()
# Move Paddle to X location
canvas.moveto(paddle, mouse_x, PADDLE_Y)
# Ball movement
canvas.move(ball, dx, dy)
# If ball hits left of right wall, change X location
if hit_left_wall(canvas, ball) or hit_right_wall(canvas, ball):
dx *= -1
# If ball hits top wall, then change Y location
elif hit_top_wall(canvas, ball):
dy *= -1
elif hit_brick(canvas, ball, paddle):
dy *= -1
if hit_bottom(canvas, ball):
canvas.delete(ball)
ball = make_ball(canvas)
# Recreates canvas
canvas.update()
# Pause time
time.sleep(1 / 50.)
canvas.mainloop()
# Finds coordinates of paddle
def hit_paddle(canvas, ball, paddle):
paddle_coords = canvas.coords(paddle)
x1 = paddle_coords[0]
y1 = paddle_coords[1]
x2 = paddle_coords[2]
y2 = paddle_coords[3]
# If any object begins to overlap with paddle, create a Hit
result = canvas.find_overlapping(x1, y1, x2, y2)
return len(result) > 1
def make_ball(canvas):
return canvas.create_oval(300, 300, 350, 350, fill="red", outline="red")
def hit_brick(canvas, ball, paddle):
ball_coord = canvas.coords(ball)
x_1 = ball_coord[0]
y_1 = ball_coord[1]
x_2 = ball_coord[2]
y_2 = ball_coord[3]
results = canvas.find_overlapping(x_1, y_1, x_2, y_2)
for object in results:
if object == paddle or object == ball:
return len(results) > 1
else:
canvas.delete(object)
def moveto(canvas, oval, x, y):
# Get current position
x0, y0, x1, y1 = canvas.coords(oval)
# Sets new position
canvas.move(oval, x - x0, y - y0)
def hit_bottom(canvas, ball):
return get_bottom_y(canvas, ball) >= CANVAS_HEIGHT
def hit_left_wall(canvas, ball):
return get_left_x(canvas, ball) <= 0
def hit_right_wall(canvas, ball):
return get_right_x(canvas, ball) >= CANVAS_WIDTH
def hit_top_wall(canvas, ball):
return get_top_y(canvas, ball) <= 0
def draw_brick(canvas, row, col):
x = col * (BRICK_WIDTH + SPACING)
y = row * (BRICK_HEIGHT + SPACING)
color = "blue"
canvas.create_rectangle(x, y, x + BRICK_WIDTH, y + BRICK_HEIGHT, fill=color, outline=color)
def get_bottom_y(canvas, ball):
return canvas.coords(ball)[3]
def get_top_y(canvas, ball):
"""
This friendly method returns the y coordinate of the top of an object.
Recall that canvas.coords(object) returns a list of the object
bounding box: [x_1, y_1, x_2, y_2]. The element at index 1 is the top-y
"""
return canvas.coords(ball)[1]
def get_left_x(canvas, ball):
"""
This friendly method returns the x coordinate of the left of an object.
Recall that canvas.coords(object) returns a list of the object
bounding box: [x_1, y_1, x_2, y_2]. The element at index 0 is the left-x
"""
return canvas.coords(ball)[0]
def get_right_x(canvas, ball):
"""
This friendly method returns the x coordinate of the right of an object.
Recall that canvas.coords(object) returns a list of the object
bounding box: [x_1, y_1, x_2, y_2]. The element at index 2 is the right-x
"""
return canvas.coords(ball)[2]
def make_canvas(width, height, title):
"""
Creates and returns a drawing canvas
of the given int size with a blue border,
ready for drawing.
"""
top = tkinter.Tk()
top.minsize(width=width, height=height)
top.title(title)
canvas = tkinter.Canvas(top, width=width + 1, height=height + 1)
canvas.pack()
return canvas
if __name__ == '__main__':
main()
The first problem is due to the if statement in the for loop inside hit_brick():
def hit_brick(canvas, ball, paddle):
ball_coord = canvas.coords(ball)
x_1 = ball_coord[0]
y_1 = ball_coord[1]
x_2 = ball_coord[2]
y_2 = ball_coord[3]
results = canvas.find_overlapping(x_1, y_1, x_2, y_2)
for object in results:
if object == paddle or object == ball: # <-- problem here
return len(results) > 1
else:
canvas.delete(object)
As the values of ball and paddle are 1 and 2 (as they are the first two canvas items created) and so results is something like (1, N) when the ball hit one of the bricks.
So the if statement returns true for the first checking and then the function exits by the return statement.
Now let the ball hits the bottom and it will be recreated with id greater than existing canvas items. The results will be something like (N, ball) when the ball hits one of the bricks.
This time the if statement will return false and the brick is deleted.
So hit_brick() should be modified as below:
def hit_brick(canvas, ball, paddle):
ball_coord = canvas.coords(ball)
results = canvas.find_overlapping(*ball_coord)
for object in results:
if object not in (paddle, ball):
canvas.delete(object)
return len(results) > 1
For the second problem, you need to declare a variable, for example lives = 3, before the while loop and decrease it by one if the ball hits the bottom.
The while loop should be terminated if lives == 0:
def main():
...
lives = 3
while lives > 0:
...
if hit_bottom(canvas.ball):
...
lives -= 1
I am using the canvas widget from tkinter to create an ellipse and have it move around in the canvas.
However when the ellipse comes in contact with the border it gets stuck to wall instead of bouncing off.
I'm struggling with debugging the code, thanks in advance!
from tkinter import *
from time import *
import numpy as np
root = Tk()
root.wm_title("Bouncing Ball")
canvas = Canvas(root, width=400, height=400, bg="black")
canvas.grid()
size=10
x = 50
y = 50
myBall = canvas.create_oval(x-size, y-size, x+size, y+size, fill = "red")
while True:
root.update()
root.after(50)
dx = 5
dy = 0
#separating x and y cooridnates from tuple of canvas.coords
x = canvas.coords(myBall)[0]+10
y = canvas.coords(myBall)[1]+10
coordinates = np.array([x, y], dtype = int)
#Checking boundaries
if coordinates[0]-size <= 0:
dx = -1*dx
if coordinates[0]+size >= 400:
dx = -1*dx
if coordinates[1]-size <= 0:
dy = -1*dy
if coordinates[1]+size >= 400:
dy = -1*dy
print(coordinates) #Used to see what coordinates are doing
canvas.move(myBall, dx, dy) #Move ball by dx and dy
Here is a simple way to organize your bouncing ball program, and get you started with GUI programming:
While loops don't work well with a GUI mainloop; it is also not necessary to call update, the mainloop handles that.
Repeated actions are best handles with root.after.
I extracted the bounce logic inside a function bounce that calls itself using root.after. You will see that I simplified the logic.
I also parametrized the canvas size.
The initial speed components dx and dy are randomly chosen from a list of possible values so the game is not too boring.
Here is how it looks:
import tkinter as tk # <-- avoid star imports
import numpy as np
import random
WIDTH = 400
HEIGHT = 400
initial_speeds = [-6, -5, -4, 4, 5, 6]
dx, dy = 0, 0
while dx == dy:
dx, dy = random.choice(initial_speeds), random.choice(initial_speeds)
def bounce():
global dx, dy
x0, y0, x1, y1 = canvas.coords(my_ball)
if x0 <= 0 or x1 >= WIDTH: # compare to left of ball bounding box on the left wall, and to the right on the right wall
dx = -dx
if y0 <= 0 or y1 >= HEIGHT: # same for top and bottom walls
dy = -dy
canvas.move(my_ball, dx, dy)
root.after(50, bounce)
if __name__ == '__main__':
root = tk.Tk()
root.wm_title("Bouncing Ball")
canvas = tk.Canvas(root, width=400, height=400, bg="black")
canvas.pack(expand=True, fill=tk.BOTH)
size=10
x = 50
y = 50
my_ball = canvas.create_oval(x-size, y-size, x+size, y+size, fill="red")
bounce()
root.mainloop()
It's just basic math. The ball moves left when you subtract some amount from the x coordinate. If it hits the left wall and you want it to bounce to the right, you need to stop subtracting from x and start adding to x. The same is true for the y coordinate.
I am currently trying to digitalize an boardgame I invented (repo: https://github.com/zutn/King_of_the_Hill). To make it work I need to check if one of the tiles (the arcs) on this board have been clicked. So far I have not been able to figure a way without giving up the pygame.arc function for drawing. If I use the x,y position of the position clicked, I can't figure a way out to determine the exact outline of the arc to compare to. I thought about using a color check, but this would only tell me if any of the tiles have been clicked. So is there a convenient way to test if an arc has been clicked in pygame or do I have to use sprites or something completely different? Additionally in a later step units will be included, that are located on the tiles. This would make the solution with the angle calculation postet below much more diffcult.
This is a simple arc class that will detect if a point is contained in the arc, but it will only work with circular arcs.
import pygame
from pygame.locals import *
import sys
from math import atan2, pi
class CircularArc:
def __init__(self, color, center, radius, start_angle, stop_angle, width=1):
self.color = color
self.x = center[0] # center x position
self.y = center[1] # center y position
self.rect = [self.x - radius, self.y - radius, radius*2, radius*2]
self.radius = radius
self.start_angle = start_angle
self.stop_angle = stop_angle
self.width = width
def draw(self, canvas):
pygame.draw.arc(canvas, self.color, self.rect, self.start_angle, self.stop_angle, self.width)
def contains(self, x, y):
dx = x - self.x # x distance
dy = y - self.y # y distance
greater_than_outside_radius = dx*dx + dy*dy >= self.radius*self.radius
less_than_inside_radius = dx*dx + dy*dy <= (self.radius- self.width)*(self.radius- self.width)
# Quickly check if the distance is within the right range
if greater_than_outside_radius or less_than_inside_radius:
return False
rads = atan2(-dy, dx) # Grab the angle
# convert the angle to match up with pygame format. Negative angles don't work with pygame.draw.arc
if rads < 0:
rads = 2 * pi + rads
# Check if the angle is within the arc start and stop angles
return self.start_angle <= rads <= self.stop_angle
Here's some example usage of the class. Using it requires a center point and radius instead of a rectangle for creating the arc.
pygame.init()
black = ( 0, 0, 0)
width = 800
height = 800
screen = pygame.display.set_mode((width, height))
distance = 100
tile_num = 4
ring_width = 20
arc = CircularArc((255, 255, 255), [width/2, height/2], 100, tile_num*(2*pi/7), (tile_num*(2*pi/7))+2*pi/7, int(ring_width*0.5))
while True:
fill_color = black
for event in pygame.event.get():
# quit if the quit button was pressed
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
x, y = pygame.mouse.get_pos()
# Change color when the mouse touches
if arc.contains(x, y):
fill_color = (200, 0, 0)
screen.fill(fill_color)
arc.draw(screen)
# screen.blit(debug, (0, 0))
pygame.display.update()
Extend the projectile and tracker to implement the following graphics game:
a. There is square box of a given dimension (choose one reasonable size box) in which
there is a projectile which randomly bounces of the four walls.
b. When a projectile hits a wall, it is launched again by randomly selecting an angle in
the allowed range and a random velocity in a given range. For example, if the
projectile hits the bottom boundary, it selects a random angle in the range 0 to 180
degrees; if it hits the right vertical wall then, it selects random angle between 90 and
270 degrees; and so on.
c. Instead of drawing the circle, move the circle and also fill it with some color.
d. Extend to two projectiles.
Don't ask user the parameters. Use a set of parameters that you think the best.
So I am having trouble trying to find how to make two cballs (the projectiles) bounce from wall to wall. I figured how to bounce them off the bottom wall of the window but it doesn't stop at the right wall and bounce from there. Not only that I have no idea on how to make the balls follow instead of continuously printing circles to Track the movement of the balls. I use ".undraw()" but its very jumpy and not smooth at all.
I would appreciate the help very much! The assignment is due tomorrow and this is what i have:
# projectilebounce.py
# Projectile hits a wall and again is launced
from math import sin, cos, radians
from graphics import *
class Projectile:
def __init__(self, angle, velocity, height):
self.xpos = 0.0
self.ypos = height
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
def update(self, time):
self.xpos = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1
def getY(self):
return self.ypos
def getX(self):
return self.xpos
def reset(self, angle, velocity, height):
self.xpos = self.getX()
self.ypos = height
theta = radians(angle)
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
class Tracker:
def __init__(self, window, objToTrack):
self.win = window
self.obj = objToTrack
def update(self):
a = Circle( Point(self.obj.getX(), self.obj.getY()), 5)
a.draw(self.win)
a.setFill("Black")
a.undraw()
def getInputs():
a1 = 60
a2 = 30
v1 = 60
v2 = 60
h1 = 10
h2 = 10
t = 0.1
return a1, a2, v1, v2, h1, h2, t
def main():
print("This program graphically depicts the flight of a cannonball.\n")
win = GraphWin("TRACKER", 600, 500)
win.setCoords(0.0, 0.0, 600, 500)
angle1, angle2, vel1, vel2, h01, h02, time = getInputs()
cball1 = Projectile(angle1, vel1, h01)
cball2 = Projectile(angle2, vel2, h02)
tracker_cball1 = Tracker(win, cball1)
tracker_cball2 = Tracker(win, cball2)
while True:
if cball1.getY() <= 0: #<---ball 1
cball1.reset(60, 60, 10)
else:
cball1.update(time)
tracker_cball1.update()
if cball2.getY() <= 0: #<---ball 2
cball2.reset(30, 60, 10)
else:
cball2.update(time)
tracker_cball2.update()
if __name__ == '__main__' : main()
Thank you!, I am a big noob at coding at the moment. Much appreciated!