def addTrapAt(self, tile, trap_type): """Create a trap of trap_type at coordinates.""" if tile.blocker or (tile.getSurface() == "Water"): return trap = Trap(tile, self) if self.visual: trap.createVisual() tile.traps.append(trap)
def run_game(): tela1 = Settings() screen = pygame.display.set_mode((tela1.altura, tela1.largura)) background = Settings() pygame.display.set_caption("Space War") nave = Ship(screen) #pygame.mouse.set_visible(0) trap = [ Trap(screen, randint(0, 1200)), Trap(screen, randint(0, 1200)), Trap(screen, randint(0, 1200)) ] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: nave.rect.centerx += 30 elif event.key == pygame.K_LEFT: nave.rect.centerx -= 30 elif event.key == pygame.K_UP: nave.rect.bottom -= 30 elif event.key == pygame.K_DOWN: nave.rect.bottom += 30 elif event.key == pygame.K_SPACE: nave.moveMissile() for i in trap: i.rect.bottom += 30 if (i.rect.colliderect(nave.rect)): nave.vida = nave.vida - 1 if (nave.vida < 1): background.bg_image = pygame.image.load( 'imagens/gameover.bmp') screen.fill(tela1.bg_color) screen.blit(background.bg_image, (0, 0)) nave.blitme() nave.blitmemissile() for i in trap: i.blitme() for i in trap: if i.rect.centery > Settings().altura: i.rect.centery = 0 i.rect.centerx = randint(0, 1200) i.rect.centery = randint(0, 200) pygame.display.flip()
def __init__(self, seed, colors): self.random = Random(seed) self.specimens = {} self.next_specimens = {} self.changed_cells = set() self.out_of_bounds = Square(OUT_OF_BOUNDS_COLOR) self.out_of_bounds.killer = True self.all_colors = [color for color in colors] self.traps = [Trap(Coordinate(0, 0))] * len(colors) for trap_type in trap_types: if trap_type is TeleportationTrap: used_traps = [] for i in range(trap_type.max_traps): if i % 2: used_traps.append(-used_traps[-1]) else: used_traps.append( self.random.choice(trap_type.possible_directions)) else: used_traps = [ self.random.choice(trap_type.possible_directions) for i in range(trap_type.max_traps) ] coloring = zip(used_traps, colors) colors = colors[len(used_traps):] for direction, color in coloring: self.traps[color] = trap_type(direction) safe_colors = colors self.squares = [[ Square( self.random.choice(self.all_colors if x < UNSAFE_BOARD_WIDTH else safe_colors)) for x in xrange(BOARD_EXTENDED_WIDTH) ] for __ in xrange(BOARD_HEIGHT)] self.starting_squares = [] for y in xrange(BOARD_HEIGHT): for x in xrange(BOARD_EXTENDED_WIDTH): coordinate = Coordinate(x, y) self.changed_cells.add(coordinate) trap = self.traps[self.get_square(coordinate).color] if trap.is_killer(): self.get_square(trap.direction + coordinate).killer = True if trap.is_mover(): self.get_square(coordinate).teleport = trap.direction if trap.is_wall(): self.get_square(coordinate).killer = True self.get_square(coordinate).wall = True
def createSquare(char): """ fonction auxilliaire pour créer chaque case du labyrinthe à modifier si on veut ajouter des nouveaux types de cases """ if char == 'O': return Wall() elif char == '.': return Door() elif char == 'U': return Exit() elif char == 'T': return Trap() else: # Tout autre caractère (y compris le X du robot) est un couloir # Le robot commence forcément dans un couloir return Corridor()
def init_new_game(self): """ Initializes new games """ logger.info(text.new_game_start) input() logger.info(text.administration) input() logger.info(text.enter_proficiency_prompt) user_input = input().lower() if user_input in DungeonGame.player.proficiencies: DungeonGame.player.proficiency = user_input else: DungeonGame.player.proficiency = "none" logger.info(text.enter_dungeon_width_prompt) width = input_number_from_boundaries(DungeonGame.MIN_MAP_WIDTH,\ DungeonGame.MAX_MAP_WIDTH) logger.info(text.enter_dungeon_height_prompt) height = input_number_from_boundaries(DungeonGame.MIN_MAP_HEIGHT,\ DungeonGame.MAX_MAP_HEIGHT) size = width * height number_of_treasures = max (size * DungeonGame.treasure_rarity,\ DungeonGame.treasure_to_win) number_of_traps = min (size - number_of_treasures - 1, size * DungeonGame.trap_rarity) traps = Trap.generate_traps(number_of_traps) starting_position = Position.generate_random_position(width, height) DungeonGame.dmap.initialize(height, width, number_of_treasures, traps, starting_position) DungeonGame.player.health = DungeonGame.default_health DungeonGame.player.bag = 0 DungeonGame.player.position = starting_position DungeonGame.player.discovered_map.initialize_discovered_map(height, width,\ starting_position) self.respawn_enemy()
def load_traps(filename="assets/traps.csv"): ''' Load a list of speed trap zones based on the file at the given filename Parameter(s): filename<string> Path of file to load and parse Return: trap_list<list><Trap> List of speed trap zones that were found in filename ''' trap_list = [] with open(filename, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') next(csvreader, None) # Skip the header for row in csvreader: site_id = row[0] direction = row[1][0:2] location = row[1][2::] speed = int(row[2]) trap = Trap(site_id, direction, location, speed) trap_list.append(trap) return trap_list
def generateEncounter(): enc_dict = {} if random.choice([True, False]): #Generates Gold g = Gold() else: g = None enc_dict["gold"] = g if random.choice([True, False]): #Generates items i = random.choice([Weapon(), Potion(), Artifact()]) else: i = None enc_dict["item"] = i if random.choice([True, False]): enc_dict["monster"] = Monster() enc_dict["trap"] = None else: enc_dict["trap"] = Trap() enc_dict["monster"] = None return enc_dict
def test_lt(self): trap_1 = Trap(50, "SB", "156 St between 99 - 98 Ave", 50) trap_2 = Trap(50, "WB", "156 St between 158 - 160 St", 50) assert trap_1 < trap_2
def test_getters(self): trap = Trap(50, "SB", "156 St between 99 - 98 Ave", 50) assert trap.get_direction() == "Southbound" assert trap.get_location() == "156 St between 99 - 98 Ave" assert trap.get_speed() == 50
def test_init(self): trap = Trap(50, "SB", "156 St between 99 - 98 Ave", 50) assert trap assert isinstance(trap, Trap)
def random(cls, width: int = 24, height: int = 15) -> "Level": OPENNESS = 0.1 # Ratio of rooms that get an extra wall removed DOOR_DENSITY = 0.6 # Ratio of valid door locations that get a door DOOR_SECRECY = 0.2 # Percentage of doors that are made secret TRAP_DENSITY = 0.05 # Ratio of free locations made a standalone trap MONSTER_DENSITY = 0.1 # Ratio of free locations made a monster LOOT_DENSITY = 0.1 # Ratio of free locations made treasure # 0. Create grid self: Level = object.__new__(cls) grid = [[Room(self, x, y) for x in range(width)] for y in range(height)] self.entrance = grid[0][0] self.exit = grid[height - 1][width - 1] # 1. Connect rooms until getting a spanning tree connected = {(0, 0)} frontier = [(0, 0)] while len(connected) < width * height: random.shuffle(frontier) fx, fy = frontier[-1] # compute neighbors neighbors = [] if fx + 1 < width and (fx + 1, fy) not in connected: neighbors.append((fx + 1, fy, Direction.EAST)) if fx - 1 >= 0 and (fx - 1, fy) not in connected: neighbors.append((fx - 1, fy, Direction.WEST)) if fy + 1 < height and (fx, fy + 1) not in connected: neighbors.append((fx, fy + 1, Direction.SOUTH)) if fy - 1 >= 0 and (fx, fy - 1) not in connected: neighbors.append((fx, fy - 1, Direction.NORTH)) if neighbors: nx, ny, d = random.choice(neighbors) new_room = grid[ny][nx] grid[fy][fx].neighbors[d] = new_room new_room.neighbors[d.opposite()] = grid[fy][fx] connected.add((nx, ny)) frontier.append((nx, ny)) else: frontier.pop() # 2. Break down more walls to open it up a bit rooms: List[Room] = sum(grid, []) for _ in range(int(width * height * OPENNESS)): r = random.choice(rooms) walls = [ d for d in Direction if d not in r.neighbors and _inside(r, d, width, height) ] if walls: # tear down random wall w w = random.choice(walls) dx, dy = w.value n = grid[r.y + dy][r.x + dx] r.neighbors[w] = n n.neighbors[w.opposite()] = r # 3. Add doors rooms.remove(self.exit) rooms.remove(self.entrance) random.shuffle(rooms) valid_door_locations = [ r for r in rooms if len(r.neighbors) == 2 and tuple(r.neighbors.keys())[0] == tuple( r.neighbors.keys())[1].opposite() ] door_count = int(len(valid_door_locations) * DOOR_DENSITY) for _ in range(door_count): r = valid_door_locations.pop() r.door = Door() if random.random() <= DOOR_SECRECY: r.door.hide_dc = 10 if random.random() <= DOOR_TRAP_PROBABILITY: r.trap = Trap() rooms.remove(r) # 4. Add traps trap_count = int(len(rooms) * TRAP_DENSITY) for _ in range(trap_count): r = rooms.pop() r.trap = Trap() # 5. Add monsters monster_count = int(len(rooms) * MONSTER_DENSITY) for _ in range(monster_count): r = rooms.pop() r.monster = Monster() # 6. Add loot loot_count = int(len(rooms) * LOOT_DENSITY) for _ in range(loot_count): r = rooms.pop() r.loot = treasure.Item.random() return self
def __init__(self, name: str) -> None: filename = f"maps/{name}.map" with open(filename, "r") as f: lines = f.readlines() width = len(lines[0]) height = len(lines) if height % 2 == 0: raise ValueError( f"Malformed map, first line has height={height}, should be odd" ) if width % 2: raise ValueError( f"Malformed map, first line has width={width}, should be even") if any(len(l) != width for l in lines): raise ValueError( f"Malformed map, some lines have width different to {width}") grid = [[Room(self, x, y) for x in range(width // 2 - 1)] for y in range(height // 2)] # set a default entrance self.entrance = grid[0][0] for x in range(width // 2 - 1): rx = 2 * x + 1 for y in range(height // 2): ry = 2 * y + 1 room = grid[y][x] # Parse walls for d in Direction: dx, dy = d.value if lines[ry + dy][rx + dx] == " ": # There is no wall in given direction, connect rooms room.neighbors[d] = grid[y + dy][x + dx] # Parse room terrain terrain = lines[ry][rx] if terrain == "#": # Door room.door = Door() if random.random() <= DOOR_TRAP_PROBABILITY: room.trap = Trap() elif terrain == "S": # Secret door room.door = Door() room.door.hide_dc = 10 if random.random() <= DOOR_TRAP_PROBABILITY: room.trap = Trap() elif terrain == "<": # Staircase down self.entrance = room elif terrain == ">": # Staircase up self.exit = room elif terrain == " ": pass elif terrain == "^": # Standalone Trap room.trap = Trap() elif terrain == "M": # Monster room.monster = Monster() elif terrain == "$": # Random treasure room.loot = treasure.Item.random() else: raise ValueError( f"line {ry+1} char {rx+1}: unknown room type {terrain!r}" ) room.validate() if "exit" not in vars(self): raise ValueError("Map has no exit!")