Beispiel #1
0
    def start(self):
        pygame.init()
        screen = pygame.display.set_mode(
            (self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        player = Player()
        game_map = Map()
        game_map.init(screen, self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
        pygame.display.set_caption("Stop The Virus")
        pygame.mouse.set_visible(1)
        pygame.mouse.set_cursor(*pygame.cursors.broken_x)
        pygame.key.set_repeat(1, 30)
        clock = pygame.time.Clock()
        hint_font = pygame.font.SysFont("comicsansms", 20)
        info_font = pygame.font.SysFont("comicsansms", 36)
        running = True

        while running:
            clock.tick(30)
            raw_time = pygame.time.get_ticks()
            game_map.check_actors(player.get_level(), raw_time)
            game_map.update(raw_time)

            if self.hint != '':
                if raw_time - self.hint_start_time > 15000:
                    self.hint = ''
                else:
                    textsurface = hint_font.render(self.hint, True,
                                                   self.TEXT_COLOR)
                    screen.blit(textsurface, (25, 15))

            textsurface = info_font.render('Points: %s' % player.get_points(),
                                           True, self.TEXT_COLOR)
            screen.blit(textsurface,
                        (self.SCREEN_WIDTH - textsurface.get_width() - 25,
                         self.SCREEN_HEIGHT - textsurface.get_height() - 15))
            textsurface = info_font.render('Level: %s' % player.get_level(),
                                           True, self.TEXT_COLOR)
            screen.blit(
                textsurface,
                (25, self.SCREEN_HEIGHT - textsurface.get_height() - 15))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.event.post(pygame.event.Event(pygame.QUIT))

                if event.type == pygame.MOUSEBUTTONDOWN:
                    game_map.check_hit(pygame.mouse.get_pos())
            pygame.display.flip()
Beispiel #2
0
    def generate_level(self):
        """Delete all tiles in desired layer"""
        for layer in self.tile_layers:
            for tile in self.tile_layers[layer]:
                tile.kill()

        #characteristics = Characteristics(616,616,350,66,0,36,1.6, [])
        #self.hero = HeroSprite(self.tile_layers, self.sprite_handler, (10,10), characteristics)
        self.hero.posReset((10, 10))
        self.map = Map()

        # place sprites/tiles
        self.map.generate(self)
Beispiel #3
0
def run_manul(file_name, stop):
    m = Map(20, 3)
    m.load_map(file_name)
    m.gen_people_by_density(0.2)
    m.check_map()
    m.draw_map()
    plt.savefig('0.png')
    # input(':')
    m.everybody_move(stop)

    plt.ioff()
    # 图形显示
    plt.show()
Beispiel #4
0
 def __init__(self, _engine):
     super(Scene, self).__init__()
     self._ais = []
     self._engine = _engine
     self._resx, self._resy = _engine.getResolution()
     self.surface = pygame.Surface((self._resx, self._resy))
     drawText(self.surface, "Wczytywanie mapy...", 48, (255, 255, 255),
              (self._resx / 2, self._resy / 2))
     self._map = Map(_engine)
     self._hub = Hub(_engine, self._map)
     self._cursor = Cursor(_engine, self._map)
     self._ais.append(AI(_engine, self._map, _engine.players[0], 0))
     self._ais.append(AI(_engine, self._map, _engine.players[1], 1))
Beispiel #5
0
def build_map(map_node, base_path):
    attributes = get_attributes(map_node)
    if attributes['version'] != '1.0':
        template = 'tmx.parse was designed for version 1.0 maps: found version %s'
        message = template % map_obj.version
        raise VersionError(message)

    map_obj = Map()

    first_gid = 1
    for node in get_nodes(map_node.childNodes, 'tileset'):
        tileset = build_tilesets(node, base_path, first_gid)
        first_gid = tileset.last_gid + 1
Beispiel #6
0
    def next_level():
        Game.message('You take a moment to rest, and recover your strength.',
                     libtcod.light_violet)
        Game.player.fighter.heal(Game.player.fighter.max_hp / 2)

        Game.message('You descend deeper into the heart of the dungeon...',
                     libtcod.red)
        libtcod.console_clear(Game.main_console)
        Game.dungeon_level += 1
        Game.map = Map(Game.MAP_WIDTH, Game.MAP_HEIGHT)
        Game.player.x = Game.map.origin[0]
        Game.player.y = Game.map.origin[1]
        Game.map.add_object(Game.player)
Beispiel #7
0
    def __init__(self):
        pygame.init()
        self.ai_settings = Settings()
        self.screen = pygame.display.set_mode((self.ai_settings.screen_width, self.ai_settings.screen_height))
        pygame.display.set_caption("Super Mario Bros.")

        self.screen_rect = self.screen.get_rect()
        self.map = Map(self.screen, 'images/world1-1.txt', 'rock_block', 'metal_block', 'stone_block', 'brick_block',
                       'question_block', 'pipe-1', 'pipe-2', 'super_coin-1', 'pole', 'flag', 'top', 'castle')
        self.mario = Mario(self.ai_settings, self.screen, self.map, self)
        self.menu = Menu(self.screen, 'Super Mario Bros', 'TOP - ', 'SCORE', 'COINS', 'TIME', self.ai_settings, self.mario)
        self.sb = Scoreboard(self.ai_settings, self.screen)
        self.load_data()
Beispiel #8
0
def single_run_test():
    cnfg.load_config_file()
    alg_map = Map()
    ea = EAlgorithm(alg_map, set_specimens=True, save_info_per_iter=True)
    ea.run()
    ea.plot_per_iteration()
    print("Single run best rating:\t",
          ea.generation.select_best_allowed_specimen().rating)
    print("Single run worst rating:\t",
          ea.generation.select_worst_allowed_specimen().rating)
    print("Single run average rating:\t",
          ea.generation.get_average_allowed_specimen_rating())
    pass
Beispiel #9
0
def enter():
    global mario, map, enemy, object, fire_ball
    mario = Mario()
    map = Map()
    enemy = Enemy()
    object = Object()
    fire_ball = Ball()

    game_world.add_object(map, 0)
    game_world.add_object(object, 1)
    game_world.add_object(mario, 0)
    game_world.add_object(enemy, 1)
    pass
Beispiel #10
0
    def clearLevel(self):
        """Tworzy pusty poziom."""

        self._level = [[[Field((x, y)) for x in xrange(MAP_SIZE)]
                        for y in xrange(MAP_SIZE)]]
        self._map = Map(self._engine, self, self._level, True)
        self._cursor = Cursor(self._engine, self._map)
        self._minimap = Minimap(self._engine, self._map)
        self._tiles = TilesGrid(self._engine, self, self._map)
        self._menu = EditorMenu(self._engine, self)
        self._submodules = (self._map, self._minimap, self._tiles, self._menu,
                            self._cursor)
        self._refresh = True
Beispiel #11
0
 def __init__(self, path, g8guy=None):
     logging.basicConfig()
     self.logger = logging.getLogger(name='guide_him')
     self.logger.setLevel(logging.INFO)
     signal.signal(signal.SIGINT, lambda sig, frame: self.close())
     self.m = Map(path)
     if g8guy is None:
         self.guy = G8Guy(*self.m.get_start())
     else:
         self.guy = g8guy
     self.gx = self.guy.x * GRID_SIZE + PADDING
     self.gy = self.guy.y * GRID_SIZE + PADDING
     self.dx = self.dy = 0
Beispiel #12
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.map = Map(self.map_viewport)
        self.history = History(self.history_viewport)
        self._cities = []

        self._cost_map = None
        self._algorithm = None
        self._alg_thread = None
        self._pause = True

        self._ga_history = []
        self._pso_history = []
Beispiel #13
0
    def __init__(self, width=640, height=480):
        """Initialize PyGame"""
        pygame.init()
        self.width, self.height = width, height
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption(GAME_TITLE)

        self.map = Map(self)

        print GAME_TITLE
        print GAME_ABOUT
        print GAME_HOTKEYS
Beispiel #14
0
def main():
    input = readFile("inputs/day3.txt")

    trees = []
    for move in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]:
        map = Map(input)
        trees.append(countTrees(map, move))

    product = 1
    for t in trees:
        product *= t

    print(product)
Beispiel #15
0
    def loadmap_test(self):
        userinput = input("Enter file name:")

        try:
            global map
            map = Map(userinput)

            self.robot = Robot(fakeRun=True, fakeMap=map)
        except FileNotFoundError:
            print("File does not exist!")
            return

        map.printmap()
Beispiel #16
0
 def green_between(
     self, steps
 ):  # Returns a list with the number of green pixels in each satellite image
     if steps == None:
         steps = 20  #Default step size
     if steps <= 0:  # Raise exception for non-positive values
         raise ValueError("Step size must be a positive number.")
     green_array = [
         Map(*location).count_green()
         for location in self.location_sequence(self.geolocate(
             self.start), self.geolocate(self.end), steps)
     ]
     return green_array
Beispiel #17
0
def enter():
    global hit_sound
    game_framework.player.stage_init()
    game_world.add_object(Map('map1.txt'), 0)
    hit_sound = load_wav('sound_resources\\hit sound.ogg')
    hit_sound.set_volume(40)
    for i in range(10):
        if random.randint(0, 100) < 50:
            monsters.append(Golem())
        else:
            monsters.append(Ghost())
    game_world.add_objects(monsters, 1)
    pass
Beispiel #18
0
    def __init__(self, num_particles=100):
        self.measurement_sigma = 1
        self.movement_sigma = 1
        self.delta = 2  # distortion coeff
        self.num_particles = num_particles

        self.particles = []
        for _ in range(num_particles):
            self.particles.append(Particle())

        self.pose = Particle()
        self.map = Map()
        self.reset()
Beispiel #19
0
 def __init__(self, name="", world_name="", duration_minutes=0):
     self.name = name
     self.active = False
     if world_name != "":
         self.world = World("hexa_" + world_name)
         self.map = Map(self.world)
     self.duration = duration_minutes * 60
     self.start_time = datetime.now()
     self.end_time = None
     self.agents_locations = {}
     self.trajectories = []
     self.current_episode_start_time = None
     self.episodes = []
Beispiel #20
0
def new_session(match_type):
    s_id = secrets.token_urlsafe(16)
    sess = Map()
    sess.id = s_id
    sess.players = []
    sess.bracket = {}
    sess.next_bracket_participants = []
    sess.bracket_level = 0
    sess.last_match_generated = 0
    sess.match_type = match_type
    m_session[s_id] = sess

    return jsonify(sess)
Beispiel #21
0
    def __init__(self,width=500,height=500,nodeSize=15):

        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = (width, height)
        self.nodeSize = nodeSize
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)
        self.map = Map(game=self, nodeSize=self.nodeSize)
        
        self.map.generateMap()

        while True:
            self.run()
Beispiel #22
0
 def currentRowChanged(self, index):
     sourceIndex = self.mProxyModel.mapToSource(index)
     isStamp = self.mTileStampModel.isStamp(sourceIndex)
     self.mDuplicate.setEnabled(isStamp)
     self.mDelete.setEnabled(sourceIndex.isValid())
     self.mAddVariation.setEnabled(isStamp)
     if (isStamp):
         self.setStamp.emit(self.mTileStampModel.stampAt(sourceIndex))
     else:
         variation = self.mTileStampModel.variationAt(sourceIndex)
         if variation:
             # single variation clicked, use it specifically
             self.setStamp.emit(TileStamp(Map(variation.map)))
Beispiel #23
0
    def __init__(self, x, y, **kw):
        self.x = x
        self.y = y

        self.load_joysticks()
        if not len(self.controllers):
            self.controllers.append(FallbackController())
        self.players_pos = []
        self.map = Map(x, y)
        self.ais = []
        if 'map' in kw:
            self.map.load_from_png_file(kw['map'])
        self.display = pygame.display.set_mode((x * 50, y * 50))
Beispiel #24
0
def main():
    # TODO: Lue kartan sijainti komentoriviparametrina

    # Karttatiedoston sisältävän kansion polku
    mapFolder = path.dirname(path.abspath(__file__))
    # Karttatiedoston absoluuttinen polku kiintolevyllä
    mapFile = path.join(mapFolder, values.default_map)

    map = Map(mapFile)

    car = Car(1, 1)
    plane = Plane(3, 3)
    boat = Boat(7, 3)

    # Muuttuja, johon valittu ajoneuvo on tallennettu
    currentVehicle = car

    # Käyttäjän syöttämä komento, alustetaan tyhjäksi
    command = ""
    while command != "q":
        clear()  # Tyhjennetään komentokehote jokaisen komennon jälkeen

        map.Draw(car, plane, boat)

        print("Liikutettava ajoneuvo:", currentVehicle.GetName())

        command = input("Syötä komento > ").strip().lower()

        # Sallitut komennot:
        # - up: liikuttaa ajoneuvoa ylöspäin
        # - down: liikuttaa ajoneuvoa alaspäin
        # - left: liikuttaa ajoneuvoa vasemmalle
        # - right: liikuttaa ajoneuvoa oikealle
        # - c: käytä autoa
        # - p: käytä lentokonetta
        # - b: käytä venettä
        # - q: sulje sovellus
        if command == "up":
            currentVehicle.Move(values.Direction.UP, map)
        elif command == "down":
            currentVehicle.Move(values.Direction.DOWN, map)
        elif command == "left":
            currentVehicle.Move(values.Direction.LEFT, map)
        elif command == "right":
            currentVehicle.Move(values.Direction.RIGHT, map)
        elif command == "c":
            currentVehicle = car
        elif command == "b":
            currentVehicle = boat
        elif command == "p":
            currentVehicle = plane
Beispiel #25
0
    def reset_game(self):
        # print("Received reset request")
        self.bgm.stop()
        # Hard or soft?
        if self.stats.lives_left == 0:
            reset_type = "Hard"
            # print("Reset - Hard")
        else:
            reset_type = "Soft"
            # print("Reset - Soft")

        # Soft - Lives remain
        #  Only score and time are refreshed
        if reset_type == "Soft":
            self.stats.score = 0
            self.stats.time = 400
            self.stats.last_time_update = pygame.time.get_ticks()
            self.reset_enemies()
            self.map = Map(self.screen, settings, self.enemies)
            self.mario = Mario(self.screen, settings, self.map)
            self.map.set_mario(self.mario)

        # Hard -  All lives are gone
        # All but high score are reset
        elif reset_type == "Hard":
            self.stats.score = 0
            self.stats.time = 400
            self.stats.last_time_update = pygame.time.get_ticks()
            self.stats.coins = 0
            self.stats.lives_left = 3
            self.reset_enemies()
            self.map = Map(self.screen, settings, self.enemies)
            self.mario = Mario(self.screen, settings, self.map)

        # The game has been reset, resume gameplay
        settings.game_status = "Ready"
        settings.game_active = True
        self.play()
Beispiel #26
0
 def _handcoded_match(problem, newcluster, connected):
     if isinstance(newcluster, Rigid) and len(newcluster.vars) >= 3:
         matches = []
         rigid1 = newcluster
         glues = filter(
             lambda o: isinstance(o, Glueable) and len(
                 o.vars.intersection(rigid1.vars)) >= 3, connected)
         for o in glues:
             connected2 = set()
             for var in o.vars:
                 dependend = problem.find_dependend(var)
                 dependend = filter(lambda x: problem.is_top_level(x),
                                    dependend)
                 connected2.update(dependend)
             rigids2 = filter(
                 lambda r2: isinstance(r2, Rigid) and r2 != rigid1 and len(
                     r2.vars.intersection(o.vars)) >= 3, connected2)
             for rigid2 in rigids2:
                 m = Map({"$r1": rigid1, "$o": o, "$r2": rigid2})
                 matches.append(m)
         return matches
     elif isinstance(newcluster, Glueable):
         matches = []
         glue = newcluster
         rigids = filter(
             lambda r: isinstance(r, Rigid) and len(
                 r.vars.intersection(glue.vars)) >= 3, connected)
         for i in range(len(rigids)):
             for j in range(i + 1, len(rigids)):
                 m = Map({
                     "$o": glue,
                     "$r1": rigids[i],
                     "$r2": rigids[j],
                 })
                 matches.append(m)
         return matches
     else:
         return []
Beispiel #27
0
    def _reset_game(self):
        game_map = Map()

        for team in self.teams:
            team.code_warns = 0
            team.move_warns = 0
            team.score = 0
            team.kills = 0

            for bot in team.bots:
                bot.reset()

        self.__init__(game_map, self.teams[0], self.teams[1])
        self.run()
Beispiel #28
0
 def init(self):
     self.initColor()
     self.initImg()
     self.mode = "main"
     self.modeLst = [
         "main", "settings", "game", "gamePause", "gameOver", "instructions"
     ]
     self.btns()
     arrow = Arrow(self.width, self.height, self.brown)
     self.arrowGroup = pygame.sprite.GroupSingle(arrow)
     map = Map(self.width, self.height, self.red)
     self.mapGroup = pygame.sprite.GroupSingle(map)
     self.control = 1
     self.percentage = 5
Beispiel #29
0
 def __init__(self):
     self.UIDcounter = 0
     self.players = []
     self.maxPlayers = 6
     self.closed = False
     self.cycle = 0
     self.started = False
     self.map = Map(self)
     Message.game = self
     self.story = ""
     self.orders = []
     self.masterPlayer = None
     self.entities = []
     self.races = []
Beispiel #30
0
    def __init__(self, root_console):
        self.gui = GUI(root_console)
        self.game_console = tcod.console.Console(40, 40)
        self.state = BaseState(self)

        self.game_map = Map(self.game_console.width, self.game_console.height)
        self.teams = ["RED_TEAM", "BLUE_TEAM"]
        self.team_entities = {}
        for team in self.teams:
            self.team_entities[team] = []
        self.place_team("RED_TEAM")
        self.place_team("BLUE_TEAM")

        self.turn = 0