def draw(self, surface, camera):
        should_draw = False
        if self.shark_alive:
            should_draw = True
        elif 0 < self.sharktimer < 4:
            should_draw = math.sin(self.sharktimer * math.pi * 2 * 4) < 0

        if should_draw:
            draw(surface, warningSign, Vector(screensize.x/2, 50), origin=Vector(0.5, 0), size=Vector(100, None))
Exemple #2
0
	def save_pattern(self, name, pattern):
		patterndatapath = os.path.join(self.PATTERNDIR, name+".txt")

		with open(patterndatapath, "w+") as patternfile:
			patternfile.write(json.dumps(pattern["data"]))

		patternimagepath = os.path.join(self.PATTERNDIR, name+".png")
		img = draw(pattern["data"])
		img.save(patternimagepath)
		# To include the new one. Could be more efficient, but hey
		self.load_patterns()
Exemple #3
0
def main():
    image = sys.stdin.readline().strip()
    arr = []
    length = 25  # additional input
    width = 6  # additional input
    step = length * width
    result = ['2' for i in range(step)]
    for i in range(0, len(image), step):
        temp = image[i:i + step]
        arr.append(temp)

    for layer in arr:
        for idx, digit in enumerate(layer):
            if result[idx] == '2' and digit != '2':
                result[idx] = digit

    for i in range(0, len(result), length):
        for ch in result[i:i + length]:
            draw(ch == '1')
        print()
Exemple #4
0
def main():
    memory = read()
    intcode = IntCodeComputer(memory)
    white_tiles = set()
    curr = [0, 0]
    white_tiles.add(tuple(curr))
    turn_to_paint = True
    face = 0
    directions = ['U', 'R', 'D', 'L']
    min_x = 10e9
    min_y = 10e9
    max_x = -10e9
    max_y = -10e9
    while not intcode.completed:
        intcode.run()
        while not intcode.output.empty():
            value = intcode.output.get()
            if turn_to_paint:
                if value == 1:
                    white_tiles.add(tuple(curr))
                elif value == 0 and tuple(curr) in white_tiles:
                    white_tiles.remove(tuple(curr))
                min_x = min(min_x, curr[0])
                min_y = min(min_y, curr[1])
                max_x = max(max_x, curr[0])
                max_y = max(max_y, curr[1])
            else:
                if value == 1:
                    face = (face + 5) % 4
                elif value == 0:
                    face = (face + 3) % 4
                update(curr, directions[face])
            turn_to_paint = not turn_to_paint
        intcode.read(int(tuple(curr) in white_tiles))

    for j in range(max_y, min_y - 1, -1):
        for i in range(min_x, max_x + 1):
            draw((i, j) in white_tiles)
        print()
Exemple #5
0
def k_means(points, min_x, max_x, min_y, max_y, min_z, max_z):
	pos1 = utl.randomPosition(min_x, min_y, min_z, max_x, max_y, max_z)
	pos2 = utl.randomPosition(min_x, min_y, min_z, max_x, max_y, max_z)
	pos3 = utl.randomPosition(min_x, min_y, min_z, max_x, max_y, max_z)

	cluster1 = Cluster(pos1, 'r')
	cluster2 = Cluster(pos2, 'g')
	cluster3 = Cluster(pos3, 'b')

	changed = True

	while(changed):
		changed = False

		while(cluster1.isEmpty() or cluster2.isEmpty() or cluster3.isEmpty()):
			cluster1.clear()
			cluster2.clear()
			cluster3.clear()


			for point in points:
				cluster = utl.closerCluster3D(cluster1, cluster2, cluster3, point)
				cluster.addPoint(point)
			
			randomPosition(cluster1, min_x, max_x, min_y, max_y, min_z, max_z)
			randomPosition(cluster2, min_x, max_x, min_y, max_y, min_z, max_z)
			randomPosition(cluster3, min_x, max_x, min_y, max_y, min_z, max_z)

		utl.draw(cluster1, cluster2, cluster3)

		cluster1.centralize();
		cluster2.centralize();
		cluster3.centralize();

		utl.draw(cluster1, cluster2, cluster3)

		for point in points:
			cluster = utl.closerCluster3D(cluster1, cluster2, cluster3, point)
			print("after center")
			if(not cluster.hasPoint(point)):
				print("changed")
				changed = True
				cluster1.clear()
				cluster2.clear()
				cluster3.clear()
				break;


	print("cluster 1:")
	for point in cluster1.points:
		print("x: ", point.x, " y: ", point.y, " z: ", point.z)
	print("cluster 2:")
	for point in cluster2.points:
		print("x: ", point.x, " y: ", point.y, " z: ", point.z)
	print("cluster 3:")
	for point in cluster3.points:
		print("x: ", point.x, " y: ", point.y, " z: ", point.z)
	utl.draw(cluster1, cluster2, cluster3)
def pc_draw(field):
    try:
        symbol = 'o'
        size = len(field)

        while True:
            number = randrange(0, size)

            if "-" in field and field[number] == "x":
                # No need to execute: print("Position is already populated.")
                continue
            elif "-" in field and field[number] == "o":
                continue
            # Offensive and defensive strategy.
            elif "-oo" in field:
                number = field.index("-oo")
                break
            elif "o-o" in field:
                number = field.index("o-o") + 1
                break
            elif "oo-" in field:
                number = field.index("oo-") + 2
                break
            elif "-xx" in field:
                number = field.index("-xx")
                break
            elif "x-x" in field:
                number = field.index("x-x") + 1
                break
            elif "xx-" in field:
                number = field.index("xx-") + 2
                break
            elif "-o-" in field:
                number = field.index("-o-")
                break
            elif "-x-" in field:
                number = field.index("-x-")
                break
            else:
                break

        if "-" in field:
            field = draw(field, number, symbol)
        else:
            print("Field is full.")

    except ValueError:
        print("There is no field.")

    return field
Exemple #7
0
	def __init__(self, images, color, pos, collision_handler=None):
		"""Ctor"""
		Sprite.__init__(self, draw([SIZE, SIZE], images[0], color), color, pos)

		self.collision_handler = collision_handler

		self.alive = True
		self.frame_count = len(images)
		self.frame = 0
		self.vertical_speed = MOVE_DISTANCE
		self.horizontal_speed = 0
		self.__jumping = False

		r_images = []
		l_images = []
		self.images = {RIGHT : r_images, LEFT : l_images}
		self.collision_group = None

		# We must have left and right images
		for image in images:
			img = draw([SIZE, SIZE], image, color)
			r_images.append(img)
			l_images.append(pygame.transform.flip(img, 1, 0))
Exemple #8
0
    def draw(self, surface, camera):
        if not self.img or (self.player.score != self.rendered_score):
            self.img = font.render(str(self.player.score), True, (255, 255, 255))
            self.rendered_score = self.player.score

        draw(surface, self.img, Vector(20, 20), origin=Vector(0, 0))
Exemple #9
0
                print("FPS of the _video is {:5.4f}".format(
                    frames / (time.time() - start)))
                cv2.imshow("frame", frame)
                key = cv2.waitKey(1)
                if key & 0xFF == ord('q'):
                    break
                continue
            output[:, 1:5] = torch.clamp(output[:, 1:5], 0.0,
                                         float(input_dimension))

            im_dim = im_dim.repeat(output.size(0), 1) / input_dimension
            output[:, 1:5] *= im_dim

            list(
                map(
                    lambda x: draw(x, frame, classes[int(x.numpy()[-1])],
                                   colors[int(x.numpy()[-1])], True), output))
            key = cv2.waitKey(1)
            cv2.imshow(video_file, frame)
            key = cv2.waitKey(1)
            if key & 0xFF == ord('q'):
                break
            frames += 1
            print(time.time() - start)
            print("FPS of the video is {:5.2f}".format(frames /
                                                       (time.time() - start)))
        else:
            break
    capture.release()
    cv2.destroyAllWindows()

else:
        img = (255 *
               img_[i:i + 1, :, :, :].permute(0, 2, 3, 1)).long().squeeze(0)
        center_mask = center_mask_[i:i + 1, :, :, :].permute(0, 2, 3,
                                                             1).numpy()
        size_mask = size_mask_[i:i + 1, :, :, :].permute(0, 2, 3, 1).numpy()
        offset_mask = offset_mask_[i:i + 1, :, :, :].permute(0, 2, 3,
                                                             1).numpy()
        #centers = get_center_from_center_mask(center_mask)
        #centers = ce
        centers = centers_[i]
        print(centers_[0][:, 0])
        print(img.shape)
        print(center_mask.shape)
        print(offset_mask.shape)
        print(size_mask.shape)
        imag = draw(img[:, :, :], centers, offset_mask[0, :, :, :],
                    size_mask[0, :, :, :])
        fig, ax = plt.subplots(3, 3)
        ax[0, 0].imshow(center_mask[0, :, :, 0], cmap='gray')
        ax[0, 1].imshow(center_mask[0, :, :, 1], cmap='gray')
        ax[0, 2].imshow(center_mask[0, :, :, 2], cmap='gray')
        ax[1, 0].imshow(center_mask[0, :, :, 3], cmap='gray')
        ax[1, 1].imshow(center_mask[0, :, :, 4], cmap='gray')
        ax[1, 2].imshow(center_mask[0, :, :, 5], cmap='gray')
        ax[2, 0].imshow(imag[:, :, ::-1])  # [0, :, :, :])
        #ax[2, 1].imshow(img[0, :, :, :])
        ax[2, 1].imshow(size_mask[0, :, :, 0], cmap='gray')
        ax[2, 2].imshow(size_mask[0, :, :, 1], cmap='gray')

        #img = img.astype('uint8')

        #plt.imshow(img[:, :, 0], cmap='gray')
Exemple #11
0
 def draw(self, surface, camera):
     draw(surface, shark, self.pos, size=Vector(self.size, None),scale=Vector(self.dir, 1), angle=self.angle, camera=camera)
Exemple #12
0
from mouse import capture_line, enhanced_line
from util import normalize, draw
from patterns import PathPatternHandler


line = capture_line()

img = draw(line)
img.show()

norm = normalize(line)
eline = enhanced_line(norm)

#for coord in eline:
#    print(coord)

handler = PathPatternHandler()#ImagePatternHandler("patterns")

pattern = handler.input_to_pattern(line)

commands = [""]

SAVE = False
name = "b"
if SAVE:
	handler.save_pattern(name, pattern)
	raise RuntimeError("Pattern saved")

closest = handler.closest_pattern(pattern)

if closest is None:
Exemple #13
0
	def __init__(self, color, pos):
		"""Ctor"""
		Sprite.__init__(self, draw([SIZE, SIZE], spike, color), color, pos, True)
Exemple #14
0
	def __init__(self, color, pos):
		"""Ctor"""
		Sprite.__init__(self, draw([SIZE, SIZE], None, color), color, pos)
Exemple #15
0
    screen = transpose(screen_slice)

    # check if bird hit something
    if not first_run or cur_screen_pos > SPLASH_LENGTH:
        for y in range(bird_pos_y_int, bird_pos_y_int + 1):
            for x in range(bird_pos_x, bird_pos_x + 5):
                if screen[y][x] != ' ':
                    print 'Game Over! (hit pipe)'
                    game_over = True

    # draw bird
    if game_over:
        bird_anim_frame = 2
    elif cur_screen_pos % 5 == 0:
        bird_anim_frame = (bird_anim_frame + 1) % 2
    draw(screen, art.bird[bird_anim_frame], bird_pos_x, bird_pos_y_int)

    # display score
    cur_segment = max(
        0,
        (cur_screen_pos - lead_in) / (art.PIPE_WIDTH + PIPE_SPACING) + 1
    )
    if cur_segment != score:
        score = cur_segment
    score_text = art.score(score)
    if not first_run or cur_screen_pos > SPLASH_LENGTH:
        draw(screen, score_text, (SCREEN_WIDTH - len(score_text[0])) / 2, 2)

    if game_over:
        draw(screen, art.game_over,
             (SCREEN_WIDTH - len(art.game_over[0])) / 2, 20)
Exemple #16
0
    for a in world:
        if isinstance(a, Drawable) and a.lighting:
            a.draw(screen, camera)

    if game_running:
        # light drawing
        if player.light: lightIntensity += dt * 2
        else: lightIntensity -= dt * 2
        lightIntensity = min(1, max(0, lightIntensity))

        f = 30 + lightIntensity * 90
        lightSurface.fill((f, f, f))

        lightPos = player.getLightPosition()
        size = 5 if player.light else 3
        draw(lightSurface, resources.gradient, lightPos, size=Vector(size, size), camera=camera)
        screen.blit(lightSurface, (0, 0), special_flags=pygame.BLEND_MULT)
        if player.light:
            draw(screen, resources.gradient, lightPos, size=Vector(0.5, 0.5), camera=camera)

        if not player.alive:
            game_running = False
            tutorial = 4
            world = []

    for a in world:
        if isinstance(a, Drawable) and not a.lighting:
            a.draw(screen, camera)

    if not game_running:
        if tutorial <= 3:
Exemple #17
0
                 1000 * (t1 - t0)), (20, int(frame_height - 90)),
             cv2.FONT_HERSHEY_SIMPLEX, .5, (100, 255, 255))
         r = rot.from_rotvec(rvec_.T).as_euler('xyz', degrees=True)
         cv2.putText(
             img,
             'Rotation(Euler angles): X: {:0.2f} Y: {:0.2f} Z: {:0.2f}'.
             format(r[0][0], r[0][1],
                    r[0][2]), (20, int(frame_height) - 50),
             cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255))
         cv2.putText(
             img,
             'Translation(mm): X: {:0.2f} Y: {:0.2f} Z: {:0.2f}'.format(
                 T[0], T[1], T[2]), (20, int(frame_height) - 10),
             cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255))
     imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
     img = util.draw(img, corners2, imgpts)
     mean_error = 0
     for i in range(len(objpoints)):
         imgpoints2, _ = cv2.projectPoints(objpoints[i], rvec, tvec, mtx,
                                           dist)
         error = cv2.norm(imgpoints[i], imgpoints2,
                          cv2.NORM_L2) / len(imgpoints2)
         mean_error += error
     cv2.putText(
         img, "reprojection error: {}".format(mean_error / len(objpoints)),
         (20, int(frame_height - 250)), cv2.FONT_HERSHEY_SIMPLEX, .5,
         (100, 255, 255))
     if RESULT_PATH is not None:
         name = RESULT_PATH + os.path.basename(fname)
         cv2.imwrite(name, img)
 cv2.imshow('img', img)
Exemple #18
0
 def draw(self, surface, camera):
     draw(surface, bubble, self.pos, size=Vector(self.size, None), camera=camera, alpha=1-0.5*self.lifetime)