def __init__(self, layer="Character"): Drawable.__init__(self, layer) Updatable.__init__(self) self.rect = pygame.Rect(0, 0, 64, 64) self.sprites = {0: loadImage("no_image.bmp")} #TODO Rename this. >.-.<
def main(): frame_duration = 1.0/60.0 for level in LEVELS: load_level(level) while not Player.main.at_exit(): frame_start_time = time.time() key = Drawable._window.checkKey() if key in KEYMAP: eval(KEYMAP[key]) Event.update() if not Config.hidden_flag: if Gold.all_taken(): HiddenLadder.showAll() Player.main.redraw() for baddie in Baddie.baddies: baddie.redraw() Config.hidden_flag = True # baddies should probably move here frame_time = time.time() - frame_start_time if frame_time < frame_duration: time.sleep(frame_duration - frame_time) Drawable.won()
def update(self, dt): Drawable.handle_deletion(self.entities) if self.chest: self.chest.update(dt) offset = 0 if self.spawn_exit: offset = self.game.dungeon_offset / self.game.TILE_WIDTH for entity in self.entities: entity.update(dt) super().update(dt) if self.spawn_exit and self.game.world.state_dt > 4 and self.game.world.progression == self.game.world.FREE_ROAM and abs( self.game.world.character.tx - offset - self.tx) < 0.6 and abs(self.game.world.character.ty - offset - self.ty - 0.5) < 0.6: if len(self.game.world.textbox.text) == 0 or self.game.keys[key.E]: self.game.world.textbox.text = ["Press E to exit the crevice."] self.game.world.textbox.faces = [None] if self.game.keys[key.E]: self.game.world.move_to = self.game.world.OVERWORLD
def __init__(self): w = config.grid_offset * config.map_size[0] + config.road_size * 2 h = config.grid_offset * config.map_size[1] + config.road_size * 2 Drawable.__init__(self, w, h) Eventable.__init__(self) self.dirty = 2 self.updates = False self.child_updates = False self.hud_mode = HUD_MODE.build self.last_playback_mode = None self.playback_mode = PLAYBACK_MODE.pause self.build_mode = BUILD_MODE.residential self.incident_spawn_timer = None self.incident_spawn_timeout_length = 10 self.incident_generator = IncidentGenerator() self.vp = None self.children = [] self.incidents = [] self.watchers = { "hud_mode_change": [], "playback_mode_change": [], "build_mode_change": [] }
def __create_items(self): self.ground = Drawable('ground.png', WORLD) self.ground.position.bottom = HEIGHT self.block1 = Drawable('block1.png', WORLD) self.block1.position.x = WIDTH + 10 self.block1.position.bottom = RULER
def update(self, level): Drawable.update(self, level) ticks = pygame.time.get_ticks() if self.isdying is True: self.position = self.position.move(0, 5) if self.position.y > level.camera.rect.height: level.objects.remove(self) else: if self.isattacking: if level.mario.position.x < self.position.x: self.direction.x = -1 else: self.direction.x = 1 lastposition = self.position self.position = self.position.move(self.direction.x * self.speed, self.direction.y) if self.ckeckblockscollision(level) is True: if self.isattacking is True: self.position = lastposition else: self.direction.x *= -1 if self.position.left <= 0 or self.position.right >= len( level.tilemap[0]) * 16: self.direction.x *= -1 self.apply_physics(level, ticks)
class Tab(object): path_to_tabs = '../resrc/tabs/' def __init__(self, wrapper, background_image_path=None): self.path_to_images = Tab.path_to_tabs + ( self.__class__.__name__.lower() if self.__class__ != Tab else '') + '/' if background_image_path is None: background_image_path = self.path_to_images + 'background.gif' self.wrapper = wrapper self.background = Drawable(background_image_path) self.objects = [] def add_drawable(self, obj): # type: (Drawable) -> None obj.set_position(obj.position + obj.get_size() // 2) self.objects.append(obj) def start(self): pass def get_size(self): # type: () -> Vector return self.background.get_size() def update(self): for obj in self.objects: obj.update() def draw(self): self.background.draw() for obj in self.objects: obj.draw()
def __init__(self, graph = nx.Graph()): Drawable.__init__(self) Named.__init__(self) self.style().set_target_type('fill') self.add_name('_line_') self.__graph = graph self.__generate_paths() return
def __init__(self, graph=nx.Graph(), options=[]): Drawable.__init__(self, options) Named.__init__(self) self.style().set_target_type("fill") self.add_name("_line_") self.__graph = graph self.__generate_paths() return
def __init__(self, text="", position=(0, 0)): Drawable.__init__(self) Translatable.__init__(self, position) Named.__init__(self) self.__text = text self.__font_size = 1 self.__scaled_direction = Vector(1, 0) return
def __init__(self, graph=nx.Graph(), options=[]): Drawable.__init__(self, options) Named.__init__(self) self.style().set_target_type('fill') self.add_name('_line_') self.__graph = graph self.__generate_paths() return
def __init__(self, text = "", position = (0, 0)): Drawable.__init__(self) Translatable.__init__(self, position) Named.__init__(self) self.__text = text self.__font_size = 1 self.__scaled_direction = Vector(1, 0) return
def __init__(self, filename=None, buffers=None): Drawable.__init__(self) self.empty() if filename: self.fromFile(filename) elif buffers: self.v, self.n, self.t = buffers
def update_graphics(self, graphics: PoolGraphics): # Fill in background self.screen.screen.fill(Drawable.BILLIARD_GREEN) # Draw the separately pockets (because they don't actually exist) for pt in graphics.pockets: x = pt.x * self.screen.ppm y = pt.y * self.screen.ppm position = [ x + self.screen.offset_x, self.screen.screen_height - y - self.screen.offset_y ] pygame.draw.circle(self.screen.screen, Drawable.BLACK, position, Constants.POCKET_RADIUS * self.screen.ppm) # Draw drawables for drawable in graphics.drawables: drawable.draw(self.screen) # Draw the pocketed balls at the bottom of the screen for ball in graphics.pocketed_balls: r = Constants.BALL_RADIUS * self.screen.ppm h = self.screen.screen.get_height() y = h - (h - self.screen.screen_height) // 2 x = (ball.number + 0.5) / 16 * self.screen.screen_width Drawable.draw_billiard_ball_helper( [x, y], r, self.screen, ball.color, Drawable.WHITE if ball.number != Constants.CUE_BALL else Drawable.BLACK, ball.number, 0) for ball in graphics.unpocketed_balls: r = Constants.BALL_RADIUS * self.screen.ppm x = ball.position[0] * self.screen.ppm y = ball.position[1] * self.screen.ppm Drawable.draw_billiard_ball_helper( [x, y], r, self.screen, ball.color, Drawable.WHITE if ball.number != Constants.CUE_BALL else Drawable.BLACK, ball.number, ball.angle) # Draw which players turn it is (blue bar if player 1, red bar if player 2) if graphics.board.get_state() == PoolState.ONGOING: width = self.screen.screen.get_width() // 2 h = self.screen.screen.get_height() height = h // 96 top = h - height if graphics.board.turn == PoolPlayer.PLAYER1: left = 0 color = Drawable.BLUE else: left = width color = Drawable.RED pygame.draw.rect(self.screen.screen, color, [left, top, width, height]) # Flip the screen and try to keep at the target FPS pygame.display.flip() self.clock.tick(Constants.TICK_RATE)
def __init__( self , filename = None , buffers = None ) : Drawable.__init__( self ) self.empty() if filename : self.fromFile( filename ) elif buffers : self.v , self.n , self.t = buffers
def __init__(self, wrapper, background_image_path=None): self.path_to_images = Tab.path_to_tabs + ( self.__class__.__name__.lower() if self.__class__ != Tab else '') + '/' if background_image_path is None: background_image_path = self.path_to_images + 'background.gif' self.wrapper = wrapper self.background = Drawable(background_image_path) self.objects = []
def __init__(self, x, y, width=1, height=1, color="#5C5C5C"): Drawable.__init__(self, width * config.block_size, height * config.block_size) self.x = x self.y = y self.offset_x = self.__calculate_offset_coord(x) self.offset_y = self.__calculate_offset_coord(y) self.color = pygame.Color(color)
def __init__( self , files ) : Drawable.__init__( self ) self.meshes = [] for path in files : self.meshes.append( Mesh(path) ) self.colors = [ (.68,.16,.19) , (.68,.16,.19) , (.74,.73,.21) , (.15,.55,.27) , (.15,.55,.27) , (.14,.15,.12) ] self.sparks = Sparks()
def __init__(self): Drawable.__init__(self, *config.window_size) Eventable.__init__(self) self.children = [ ModeSwitchPanel(), PlaybackControlPanel(), EditorPanel() ] self.dirty = 2
def __init__(self, x, y, direction): if direction == ROAD_DIRECTION.north or direction == ROAD_DIRECTION.south: Drawable.__init__(self, config.block_size + (2*config.road_size), config.road_size) else: Drawable.__init__(self, config.road_size, config.block_size + (2*config.road_size) ) self.direction = direction self.x = x self.y = y self.color = pygame.Color("#4A4A4A")
def __init__(self, node_list, options=[]): Drawable.__init__(self, options) Named.__init__(self) self.__node_list = node_list cycle_graph = nx.Graph() if node_list: for n in range(1, len(node_list)): cycle_graph.add_edge(node_list[n - 1], node_list[n]) self.style().set_target_type('fill') self.__frame = OpenGraph(cycle_graph, options) self.__frame.style().set_target_type('frame') return
def __init__(self, node_list): Drawable.__init__(self) Named.__init__(self) self.__node_list = node_list cycle_graph = nx.Graph() if node_list: for n in range(1, len(node_list)): cycle_graph.add_edge(node_list[n - 1], node_list[n]) self.style().set_target_type("fill") self.__frame = OpenGraph(cycle_graph) self.__frame.style().set_target_type("frame") return
def __init__( self , f = None ) : Drawable.__init__( self ) self.verts , self.v , self.n , self.t , self.ev , self.et , self.tn = [[]] * 7 self.volume_size = 0 self.volume = np.zeros( 0 , np.float32 ) self.normal = np.zeros( 0 , np.float32 ) self.pts_len = 0 self.lpos = [0]*3 self.prog = None if file : self.fromFile( f )
def __init__(self): Drawable.__init__(self, 200, 50) self.font = pygame.font.Font(pygame.font.get_default_font(), 20) self.bg_color = pygame.Color("#242424") self.button_color = pygame.Color("#3B3B3B") self.button_color_alt = pygame.Color("#474747") self.fg_color = pygame.Color("#616161") self.button_build_hotzone = None self.button_run_hotzone = None sim_control.register_watcher("hud_mode_change", self) self.panel_mask = pygame.Rect(config.window_size[0] - self.w, 0, self.w, self.h)
def __init__(self, ship): self.direction = 1 self.step = 1 self.stages = [ '. ', '` ', ': ', ':.', ':`', '::' ] Drawable.__init__(self, self.get_art()) self.width = 3 self.set_color(curses.COLOR_YELLOW) self.set_attrs(curses.A_BOLD)
def __init__(self): Drawable.__init__(self, 355, 50) self.font = pygame.font.Font(pygame.font.get_default_font(), 20) self.bg_color = pygame.Color("#242424") self.button_color = pygame.Color("#3B3B3B") self.button_color_alt = pygame.Color("#474747") self.fg_color = pygame.Color("#616161") self.button_play_hotzone = None self.button_pause_hotzone = None self.button_play_x2_hotzone = None self.panel_mask = pygame.Rect(0, 0, self.w, self.h) sim_control.register_watcher("hud_mode_change", self)
def __init__(self, f=None): Drawable.__init__(self) self.verts, self.v, self.n, self.t, self.ev, self.et, self.tn = [[] ] * 7 self.volume_size = 0 self.volume = np.zeros(0, np.float32) self.normal = np.zeros(0, np.float32) self.pts_len = 0 self.lpos = [0] * 3 self.prog = None if file: self.fromFile(f)
def __init__(self, image, x, y, w, h, nbframes, blitx, blity): Drawable.__init__(self, image, x, y, w, h, nbframes, blitx, blity) self.speed = 1 self.originalspeed = 1 self.strength = 1 self.upspeed = 0 self.gravity = 6 self.speedy = 0 self.life = 1 self.direction = Vector2(-1, 0) self.updateframetime = 200 self.lastupdatejump = pygame.time.get_ticks() self.ismoving = False self.randomevent = random.randint(1000, 5000) self.score = 1 self.isattacking = False self.isdying = False
def __init__(self): super().__init__() # Using a deque as a linked list improves performance # Due to needing multiple remove() calls self.balls: deque[b2Body] = deque() self.pocketed_balls: List[Ball] = [] self.drawables: List[Drawable] = [] self.pockets = PoolWorld.create_pockets() self.to_remove: Set[b2Body] = set() self.board: PoolBoard = None self.cue_ball: b2Body = None self.world = b2World(gravity=(0, 0), doSleep=True) self.world.autoClearForces = True self.world.contactListener = self # Create the pocket fixtures which are sensors # The radius is such that a collision only occurs when the center of the ball # overlaps with the edge of the pocket pocket_fd = b2FixtureDef(shape=b2CircleShape( radius=Constants.POCKET_RADIUS - Constants.BALL_RADIUS)) pocket_fd.isSensor = True for pocket in self.pockets: body: b2Body = self.world.CreateStaticBody( position=pocket.to_tuple(), fixtures=pocket_fd) body.userData = PoolData(PoolType.POCKET) self.drawables.append( Drawable(body, Drawable.BLUE, Drawable.draw_circle, outline_color=Drawable.RED)) # Create the edges of the pool table top_left = self.pockets[0] top_middle = self.pockets[1] top_right = self.pockets[2] bottom_left = self.pockets[3] bottom_middle = self.pockets[4] bottom_right = self.pockets[5] thickness = Constants.POCKET_RADIUS self.create_boundary_wall(top_left, top_middle, True) self.create_boundary_wall(Point(top_middle.x, top_middle.y + 0.1), top_right, True) self.create_boundary_wall(top_right, bottom_right, False) self.create_boundary_wall( Point(top_left.x - thickness, top_left.y), Point(bottom_left.x - thickness, bottom_left.y), False) self.create_boundary_wall( Point(bottom_left.x, bottom_left.y + thickness), Point(bottom_middle.x, bottom_middle.y + thickness), True) self.create_boundary_wall( Point(bottom_middle.x, bottom_middle.y + thickness - 0.1), Point(bottom_right.x, bottom_right.y + thickness), True)
def __init__(self, image, x, y, nbcoins, radius, direction): Drawable.__init__(self, image, x, y, 16, 16, 4, 0, 32) self.coins = [] self.position = Rect(x, y, radius * 2, radius * 2) self.angle = 0.0 self.radius = radius self.lastupdateframe = pygame.time.get_ticks() self.updateframetime = 10 self.nbcoins = nbcoins self.direction = direction coinsize = 16 for i in range(nbcoins): obj = YellowCoin( image, self.position.centerx - coinsize / 2 + math.cos(self.angle) * radius, self.position.centery - coinsize / 2 - math.sin(self.angle) * radius) self.coins.append(obj) self.angle += (2 * math.pi) / nbcoins
class World: def __init__(self, robot): self.rects = [] self.mask = [] self.robot = robot self.block1 = None self.ground = None self.__create_rects() self.__create_items() @property def distance(self): d = int(self.block1.position.x - self.robot.position.x) if not self.robot.isJumping and 0 < d and d < 96: self.robot.jump() return d def __create_rects(self): x = self.robot.position.center[0] for idx in range(0, 23): rect = Rect((x + 10 * idx, 0), (10, 10)) rect.bottom = RULER self.rects.append(rect) self.mask = np.zeros(len(self.rects), np.uint8) def __create_items(self): self.ground = Drawable('ground.png', WORLD) self.ground.position.bottom = HEIGHT self.block1 = Drawable('block1.png', WORLD) self.block1.position.x = WIDTH + 10 self.block1.position.bottom = RULER def draw(self, screen): self.ground.draw(screen) self.ground.scroll(0, WIDTH) self.block1.draw(screen) self.block1.scroll(WIDTH + 10, -10) for idx in range(0, len(self.rects)): rect = self.rects[idx] rect.right = self.robot.position.center[0] + 10 * idx if rect.colliderect(self.block1.rect): self.mask[idx] = 1 screen.fill(RED, rect) else: self.mask[idx] = 0 screen.fill(BLUE, rect)
def __init__(self, x, y, metadata): Drawable.__init__(self, config.block_size, config.block_size) self.x = x self.y = y self.draw_priority = 2 self.offset_x = self.__calculate_offset_coord(x) self.offset_y = self.__calculate_offset_coord(y) self.id = metadata["id"] self.description = metadata["description"] self.call_time = metadata["callTime"] self.leave_time = metadata["leaveTime"] self.travel_time = metadata["travelTime"] self.event_time = metadata["eventTime"] self.color = pygame.Color("#FFD900")
def __init__(self, hud_space): Drawable.__init__(self, "Hud_BG") Updatable.__init__(self) self.rect = hud_space #Make a black box for the background self.background = pygame.Surface( (self.rect.width, self.rect.height) ) self.background.fill( (0,0,0) ) #Make a simple health bar health_bar_box = pygame.Rect(self.rect.width/2 + 64, 16, self.rect.width/2 - 128, 32) health_bar_box.x += self.rect.x health_bar_box.y += self.rect.y self.health_bar = HealthBar(health_bar_box) #Make a kill counter kill_counter_box = pygame.Rect(16, 0, (32 * 6), 64) kill_counter_box.x += self.rect.x kill_counter_box.y += self.rect.y self.kill_counter = KillCounter(kill_counter_box)
def __init__(self, target1, target2, position): t1_shadow = target1.get_shadow() t2_shadow = target2.get_shadow() x1 = target1.scene.objects[target1.stacking_order].x2 + 1 x2 = target2.scene.objects[target2.stacking_order].x1 - 1 y = target1.scene.objects[target1.stacking_order].y1 for line in t1_shadow: if y == position: for x in range(len(line) - 1, 0, -1): if not line[x]: x1 -= 1 else: break break y += 1 y = target2.scene.objects[target2.stacking_order].y1 for line in t2_shadow: if y == position: for x in range(0, len(line) - 1): if not line[x]: x2 += 1 else: break break y += 1 Drawable.__init__(self, ''.ljust(x2 - x1 + 1, '-')) self.x_position = None self.speed = None self.x1 = x1 self.x2 = x2 self.y = position self.set_color(curses.COLOR_RED, curses.COLOR_BLACK) self.set_attrs(curses.A_BOLD)
def __init__(self, msg): width = 0 msg = msg.split('\n') height = len(msg) + 2 for line in msg: line = line.strip() if len(line) > width: width = len(line) Drawable.__init__(self, '') width += 2 self.art = [[' '] * width] for line in msg: line = line.strip() diff = width - len(line) art = [' '] * (diff // 2) for char in line: art.append(char) diff = width - len(art) art.extend([' '] * diff) self.art.append(art) self.art.append([' '] * width) self.shadow = [] for y in range(0, height): self.shadow.append([True] * width) self.width = width self.height = height self.set_attrs(curses.A_DIM) self.set_color(curses.COLOR_RED, curses.COLOR_WHITE)
def __init__(self): Drawable.__init__(self) self.arena_matrix = [ [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 3, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 3, 1, 3, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 3, 1, 3, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 0, 1, 3, 1, 0, 1, 3, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 4], [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]] self.arena_surface = self._load_arena_surface() self.non_destructible_walls = self._load_non_destructible_walls() self.destructible_walls = self._load_destructible_walls() self.players = list() self.physics = Physics(self)
def _convert_notification(self, notif: Notification) -> Drawable: text = notif.title if notif.message: text += f". {notif.message}" color = 2 font = ImageFont.truetype(self.__font_path, self.__font_size) w = font.getsize(text)[0] image = Image.new('L', (w, self.__matrix.height), 1) draw = ImageDraw.Draw(image) draw.text((0, 0), text, font=font) arr = np.asarray(image) arr = np.where(arr, 0, color) return Drawable(pixels=arr)
def __init__(self, e_type, x, y, playWidth): self.x = x self.y = y self.velocity = random.randrange(-3, 3) self.playWidth = playWidth self.e_type = e_type self.dying = False if (self.e_type == "rb"): self.sprites = RB_SPRITES self.sprite = self.sprites[0] self.speed = 5 self.drawable = Drawable(self.sprites, x, y) self.health = 2 if (self.e_type == "wb"): self.sprites = WB_DEATH self.sprite = self.sprites[0] self.speed = 6 self.drawable = Drawable(self.sprites, x, y) self.health = 1 if (self.e_type == "cb"): self.sprites = CB_SPRITES self.sprite = self.sprites[0] self.speed = 4 self.drawable = Drawable(self.sprites, x, y) self.health = 1 if (self.e_type == "vb"): self.sprites = VB_SPRITES self.sprite = self.sprites[0] self.speed = 4 + random.uniform(-1.5, 2) self.drawable = Drawable(self.sprites, x, y) self.drawable.initialize_animation(5, 0) self.health = 99
def create_boundary_wall(self, pocket1: Point, pocket2: Point, horizontal: bool): vertices = [] diff = Constants.POCKET_RADIUS + 0.05 thickness = Constants.POCKET_RADIUS if horizontal: vertices.append((pocket1.x + diff, pocket1.y)) vertices.append((pocket2.x - diff, pocket1.y)) vertices.append((pocket2.x - diff, pocket1.y - thickness)) vertices.append((pocket1.x + diff, pocket1.y - thickness)) else: vertices.append((pocket1.x, pocket1.y + diff)) vertices.append((pocket1.x, pocket2.y - diff)) vertices.append((pocket1.x + thickness, pocket2.y - diff)) vertices.append((pocket1.x + thickness, pocket1.y + diff)) vertices.append(vertices[0]) fixture = b2FixtureDef(shape=b2ChainShape(vertices_chain=vertices)) body: b2Body = self.world.CreateStaticBody(fixtures=fixture) body.userData = PoolData(PoolType.WALL) self.drawables.append( Drawable(body, Drawable.BROWN, Drawable.draw_rect, outline_color=(25, 14, 16)))
def load_level(num): Config.config_level(num) Drawable.recreateWindow() Tile.load_level(num) Character.load_characters(num)
def __init__(self, name, art): Drawable.__init__(self, art) self.add_attrs(curses.A_BOLD) self.name = name self.program = None
DEFAULT_POINTER_COLOR = (0.5, 1, 0.5, 1) POINTER_RADIUS = 15 POINTER_WIDTH = 30 POINTER_HEIGHT = 30 POINTER_BORDER_WIDTH = 1 POINTER_COLOR_MODE = 'rgba' def __init__(self, center, color=DEFAULT_POINTER_COLOR): self.drawableType = DrawableType.Pointer self.center = center self.color = color # the unique Annotation IDentifier self.anid = self.UUID() # Must be called from within a `with canvas: ` def draw(self, window, group): Color(self.color[0], self.color[1], self.color[2], self.color[3], mode=self.POINTER_COLOR_MODE) Line(ellipse=(self.center.x - self.POINTER_RADIUS, self.center.y - self.POINTER_RADIUS, self.POINTER_WIDTH, self.POINTER_HEIGHT), width=self.POINTER_BORDER_WIDTH, group=group) Drawable.register(Pointer)
def __init__(self, character, color, location): Drawable.__init__(self, character, color, location, PLAYER_SIZE) HandlesEvents.__init__(self, []) self.events.append(MovementEvent)
hud.registerListeners(cricket, crabspawner) clock = pygame.time.Clock() #display.fill(blue) pygame.display.flip() while 1: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): sys.exit() if((event.type == KEYDOWN) or (event.type == KEYUP)): keyhandler.handle(event) dt = clock.get_time() timerhandler.updateTimers(dt) Updatable.updateAll(dt) #for (collider, wall) in pygame.sprite.groupcollide(character.wall_colliders, entity.walls, False, False): # collider.onWallCollision(wall) for enemy in pygame.sprite.spritecollide(cricket, character.enemies, False): enemy.onPlayerCollision(cricket) display.fill(blue) dirty_rects = Drawable.drawAll(display) pygame.display.update(dirty_rects)
def __init__(self, displayWidth, displayHeight): self.drawable = Drawable(PLAYER_SPRITE, (int)(0.5 * displayWidth), (int)(0.8 * displayHeight)) self.displayWidth = displayWidth self.displayHeight = displayHeight self.health = MAX_HEALTH self.damage_counter = 0
def __init__( self ) : Drawable.__init__( self )
def play(self): self.p1.status_win.display( curses.COLS // 2 - self.ship_space - self.max_health, 2 ) self.p2.status_win.display( curses.COLS // 2 + self.ship_space, 2 ) if self.p1.scene.objects[self.p1.stacking_order].x2 != self.midpoint_x - self.ship_space: self.main_win.move_to(self.p1, x=self.midpoint_x - self.ship_space - self.p1.width) self.main_win.pan(x=self.main_win.width - self.main_win.win_width) laser = Laser(self.p1, self.p2, self.main_win.height // 2) self.main_win.add_object(laser, laser.x1, laser.y) shield1 = Drawable(')') shield1.set_color(curses.COLOR_CYAN) shield1.set_attrs(curses.A_BOLD) self.main_win.add_object(shield1, laser.x1, laser.y) self.main_win.hide(shield1) shield2 = Drawable('(') shield2.set_color(curses.COLOR_CYAN) shield2.set_attrs(curses.A_BOLD) self.main_win.add_object(shield2, laser.x2, laser.y) self.main_win.hide(shield2) self.main_win.refresh() self.main_win.auto_refresh = True step = 0 while not self.p1.health.is_empty() and not self.p2.health.is_empty(): time.sleep(0.5) target1 = self.p1.get_target() target2 = self.p2.get_target() target = None successful = True if step < 5: target = self.p1 if not self.is_valid_target(target1): target1 = 0 elif not self.is_valid_target(target2) or target1 == target2: successful = False else: target = self.p2 if not self.is_valid_target(target2): target2 = 0 elif not self.is_valid_target(target1) or target1 == target2: successful = False self.p1.show_target(target2) self.p2.show_target(target1) direction = 1 if target is self.p1: direction = -1 self.main_win.show(laser) laser.start(direction) time.sleep(0.01) while laser.advance(): time.sleep(0.02) if not successful: if direction > 0: self.main_win.show(shield2) time.sleep(0.5) self.main_win.hide(shield2) else: self.main_win.show(shield1) time.sleep(0.5) self.main_win.hide(shield1) self.main_win.hide(laser) if successful: target.health.decrease() target.set_color(curses.COLOR_RED) if target.health.is_empty(): continue time.sleep(0.2) target.set_color(curses.COLOR_WHITE) step = (step + 1) % 10 explosion = Explosion(target) explosion.set_color(curses.COLOR_YELLOW) explosion.set_attrs(curses.A_BOLD) self.main_win.add_object(explosion, explosion.x, explosion.y) explosion.explode() self.winner = self.p2 if target is self.p2: self.winner = self.p1
def __init__( self, x, y ): Point2D.__init__( self, x, y ) Physical.__init__( self ) Drawable.__init__( self )
def __init__(self, image, x, y): Drawable.__init__(self, image, x, y, 16, 25, 5, 0, 215) self.value = 1
def __init__(self, image, x, y): Drawable.__init__(self, image, x, y, 16, 16, 4, 0, 32) self.value = 3
def __init__(self, health): Drawable.__init__(self, ".".rjust(health + 1)) self.health = health self.width = health self.set_color(curses.COLOR_WHITE, curses.COLOR_GREEN)
def __init__( self , f = None ) : Drawable.__init__( self ) self.verts , self.v , self.n , self.t , self.ev , self.et = [[]] * 6 if file : self.fromFile( f )
def __init__( self , size , m ) : Drawable.__init__( self ) self.size = map( lambda x : x*.5 , size ) self.m = m
def __init__(self, position, width, height): Drawable.__init__(self) self.x = position[0] self.y = position[1] self.width = width self.height = height
def __init__(self): Drawable.__init__(self, "Floor") self.image = loadImage("test_bgd_large.bmp", use_transparency = False) self.rect = self.image.get_rect()
def __init__(self): Drawable.__init__(self, "Hud_Elem") Updatable.__init__(self) Hud.hud_elements.append(self)
def update(self, dt): Drawable.handle_deletion(self.entities[self.state]) self.state_dt += dt if self.move_to == self.DUNGEON: self.move_to_dungeon() self.move_to = None self.state_dt = 0 elif self.move_to == self.OVERWORLD: self.move_to_overworld() self.move_to = None self.state_dt = 0 if self.character.health <= 0: self.move_to_overworld() self.character.health = 8 self.textbox.text = ["That was close! I've saved you this time, but don't test your luck."] self.textbox.faces = [2] if self.progression == self.SKULLS_FOUND and len(self.textbox.text) == 0: self.progression = self.TITLE_COMPLETE self.sprites[self.title_i].visible = True self.sprites_rel[self.title_i] = (self.character.x - 30, self.character.y - 80) self.need_pos_update = True if self.progression == self.TITLE and self.game.keys[key.SPACE]: self.sprites[self.title_i].visible = False self.progression = self.INTRO self.textbox.text = ["It's another sunny day in your hometown.", "Your uncle Jim has left you to look after his goat farm.", "Choose the grass seeds and LEFT CLICK to use."] if self.progression == self.USED_SEEDS and self.textbox and len(self.textbox.text) == 0: self.progression_dt += dt if self.progression_dt > 8: self.progression_dt = 0 self.progression = self.ENCOUNTER if self.progression == self.ENCOUNTER: if self.dungeon_entry is None and self.character.ty > 2 and self.character.tx > 1 and self.character.tx + 2 < self.WIDTH[self.OVERWORLD] and self.character.ty + 1 < self.HEIGHT[self.OVERWORLD]: self.dungeon_entry = DungeonEntry(self.game, self.character.tx+1, self.character.ty-1, self.group_for(self.character.ty-1)) if self.dungeon_entry and self.dungeon_entry.progress == 3 and self.dungeon_entry.char_dt >= 2: self.progression = self.ENCOUNTER_TEXT self.textbox.text = ["MORTAL! What are you doing on my grounds?!", "!!!", "I.. this is my uncle's property! I'm sorry!", "Ah. I see. Well, since it isn't your fault, I have a deal for you.", "I need to sacrifice a goat. In exchange, I will give you rewards beyond your wildest dreams.", "What? I can't. That would be cruel!", "LEFT CLICK a goat to choose a sacrifice."] self.textbox.faces = [2, 1, 1, 2, 2, 1, None] if self.progression == self.ENCOUNTER_TEXT and self.textbox and len(self.textbox.text) == 0: self.progression = self.SACRIFICING self.sacrifice_mode = True if self.progression == self.INTRO and self.textbox and len(self.textbox.text) == 0: self.progression = self.USE_SEEDS self.inventory = Inventory(self.game, self.game.camera.width / self.game.camera.zoom - Inventory.WIDTH - 10, 10, self.hud_group) if self.progression == self.SACRIFICING_TEXT and self.textbox and len(self.textbox.text) == 2: self.game.camera.target = self.character if self.progression == self.SACRIFICING_TEXT and self.textbox and len(self.textbox.text) == 0: self.inventory.add_item(WaterGem(self.game, 25)) self.textbox.text = ["How strange. Maybe I should check out that crevice.."] self.textbox.faces = [1] self.dungeon_entry.remove_character = True self.progression = self.FREE_ROAM #if self.progression == self.FREE_ROAM and self.state == self.OVERWORLD: # self.progression_dt += dt # if self.progression_dt > 5: # self.progression_dt = 0 if not self.has_init[self.OVERWORLD] and self.state == self.OVERWORLD: for i in range(random.randint(10, 30)): tx = (random.random() * self.WIDTH[self.OVERWORLD] - 1) + 1 ty = (random.random() * self.HEIGHT[self.OVERWORLD] - 1) + 1 self.entities[self.OVERWORLD].append(Goat(self.game, tx, ty, self.group_for(ty))) for ty in range(self.HEIGHT[self.OVERWORLD]): for tx in range(self.WIDTH[self.OVERWORLD]): self.tiles[self.OVERWORLD].append(GrassTile(self.game, tx, ty, self.group_for(ty+1))) self.has_init[self.OVERWORLD] = True if not self.has_init[self.DUNGEON] and self.state == self.DUNGEON: rooms = image.load('sprites/dungeon_rooms.png') raw_image = rooms.get_image_data() img_format = 'RGB' pitch = raw_image.width * len(img_format) pixels = raw_image.get_data(img_format, pitch) room_width = DungeonTemplate.WIDTH room_height = DungeonTemplate.HEIGHT dungeon_templates = [] for i in range(raw_image.width // room_width): room_pixels = [] for j in range(room_height): for ii in range(room_width): room_pixels.append(tuple([int(pixels[p + len(img_format) * (j * raw_image.width + i*room_width + ii)]) for p in range(len(img_format))])) for rot in range(4): if rot > 0: room_pixels_temp = [] for y in range(room_height): for x in range(room_width): # 90 degrees rotation CW j = x * room_width + (room_height - y - 1) room_pixels_temp.append(room_pixels[j]) room_pixels = room_pixels_temp template = DungeonTemplate(self.game, copy.copy(room_pixels), i, i == 0) dungeon_templates.append(template) room_instances = [copy.copy(dungeon_templates[0])] tx, ty = self.WIDTH[self.DUNGEON] // 2, self.HEIGHT[self.DUNGEON] // 2 room_instances[0].tx = tx room_instances[0].ty = ty if self.first_dungeon_visit: room_instances[0].can_spawn_entity = False room_instances[0].clear_chest_spawns() room_instances[0].set_chest_spawn(1, 3, True) self.first_dungeon_visit = False exits_uncovered = [(tx, ty)] occupied = [(tx, ty)] while len(exits_uncovered) > 0: random.shuffle(dungeon_templates) tx, ty = exits_uncovered.pop(0) for instance in room_instances: if (instance.tx, instance.ty) == (tx, ty): missed_exits = instance.exit_walls() missed_walls = [len(missed_exits[i]) > 0 for i in range(4)] for (ix, iy) in instance.exits: if not missed_walls[instance.exit_wall_index(ix, iy)]: continue for template in dungeon_templates: if template.i == instance.i: continue found_match = False new_coords = False for (ex, ey) in template.exits: if ix == 0 and ey == iy and ex == room_width - 1: found_match = (-1, 0) elif iy == 0 and ex == ix and ey == room_height - 1: found_match = (0, -1) elif ix == room_width - 1 and ey == iy and ex == 0: found_match = (1, 0) elif iy == room_height - 1 and ex == ix and ey == 0: found_match = (0, 1) if found_match: new_coords = (tx + found_match[0] * room_width, ty + found_match[1] * room_height) if new_coords in occupied: found_match = False else: break if found_match: break if found_match and new_coords: new_instance = copy.copy(template) new_instance.tx, new_instance.ty = new_coords if new_instance.tx >= 0 and new_instance.tx + 5 < self.WIDTH[self.DUNGEON] and new_instance.ty >= 0 and new_instance.ty + 5 < self.HEIGHT[self.DUNGEON]: room_instances.append(new_instance) exits_uncovered.append(new_coords) occupied.append(new_coords) dungeon_templates.remove(template) missed_walls[instance.exit_wall_index(ix, iy)] = False missed_exits[instance.exit_wall_index(ix, iy)].remove((ix, iy)) new_instance.exits.remove((ex, ey)) found_match = False new_coords = False for i in range(len(missed_exits)): for ix, iy in missed_exits[i]: instance.remove_exit(ix, iy) temp_tiles = [None for _ in range(self.HEIGHT[self.DUNGEON]) for _ in range(self.WIDTH[self.DUNGEON])] count = 0 for instance in room_instances: for x in range(room_width): for y in range(room_height): tx = x + instance.tx ty = y + instance.ty j = ty*self.WIDTH[self.DUNGEON] + tx i = y*room_width + x temp_tiles[j] = DungeonTile(self.game, tx, ty, self.group_for(ty, self.DUNGEON), instance.tile_types[i]) temp_tiles[j].can_spawn_entity = instance.can_spawn_entity self.tiles[self.DUNGEON] = temp_tiles for tile in self.tiles[self.DUNGEON]: if tile: tile.init_tile() self.has_init[self.DUNGEON] = True self.change_state(self.DUNGEON) if self.last_hover: self.hover_dt += dt if self.last_hover and self.hover_dt >= 0.05 and self.sacrifice_mode and self.state == self.OVERWORLD: mouse_hover = self.update_hover() self.hover_dt = 0 self.last_hover = None self.game.cursor = self.game.window.CURSOR_HAND if mouse_hover else self.game.window.CURSOR_DEFAULT for drawable in self.tiles[self.state] + self.entities[self.state] + [self.textbox, self.inventory, self.character, self.dungeon_entry]: if drawable: drawable.update(dt) super().update(dt)
def __init__(self, image, x, y, blitx, blity, w, h, nbframes, zindex): Drawable.__init__(self, image, x, y, w, h, nbframes, blitx, blity) self.zindex = zindex
def __init__(self,pos): self.pos = pos Drawable.__init__(self)
def __init__( self , size ) : Drawable.__init__( self ) self.size = map( lambda x : x*.5 , size ) self.m = tr.identity_matrix()