Question

Modify the provided code to do the following: 1) Add starting position to the Ball init...

Modify the provided code to do the following:

1) Add starting position to the Ball init function
2) Move the wall collision code into a collision function that is called by the update function
3) Add Ball collision code that checks for collisions between ball and ball2 objects. Upon collision, send the balls in a realistic direction.

Be sure to use bounding circles for collision accuracy.

Python tkinter code below:

from tkinter import *
import math

WIDTH=800
HEIGHT=600
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="blue")
canvas.pack()

class Ball:
def __init__(self, tag, color, size, vx, vy):
self.shape = canvas.create_oval(0, 0, size, size, fill=color, tags=tag)
self.vx = vx
self.vy = vy

def update(self):
canvas.move(self.shape, self.vx, self.vy)
[x1,y1,x2,y2] = canvas.coords(self.shape)
if x2 >= WIDTH or x1 <= 0:
self.vx *= -1
if y2 >= HEIGHT or y1 <= 0:
self.vy *= -1

def cycle():
canvas.tag_raise("bg")
ball.update()
canvas.tag_raise("ball")
ball2.update()
canvas.tag_raise("ball2")
tk.update_idletasks()
tk.after(3, cycle)

bg = canvas.create_rectangle(0, 0, WIDTH+1, HEIGHT+1, fill="blue", tags="bg")
ball = Ball("ball","black",40,4,4)
ball2 = Ball("ball2","red",20,6,6)
tk.after(0, cycle)
tk.mainloop()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below::

from tkinter import *
import math

WIDTH=800
HEIGHT=600
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="blue")
canvas.pack()

class Ball:
def __init__(self, tag, color, size, vx, vy,startingX,startingY):
self.shape = canvas.create_oval(startingX, startingY, startingX+size, startingY+size, fill=color, tags=tag)
self.vx = vx
self.radius = size/2
self.vy = vy
  
def update(self):
self.checkWallCollision()
  
def checkWallCollision(self):
canvas.move(self.shape, self.vx, self.vy)
[x1,y1,x2,y2] = canvas.coords(self.shape)
if x2 >= WIDTH or x1 <= 0:
self.vx *= -1
if y2 >= HEIGHT or y1 <= 0:
self.vy *= -1
  
def checkBallCollision(ball1,ball2):
radius1 = ball1.radius
radius2 = ball2.radius
totalRadiusDistance = radius1+radius2
[x1,y1,x2,y2] = canvas.coords(ball1.shape)
centerX1 = x1+radius1
centerY1 = y1+radius1
[xx1,yy1,xx2,yy2] = canvas.coords(ball2.shape)
centerX2 = xx1+radius2
centerY2 = yy1+radius2
centerDistances = math.sqrt( math.pow(centerX1-centerX2, 2) + math.pow(centerY1-centerY2, 2))
if(centerDistances<=totalRadiusDistance):
ball1.vx *= -1
ball1.vy *= -1
ball2.vx *= -1
ball2.vy *= -1
  
  
def cycle():
canvas.tag_raise("bg")
ball.update()
canvas.tag_raise("ball")
ball2.update()
checkBallCollision(ball,ball2)
canvas.tag_raise("ball2")
tk.update_idletasks()
tk.after(3, cycle)

bg = canvas.create_rectangle(0, 0, WIDTH+1, HEIGHT+1, fill="blue", tags="bg")
ball = Ball("ball","black",40,4,4,0,0)
ball2 = Ball("ball2","red",20,6,6,100,0)
tk.after(0, cycle)
tk.mainloop()

output:

Add a comment
Know the answer?
Add Answer to:
Modify the provided code to do the following: 1) Add starting position to the Ball init...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please write a code in python! Define and test a function named posterize. This function expects...

    Please write a code in python! Define and test a function named posterize. This function expects an image and a tuple of RGB values as arguments. The function modifies the image like the blackAndWhite function, but it uses the given RGB values instead of black. images.py import tkinter import os, os.path tk = tkinter _root = None class ImageView(tk.Canvas): def __init__(self, image, title = "New Image", autoflush=False): master = tk.Toplevel(_root) master.protocol("WM_DELETE_WINDOW", self.close) tk.Canvas.__init__(self, master, width = image.getWidth(), height = image.getHeight())...

  • // ====== FILE: Point.java ========= // package hw3; /** * A class to that models a...

    // ====== FILE: Point.java ========= // package hw3; /** * A class to that models a 2D point. */ public class Point { private double x; private double y; /** * Construct the point (<code>x</code>, <code>y</code>). * @param x the <code>Point</code>'s x coordinate * @param y the <code>Point</code>'s y coordinate */ public Point(double x, double y) { this.x = x; this.y = y; } /** * Move the point to (<code>newX</code>, <code>newY</code>). * @param newX the new x coordinate for...

  • Question: I am unable to get a output of my function on my label1 when I...

    Question: I am unable to get a output of my function on my label1 when I click on button 1, please help? - x Lè DRAFT P1.py - C:\Users\Darren Louw\Desktop\DRAFT P1.py (3.8.2)* File Edit Format Run Options Window Help from tkinter import* HEIGHT=300 WIDTH=400 root=Tk) lowerframe=Frame (root, bg='green', bd=10) lowerframe.place (relx=0.5, rely=0.6, relwidth=0.75, relheight=0.2, anchor='n') labell-Label (lowerframe, bg='white', font=30) labell.place (relwidth=0.25, relheight=0.8, relx=0) def countl(): countl=0 for i in range (1,1001): num= i*i if num>1000: countl=countlul print('numbers in range 1...

  • Urgent! Consider the following code for the point class studied in week 2: Import math class...

    Urgent! Consider the following code for the point class studied in week 2: Import math class Point: #static attribute _count = 0 # to count how many points we have created so far # initialization method def _init__(self, x = 0, y = 0): #default arguments technique self._x = x self._y=y Point_count += 1 #updating the point count #updating the Point count #getters def getX(self): return self._x def getY(self): return self._y def printPoint(self): return " + str(self._x)+ ' ' +...

  • JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...

    JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to maintain a list of shapes drawn as follows: Replace and upgrade all the AWT components used in the programs to the corresponding Swing components, including Frame, Button, Label, Choice, and Panel. Add a JList to the left of the canvas to record and display the list of shapes that have been drawn on the canvas. Each entry in the list should contain the name...

  • Here is my code for minesweeper in python and it has something wrong. Could you please help me to fix it? import tkinter as tk import random class Minesweeper: def __init__(self): self.main = tk.Tk()...

    Here is my code for minesweeper in python and it has something wrong. Could you please help me to fix it? import tkinter as tk import random class Minesweeper: def __init__(self): self.main = tk.Tk() self.main.title("mine sweeper") self.define_widgets() self.mines = random.sample( [(i,j) for i in range(25) for j in range(50) ],self.CustomizeNumberOfMines()) print(self.mines) self.main.mainloop() self.CustomizeNumberOfMines() def define_widgets(self): """ Define a canvas object, populate it with squares and possible texts """ self.canvas = tk.Canvas(self.main, width = 1002, height=502, bg="#f0f0f0") self.canvas.grid(row=0, column=0) self.boxes =...

  • Add another changeColor() method (i.e. you will now have 2 methods called "changeColor"). This one accepts...

    Add another changeColor() method (i.e. you will now have 2 methods called "changeColor"). This one accepts an int parameter and changes the color based on that int. The valid colors are "red", "yellow", "green", "blue", "magenta" and "black". In your code, map each color to an integer (e.g. in my code 3 means green.) If the number passed to the method is not valid, change the color to red. In the bounceTheBall() method, where you test for collisions with top...

  • In Python, starting with the 8x8 board solution that will be appended here add the following...

    In Python, starting with the 8x8 board solution that will be appended here add the following functionality: 1) Add code to create a list, containing 8 lists, with each of the 8 lists containing 8 null strings as values. Call the list of lists board. code provided by prof: import turtle validMovesList=['A0','A2','A4','A6','B1','B3','B5','B7', 'C0','C2','C4','C6','D1','D3','D5','D7', 'E0','E2','E4','E6','F1','F3','F5','F7', 'G0','G2','G4','G6','H1','H3','H5','H7','quit'] def drawSquare(t,length,color): t.fillcolor(color) t.begin_fill() for num in range(4): t.forward(length) t.left(90) t.end_fill() def drawRow(t,length,color1,color2): for i in range(4): drawSquare(t,length,color1) t.forward(length) drawSquare(t,length,color2) t.forward(length) def drawCircleFilled(t,size,color): t.fillcolor(color) t.begin_fill()...

  • Using python Here is the code import turtle def draw_triangle(vertex, length, k): ''' Draw a ...

    Using python Here is the code import turtle def draw_triangle(vertex, length, k): ''' Draw a triangle at depth k given the bottom vertex.    vertex: a tuple (x,y) that gives the coordinates of the bottom vertex. When k=0, vertex is the left bottom vertex for the outside triangle. length: the length of the original outside triangle (the biggest one). k: the depth of the input triangle. As k increases by 1, the triangles shrink to a smaller size. When k=0, the...

  • Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent()...

    Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent() method to check when the ball has hit the edge of the window. When the ball reaches an edge, you will need to reverse the corresponding delta direction and position the ball back in bounds. Make sure that your solution still works when you resize the window. Your bounds checking should not depend on a specific window size This is the java code that...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT