Esempio n. 1
0
def new_game():
    global player, inventory, game_msgs, game_state, dungeon_level, objects
	
    o.objects = []
    #create object representing the player
    fighter_component = Fighter(hp=100, defense=1, power=2, xp=0, death_function=player_death)
    player = o.Object(0, 0, '@', 'player', ltc.white, blocks=True, fighter=fighter_component)
	

    player.level = 1

    #generate map (at this point it's not drawn to the screen)
    #dungeon_level = 1
    m.make_map()
    m.initialize_fov()
 
    game_state = 'playing'
    inventory = []

 
    #create the list of game messages and their colors, starts empty
    game_msgs = []
 
    #a warm welcoming message!
    message('Welcome stranger! Prepare to perish in the Tombs of the Ancient Kings.', ltc.red)
 
    #initial equipment: a dagger
    equipment_component = Equipment(slot='right hand', power_bonus=2)
    obj = o.Object(0, 0, '-', 'dagger', ltc.sky, equipment=equipment_component)
    inventory.append(obj)
    equipment_component.equip()
    obj.always_visible = True
    print "new_game pass"
Esempio n. 2
0
 def change_floor(self, amount):
     global game_state, level, actors, game_log, player, stairs_up, stairs_down
     self.store_map()
     
     level = level + amount
     
     actors = []
     actors.append(player)
     actors.append(stairs_up)
     actors.append(stairs_down)
     
     if not os.path.isfile('l'+str(level)+'.s'): #if new floor is new, make it
         map.make_map()
     else:
         self.restore_map() #else load it
     
     if amount > 0: #down
         player.x = stairs_up.x
         player.y = stairs_up.y
     else:
         player.x = stairs_down.x
         player.y = stairs_down.y
     log("you are now at floor", level)
     log_turn()
     map.fov_recompute(player.x, player.y)
     game_state = enum.GameS.IDLE
     tcod.console_flush()
Esempio n. 3
0
def competition(compid):
    from compUtils import get_comp_json
    # get the latest comp result file, not the active one. This is so we can display tasks that have published
    # results that are not yet official and therefore in the comp overall results
    result_file = get_comp_json(int(compid), latest=True)
    all_tasks = []
    layer = {}
    country_scores = False
    task_ids = []
    overall_available = False
    if result_file != 'error':
        if result_file['formula'].get('country_scoring') == 1:
            country_scores = True
        overall_available = True if get_comp_json(int(compid)) != 'error' else False
        for task in result_file['tasks']:
            task_ids.append(int(task['id']))
            wpt_coords, turnpoints, short_route, goal_line, tolerance, bbox, _, _ = get_map_json(task['id'])
            layer['geojson'] = None
            layer['bbox'] = bbox
            task_map = make_map(layer_geojson=layer, points=wpt_coords, circles=turnpoints, polyline=short_route,
                                goal_line=goal_line, margin=tolerance)
            task['opt_dist'] = '{:0.2f}'.format(task['opt_dist'] / 1000) + ' km'
            task['tasQuality'] = '{:0.2f}'.format(task['day_quality'])
            task.update({'map': task_map._repr_html_()})
            all_tasks.append(task)

    comp, non_scored_tasks = frontendUtils.get_comp_info(compid, task_ids)
    comp_start = comp['date_from']
    if comp['date_from']:
        comp['date_from'] = comp['date_from'].strftime("%Y-%m-%d")
    if comp['date_to']:
        comp['date_to'] = comp['date_to'].strftime("%Y-%m-%d")
    if comp_start > datetime.now().date():
        return render_template('public/future_competition.html', comp=comp)

    if non_scored_tasks:
        for t in non_scored_tasks:
            task = t._asdict()
            task['status'] = "Not yet scored"
            if not t.opt_dist or t.opt_dist == 0:
                task['status'] = "Task not set"
                task['opt_dist'] = '0 km'
            else:
                wpt_coords, turnpoints, short_route, goal_line, tolerance, bbox, _, _ = get_map_json(task['id'])
                layer['geojson'] = None
                layer['bbox'] = bbox
                task_map = make_map(layer_geojson=layer, points=wpt_coords, circles=turnpoints, polyline=short_route,
                                    goal_line=goal_line, margin=tolerance)
                task['opt_dist'] = '{:0.2f}'.format(task['opt_dist'] / 1000) + ' km'
                task.update({'map': task_map._repr_html_()})

            task['tasQuality'] = "-"
            task['date'] = task['date'].strftime("%Y-%m-%d")
            all_tasks.append(task)
    all_tasks.sort(key=lambda k: k['date'], reverse=True)

    return render_template('public/comp.html', tasks=all_tasks, comp=comp, overall_available=overall_available,
                           country_scores=country_scores)
def new_level(map_w,
              map_h,
              entities,
              G_TRAP_CHARS,
              G_GLYPH_CHARS,
              player_floor=1):
    level_map = map.Map(map_w, map_h)
    map.make_map(level_map, entities, G_TRAP_CHARS, player_floor)
    paper_map = map.Map(map_w, map_h)
    for y in range(map_h):
        for x in range(map_w):
            z = level_map.t_[x][y].type
            paper_map.t_[x][y] = map.newtile(cx.TERRAIN[z])
            paper_map.t_[x][y].fg = drawval.COLORS["map-black"]
            paper_map.t_[x][y].bg = drawval.COLORS["map-white"]

    paper_map.walls_and_pits()

    for y in range(map_h):
        for x in range(map_w):
            if paper_map.t_[x][y].type == "wall":
                paper_map.t_[x][y].char += 64
            if paper_map.t_[x][y].type == "pit":
                paper_map.t_[x][y].fg = drawval.COLORS["map-black"]
                paper_map.t_[x][y].bg = drawval.COLORS["map-white"]
                paper_map.t_[x][y].char += 64
            if paper_map.t_[x][y].type == "floor":
                paper_map.t_[x][y].char = 32
            if paper_map.t_[x][y].type == "solidwall":
                paper_map.t_[x][y].char = 32
                paper_map.t_[x][y].fg = drawval.COLORS["map-white"]
                paper_map.t_[x][y].bg = drawval.COLORS["map-white"]
            for entity in entities:
                RAND_CHARS = [drawval.CHARS["gold"]]
                RAND_CHARS.extend(G_GLYPH_CHARS)
                if ((entity.x == x) and (entity.y == y) and entity.istrap):
                    if entity.dispname not in ("gold", "Boulder", "stairs",
                                               "artifact"):
                        paper_map.t_[x][y].char = G_GLYPH_CHARS[
                            entity.traptype]
                        paper_map.t_[x][y].fg = drawval.COLORS["map-red"]
                        paper_map.t_[x][y].type = "trap"
                    elif entity.dispname == "gold":
                        paper_map.t_[x][y].char = drawval.CHARS["gold"]
                        paper_map.t_[x][y].fg = drawval.COLORS["map-red"]
                    elif entity.dispname == "stairs":
                        paper_map.t_[x][y].char = drawval.CHARS["stairs"]
                        paper_map.t_[x][y].fg = drawval.COLORS["map-green"]
                    elif entity.dispname == "artifact":
                        paper_map.t_[x][y].char = drawval.CHARS["artifact"]
                        paper_map.t_[x][y].fg = drawval.COLORS["map-green"]
                    if player_floor > 1:
                        if entity.dispname not in ("stairs", "artifact"):
                            zrand = randint(0, len(RAND_CHARS) - 1)
                            paper_map.t_[x][y].char = RAND_CHARS[zrand]

    return level_map, paper_map
Esempio n. 5
0
def next_level():
    #advance to the next level
    global dungeon_level
    message('You take a moment to rest, and recover your strength.', ltc.light_violet)
    player.fighter.heal(player.fighter.max_hp / 2)  #heal the player by 50%
 
    dungeon_level += 1
    message('After a rare moment of peace, you descend deeper into the heart of the dungeon...', ltc.red)
    m.make_map()  #create a fresh new level!
    r.initialize_fov()
Esempio n. 6
0
def new_game():
	global game_state
	game_state = 'playing'
	#create the map
	maps.make_map()
	maps.init_fov()		
	draw.game_msgs = []
			
	#define initial objects
	objects.init()
	objects.create_player(maps.startx, maps.starty)
	objects.create_mom(maps.endx, maps.endy)
	objects.generate_monsters_and_items()
	
	draw.fov_update(objects.player.x, objects.player.y)
Esempio n. 7
0
def new_game():
    global game_state
    game_state = 'playing'
    #create the map
    maps.make_map()
    maps.init_fov()
    draw.game_msgs = []

    #define initial objects
    objects.init()
    objects.create_player(maps.startx, maps.starty)
    objects.create_mom(maps.endx, maps.endy)
    objects.generate_monsters_and_items()

    draw.fov_update(objects.player.x, objects.player.y)
Esempio n. 8
0
def get_task_turnpoints(task):
    turnpoints = task.read_turnpoints()
    max_n = 0
    total_dist = ''
    for tp in turnpoints:
        tp['original_type'] = tp['type']
        tp['partial_distance'] = '' if not tp['partial_distance'] else round(
            tp['partial_distance'] / 1000, 2)
        if int(tp['num']) > max_n:
            max_n = int(tp['num'])
            total_dist = tp['partial_distance']
        if tp['type'] == 'speed':
            if tp['how'] == 'entry':
                tp['type'] = 'SSS - Out/Enter'
            else:
                tp['type'] = 'SSS - In/Exit'
        elif tp['type'] == 'endspeed':
            tp['type'] = 'ESS'
        elif tp['type'] == 'goal':
            if tp['shape'] == 'circle':
                tp['type'] = 'Goal Cylinder'
            else:
                tp['type'] = 'Goal Line'
        else:
            tp['type'] = tp['type'].capitalize()
    if task.opt_dist is None or total_dist == '':
        total_dist = 'Distance not yet calculated'
    else:
        total_dist = str(total_dist) + "km"
    # max_n = int(math.ceil(max_n / 10.0)) * 10
    max_n += 1

    task_file = Path(MAPOBJDIR, 'tasks', str(task.task_id) + '.task')
    if task_file.is_file():
        with open(task_file, 'r') as f:
            data = jsonpickle.decode(f.read())
            task_coords = data['task_coords']
            map_turnpoints = data['turnpoints']
            short_route = data['short_route']
            goal_line = data['goal_line']
            tolerance = data['tolerance']
            bbox = data['bbox']
            layer = {'geojson': None, 'bbox': bbox}
            task_map = make_map(layer_geojson=layer,
                                points=task_coords,
                                circles=map_turnpoints,
                                polyline=short_route,
                                goal_line=goal_line,
                                margin=tolerance)
            task_map = task_map._repr_html_()

    else:
        task_map = None

    return {
        'turnpoints': turnpoints,
        'next_number': max_n,
        'distance': total_dist,
        'map': task_map
    }
Esempio n. 9
0
def new_game():
    #create object representing the player
    fighter_component = entities.Fighter(hp=100,
                                         defense=3,
                                         power=6,
                                         xp=0,
                                         death_function=entities.player_death)
    Game.player = entities.Object(data.SCREEN_WIDTH / 2,
                                  data.SCREEN_HEIGHT / 2,
                                  '@',
                                  'Roguetato',
                                  libtcod.white,
                                  tilechar=data.TILE_MAGE,
                                  blocks=True,
                                  fighter=fighter_component)

    Game.player.level = 1
    #generate map (at this point it's not drawn to screen)
    Game.dungeon_level = 1

    map.make_map(Game)
    map.initialize_fov(Game)

    Game.game_state = data.STATE_PLAYING
    Game.inventory = []

    #create the list of the game messages and their colors, starts empty
    Game.player.game_turns = 0

    #initial equipment
    equipment_component = entities.Equipment(slot='wrist', max_hp_bonus=5)
    obj = entities.Object(0,
                          0,
                          '-',
                          'wristguards of the whale',
                          libtcod.gold,
                          equipment=equipment_component)
    Game.inventory.append(obj)
    equipment_component.equip(Game)
    obj.always_visible = True

    #a warm welcoming message!
    message('Welcome to MeFightRogues! Good Luck! Don\'t suck!', Game,
            libtcod.blue)
Esempio n. 10
0
def multimap(trackid, extra_trackids):
    trackids = []
    for t in extra_trackids.split(','):
        trackids.append(t)
    # if trackids is None:
    #     map(trackid)
    layer = {}
    extra_layer = {}
    print(f"trackid={trackid} trackids={trackids}")
    wpt_coords, turnpoints, short_route, goal_line, tolerance = get_task_json(
        66)
    colours = [
        '#0000ff', '#33cc33', '#ffff00', '#9900cc', '#006600', '#3399ff',
        '#ff99cc', '#663300', '#99ffcc'
    ]
    # blue, green, yellow, purple, dark green,light blue, pink, brown, turquoise
    c = 0
    legend = {}
    extra_tracks = []
    for t in trackids:
        layer['geojson'] = read_tracklog_map_result_file(t, 66)
        track = {
            'name': t,
            'track': layer['geojson']['tracklog'],
            'colour': colours[c]
        }
        extra_tracks.append(track)
        legend[t] = colours[c]
        c += 1

    layer['geojson'] = read_tracklog_map_result_file(trackid, 66)
    layer['bbox'] = layer['geojson']['bounds']
    map = make_map(layer_geojson=layer,
                   points=wpt_coords,
                   circles=turnpoints,
                   polyline=short_route,
                   goal_line=goal_line,
                   margin=tolerance,
                   thermal_layer=False,
                   waypoint_layer=False,
                   extra_tracks=extra_tracks)
    waypoint_achieved_list = list(
        list(w for w in layer['geojson']['waypoint_achieved']))
    pilot_name = trackids
    c = 0

    map_id = map.get_name()

    macro = mapUtils.map_legend(legend)
    map.get_root().add_child(macro)
    map = map._repr_html_()
    return map
Esempio n. 11
0
 def new_game(self):
     global game_state, actors, game_log, player, stairs_up, stairs_down, level
     self.clean_stored_maps()
     game_state = enum.GameS.STARTUP
     actors = []
     game_log = []
     level = 1
     
     player = ent.Player(0,0)
     stairs_up = ent.Entity(1,2,"<", "upward staircase", blocks=False)
     stairs_down = ent.Entity(1,2,">", "downward staircase", blocks=False)
     
     actors.append(stairs_up)
     actors.append(stairs_down)
     actors.append(player)
     
     map.make_map()
     map.fov_recompute(player.x, player.y)
     
     stairs_up.x, stairs_up.y = (-1, -1)
     game_state = enum.GameS.IDLE
     tcod.console_flush()
Esempio n. 12
0
def new_game():
    # create object representing the player
    fighter_component = entities.Fighter(hp=100, defense=3, power=6, xp=0, death_function=entities.player_death)
    Game.player = entities.Object(
        data.SCREEN_WIDTH / 2,
        data.SCREEN_HEIGHT / 2,
        "@",
        "Roguetato",
        libtcod.white,
        tilechar=data.TILE_MAGE,
        blocks=True,
        fighter=fighter_component,
    )

    Game.player.level = 1
    # generate map (at this point it's not drawn to screen)
    Game.dungeon_level = 1

    map.make_map(Game)
    map.initialize_fov(Game)

    Game.game_state = data.STATE_PLAYING
    Game.inventory = []

    # create the list of the game messages and their colors, starts empty
    Game.player.game_turns = 0

    # initial equipment
    equipment_component = entities.Equipment(slot="wrist", max_hp_bonus=5)
    obj = entities.Object(0, 0, "-", "wristguards of the whale", libtcod.gold, equipment=equipment_component)
    Game.inventory.append(obj)
    equipment_component.equip(Game)
    obj.always_visible = True

    # a warm welcoming message!
    message("Welcome to MeFightRogues! Good Luck! Don't suck!", Game, libtcod.blue)
Esempio n. 13
0
def map(paridtaskid):
    from airspaceUtils import read_airspace_map_file
    from mapUtils import create_trackpoints_layer

    parid, taskid = paridtaskid.split("-")
    parid = int(parid)
    taskid = int(taskid)

    full_tracklog = bool(request.form.get('full'))
    layer = {}
    trackpoints = None
    '''task map'''
    wpt_coords, turnpoints, short_route, goal_line, tolerance, _, offset, airspace = get_map_json(taskid)

    '''tracklog'''
    layer['geojson'] = read_tracklog_map_result_file(parid, taskid)
    layer['bbox'] = layer['geojson']['bounds']
    pilot_name = layer['geojson']['info']['pilot_name']
    task_name = layer['geojson']['info']['task_name']
    '''full track log creation if requested'''
    if 'track_file' in layer['geojson']['info'] and full_tracklog:
        trackpoints = create_trackpoints_layer(layer['geojson']['info']['track_file'], offset)
    other_tracks = mapUtils.get_other_tracks(taskid, parid)

    '''airspace'''
    if airspace:
        airspace_layer = read_airspace_map_file(airspace)['spaces']
        infringements = layer['geojson']['infringements']
    else:
        airspace_layer = None
        infringements = None

    map = make_map(layer_geojson=layer, points=wpt_coords, circles=turnpoints, polyline=short_route,
                   goal_line=goal_line, margin=tolerance, thermal_layer=True, waypoint_layer=True,
                   airspace_layer=airspace_layer, infringements=infringements, trackpoints=trackpoints)
    waypoint_achieved_list = list(w for w in layer['geojson']['waypoint_achieved'])
    add_tracks = SelectAdditionalTracks()
    add_tracks.track_pilot_list = other_tracks
    return render_template('public/map.html',
                           other_tracks=other_tracks,
                           add_tracks=add_tracks,
                           map=get_map_render(map),
                           wpt_achieved=waypoint_achieved_list,
                           task={'name': task_name, 'id': taskid},
                           pilot={'name': pilot_name, 'id': parid},
                           full_tracklog=full_tracklog)
Esempio n. 14
0
def run_game():
    #Initialize game and create a screen object.
    pygame.init()
    settings = Settings()
    g.settings = Settings()

    g.settings_g = Settings()

    pygame.display.set_caption(settings.title)

    # Initialize Map
    grid = Grid(settings)
    g.tiles = Group()

    # Map Matrix initialisieren und Tiles hinzufügen
    tiles_init(settings, g.tiles)

    #Player
    fighter_comp = Fighter(hp=30,
                           defense=2,
                           power=5,
                           death_function=gf.player_death)
    g.player = GameObject(settings,
                          "player",
                          1,
                          1,
                          colors.gold,
                          img=r.player,
                          blocks=True,
                          fighter=fighter_comp)

    # Create Random Map
    make_map()

    # Initialize GUI and Inventory
    g.gui_elements = GUI(settings)
    g.inventory_menu = InventoryMenu(settings)

    #Print Welcome Message
    print_message("Welcome to the BEIDL", colors.black, colors.dark_red)

    #Initialize groups
    g.monster_group = Group()
    g.item_group = Group()
    g.dead_group = Group()
    g.inventory = Group()
    g.graphics_group = Group()
    """F**K AROUND"""
    #vvvvvvvvvvv#

    for i in range(10):
        testi_place_objects('item')

    for i in range(50):
        testi_place_objects('enemy')

    # """Test: Dummy Walls"""
    # g.map_matrix[4][5].blocked = True
    # g.map_matrix[4][5].block_sight = True
    # g.map_matrix[4][6].blocked = True
    # g.map_matrix[4][6].block_sight = True
    #
    # g.map_matrix[15][21].blocked = True
    # g.map_matrix[15][21].block_sight = True
    # g.map_matrix[16][21].blocked = True
    # g.map_matrix[16][21].block_sight = True

    #^^^^^^^^^#
    """F**K AROUND"""

    # Start the main loop for the game.
    while True:
        """MENU"""
        # Menu Screen
        #while settings.game_state == "menu":
        #gf.check_events_menu(settings, all_groups)
        #gf.update_screen_menu(settings, all_groups)
        """GAME"""
        #while g.game_state == "playing":
        while True:

            g.clock.tick(FPS)
            # ticks = pygame.time.get_ticks()

            gf.update_screen(settings)

            # Check game_state for Contol Setup
            # TODO game state control handling like this?
            if g.game_state == 'inventory':
                player_action = gf.controls_inventory(settings)
            else:
                player_action = gf.controls(settings, g.player)

            # Let Enemys take turns
            if g.game_state == 'playing' and player_action != "noturn":
                for obj in g.monster_group:
                    if obj.ai:
                        obj.ai.take_turn()

            # TODO Turn for using inventory item, redundant, use in game state?
            if player_action == "turn":
                for obj in g.monster_group:
                    if obj.ai:
                        obj.ai.take_turn()
Esempio n. 15
0
def findbirds(target_dir, output_dir):

    parks = []
    parknames = []
    sf = shapefile.Reader("UKParks.shp")

    for i in range(0, len(sf.shapeRecords())):
        parks.append(shape(sf.shapeRecord(i).shape))
        parknames.append(sf.record(i)[2])

    #darknet setup
    dn.set_gpu(0)
    #download yolov3.weights from  https://pjreddie.com/media/files/yolov3.weights
    net = dn.load_net("darknet/cfg/yolov3.cfg", "darknet/yolov3.weights", 0)
    meta = dn.load_meta("darknet/cfg/coco.data")

    #list of extensions to process
    extensions = ('.jpeg', '.jpg')

    font = cv2.FONT_HERSHEY_DUPLEX

    tick_img = cv2.imread("tick.png", -1)
    cross_img = cv2.imread("cross.png", -1)
    csvfile = open(output_dir + '/data.csv', 'w')
    csvfile.write(
        "\"Filename\",\"Latitude\",\"longitude\",\"Park Name\",\"Bird\"\n")

    #loop through all the image files in the target directory
    for subdir, dirs, files in os.walk(target_dir):
        print files
        for file in files:

            #only process extensions we're interested in
            fullfile = target_dir + "/" + file
            ext = os.path.splitext(fullfile)[-1].lower()

            if ext in extensions:
                print "Processing image " + file
                image = Image.open(fullfile)
                #get JPEG Exif header to find the GPS coordinates of the image
                exif_data = get_exif_data(image)
                image.close()
                lat_lon = get_lat_lon(exif_data)

                if lat_lon[0] is None:
                    print file + " has no geolocation data"
                    continue

                lat = lat_lon[0]
                lon = lat_lon[1]
                parkname = get_park_name(lat, lon, parks, parknames)

                #load the image and run the darknet/yolo detector on it
                im = cv2.imread(fullfile)
                r = dn.detect(net, meta, fullfile)
                birdfound = 0

                #loop through all the objects found by darknet
                for obj in r:
                    objclass = str(obj[0])
                    if objclass == "bird":
                        birdfound = 1

                        #get the image bounding box
                        x = int(obj[2][0])
                        y = int(obj[2][1])
                        h = int(obj[2][3])
                        w = int(obj[2][2])

                        x = x - (w / 2)
                        y = y - (h / 2)
                        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0),
                                      4)
                        cv2.putText(im, str(obj[0]), (x, y - 10), font, 2,
                                    (0, 255, 0), 2)

                #draw the text in black and white with slight offsets between them
                #this makes it readable whether there's a dark or light area under it
                cv2.putText(im, "Bird:", (850, 150), font, 3, (255, 255, 255),
                            2)
                cv2.putText(im, "Bird:", (854, 154), font, 3, (0, 0, 0), 2)

                #display tick/cross images depending on whether the image has a bird
                #and was taken in a park or not
                if birdfound == 1:
                    overlay_image(1100, 80, tick_img, im)

                else:
                    overlay_image(1100, 80, cross_img, im)

                cv2.putText(im, "Park:", (1500, 150), font, 3, (255, 255, 255),
                            2)
                cv2.putText(im, "Park:", (1504, 154), font, 3, (0, 0, 0), 2)

                if parkname is None:
                    overlay_image(1800, 80, cross_img, im)
                    parkname = "none"

                else:
                    overlay_image(1800, 80, tick_img, im)

                #resize output file so its not so big
                small = cv2.resize(im, (0, 0), fx=0.35, fy=0.35)

                #draw the map of the geolocation onto the image
                make_map(lat, lon, small, output_dir + "/" + file)

                #save output to a CSV file
                csvfile.write("\"%s\",%f,%f,%s,%d\n" %
                              (fullfile, lat, lon, parkname, birdfound))

    csvfile.close()