def __init__(self, width=400, height=400): self.width, self.height = width, height self.target = TargetArea() self.canon = Canon() self.missiles = [] self.obstacles = [] self.holes = [] self.trajectoryDict = TrajectoryDict() self.showTrajectories = False self.interaction = False self.nt = 1 self.dt = 1.
def __init__(self): self.change_scene('scene') print(self.N) try: self.canon = Canon() self.canon.setup_preview() except Exception as e: print(e) print('Failed to connect to camera!') self.canon = None self.alpha = 0.70 self.frame_rate = 12 self.check_before_delete = True
def initialize(self, world): for i in range(-5, 6): world.addObstacle( Circle(r=15, pos=[ world.width / 2 + i * world.width / 13, 0.36 * world.height ])) world.addObstacle( Circle(r=15, pos=[ world.width / 2 + i * world.width / 13, 0.2 * world.height ])) for i in range(-5, 5): world.addObstacle( Circle(r=15, pos=[ world.width / 2 + world.width / 39 + i * world.width / 13, 0.28 * world.height ])) world.addObstacle( Circle(r=15, pos=[ world.width / 2 + world.width / 39 + i * world.width / 13, 0.44 * world.height ])) world.canon = Canon(r=75, pos=[world.width / 2, world.height], theta=-np.pi / 2) world.target = TargetArea(pos=(world.width / 2, world.height * 0.05), width=world.width * 0.05, height=world.height * 0.05)
def initialize(self, world): world.addObstacle( Circle(world.height * 0.25, (world.width * 0.5, world.height * 0.5), 1.0)) world.canon = Canon(r=75, pos=[world.width / 2, world.height], theta=-np.pi / 2) world.canon.shotQuantity = 6 world.showTrajectories = True
def initialize(self, world): world.addObstacle( Rectangle(world.width * 0.625, world.height * 0.33, world.width * 0.75, 50, 0)) world.addObstacle( Rectangle(world.width * 0.375, world.height * 0.66, world.width * 0.75, 50, 0)) world.target = TargetArea(pos=(world.width * 0.85, world.height * 0.15), width=world.width * 0.2, height=world.height * 0.2) world.canon = Canon(r=75, pos=[world.width * 0.5, world.height], theta=-np.pi / 2)
def initialize(self, world): world.addObstacle( Circle(r=150, pos=[world.width / 2, world.height / 2])) world.addObstacle( Circle(r=world.height, pos=[-world.height * np.sqrt(3) / 2, world.height / 2])) world.addObstacle( Circle(r=world.height, pos=[ world.width + world.height * np.sqrt(3) / 2, world.height / 2 ])) world.canon = Canon(r=75, pos=[world.width / 2, world.height], theta=-np.pi / 2) world.target = TargetArea(pos=(world.width / 2, world.height * 0.21), width=world.height * 0.04, height=world.height * 0.04)
def initialize(self, world): world.addObstacle( Line(world.width * 0.75, world.height / 2, world.width * 0.3, np.pi * 0.5)) world.addObstacle( Line(world.width * 0.6, world.height / 4, world.width * 0.3, 0)) world.addObstacle( Rectangle(world.width * 0.2, world.height * 0.42, world.width * 0.45, 30, 0)) world.addObstacle( Rectangle(world.width * 0.2, world.height * 0.58, world.width * 0.5, 35, 0)) world.addObstacle( Circle(r=20, pos=[world.width * 0.43, world.height * 0.42])) world.addObstacle( Circle(r=55, pos=[world.width * 0.46, world.height * 0.58])) world.canon = Canon(r=75, pos=[world.width / 2, world.height], theta=-np.pi / 2) world.target = TargetArea(pos=(world.width * 0.35, world.height * 0.5), width=world.height * 0.1, height=world.height * 0.1)
class StopMotion: def __init__(self): self.change_scene('scene') print(self.N) try: self.canon = Canon() self.canon.setup_preview() except Exception as e: print(e) print('Failed to connect to camera!') self.canon = None self.alpha = 0.70 self.frame_rate = 12 self.check_before_delete = True def start_preview(self): self.fig, _ = plt.subplots() self.fig.canvas.mpl_connect('key_press_event', self.get_command) self.preview() plt.show() self.canon.exit() def print_header(self): print(""" Use the keyboard. Type a command. q - quit p - preview f - tave a frame v - view previous photo d - delete previous photo. Go to terminal to confirm r - render the photos into a video n - create a new scene. Go to terminal to enter name. Camera:\t{} Next image:\t{} """.format('Connected' if self.canon else 'Failed', self.get_image_name())) def get_image_number(self): files = glob.glob(self.scene + '/*jpg') if files: self.N = max(int(f.strip('.jpg')[-4:]) for f in files) + 1 else: self.N = 0 def get_image_name(self, scene=None, N=None): if scene is None: scene = self.scene if N is None: N = self.N return '{}/{:04d}.jpg'.format(scene, N) def get_image(self, scene, N): image_name = self.get_image_name(scene=scene, N=N) if os.path.isfile(image_name): return Image.open(image_name) else: return None def save_frame(self): if self.canon is None: print('Cannot save frame. Camera not connected.') return target = self.get_image_name() self.canon.capture_image(target) self.N += 1 def delete_frame(self): prev_image_name = self.get_image_name(N=self.N-1) if os.path.isfile(prev_image_name): if self.check_before_delete: raw = input('Are you sure you want to delete {}? [y/n]\n'.format(prev_image_name)) if raw == "" or raw.lower()[0] != 'y': return os.remove(prev_image_name) self.N -= 1 print("Deleted {}".format(prev_image_name)) else: print('Could not find {}'.format(prev_image_name)) def view_prev_frame(self): prev_image_name = self.get_image_name(self.scene, self.N-1) if os.path.isfile(prev_image_name): print('Displaying {}'.format(prev_image_name)) Image.open(prev_image_name).show() else: print('Could not load {}'.format(prev_image_name)) def get_transparency_preview(self): curr_img = self.canon.get_preview() prev_img = self.get_image(self.scene, self.N-1) if prev_img is None: preview = curr_img else: prev_img = np.asarray(prev_img.resize((curr_img.shape[1], curr_img.shape[0]))) preview = (curr_img * self.alpha + prev_img * (1. - self.alpha)).astype(np.uint8) return preview def preview(self): if self.canon is None: print('Cannot preview. Camera not connected.') plt.imshow(np.zeros([540,960,3])) # show a black screen else: plt.imshow(self.get_transparency_preview()) self.fig.canvas.draw() def change_alpha(self, key): self.alpha += 0.05 if key == 'up' else -0.05 self.alpha = np.clip(self.alpha, 0., 1.) print('Alpha: {}'.format(self.alpha)) def change_scene(self, new_scene_name=None): if new_scene_name is None: new_scene_name = input('Enter a scene name: ') if new_scene_name == '': return if os.path.isdir(new_scene_name): print('Changing scene to {}'.format(new_scene_name)) self.scene = new_scene_name self.get_image_number() elif os.path.isfile(new_scene_name): print('{} already exists as a file'.format(new_scene_name)) return else: os.mkdir(new_scene_name) print('Created new scene, {}'.format(new_scene_name)) self.scene = new_scene_name self.N = 0 def render(self): out_filename = '{}/out.mp4'.format(self.scene) if os.path.isfile(out_filename): os.remove(out_filename) command = ['ffmpeg', '-i', '{}/%04d.jpg'.format(self.scene), '-c:v', 'libx264', '-vf', 'fps={},format=yuv420p'.format(self.frame_rate), out_filename] subprocess.Popen(command) def get_command(self, event): self.print_header() sys.stdout.flush() if event.key == 'p': pass elif event.key == 'f': self.save_frame() elif event.key == 'v': self.view_prev_frame() return # we don't want to refresh preview elif event.key == 'd': self.delete_frame() elif event.key == 'r': self.render() # we don't want to refresh preview elif event.key == 'up' or event.key == 'down': self.change_alpha(event.key) elif event.key == 'n': self.change_scene() else: return self.preview() def loop(self): while True: self.print_header() self.get_command()
def _checkCollision(self, paddleobj, ballobj, cannonobj): if (self._x + self._xvel >= paddleobj._x and paddleobj._y <= self._y < paddleobj._y + paddleobj._ylength): self._x = paddleobj._x - 1 - self._xvel # print(self._type,self._x,self._y) if (self._type == "E"): paddleobj.powerups[self._type].append(POWERUPTIME) paddleobj._ylength += EXPANDSIZE elif (self._type == "S"): paddleobj.powerups[self._type].append(POWERUPTIME) if (paddleobj._ylength != 3): paddleobj._ylength -= SHRINKSIZE elif (self._type == "M"): newballs = [] for ball in ballobj: nball = Ball(ball._x, ball._y, ball._xlength, ball._ylength, -1 * ball._xvel, -1 * ball._yvel) nball.isCollidedWithPaddle = False newballs.append(nball) for i in newballs: ballobj.append(i) paddleobj.powerups[self._type].append(-1) elif (self._type == "F"): paddleobj.powerups[self._type].append(POWERUPTIME) for ball in ballobj: ball._xvel = ball._xvel + self.ballvel( ball._xvel) * INCREASEBALLXSPEED ball._yvel = ball._yvel + self.ballvel( ball._yvel) * INCREASEBALLYSPEED elif (self._type == "T"): paddleobj.powerups[self._type].append(POWERUPTIME) for ball in ballobj: ball.isThrough = True elif (self._type == "G"): paddleobj.powerups[self._type].append(POWERUPTIME) elif (self._type == "B"): paddleobj.powerups[self._type].append(40) cannonobj.append( Canon(paddleobj._x - 1, paddleobj._y, 1, 1, 0, 0, 0)) cannonobj.append( Canon(paddleobj._x - 1, paddleobj._y + paddleobj._ylength - 1, 1, 1, 0, 0, 1)) elif (self._type == "@"): rIndex = [] for i in ballobj: rIndex.append(i) for i in rIndex: ballobj.remove(i) elif (self._type == "A"): paddleobj.powerups[self._type].append(POWERUPTIME) for ball in ballobj: ball.isFire = True self.isCollided = True if (self._x + self._xvel >= config.FRAMEHEIGHT): self._x = 0 self.isCollided = True elif (self._x + self._xvel <= 0): self._x = 0 - self._xvel self._xvel = -1 * self._xvel if (self._y + self._yvel >= config.FRAMEWIDTH): self._y = config.FRAMEWIDTH - self._yvel - 1 self._yvel = -1 * self._yvel elif (self._y + self._yvel <= 0): self._y = 0 - self._yvel self._yvel = -1 * self._yvel
class World(object): def __init__(self, width=400, height=400): self.width, self.height = width, height self.target = TargetArea() self.canon = Canon() self.missiles = [] self.obstacles = [] self.holes = [] self.trajectoryDict = TrajectoryDict() self.showTrajectories = False self.interaction = False self.nt = 1 self.dt = 1. def addMissile(self): self.missiles += self.canon.getMissile() self.adjust() def addObstacle(self, obstacle): self.obstacles.append(obstacle) def addHole(self, hole): self.holes.append(hole) def adjust(self): if len(self.missiles) == 0: return vmax = np.max([m.vabs for m in self.missiles]) self.nt = 1 * int(np.ceil(vmax)) self.dt = 1. / self.nt def move(self, winCallback, loseCallback): self.adjust() self.trajectoryDict.appendTrajectory(self.missiles) for it in range(self.nt): for m in self.missiles: if (m.x + m.vx * self.dt >= self.width - m.r or m.x + m.vx * self.dt <= m.r): m.vx = -m.vx elif (m.y + m.vy * self.dt <= m.r or m.y + m.vy * self.dt >= self.height - m.r): m.vy = -m.vy for o in self.obstacles: o.reflectMissile(m, self.dt) for h in self.holes: if h.catch(m): loseCallback() if self.target.catch(m): winCallback() if self.interaction: for n in self.missiles: if not n is m: n.reflectMissile(m, self.dt) m.x, m.y = m.x + m.vx * self.dt, m.y + m.vy * self.dt def display(self, screen): if self.showTrajectories == True: self.trajectoryDict.display(screen) self.target.display(screen) for h in self.holes: h.display(screen) for o in self.obstacles: o.display(screen) for m in self.missiles: m.display(screen) self.canon.display(screen)
def initialize(self, world): world.canon = Canon(r=75, pos=[world.width / 2, world.height], theta=-np.pi / 2) world.canon.shotQuantity = 6 world.showTrajectories = True
def fire_canon(ai_settings,screen,ship,bullets): # Limit number of shots fired to the number declared in the settings file if len(bullets) < ai_settings.nr_bullets: bullet = Canon(ai_settings,screen,ship) bullets.add(bullet)