Exemplo n.º 1
0
def main(r, g, b, negdh, posdh, mins, maxs, minv, maxv, input_path, output_path):
    if input_path is None:
        camera = cv2.VideoCapture(0)
        camera.set(
            cv2.CAP_PROP_FRAME_WIDTH, 800
        )  # Higer value will cause error on FPGA
        camera.set(
            cv2.CAP_PROP_FRAME_HEIGHT, 600
        )  # Higer value will cause error on FPGA
        camera.set(cv2.CAP_PROP_FPS, 5)
        _, frame = camera.read()
    else:
        frame = cv2.imread(input_path)

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    mask, frame = apply_mask(frame, r, g, b, negdh, posdh, mins, maxs, minv, maxv)
    nrpc = calculate_nrpc(mask)

    if output_path is not None:
        time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        text = "{}, NRPC: {:.4f}".format(time_str, nrpc)
        draw_text(img=frame, text=text)
        cv2.imwrite(output_path, frame)

    return nrpc
def connect_notice(status):
    """
    This function displays information about
    the microbit connection status before the
    game starts.
    status - Boolean value, true if connected.
    """
    screen.fill((0, 0, 0))
    microbit_img = pygame.image.load("connection_files" + utils.sep +
                                     "microbit.png").convert_alpha()
    microbit_rect = microbit_img.get_rect()
    microbit_rect.center = (utils.width / 2, utils.height / 2)
    screen.blit(microbit_img, microbit_rect)
    if status == False:
        utils.draw_text(screen, "Please connect a microbit controller",
                        utils.width / 2, utils.height - (utils.height / 5))
        pygame.display.flip()
    else:
        # Init checkmark sprite
        checkmark = connection_files.checkmark.Checkmark()
        checkmark_sprites = pygame.sprite.Group()
        checkmark_sprites.add(checkmark)
        while utils.done_setup == False:
            checkmark.animate()
            checkmark_sprites.update()
            checkmark_sprites.draw(screen)
            pygame.display.flip()
            utils.clock.tick(60)
        pygame.time.wait(1500)
Exemplo n.º 3
0
    def draw(self, app, cr):
        utils.draw_rectangle(
            cr, self._rect, self._fill_color, self._outline_color)

        node_data = [
            # Nodes, input, offset, text align
            (self._component.inputs, True,
             (NODE_RADIUS+2, 0), utils.TextHAlign.LEFT),
            (self._component.outputs, False,
             (-NODE_RADIUS-2, 0), utils.TextHAlign.RIGHT),
        ]

        for nodes, is_input, offset, text_align in node_data:
            for i, node in enumerate(nodes):
                position = self.node_pos(is_input, i)
                connected = node.is_connected()
                fill_color = _node_color(node.value, connected)
                utils.draw_circle(cr, position, NODE_RADIUS, fill_color, BLACK)
                utils.draw_text(
                    cr, node.label, position + offset, size=10,
                    bold=True, h_align=text_align)

        name = self._component.name
        if name:
            position = self.center - (0, self._rect.height/2+8)
            utils.draw_text(cr, name, position, bold=True)

        self._component.on_draw(app, cr)
Exemplo n.º 4
0
    def redraw(self):
        prog_percent = self.progress / self.max_progress
        self.image = self.orig_image.copy()
        self.image.set_colorkey(WHITE)

        if not self.troll:
            pygame.draw.circle(self.image, DARKGREEN, (32, 32), self.radius)
            draw_text(self.image,
                      self.name[0],
                      2 * self.radius, (254, 254, 254),
                      alignment='center',
                      x=self.rect.w / 2,
                      y=self.rect.h / 2,
                      bold=True)

        if self.progress != 0:
            if prog_percent >= 1:
                color = BLUE
            elif prog_percent >= 0.5:
                color = GREEN
            elif prog_percent >= 0.2:
                color = YELLOW
            elif prog_percent > 0:
                color = WHITE
            else:
                color = RED

            pygame.draw.rect(self.image, color,
                             (0, 0, abs(prog_percent) * self.rect.w, 5))
Exemplo n.º 5
0
 def draw(self):
     super().draw()
     w, h = utils.get_font_size(self.name)
     utils.draw_text(self.name,
                     self.x + self.width // 2 - w // 2,
                     self.y + self.height // 2 - h // 2,
                     color=colors.black)
Exemplo n.º 6
0
    def render(self):
        text_sep_dist = 10

        if isinstance(self.parent, HorizontalLayout):
            x_coord = self.x + self.width / 2.0

            # TODO: implement label rendering (should rotate Draw.Text somehow?)
            draw_line(0.5, self.color, x_coord, self.y, x_coord,
                      self.y + self.height)

        if isinstance(self.parent, VerticalLayout):
            y_coord = self.y + self.height / 2.0

            # HACK! draw text in some not visible place to get its width (needed for centering)
            text_width = draw_text(self.label, -10000.0, -10000.0)

            text_x = self.x + (self.width - text_width) / 2.0

            sep_begin_x = self.x
            sep_end_x = max(sep_begin_x, text_x - text_sep_dist)
            draw_line(0.5, self.color, sep_begin_x, y_coord, sep_end_x,
                      y_coord)

            text_y = y_coord - 5  # 5 = half of text height
            draw_text(self.label, text_x, text_y)

            sep_end_x = self.x + self.width
            sep_begin_x = min(sep_end_x, text_x + text_width + text_sep_dist)
            draw_line(0.5, self.color, sep_begin_x, y_coord, sep_end_x,
                      y_coord)
Exemplo n.º 7
0
    def __big_event_handler(self, event_text):
        self.screen.blit(self.background, (0, 0))

        utils.draw_text(event_text,
                        self.font48,
                        self.screen,
                        config.screen_width/2,
                        config.screen_height/5)

        for e in pygame.event.get():
            if e.key == ord('y'):
                #self.break_flag = True
                #we lost all lives or we won and trying to play again
                # so initialize all score variables again with zero
                self.pacman.pellets = 0
                self.pacman.score = 0
                self.prev_life_score = 0
                self.lives_cntr = 3
                self.main_loop()
            elif e.key == ord('n'):
                self.pacman.pellets = 0
                self.pacman.score = 0
                self.prev_life_score = 0
                self.lives_cntr = 3
                self.set_menu = False
                self.main_loop()
Exemplo n.º 8
0
def draw_pose_note(context, name, pose, color, font, font_align):
    # Draw notes
    num_dec = len(str(
        (bpy.context.scene.TOL - int(bpy.context.scene.TOL)))) - 2
    loc = pose.loc
    rot = pose.rotation

    txt = '(x={:0.4f}, y={:0.4f}, z={:0.4f}) [meters]'.format(
        loc.x, loc.y, loc.z)

    hint_space = 10
    rotation = 0
    loc_note_name = utils.draw_text(context, name, txt, loc, color, hint_space,
                                    font, font_align, rotation)

    bpy.data.objects[loc_note_name].lock_location[0:3] = (True, True, True)
    bpy.data.objects[loc_note_name].lock_rotation[0:3] = (True, True, True)
    bpy.data.objects[loc_note_name].lock_scale[0:3] = (True, True, True)
    bpy.data.objects[loc_note_name].protected = True

    txt = '(x={:0.4f}, y={:0.4f}, z={:0.4f}) degrees'.format(
        degrees(rot.x), degrees(rot.y), degrees(rot.z))

    rot_note_name = utils.draw_text(context, name, txt, loc, color, hint_space,
                                    font, font_align, rotation)

    bpy.data.objects[rot_note_name].location += rot.to_matrix().col[2]

    bpy.data.objects[rot_note_name].lock_location[0:3] = (True, True, True)
    bpy.data.objects[rot_note_name].lock_rotation[0:3] = (True, True, True)
    bpy.data.objects[rot_note_name].lock_scale[0:3] = (True, True, True)
    bpy.data.objects[rot_note_name].protected = True

    return loc_note_name, rot_note_name
Exemplo n.º 9
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    # You are allowed to change the img_url to your own image URL.
    # Display the image. If you are running on a server, change this line to
    # result.save('test.jpg')
    import utils
    request.urlretrieve(img_url, os.path.join(SRC_PATH, 'test.jpg'))
    result_img = utils.Image.open('test.jpg')
    utils.draw_text(result_img, 'b07902023')
    result_img.save('test.jpg')
    # result_img.show()
    # End of TODO

    return result_img
Exemplo n.º 10
0
def main():
	#开始测试
	for file in dirs:
		image_path = os.path.join(text_floder, os.path.basename(file))
		#print(os.path.basename(file))
		#print(image_path)
		# 加载灰度图像和灰度图片
		rgb_image = load_image(image_path, grayscale=False, color_mode = "rgb")
		gray_image = load_image(image_path, grayscale=True,color_mode = "grayscale")
		# 去掉维度为1的维度(只留下宽高,去掉灰度维度)
		gray_image = np.squeeze(gray_image)
		gray_image = gray_image.astype("uint8")
		faces = detect_faces(face_detection, gray_image)
		#print("-----")
		#print(len(faces))
		for face_coordinates in faces:
			#获取人脸在图像中的矩形坐标的对角两点
			x1, x2, y1, y2 = get_coordinates(face_coordinates)
			#print(x1, x2, y1, y2 )
			# 截取人脸图像像素数组
			gray_face = gray_image[y1:y2, x1:x2]

			try:
				# 将人脸reshape模型需要的尺寸
				gray_face = cv2.resize(gray_face,(emotion_target_size))
			except:
				continue

			gray_face = preprocessing_input(gray_face)
			gray_face = np.expand_dims(gray_face, 0)
			gray_face = np.expand_dims(gray_face, -1)
			# print(gray_face.shape)

			# 预测
			emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face))
			emotion_text = emotion_labels[emotion_label_arg]

			color = (255,0,0)
			# 画边框
			draw_bounding_box(face_coordinates, rgb_image, color)
			# 画表情说明
			draw_text(face_coordinates, rgb_image, emotion_text, color, 0, face_coordinates[3]+30, 1, 2)

			# 将图像转换为BGR模式显示
			bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
			cv2.imwrite("./pic_test/"+"predict"+os.path.basename(file), bgr_image)

			cv2.waitKey(1)
			cv2.destroyAllWindows()

	print("已识别%d张图片" % int(len(dirs)))
Exemplo n.º 11
0
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    from PIL import Image
    # use the last token of url as file name
    file_name = img_url.split("/")[-1]
    # download image
    request.urlretrieve(img_url, f"./{file_name}")
    # convert image to PIL Image object
    result_img = Image.open(f"./{file_name}")
    # In order to import module from parent directory, add "../" to sys.path
    import sys
    sys.path.append('../')
    # import function "draw_text" and use it
    from utils import draw_text
    draw_text(result_img, "I am B07902075", (50, 50), (255, 255, 255))

    # End of TODO

    return result_img
Exemplo n.º 12
0
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module
    Args:
        img_url: address of an image
    Returns:
        result_img: an PIL Image
    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''

    #font = ImageFont.truetype("arial.ttf", 15)

    result_img = None
    from urllib import request
    from utils import draw_text
    from PIL import Image
    import io

    image = request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(image))
    result_img = draw_text(result_img, 'B06902101')

    return result_img
Exemplo n.º 13
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module
    Args:
        img_url: address of an image
    Returns:
        result_img: an PIL Image
    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''

    #font = ImageFont.truetype("arial.ttf", 15)

    result_img = None
    from urllib import request
    from utils import draw_text
    from PIL import Image
    import io

    image = request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(image))
    result_img = draw_text(result_img, 'B06902101')

    return result_img
Exemplo n.º 14
0
def credits():
    """
    This function handles the credits display.
    """
    credit_lines = []
    credit_objects = []
    utils.text_size = 20
    utils.text_colour = (255, 255, 255)

    with open("credits.txt") as f:
        # Strip \n from each line and store in a list
        credit_lines = [line.rstrip() for line in f]

    for line in range(0, len(credit_lines)):
        # Create all the text objects
        credit_objects.append(
            utils.draw_text(screen, credit_lines[line], utils.width / 2,
                            utils.height + (50 * line)))

    while credit_objects[len(credit_lines) - 1][1].y > 0:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # This loop scrolls the text up util the last line is outside of the screen
        screen.fill((0, 0, 0))
        for line in range(0, len(credit_lines)):
            credit_objects[line][1].y -= 5
            if credit_objects[line][1].y > 0:
                screen.blit(credit_objects[line][0], credit_objects[line][1])
        pygame.display.flip()
        utils.clock.tick(25)
    utils.text_size = 100
Exemplo n.º 15
0
def render():
    """
    Renders a single frame.

    Returns
    -------
    ndarray
        Array representing a frame in BGR color format.
    """
    global masked_frame, image

    ret, frame = camera.read()
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    mask, masked_frame = apply_mask(
        frame=frame,
        r=selected_color[0][0][2],
        g=selected_color[0][0][1],
        b=selected_color[0][0][0],
        negdh=cv2.getTrackbarPos(hue_delta_minus_name, window_name),
        posdh=cv2.getTrackbarPos(hue_delta_plus_name, window_name),
        mins=cv2.getTrackbarPos(min_saturation_name, window_name),
        maxs=cv2.getTrackbarPos(max_saturation_name, window_name),
        minv=cv2.getTrackbarPos(min_value_name, window_name),
        maxv=cv2.getTrackbarPos(max_value_name, window_name),
    )

    # Calculate and draw metric value.
    nrpc = calculate_nrpc(mask)
    time_str = time.strftime("%H:%M:%S", time.localtime())
    text = "{}, FPS: {:05.2f}, NRPC: {:.4f}".format(time_str, fps, nrpc)
    draw_text(img=frame, text=text)

    # Change color format back from RGB to BGR.
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    masked_frame = cv2.cvtColor(masked_frame, cv2.COLOR_RGB2BGR)

    # Concatenate horizontally (1) frames and (2) colors. Then, concatenate
    # vertically (1) and (2) vertically.
    frames = np.concatenate((frame, masked_frame), axis=1)
    colors = np.concatenate(
        (current_color, selected_color, lower_filtered_color, upper_filtered_color),
        axis=1,
    )
    image = np.concatenate((frames, colors), axis=0)

    return image
Exemplo n.º 16
0
 def draw(
     self, sm, screen
 ):  # We pass in sm referring to its instance within the scene manager.
     screen.fill(self.c.black)
     utils.draw_text(screen, "Main Menu")
     utils.draw_text(
         screen, "Click [G] for Game",
         pos=(20, 300))  # Choosing which parameter we want to customize.
     utils.draw_text(screen, "Click [S] for Settings", pos=(20, 550))
     utils.draw_text(screen, "Click [Q] to Quit", pos=(20, 800))
Exemplo n.º 17
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    from PIL import image
    import requests
    from io import BytesIO
    import sys
    sys.path.append("..")
    from utils import draw_text
    respond = requests.get(img_url)
    result_img = Image_open(ByesIO(respond.content))
    draw_text(result_img, 'b06202007')
    #result_img.show()
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 18
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.
    # You are allowed to change the img_url to your own image URL.

    from PIL import Image
    import utils
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
    r = request.urlopen(img_url)
    data = r.read()
    with open("1234.jpg", 'wb') as f:
        f.write(data)
    result_img = Image.open('1234.jpg')
    utils.draw_text(result_img, "B07902073")
    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 19
0
    def draw_debug_values(self, app, cr):
        if not self._debug:
            return

        color = GRAY

        for i, node in enumerate(self._component.inputs):
            position = self.node_pos(True, i)
            utils.draw_text(
                cr, str(node.value), position - (NODE_RADIUS+1, 0), size=10,
                h_align=utils.TextHAlign.RIGHT,
                bold=True, background_color=color)

        for i, node in enumerate(self._component.outputs):
            position = self.node_pos(False, i)
            utils.draw_text(
                cr, str(node.value), position + (NODE_RADIUS+1, 0), size=10,
                h_align=utils.TextHAlign.LEFT,
                bold=True, background_color=color)
Exemplo n.º 20
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.
    import utils
    request.urlretrieve(img_url, 'test.jpg')
    from PIL import Image
    result_img = Image.open('test.jpg')
    utils.draw_text(result_img, "b07902049")

    # reference : https://blog.csdn.net/qq_28304687/article/details/76551196

    # End of TODO

    return result_img
Exemplo n.º 21
0
def game_over(pygame, font, screen, screen_rect, userName):
    click = False
    running = True
    while running:
        # Define mouse click to false
        mx, my = pygame.mouse.get_pos(
        )  # Init mouse cursor position for the menu
        utils.init_game_background(
            pygame, screen)  # Start the init_game_background function

        gameover = pygame.image.load('../img/wasted.png')
        screen.blit(gameover, (285, 150))

        button_1 = pygame.Rect(
            250, 400, 400, 100
        )  # Init button_1 rectangleparameters -> Rect(left, top, width, height)
        button_1.centerx = screen_rect.centerx  # The button x-center value is set to be equal to the screen x-center value

        pygame.draw.rect(screen, (205, 205, 205),
                         button_1)  # Draw the menubutton_1

        utils.draw_text('QUIT', font, (0, 0, 0), screen, 300, 427, True)

        # Event loop that will check if any input event occurs
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    print("Escape has been pushed -> QUIT")
                    running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True

        if button_1.collidepoint((mx, my)):
            if click:
                print("QUIT button clicked")
                running = False

        pygame.display.flip()  # Refresh screen
Exemplo n.º 22
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    # result_img = Image.open(request.urlopen(img_url))
    fullname = 'b03204032.jpg'
    fname, h = request.urlretrieve(img_url, fullname)
    from PIL import Image
    result_img = Image.open(fname)
    import utils
    utils.draw_text(result_img, "b03204032", (0, 0), (0, 0, 0))

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 23
0
    def draw(self, info=None):

        if self.win is None: return

        ntotal = self.ttt.n1won + self.ttt.n2won + self.ttt.nties

        if ntotal > 0:
            yfrac1 = self.ttt.n1won / ntotal
            yfrac2 = self.ttt.n2won / ntotal

            self.win.fill(tocolor('gray'),
                          (self.x0, self.y0, self.xrng, self.yrng))
            self.win.fill(tocolor('indianred'),
                          (self.x0, self.y1 - yfrac1 * self.yrng, self.xrng,
                           yfrac1 * self.yrng))
            self.win.fill(tocolor('cyan'),
                          (self.x0, self.y0, self.xrng, yfrac2 * self.yrng))

        for (l_start, l_end) in [self.vl1, self.vl2, self.hl1, self.hl2]:
            pygame.draw.line(self.win, self.lc, l_start, l_end, 2)

        for (l_start, l_end) in [self.hl3, self.hl4, self.vl3, self.vl4]:
            pygame.draw.line(self.win, self.lc, l_start, l_end, 6)

        for row, col in itertools.product(range(3), range(3)):
            if self.ttt.state[row, col] != 0:
                mark = 'X' if self.ttt.state[row, col] == 1 else 'O'
                color = 'darkred' if self.ttt.state[row, col] == 1 else 'blue'
                draw_text(self.win,
                          mark,
                          xy=(self.centx[row, col], self.centy[row, col]),
                          color=color)

        if info is not None:
            draw_text(self.win,
                      info,
                      xy=(self.centx[1, 1], self.centy[1, 1] - self.yrng / 9),
                      color='black')
Exemplo n.º 24
0
 def on_draw(component, app, cr):
     lines = list(itertools.chain.from_iterable(
         textwrap.wrap(line, width=max_width, tabsize=4)
         for line in component.data['text'].split('\n')
     ))
     if lines and not lines[-1]:
         lines.pop()
     lines = lines[-max_height:]
     grid_size = app.grid_size
     position = (
         component.display.rect.bottom_left +
         (grid_size//2, -grid_size//2)
     )
     rect = shapes.Rectangle(
         position=position-(4, 12*max_height),
         size=(max_width*7+8, max_height*12+4))
     utils.draw_rectangle(cr, rect, (0.9, 0.9, 0.9), (0, 0, 0))
     for i, line in enumerate(reversed(lines)):
         pos = position - (0, i*12)
         utils.draw_text(
             cr, line, pos,
             h_align=utils.TextHAlign.LEFT,
             v_align=utils.TextVAlign.BOTTOM)
Exemplo n.º 25
0
    def __big_event_handler(self, event_text):
        self.screen.blit(self.background, (0, 0))

        utils.draw_text(event_text, self.font48, self.screen,
                        config.screen_width / 2, config.screen_height / 5)

        for e in pygame.event.get():
            if e.key == ord('y'):
                #self.break_flag = True
                #we lost all lives or we won and trying to play again
                # so initialize all score variables again with zero
                self.pacman.pellets = 0
                self.pacman.score = 0
                self.prev_life_score = 0
                self.lives_cntr = 3
                self.main_loop()
            elif e.key == ord('n'):
                self.pacman.pellets = 0
                self.pacman.score = 0
                self.prev_life_score = 0
                self.lives_cntr = 3
                self.set_menu = False
                self.main_loop()
Exemplo n.º 26
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    from PIL import Image
    import io
    import utils
    r = request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(r))
    result_img = utils.draw_text(result_img, 'b07902133')

    #    import io
    #    from PIL import Image
    #    import utils
    #    result_img = None
    #    ret = request.urlopen(img_url).read()
    #    result_img = Image.open(io.BytesIO(ret)) # transfer bytes into PIL object
    #    result_img = utils.draw_text(result_img, 'b07902133')

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 27
0
def draw_robot_note(context, loc, text, color, font, font_align):
    # Draw notes
    name = "Robot_note"
    hint_space = 10
    rotation = 0
    robot_note = utils.draw_text(context, name, text, loc, color, hint_space,
                                 font, font_align, rotation)

    bpy.data.objects[robot_note].lock_location[0:3] = (True, True, True)
    bpy.data.objects[robot_note].lock_rotation[0:3] = (True, True, True)
    bpy.data.objects[robot_note].lock_scale[0:3] = (True, True, True)
    bpy.data.objects[robot_note].protected = True

    bpy.data.objects[robot_note].object_type = "ROBOT_NOTE"

    return robot_note
Exemplo n.º 28
0
def draw_bluetooth_note(context, name, loc):
    color = Vector((1.0, 1.0, 1.0, 1.0))
    font = 14
    font_align = 'C'
    hint_space = 0.1
    font_rotation = 0
    text = str(name) + "(bluetooth)"

    nota = utils.draw_text(context, name + "_note", text, loc, color,
                           hint_space, font, font_align, font_rotation)

    bpy.data.objects[nota].lock_location[0:3] = (True, True, True)
    bpy.data.objects[nota].lock_rotation[0:3] = (True, True, True)
    bpy.data.objects[nota].lock_scale[0:3] = (True, True, True)

    bpy.data.objects[nota].hide_select = True

    return nota
Exemplo n.º 29
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.
    from PIL import Image
    import utils
    import io
    temp = request.urlopen(img_url).read()
    result_img = Image.open(io.BytesIO(temp))
    result_img = utils.draw_text(result_img, 'b07902059')
    # Note: the main reference for task 8 is this website:
    # https://docs.python.org/3.4/howto/urllib2.html
    # Also, the code is written after discussion with classmates,
    # so it might be similar to theirs
    # End of TODO

    return result_img
Exemplo n.º 30
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    result_img = None

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.
    from PIL import Image
    import utils
    import io
    x = request.urlopen(img_url)
    result_img = Image.open(io.BytesIO(x.read()))
    result_img = utils.draw_text(result_img, 'B07902117')
    # reference 1:https://www.journaldev.com/20795/python-urllib-python-3-urllib
    # reference 2:https://stackoverflow.com/questions/38114499/difference-between-requests-get-and-urrlib-request-urlopen-python
    # reference 3:https://www.tutorialspoint.com/python/python_files_io.htm

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 31
0
 def draw(self):
     super().draw()
     utils.draw_text("Wait Score : %d" % int(self.wait_score),
                     100,
                     100,
                     color=colors.white)
     utils.draw_text("Cook Score : %d" % int(self.cook_score),
                     100,
                     200,
                     color=colors.white)
     utils.draw_text("Build Score : %d" % int(self.build_score),
                     100,
                     300,
                     color=colors.white)
Exemplo n.º 32
0
def task_8(img_url: str = 'https://http.cat/404') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from urllib import request
    from PIL import Image, ImageFont, ImageDraw
    from utils import draw_text

    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_text() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    local_filename, headers = request.urlretrieve(img_url)
    img = Image.open(local_filename)
    result_img = draw_text(img, 'B07902123')

    # Display the image:
    #result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img
Exemplo n.º 33
0
def task_8(img_url: str = 'https://i.imgur.com/B75zq0x.jpg') -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    import urllib.request
    result_img = None
    from utils import draw_text
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.
    from PIL import Image
    urllib.request.urlretrieve(
        img_url, '/mnt/c/users/attis/desktop/pythonhomework/src/b07902113.jpg')
    with Image.open(
            '/mnt/c/users/attis/desktop/pythonhomework/src/b07902113.jpg'
    ) as result_img:
        result_img = draw_text(result_img, 'b07902113')
        result_img.show()
    # result_img.show(req)
    # You are allowed to change the img_url to your own image URL.
    # Display the image. If you are running on a server, change this line to
    # result.save('test.jpg')

    # End of TODO

    return result_img
Exemplo n.º 34
0
def directions(screen, potions_list, buttons_list, get_data):
    """
    Provides the user with the initial shuffling code.
    - screen: The pygame.display to load into
    - potions_list: List of pygame Surfaces
    - buttons_list: List of the buttons related to the items in potions_list
    - get_data: get_data function to retrieve data
                from the microbit.
    """
    global X
    global Y

    buttons = buttons_list.copy()
    for i in range(0, len(buttons)):
        if buttons[i] == 1:
            buttons[i] = "U"
        elif buttons[i] == 2:
            buttons[i] = "L"
        elif buttons[i] == 3:
            buttons[i] = "D"
        elif buttons[i] == 4:
            buttons[i] = "R"
    screen.fill((0, 0, 0))
    # Adjusted coordinates for better display of the sprites
    rect0 = potions_list[0].get_rect()
    rect0.center = (X / 4, Y)
    rect1 = potions_list[1].get_rect()
    rect1.center = (X / 2, Y)
    rect2 = potions_list[2].get_rect()
    rect2.center = (X - (X / 4), Y)
    screen.blit(potions_list[0], rect0)
    screen.blit(potions_list[1], rect1)
    screen.blit(potions_list[2], rect2)
    # Show which is which
    utils.draw_text(screen, buttons[0], X / 4, Y + 300)
    utils.draw_text(screen, buttons[1], X / 2, Y + 300)
    utils.draw_text(screen, buttons[2], X - (X / 4), Y + 300)
    pygame.display.flip()
    utils.run_in_thread(get_data)  # Clean the buffer before the game starts
    pygame.time.wait(2000)
    utils.run_in_thread(get_data)  # Clean the buffer before the game starts
    return
Exemplo n.º 35
0
    def main_loop(self):

        self.clock = pygame.time.Clock()

        if not self.set_menu:
            self.set_menu = True
            main_menu(self.screen)

        #loading sprites
        self.__load_sprites()
        self.pacman.score = self.prev_life_score
        self.pacman.lives = self.lives_cntr
        #setting background
        self.__set_backgrnd()

        self.block_sprites.draw(self.background)
        self.gwall_sprites.draw(self.background)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type is KEYDOWN:
                    if event.key in [K_RIGHT, K_LEFT, K_UP, K_DOWN]:
                        self.pacman.move(self.block_sprites, event.key)

            # enemies random move
            for ghost in self.enemies:
                ghost.move(self.block_sprites)

            if pygame.sprite.spritecollide(self.pacman, self.enemies_sprites, False):
                #we have collision with ghost so increment ghost collision counter
                #and drop to zero number of eaten pellets
                self.enemy_cols += 1
                self.pacman.pellets = 0
                #if we lost 3 lives game over and ask for playing again
                if self.enemy_cols == self.enemy_max_cols:
                    self.enemy_cols = 0
                    while True:
                        self.__big_event_handler("You lost. Play again (y/n)?")
                        pygame.display.flip()
                #going out from loop and restart it
                break

            #check collisions True means: kill sprite from group in collision
            pacman_pellets_cols = pygame.sprite.spritecollide(self.pacman, self.pellet_sprites, True)
            #count score 
            for dot in pacman_pellets_cols:
                self.pacman.pellets += 1
                self.pacman.score += 10
                if self.pacman.pellets == self.max_pellets:
                    while True:
                        self.__big_event_handler("You Won!!! Play again (y/n)?")
                        pygame.display.flip()

            #adding background on the screen
            self.screen.blit(self.background, (0, 0))
            
            #draw sprites
            self.pellet_sprites.draw(self.screen)
            self.pacman_sprite.draw(self.screen)
            self.enemies_sprites.draw(self.screen)
            utils.draw_text("Score: %d "%self.pacman.score,
                            self.font30,
                            self.screen,
                            70,
                            20)
            utils.draw_text("Lives: %d "%self.lives_cntr,
                            self.font30,
                            self.screen,
                            270,
                            20)

            pygame.display.flip()
            self.clock.tick(40)

        self.sounds['die'].play()
        #we killed ,so minus one life
        #and we need to save previos score cause after start main loop below
        #self.pacman.score variable will be initialized with zero again
        self.lives_cntr -= 1
        self.prev_life_score = self.pacman.score
        self.main_loop()
def templateminigame_game(screen, get_data, decrease_lives):
    """
    This function handles the 'template-minigame' minigame.
    - screen: pygame.display to draw to.
    - get_data: get_data function to retrieve data
                from the microbit.
    """
    global X
    global Y
    global background

    # Initialise points variable
    points_counter = utils.points

    # Load main sprite:
    # Use this method only if the sprite is a single image.
    # If you want to animate it, jump to line #68
    # to see how to import an animated sprite.
    main_sprite = pygame.image.load("template-minigame_files" + utils.sep + "main.png").convert_alpha()

    # Main sprite's coordinates
    X = 600
    Y = utils.height - 20 - 320 # 320 is the sprite's height, just an example

    # Init animated sprite
    animated_sprite = template-minigame_files.sprite1.Sprite1()
    animated_sprite_g = pygame.sprite.Group()
    animated_sprite_g.add(animated_sprite)

    # Load backgound image
    background = pygame.image.load("template-minigame_files" + utils.sep + "background.png").convert_alpha()

    # Game
    pygame.mixer.music.load("template-minigame_files" + utils.sep + "music.ogg")
    pygame.mixer.music.play(1) # Do not loop the song, play it once. -1 to play in a loop if you ever need it.
    seconds_counter = time.time()
    utils.text_colour = (255, 255, 255) # Set the text colour for the minigame
    while True:
        # Game logic
        if time.time() - seconds_counter > 1:
            # Timer
            utils.time_remaining -= 1
            seconds_counter = time.time()

        if utils.time_remaining > 0: # Enough time remaining condition
            utils.run_in_thread(get_data)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            screen.fill((0, 0, 0))

            # Microbit input here. Manipulate the data
            # as per minigame's needs. The data comes in
            # an array stored in the utils.data variable.
            # Example of data manipulation (from dinorun minigame):
            jump = (utils.data[0] == 1)

            animated_sprite.animate()

            screen.blit(background, (0, 0))
            animated_sprite_g.draw(screen)
            animated_sprite_g.update()

            # Info
            utils.draw_text(screen, "Insert info here", utils.width / 2, 322)
            utils.draw_points(screen)
            utils.draw_time(screen, utils.time_remaining)
            utils.run_in_thread(utils.draw_volume(screen))

            pygame.display.flip()
            utils.clock.tick(60) # Pick the clock that best suits your game
        else:
            pygame.mixer.music.stop()
            if utils.points - points_counter < 6:
                # If true, the user lost. Feel free to change the points needed to win
                decrease_lives()
                end_anim(screen, False)
            else:
                end_anim(screen, True)

            utils.minigame_end(screen, get_data)
            break
    return
Exemplo n.º 37
0
 def on_draw(component, app, cr):
     text = str(component.inputs[0].value)
     position = component.display.center
     utils.draw_text(cr, text, position)