def __init__(self): self._init_pygame() self.screen = pygame.display.set_mode(SCREEN_RES) self.clock = pygame.time.Clock() self.font = pygame.font.Font(None, 64) self.message = "" self.ball = Ball( Vector2(SCREEN_RES) / 2, load_sprite("ball"), random_velocity(15, 30)) self.camera = cv2.VideoCapture(0) self.camera.set(3, SCREEN_RES[0]) self.camera.set(4, SCREEN_RES[1]) self.frame = None self.finger_coords = []
def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() self.camera.release() cv2.destroyAllWindows() sys.exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self.ball = Ball( Vector2(SCREEN_RES) / 2, load_sprite("ball"), random_velocity(15, 30), ) return
def _draw_scene(robot: Robot, ball: Ball, obstacles: List[MovingObstacle], ball_predicted_positions, barriers_predicted_positions): screen = numpy.full((constants.WINDOW_HEIGHT, constants.WINDOW_WIDTH, 3), Color.BLACK, dtype=numpy.uint8) robot.draw(screen) for obstacle in obstacles: obstacle.draw(screen) ball.draw(screen) screen_picture = copy.deepcopy(screen) _draw_edges(screen, ball_predicted_positions, Color.YELLOW) _draw_edges(screen, barriers_predicted_positions, Color.GREEN) return cv2.cvtColor(screen, cv2.COLOR_BGR2RGB), screen_picture
def __get_model(self, name, k, n) -> BenchmarkModel: B = [1] * k return { 'ball': Ball(n=n, B=B), 'cube': Cube(n=n, B=B), 'simplex': Simplex(n=n, B=B) }[name]
def update_balls(balls): updated_balls = [] # Check for ball collisions active_balls = [ball for ball in balls if ball.vel] if len(active_balls) > 1: x_points = [] for ball in active_balls: x_points.append((ball.pos.x - ball.size, True, ball)) x_points.append((ball.pos.x + ball.size, False, ball)) x_points.sort(key=lambda t: (t[0], t[1])) entered = 0 potential_collisions = set() for x_point in x_points: _, entered, ball = x_point if entered: potential_collisions.add(ball) else: potential_collisions.remove(ball) for other in potential_collisions: if (ball.pos - other.pos).mag <= ball.size + other.size: Ball.separate_balls(ball, other) Ball.change_velocities(ball, other) # Wall collisions, update position, apply friction for ball in balls: ball.size = BALL_SIZE if ball.vel: # wall collision checks if (ball.pos.x <= 0 and ball.vel.x < 0) or (ball.pos.x >= WIDTH and ball.vel.x > 0): ball.vel.x *= -ELASTICITY ball.vel.y *= ELASTICITY if (ball.pos.y <= 0 and ball.vel.y < 0) or (ball.pos.y >= HEIGHT and ball.vel.y > 0): ball.vel.y *= ELASTICITY ball.vel.y *= -ELASTICITY # apply friction ball.vel -= ball.vel.norm * FRICTION * ball.size # let balls move themselves according to velocity and acceleration vectors ball.update(FRAME_RATE) # remove ball if it's all the way off screen if (ball.pos.x < -50 or ball.pos.x > WIDTH + 50 or ball.pos.y < -50 or ball.pos.y > HEIGHT + 50): continue updated_balls.append(ball) return updated_balls
def test_no_obs2(): robot = Robot(constants.x_start, constants.y_start, constants.theta_start) ball = Ball(constants.WINDOW_CORNERS[2] - 1, constants.WINDOW_CORNERS[3] - 1, 0, 0) result = main.run_simulation(robot, ball, [], simulation_delay=1000, enable_detection=False) assert result
def _main(): ball = Ball.create_randomized() obstacles = [] # _generate_obstacles(cnt=constants.OBSTACLES_COUNT) robots = _generate_robots() run_simulation(robots, ball, obstacles, enable_detection=False, drawable_obs_avoidance=constants.DRAWABLE_OBS_AVOIDANCE)
def test_no_obs(): robot = Robot(1, -2, utils.to_radians(-60)) ball = Ball(0, 0, 0, 0) result = main.run_simulation(robot, ball, [], simulation_delay=1000, enable_detection=False, drawable_obs_avoidance=True) assert result
def test_vshyvost(): for seed in seeds: print(seed) constants.RANDOM_SEED = seed ball = Ball.create_randomized() obstacles = main._generate_obstacles(cnt=constants.OBSTACLES_COUNT) robot = Robot(constants.x_start, constants.y_start, constants.theta_start) result = main.run_simulation(robot, ball, obstacles, enable_detection=True) assert result
def test_static_obs(): robot = Robot(constants.x_start, constants.y_start, constants.theta_start) ball = Ball(constants.WINDOW_CORNERS[2] - 1, constants.WINDOW_CORNERS[3] - 1, 0, 0) obstacles = [ MovingObstacle(ball.x - 0.5, ball.y - 0.5, 0, 0) # MovingObstacle.create_randomized(), ] result = main.run_simulation(robot, ball, obstacles, simulation_delay=1000, enable_detection=True, drawable_obs_avoidance=True) assert result
def test_static_hist(): # robot = Robot(constants.x_start, constants.y_start + 1, 1.75) robot = Robot(constants.x_start, constants.y_start, 1.75) ball = Ball(constants.WINDOW_CORNERS[2] - 1, constants.WINDOW_CORNERS[3] - 1, 0, 0) obstacles = [ # MovingObstacle(constants.x_start + 0.8, constants.y_start + 1.8, 0, 0), MovingObstacle(constants.x_start + 0.4, constants.y_start + 0.4, 0, 0) # MovingObstacle.create_randomized(), ] result = main.run_simulation(robot, ball, obstacles, simulation_delay=1000, enable_detection=True, drawable_obs_avoidance=True) assert result
from models import Ball, Paddle, Brick pygame.init() screen = pygame.display.set_mode((Screen.WIDTH, Screen.HEIGHT)) pygame.display.set_caption('2D Brick Breaker') pygame.mixer.music.load('resources/music/background.wav') pygame.mixer.music.play(-1) fx1 = pygame.mixer.Sound('resources/fx/fx1.wav') fx2 = pygame.mixer.Sound('resources/fx/fx2.wav') fx3 = pygame.mixer.Sound('resources/fx/fx3.wav') fxs = [fx1, fx2, fx3] clock = pygame.time.Clock() background_image = pygame.image.load('resources/img/background.jpg') ball = Ball(Screen.WIDTH / 2 - 100, Screen.HEIGHT - 250, 15, Color.WHITE, [0, 5]) paddle = Paddle(Screen.WIDTH / 2 - 100, Screen.HEIGHT - 30, 200, 20, Color.PINK, None) bricks = [ Brick(i * 160 + 5, j * 40 + 5, 150, 30, Color.BLACK) for i in range(5) for j in range(5) ] running = True def draw_window(): screen.blit(background_image, (0, 0)) ball.draw(screen) paddle.draw(screen) for brick in bricks:
continue updated_balls.append(ball) return updated_balls while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: mouse_down = True mouse_pos = Vector(*event.pos) balls.append( Ball(mouse_pos, start_vel=None, start_acc=GRAVITY, size=BALL_SIZE)) if event.type == pygame.MOUSEBUTTONUP: if not balls: continue mouse_pos = Vector(*event.pos) ball = balls[-1] ball.vel = (ball.pos - mouse_pos) * INITIAL_VELOCITY_SCALAR mouse_down = False if event.type == pygame.MOUSEMOTION: mouse_pos = Vector(*event.pos) if event.type == pygame.KEYDOWN: if event.key in {pygame.K_ESCAPE, pygame.K_q}: pygame.quit() quit() if event.key == pygame.K_r: # reset
class FingPong: def __init__(self): self._init_pygame() self.screen = pygame.display.set_mode(SCREEN_RES) self.clock = pygame.time.Clock() self.font = pygame.font.Font(None, 64) self.message = "" self.ball = Ball( Vector2(SCREEN_RES) / 2, load_sprite("ball"), random_velocity(15, 30)) self.camera = cv2.VideoCapture(0) self.camera.set(3, SCREEN_RES[0]) self.camera.set(4, SCREEN_RES[1]) self.frame = None self.finger_coords = [] def main_loop(self): while True: self._handle_input() self._update_frame() self._process_game_logic() self._draw() return def _init_pygame(self): pygame.init() pygame.display.set_caption("Fing Pong") return def _update_frame(self): img = get_webcam_img(self.camera) self.finger_coords = process_hands(img) for finger_pair in self.finger_coords: # no. of pairs = no. of hands detected for fingertip_coords in finger_pair: cv2.circle(img, fingertip_coords, 5, (255, 0, 255), cv2.FILLED) cv2.line(img, finger_pair[0], finger_pair[1], (222, 22, 222), 2) self.frame = img return def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() self.camera.release() cv2.destroyAllWindows() sys.exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self.ball = Ball( Vector2(SCREEN_RES) / 2, load_sprite("ball"), random_velocity(15, 30), ) return def _process_game_logic(self): self.ball.move() self.ball.handle_wall_collision() self.ball.handle_paddle_collision(self.finger_coords) self.message = f"{self.ball.bounces} bounces" if self.ball.is_oob_horizontal(): self.message = ( f"You lost! Score: {self.ball.bounces} bounces. SPACE to restart." ) return def _draw(self): img_fmtd = cv2_img_to_surface(self.frame) self.screen.blit(img_fmtd, (0, 0)) self.ball.draw(self.screen) if self.message: print_text_bottom(self.screen, self.message, self.font) pygame.display.flip() self.clock.tick(60) return
def read_ball_data(): new_ball = Ball() new_ball.color = input('Informe a cor da bola: ') new_ball.circumference = float(input('Informe a circunferĂȘncia da bola: ')) new_ball.brand = input('Informe a marca da bola: ') return new_ball
def main(): start_time = time.time() dt = 0.1 ball = Ball.create_randomized() obstacles = _generate_obstacles(cnt=constants.OBSTACLES_COUNT) robot = Robot(constants.x_start, constants.y_start, constants.theta_start) ball_predicted_positions = [] barriers_predicted_positions = [] fps = 30 width = constants.WINDOW_WIDTH height = constants.WINDOW_HEIGHT out = cv2.VideoWriter('result.mov', cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height)) while True: screen, screen_picture = _draw_scene(robot, ball, obstacles, ball_predicted_positions, barriers_predicted_positions) cv2.imshow('robot football', screen) out.write(screen) ball_predicted_positions, barriers_predicted_positions = obstacle_detection.forward( screen_picture, [(Color.RED, 1), (Color.LIGHTBLUE, constants.OBSTACLES_COUNT)]) ball_predicted_positions = cast_detector_coordinates( ball_predicted_positions) barriers_predicted_positions = cast_detector_coordinates( barriers_predicted_positions) # Planning # # Call obstacle avoidance algorithm and move to returned dot. # # At the moment it has the same call rate as simulation update rate: # it is called each quantum of time as the simulation updates. # # If obstacle_avoidance() call rate will be different from simulation update rate # then move_to_dot_again() should be called instead of obstacle_avoidance() and move_to_dot() # in this 'while' cycle if time of calling obstacle_avoidance() is not reached yet. target_x, target_y = obstacle_avoidance(robot.get_pos(), ball_predicted_positions, barriers_predicted_positions) vl, vr, ro, alpha, beta = move_to_dot(target_x, target_y, robot.x, robot.y, ball_predicted_positions[0][0], ball_predicted_positions[0][1], robot.angle) # Actually now move robot based on chosen vl and vr ball.move(dt) robot.set_velocity(vl, vr) robot.move(dt) for player in obstacles: player.move(dt) dist_to_obstacle = robot.get_closest_dist_to_obstacle(obstacles) dist_to_target = robot.get_dist_to_target(ball) if dist_to_obstacle < 0.001 or dist_to_target < MovingObstacle.RADIUS + Robot.RADIUS: if dist_to_obstacle < 0.001: print('Crash!') print(f'Result: {time.time() - start_time} sec') while cv2.getWindowProperty('robot football', cv2.WND_PROP_VISIBLE) == 1: out.release() cv2.waitKey(int(dt * 10)) break cv2.waitKey(int(dt * 10)) if cv2.getWindowProperty('robot football', cv2.WND_PROP_VISIBLE) < 1: break out.release() cv2.destroyAllWindows()
MAP_ELEMENT_TEXTURES['water'].set_alpha(170) powerMeter = pygame.image.load(os.path.join('img', 'power.png')) powerMeter = pygame.transform.scale(powerMeter, (150,150)) # SET ICON pygame.display.set_icon(icon) # GLOBAL VARIABLES angle = 0 rollVel = 0 strokes = 0 par = 0 level = 1 coins = 0 shootPos = () ball = Ball(0, 0, (255,255,255)) line = None power = 0 level_map = Map([]) put = False shoot = False # LOAD MUSIC if SOUND: wrong = pygame.mixer.Sound(os.path.join('sounds', 'wrong12.wav')) puttSound = pygame.mixer.Sound(os.path.join('sounds', 'putt.wav')) inHole = pygame.mixer.Sound(os.path.join('sounds', 'inHole.wav')) song = pygame.mixer.music.load(os.path.join('sounds', 'music.mp3')) splash = pygame.mixer.Sound(os.path.join('sounds', 'splash.wav')) pygame.mixer.music.play(-1)