Trace #1:
Run the following code by hand/IDE :
from cmu_graphics import *
def onAppStart(app):
app.cx = 200
app.cy = 200
app.r = 50
app.dx = 7
app.dy = 11
app.paused = True
def redrawAll(app):
drawLabel("Bouncing Horizontally and Vertically", 200, 30, size=16)
drawLabel("Press s to step", 200, 50, size=12)
drawLabel("Press p to pause/unpause", 200, 70, size=12)
drawCircle(app.cx, app.cy, app.r, fill="blue")
def onKeyPress(app, key):
if key == "p":
app.paused = not app.paused
elif key == "s":
takeStep(app)
def takeStep(app):
bounceHorizontally(app)
bounceVertically(app)
def bounceHorizontally(app):
app.cx += app.dx
if app.cx >= app.width:
app.cx = app.width
app.dx = -app.dx
elif app.cx <= 0:
app.cx = 0
app.dx = -app.dx
def bounceVertically(app):
app.cy += app.dy
if app.cy >= app.height:
app.cy = app.height
app.dy = -app.dy
elif app.cy <= 0:
app.cy = 0
app.dy = -app.dy
def onStep(app):
if not app.paused:
takeStep(app)
def main():
runApp()
main()
Notice how the ball goes partially off the screen before bouncing back? Fix it so the ball bounces back as soon as it touches the edge of the screen.