CPSC120B
Fundamentals of Computer Science I

Day 15 Notes

Logical Operators

Computer Science Thing of the Day

Reading Questions

Quiz

Logical Operators

Boolean Functions

Example - Point in Circles

import graphics

POINT_WIDTH = 10

# PRE:  point_x, point_y, circle_x, circle_y, and circle_radius are
#       positive numbers
# POST: returns whether the specified point is inside the specified
#       circle
def is_point_in_circle(point_x, point_y, circle_x, circle_y, circle_radius):
    delta_x = circle_x - point_x
    delta_y = circle_y - point_y
    distance = (delta_x * delta_x + delta_y * delta_y) ** (1 / 2)
    return distance <= circle_radius

circle_offset = 50
circle_1_x = graphics.window_width() / 2 - circle_offset
circle_1_y = graphics.window_height() / 2 
circle_1_radius = 100
circle_1_width = circle_1_radius * 2
circle_1_height = circle_1_width
circle_2_x = graphics.window_width() / 2 + circle_offset
circle_2_y = graphics.window_height() / 2 
circle_2_radius = 100
circle_2_width = circle_2_radius * 2
circle_2_height = circle_2_width

graphics.clear()
graphics.draw_oval(circle_1_x, circle_1_y, circle_1_width, circle_1_height)
graphics.draw_oval(circle_2_x, circle_2_y, circle_2_width, circle_2_height)
while graphics.window_open():
    if graphics.button_down(1):
        point_x = graphics.mouse_x()
        point_y = graphics.mouse_y()
        in_circle_1 = is_point_in_circle(point_x, point_y,
                                         circle_1_x, circle_1_y,
                                         circle_1_radius)
        in_circle_2 = is_point_in_circle(point_x, point_y,
                                         circle_2_x, circle_2_y,
                                         circle_2_radius)
        if in_circle_1 or in_circle_2:
            graphics.draw_oval(point_x, point_y, POINT_WIDTH, POINT_WIDTH,
                               fill="green")
        else:
            graphics.draw_oval(point_x, point_y, POINT_WIDTH, POINT_WIDTH,
                               fill="red")
    graphics.wait()

Lab