Sunday, November 3, 2013

Do the Point and Rectangle ever Overlap?

Problem :
Convert the following specification into code. Do the point and rectangle ever overlap?
A point starts at [10, 20]. It repeatedly changes position by [3, 0.7] — e.g., under button or timer control. Meanwhile, a rectangle stays in place. Its corners are at [50, 50] (upper left), [180, 50] (upper right), [180, 140] (lower right), and [50, 140] (lower left).
To check for overlap, i.e., collision, just run your code and check visually. You do not need to implement a point-rectangle collision test. However, we encourage you to think about how you would implement such a test.




CODE :

import simplegui

# initialize state
width = 200
height = 200
position = [10, 20]
radius = 2
velocity = [3,0.7]

# event handlers
def keydown(key):
    if key == simplegui.KEY_MAP['down']:
        position[1] = position[1] - velocity[1]
        position[0] = position[0] - velocity[0]
 

    elif key == simplegui.KEY_MAP['up']:
        position[1] = position[1] + velocity[1]
        position[0] = position[0] + velocity[0]
  
   
def draw(canvas):
    canvas.draw_circle(position, radius, 2, "red", "red")
    canvas.draw_line((50, 50), (50, 140), 2, "White")
    canvas.draw_line((50, 140), (180, 140), 2, "White")
    canvas.draw_line((180, 50), (50, 50), 2, "White")
    canvas.draw_line((180, 140), (180, 50), 2, "White")

# create frame
frame = simplegui.create_frame("Key Handling", width, height)

# register event handlers
frame.set_keydown_handler(keydown)
frame.set_draw_handler(draw)

# start frame
frame.start()



# http://www.codeskulptor.org/#user22_YXZnJWQnbLfSi81.py

Output :