示例#1
0
    def key_down(self, key):

        if self.game == True:
            if key in (K_w, K_UP):
                self.player.dir[0] = 1
            if key in (K_a, K_LEFT):
                self.player.dir[1] = 1
            if key in (K_s, K_DOWN):
                self.player.dir[2] = 1
            if key in (K_d, K_RIGHT):
                self.player.dir[3] = 1
            if key == K_ESCAPE:
                pygame.quit()
            if key == K_2:
                if self.cd2 < self.delta_time:
                    self.ball = Powers(self.player.level, self.player.rect.center)
                    self.ball.fire_ball()
                    if self.player.mana >= self.ball.manacost:
                        self.ball.set_collision(self.rooms, self.l_mobs)
                        self.powergroup.add(self.ball.effect)
                        self.ball.effect.fire(self.player.rect.center, self.b_pos)
                        self.player.shout_spell(self.ball.name)
                        self.player.mana -= self.ball.manacost
                        self.cd2 = self.delta_time + self.ball.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_3:
                if self.cd3 < self.delta_time:
                    self.cone = Powers(self.player.level, self.player.rect.center)
                    self.cone.cone_of_frost()
                    if self.player.mana >= self.cone.manacost:
                        self.b3 = True
                        self.cone.set_collision(None, self.l_mobs)
                        self.powergroup.add(self.cone.effect)
                        self.player.shout_spell(self.cone.name)
                        self.player.mana -= self.cone.manacost
                        self.cd3 = self.delta_time + self.cone.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_4:
                if self.cd4 < self.delta_time:
                    self.ring = Powers(self.player.level, self.player.rect.center)
                    self.ring.ring_of_fire()
                    if self.player.mana >= self.ring.manacost:
                        self.ring.set_collision(None, self.l_mobs)
                        self.powergroup.add(self.ring.effect)
                        self.ring.effect.fire(self.player.rect.center, None)
                        self.player.shout_spell(self.ring.name)
                        self.player.mana -= self.ring.manacost
                        self.cd4 = self.delta_time + self.ring.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_p:
                if self.player_window.state == False:
                    self.player_window.update()
                    self.player_window.state = True
                elif self.player_window.state == True:
                    self.player_window.state = False
            if key == K_LSHIFT:
                self.mouse_over.state = 2
示例#2
0
    def mouse_down(self, button, pos):

        if self.game == True:
            if button == 1:
                if self.player_window.state == True:
                    self.player_window.mouse_button(button)
                if self.cd1 < self.delta_time:
                    self.missile = Powers(self.player.level, self.player.rect.center)
                    self.missile.magic_missile()
                    if self.player.mana >= self.missile.manacost:
                        self.missile.set_collision(self.rooms, self.l_mobs)
                        self.powergroup.add(self.missile.effect)
                        self.missile.effect.fire(self.player.rect.center, self.b_pos)
                        self.player.shout_spell(self.missile.name)
                        self.player.mana -= self.missile.manacost
                        self.cd1 = self.delta_time + self.missile.cooldown
                    else:
                        print "Not enough Mana"
        else:
            if button == 1:
                menu_button = self.start_menu.mouse_press()
                if menu_button == 1:
                    self.player = Player()
                    self.player.level_init()
                    self.game_init()
                elif menu_button == 3:
                    self.running = False
示例#3
0
class Game(Engine):
    def __init__(self):
        # First I load my chosen screen size and use it to override the default one, while initializing the engine.
        self.w = 1240
        self.h = 960
        Engine.__init__(self, size=(self.w, self.h), fill=(255, 255, 255))
        self.screen_rect = pygame.Rect(0, 0, self.w, self.h)

        # Here we set up an image file for the mouse cursor
        # (making sure to convert it and keep transparency)
        self.mouse_over = MouseOver()
        self.mouse_image = self.mouse_over.mouse_img()
        self.mouse_rect = self.mouse_image.get_rect()
        self.mouse_pos = (0, 0)

        self.player = Player()
        self.player.level_init()
        self.inventory = Inventory()

        self.current_level = 0
        self.game = False
        self.start_menu = StartMenu((self.w, self.h))
        self.start_menu.update()

    def game_init(self):

        # Some colors, these will change.
        blackColor = (0, 0, 0)
        white_color = (255, 255, 255)
        sgidarkgray = (85, 85, 85)
        yellowColor = (255, 255, 0)

        # Setting up the background surface (the game map).
        self.blocksize = 32
        self.background = GameSurface((8000, 8000), (0, 0), blackColor)
        self.bg = pygame.sprite.LayeredDirty(self.background)

        # Here we start making the map. (This takes the longest time to load)
        self.rooms = self.generate_levels(self.blocksize, self.background.levelsize)
        self.add_exit(self.rooms, self.blocksize)

        # Here I load up the player, and the variables necessary
        # for movement and rotation.
        self.cp = pygame.Rect(0, 0, self.player.rect.width, self.player.rect.height)
        self.player.set_collide(self.rooms)

        # Here we mage the Gui
        self.gui = GUI((self.w, self.h), self.player)
        self.player_window = PlayerWindow((self.w, self.h), self.player)
        self.power_window = PowerWindow((self.w, self.h), self.player)
        self.power_window.update()
        self.test_text = []

        # Some Timer variables.
        self.time_passed = self.clock.get_fps()
        self.cd1 = 0.0
        self.cd2 = 0.0
        self.cd3 = 0.0
        self.cd4 = 0.0

        # Then we need to set up the rooms, placing the player in the first one.
        # (and centering the screen on him)
        self.background.rect.x, self.background.rect.y = self.set_rooms(
            self.rooms, self.player, self.background.rect.x, self.background.rect.y, self.cp, self.w, self.h
        )

        # Time to add some mobs.
        self.mobs = self.add_mobs((random.randint(1, 10)), self.rooms, self.player, self.background)
        self.l_mobs = []

        # And we set up the players powers
        self.powergroup = pygame.sprite.LayeredDirty()
        self.b3 = False

        self.game = True

    def generate_levels(self, block, size):

        if self.current_level == 0:
            rooms = self.generate_room(block, (size[0] / 4, size[1] / 4))
            self.current_level += 1
        elif self.current_level == 1:
            rooms = self.generate_room(block, (size[0] / 2.5, size[1] / 2.5))
            self.current_level += 1
        elif self.current_level == 2:
            rooms = self.generate_room(block, (size[0] / 2, size[1] / 2))
            self.current_level += 1
        elif self.current_level == 3:
            rooms = self.generate_room(block, size)

        return rooms

    # the update method. This one is called in the game_loop (from the engine)
    # but it must be run in this file.
    def update(self):
        self.mouse_image = self.mouse_over.mouse_img()

        if self.game == True:
            if self.player.nextlevel == True:
                self.player.nextlevel = False
                self.game_init()

            # Updating the gui.
            self.gui.update(self.player)

            # This is the rectangle for our screen.
            self.screen_rect.topleft = (-self.background.rect.x, -self.background.rect.y)
            # We then use that rectangle to cut away anything we do not need to render.
            self.limit_rooms(self.rooms, self.screen_rect)
            self.l_mobs = self.limit_mobs(self.screen_rect, self.mobs)

            # Adding the cut down sprites to the draw group.
            self.wallsprites = self.add_rooms()

            self.mobgroup = pygame.sprite.LayeredDirty()
            self.mobgroup.add(self.player)
            self.mobgroup.add(self.l_mobs)

            self.inventory.update(self.player)

            # Movement for the player.
            self.player.move(self.player.dir, self.cp, (self.w, self.h))
            self.cp.x, self.cp.y = self.find_position(
                self.player.rect.x, self.player.rect.y, self.background.rect.x, self.background.rect.y
            )

            # Here we scroll the map using the mouse pointer.
            self.map_move(self.background, self.cp, self.w, self.h)

            if self.b3 == True:
                self.cone.effect.fire(self.player.rect.center, self.b_pos, self.delta_time)

            self.greenbars = []
            self.redbars = []
            for mob in self.l_mobs:
                mob.run(self.rooms, self.l_mobs, self.player, self.delta_time)
                redbar, greenbar = mob.health_bar()
                self.redbars.append(redbar)
                self.greenbars.append(greenbar)
                if mob.state == "DEAD":
                    self.inventory.spawn_item(mob)

            self.mouse_over.check_mobs(self.l_mobs, self.background)
            self.mouse_over.check_tiles(self.wallsprites, self.background)
            if self.player.state == "DEAD":
                self.game = False
                self.current_level = 0
                self.start_menu.select(2)
                self.start_menu.update()

    # The draw function. This is where things are actually drawn to screen.
    # Its called in the engines mainloop, but must be run in this file.
    def draw(self):

        if self.game == True:

            # Here we clip to the clipping rectangle.
            self.wallsprites.set_clip(self.screen_rect)
            # And run the necesary updates.
            self.wallsprites.update()
            self.mobgroup.update(self.delta_time)
            self.powergroup.update(self.delta_time)

            # Now we draw things in order.
            # First we draw the levels.
            self.wallsprites.draw(self.background.image)

            # Then we draw the Player and mobs.
            self.mobgroup.draw(self.background.image)
            for mob in self.mobgroup:
                if mob.state == "SHOUTING":
                    self.background.image.blit(mob.mssg, mob.mssg_rect)

            # Then we draw the Inventory items
            self.inventory.draw(self.background.image)

            # Then we draw the powers.
            self.powergroup.draw(self.background.image)
            for power in self.powergroup:
                if power.state == "EXPLODING":
                    pygame.draw.circle(self.background.image, (255, 255, 255), power.pos.inttup(), power.radius, 1)
                elif power.state == "CONE":
                    pygame.draw.aalines(self.background.image, (255, 255, 255), True, power.vectorlist)

            # Here we draw the healthbars of the mobs.
            for bars in self.redbars:
                pygame.draw.rect(self.background.image, pygame.Color("red"), bars)
            for bars in self.greenbars:
                pygame.draw.rect(self.background.image, pygame.Color("green"), bars)

            pygame.draw.rect(self.background.image, (255, 255, 255), self.screen_rect, -1)

            # Then we draw the everything to the screen.
            self.bg.draw(self.screen)

            # Everything below this line is drawn directly to the Screen
            #  not the Background Surface

            # Then we draw the GUI.
            self.gui.draw(self.screen)
            if self.player_window.state == True:
                self.player_window.draw(self.screen)
            if self.player_window.powerstate == True:
                self.player_window.state = False
                self.power_window.draw_window(self.screen)
        else:
            self.start_menu.draw(self.screen)

        # Then we draw the mousepointer.
        self.mouse_over.draw(self.screen)
        self.screen.blit(self.mouse_image, self.mouse_pos)
        pygame.display.update()

    def user_event(self, event):
        pass

    # An event method giving us all key down presses.
    def key_down(self, key):

        if self.game == True:
            if key in (K_w, K_UP):
                self.player.dir[0] = 1
            if key in (K_a, K_LEFT):
                self.player.dir[1] = 1
            if key in (K_s, K_DOWN):
                self.player.dir[2] = 1
            if key in (K_d, K_RIGHT):
                self.player.dir[3] = 1
            if key == K_ESCAPE:
                pygame.quit()
            if key == K_2:
                if self.cd2 < self.delta_time:
                    self.ball = Powers(self.player.level, self.player.rect.center)
                    self.ball.fire_ball()
                    if self.player.mana >= self.ball.manacost:
                        self.ball.set_collision(self.rooms, self.l_mobs)
                        self.powergroup.add(self.ball.effect)
                        self.ball.effect.fire(self.player.rect.center, self.b_pos)
                        self.player.shout_spell(self.ball.name)
                        self.player.mana -= self.ball.manacost
                        self.cd2 = self.delta_time + self.ball.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_3:
                if self.cd3 < self.delta_time:
                    self.cone = Powers(self.player.level, self.player.rect.center)
                    self.cone.cone_of_frost()
                    if self.player.mana >= self.cone.manacost:
                        self.b3 = True
                        self.cone.set_collision(None, self.l_mobs)
                        self.powergroup.add(self.cone.effect)
                        self.player.shout_spell(self.cone.name)
                        self.player.mana -= self.cone.manacost
                        self.cd3 = self.delta_time + self.cone.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_4:
                if self.cd4 < self.delta_time:
                    self.ring = Powers(self.player.level, self.player.rect.center)
                    self.ring.ring_of_fire()
                    if self.player.mana >= self.ring.manacost:
                        self.ring.set_collision(None, self.l_mobs)
                        self.powergroup.add(self.ring.effect)
                        self.ring.effect.fire(self.player.rect.center, None)
                        self.player.shout_spell(self.ring.name)
                        self.player.mana -= self.ring.manacost
                        self.cd4 = self.delta_time + self.ring.cooldown
                    else:
                        print "Not enough Mana"
            if key == K_p:
                if self.player_window.state == False:
                    self.player_window.update()
                    self.player_window.state = True
                elif self.player_window.state == True:
                    self.player_window.state = False
            if key == K_LSHIFT:
                self.mouse_over.state = 2

    # An event method giving us all key up presses.
    def key_up(self, key):

        if self.game == True:
            if key in (K_w, K_UP):
                self.player.dir[0] = 0
            if key in (K_a, K_LEFT):
                self.player.dir[1] = 0
            if key in (K_s, K_DOWN):
                self.player.dir[2] = 0
            if key in (K_d, K_RIGHT):
                self.player.dir[3] = 0
            if key == K_3:
                self.b3 = False
                self.cone.effect.state = "DEAD"
            if key == K_LSHIFT:
                self.mouse_over.state = 1

    # Two event Methods for the mouse keys (down and up). buttons are 1=left , 2=middle, 3=right.
    def mouse_down(self, button, pos):

        if self.game == True:
            if button == 1:
                if self.player_window.state == True:
                    self.player_window.mouse_button(button)
                if self.cd1 < self.delta_time:
                    self.missile = Powers(self.player.level, self.player.rect.center)
                    self.missile.magic_missile()
                    if self.player.mana >= self.missile.manacost:
                        self.missile.set_collision(self.rooms, self.l_mobs)
                        self.powergroup.add(self.missile.effect)
                        self.missile.effect.fire(self.player.rect.center, self.b_pos)
                        self.player.shout_spell(self.missile.name)
                        self.player.mana -= self.missile.manacost
                        self.cd1 = self.delta_time + self.missile.cooldown
                    else:
                        print "Not enough Mana"
        else:
            if button == 1:
                menu_button = self.start_menu.mouse_press()
                if menu_button == 1:
                    self.player = Player()
                    self.player.level_init()
                    self.game_init()
                elif menu_button == 3:
                    self.running = False

    def mouse_up(self, button, pos):
        pass

    # Event method for mouse motion.
    def mouse_motion(self, buttons, pos, rel):
        self.mouse_pos = pos
        self.mouse_over.update_pos(pos)

        if self.game == True:
            if self.player_window.state == True:
                self.player_window.mouse_mov(pos, buttons)

            b_pos_x = pos[0] - self.background.rect.x
            b_pos_y = pos[1] - self.background.rect.y
            self.b_pos = (b_pos_x, b_pos_y)

            # Here we call the method to rotate the mouse.
            self.player.rot = self.rotate(
                (self.cp.centerx, self.cp.centery),
                (self.mouse_pos[0] + (self.mouse_rect.width / 2), self.mouse_pos[1] + (self.mouse_rect.height / 2)),
            )
            self.player.image = self.rotate_image(self.player.base_img, (self.player.rot))

            self.map_scroll(self.mouse_pos, self.w, self.h)
        else:
            self.start_menu.mouse_mov(self.mouse_pos)

    def screen_message(self, text):
        pass
示例#4
0
def importDownloaded(db):
  if not os.path.exists(Options.getPath('systems.json')) or not os.path.exists(Options.getPath('commodities.json')) or not os.path.exists(Options.getPath('stations.json')):
    print("eddb json files missing! - required: systems.json, commodities.json, stations.json")
    return False

  # -- commodities --

  print("importing eddb commodities")
  commoditiesdata = readJSON("commodities.json")
  if commoditiesdata is None:
    print("parsing commodities.json failed")
    return False

  # remap database columns
  for commodity in commoditiesdata:
    commodity['average']=commodity['average_price']

  # insert into db and retrieve new ids
  importedCommodities=db.importCommodities(commoditiesdata)

  # name to id map
  importedCommoditiesMap=dict( (o["name"].lower(),o["id"]) for o in importedCommodities )

  # eddb to EliteDB id map
  commodities_importmap=dict( (o["id"],importedCommoditiesMap[o["name"].lower()]) for o in commoditiesdata )

  # commodityname to EliteDB id map (for prohibited commodities later on)
  importedCommoditiesByName=dict( (o["name"],importedCommoditiesMap[o["name"].lower()]) for o in commoditiesdata )

  # -- systems --

  systemsdata = readJSON("systems.json")
  if systemsdata is None:
    print("parsing systems.json failed")
    return False

  print('resolving system allegiances')

  allegiance={
    None:None,
    "Empire":3,
    "Federation":2,
    "Alliance":1
  }

  def distance3d(x,y,z,i,j,k):
    return ((x-i)**2+(y-j)**2+(z-k)**2)**.5

  powerstats=dict()

  # reformat faction allegiances, find power control systems
  for system in systemsdata:
    if system['allegiance'] in allegiance:
      system['allegiance']=allegiance[system['allegiance']]
    else:
      system['allegiance']=0

    # control systems
    system['controlled']=None
    system['exploited']=None
    if system['power_state']=='Expansion': # we don't care about expansion
      continue
    powerid=Powers.nameToVal(system['power'])
    if system['power_state']=='Exploited':
      system['exploited']=powerid
    if system['power_state']=='Control':
      system['controlled']=powerid
      system['exploited']=powerid
    if system['power_state']=='Contested':
      system['exploited']=-1

    if system['power'] is not None:
      if system['power'] not in powerstats:
        powerstats[system['power']]={
          'Control':0,
          'Exploited':0
        }
      powerstats[system['power']][system['power_state']]+=1

  for power in powerstats:
    print(power +" has "+ str(powerstats[power]['Control']) +" Control systems & "+ str(powerstats[power]['Exploited']) +" Exploited systems")

  print("importing eddb systems")

  # insert into db and retrieve new ids
  importedSystems=db.importSystems(systemsdata)

  # name to id map
  importedSystemsMap=dict( (o["name"].lower(),o["id"]) for o in importedSystems )

  # eddb to EliteDB id map
  systems_importmap=dict( (o["id"],importedSystemsMap[o["name"].lower()]) for o in systemsdata )

  # id to row map
  systemRowById=dict( (o["id"],o) for o in importedSystems )


  # -- stations --

  print("importing eddb stations")
  stationsdata = readJSON("stations.json")
  if stationsdata is None:
    print("parsing stations.json failed")
    return False

  # remap database
  for station in stationsdata:
    station["systemId"]=systems_importmap[station["system_id"]]
    station["distance"]=station["distance_to_star"]
    system=systemRowById[station["systemId"]]
    Powers.applyPowerPolicy(system['controlled'],system['exploited'],[station])

  # insert into db and retrieve new ids
  importedStations=db.importBases(stationsdata)

  # name to id map
  importedStationsMap=dict( (o["name"].lower()+'~'+str(o["systemId"]),o["id"]) for o in importedStations )

  # eddb to EliteDB id map
  stations_importmap=dict( (o["id"],importedStationsMap[o["name"].lower()+'~'+str(o["systemId"])]) for o in stationsdata )

  # -- station metadata --

  print("importing eddb station metadata")

  padsize={
    None:None,
    "S":0,
    "M":1,
    "L":2
  }
  # remap database
  for station in stationsdata:
    station["id"]=stations_importmap[station["id"]]
    station["blackMarket"]=station["has_blackmarket"]
    station["landingPadSize"]=padsize[station["max_landing_pad_size"]]

  db.importBaseInfos(stationsdata)

  # -- merge market data --

  print("reading eddb listings")

  listingsdata = readCSV("listings.csv")
  if listingsdata is None:
    print("parsing listings.csv failed")
    return False

  print("importing eddb market data")

  # limit data age - allow twice the age for desperate routes
  #validityhorizon=float( time.time() - (60*60*24* int(Options.get("Market-valid-days", 7) *2 ) ))
  validityhorizon=0 # do filtering in db - for more desperate routes

  marketdata=[]
  prohibiteddata=[]

  for listing in listingsdata:
    for col in listing:
      listing[col]=int(listing[col]) # python csv parsing is shit so we do it live
    listing["station_id"]=stations_importmap[listing["station_id"]]
    if validityhorizon < listing["collected_at"]: # no old data
      listing["baseId"]=listing["station_id"] # stationid already remapped
      listing["commodityId"]=commodities_importmap[listing["commodity_id"]]
      listing["importPrice"]=listing["sell_price"] # note: eddb works from the perspective of the player - "sell" is import, "buy" is export
      listing["exportPrice"]=listing["buy_price"]
      listing["lastUpdated"]=listing["collected_at"]
      marketdata.append(listing)
      # todo: remove legals
      #legalcommodities.append(commodities_importmap[commodity["commodity_id"]]) # keep track for black market

  # -- station market data --

  # remap database
  for station in stationsdata:
    legalcommodities=[]
    if station['has_blackmarket']:
      for contraband in station['prohibited_commodities']: # black market listings
        if importedCommoditiesByName[contraband] not in legalcommodities: # only add if not in legal market
          item=dict()
          item['baseId']=station['id']
          item['commodityId']=importedCommoditiesByName[contraband]
          prohibiteddata.append(item)

  db.importCommodityPrices(marketdata)

  print("importing eddb black market data")

  db.deleteProhibitedCommodities() # these may change a lot if station changes owner - better to nuke on update

  db.importProhibitedCommodities(prohibiteddata)

  #db.vacuum() # todo: uncomment if skipping this causes slowdown

  print("eddb import complete")
示例#5
0
        def data(self, index, role):
            if not index.isValid():
                return None
            if index.row() >= len(self.mw.result):
                return None
            data = self.mw.result[index.row()]
            section=index.column()

            columnorder=self.columnorder[self.mw.searchType]

            if section >= len(columnorder):
                return None

            # roles:    http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum

            ########### ICONS ##################

            if role == QtCore.Qt.DecorationRole:
                if "celltype" not in data:
                  if columnorder[section] in ["Asystemname"]:
                    powerid=None
                    if data['Acontrolled'] is not None:
                      powerid=data['Acontrolled']
                    if data['Aexploited'] is not None:
                      powerid=data['Aexploited']
                    if powerid is not None and powerid != -1:
                      return QtGui.QPixmap("img/power_"+str(powerid)+".png")
                  if columnorder[section] in ["Bsystemname"]:
                    powerid=None
                    if data['Bcontrolled'] is not None:
                      powerid=data['Bcontrolled']
                    if data['Bexploited'] is not None:
                      powerid=data['Bexploited']
                    if powerid is not None and powerid != -1:
                      return QtGui.QPixmap("img/power_"+str(powerid)+".png")
                  if columnorder[section] in ["commodityname"]:
                    if data['blackmarket']==1:
                      return QtGui.QPixmap("img/illegal.png")

            ########### TEXT COLOR ###########

            if role == QtCore.Qt.TextColorRole:
                if "celltype" not in data:
                  if columnorder[section] in ["AexportPrice"]:
                    if int(data['AlastUpdated'])<time.time()-60*60*24*int(Options.get('Market-valid-days',7)):
                      return QtGui.QBrush(QtGui.QColor(255,255,0))
                  if columnorder[section] in ["Asupply"]:
                    if int(data['Asupply']<100):
                      return QtGui.QBrush(QtGui.QColor(255,255,0))
                  if columnorder[section] in ["BimportPrice"]:
                    if int(data['BlastUpdated'])<time.time()-60*60*24*int(Options.get('Market-valid-days',7)):
                      return QtGui.QBrush(QtGui.QColor(255,255,0))
                  if columnorder[section] in ["commodityname"]:
                    if data['blackmarket']==1:
                      return QtGui.QBrush(QtGui.QColor(250,250,250))


            ########### BACKGROUND COLOR ##########

            if role == QtCore.Qt.BackgroundRole:
                if "celltype" in data:
                    if data["celltype"]=='emptyrow':
                        return QtGui.QBrush(QtGui.QColor(255,255,255))
                    if data["celltype"]=='separatorrow':
                        return QtGui.QBrush(QtGui.QColor(200,200,200))
                if columnorder[section] in ["Asystemname","Abasename"]:
                    if data['Aallegiance']==1:
                      return QtGui.QBrush(QtGui.QColor(200,255,200))
                    if data['Aallegiance']==2:
                      return QtGui.QBrush(QtGui.QColor(255,200,200))
                    if data['Aallegiance']==3:
                      return QtGui.QBrush(QtGui.QColor(200,200,255))
                    return QtGui.QBrush(QtGui.QColor(255,255,230))
                if columnorder[section] in ["Bsystemname","Bbasename"]:
                    if data['Ballegiance']==1:
                      return QtGui.QBrush(QtGui.QColor(200,255,200))
                    if data['Ballegiance']==2:
                      return QtGui.QBrush(QtGui.QColor(255,200,200))
                    if data['Ballegiance']==3:
                      return QtGui.QBrush(QtGui.QColor(200,200,255))
                    return QtGui.QBrush(QtGui.QColor(255,255,230))
                if columnorder[section] in ["AexportPrice"]:
                    r,g,b=self.mw.AgeToColor(data['AlastUpdated'])
                    return QtGui.QBrush(QtGui.QColor(r,g,b))
                if columnorder[section] in ["BimportPrice"]:
                    r,g,b=self.mw.AgeToColor(data['BlastUpdated'])
                    return QtGui.QBrush(QtGui.QColor(r,g,b))
                if columnorder[section] in ["Asupply"]:
                    b=(data['Asupply'])/5000
                    g=b*2
                    g=max(min(1,g),0)*255
                    b=max(min(1,b),0)*255
                    r=255
                    return QtGui.QBrush(QtGui.QColor(r,g,b))
                if columnorder[section] in ["profit","Cprofit","totalprofit"]:
                    return QtGui.QBrush(QtGui.QColor(255,230,255))
                if columnorder[section] in ["commodityname"]:
                    if data['blackmarket']==1:
                      return QtGui.QBrush(QtGui.QColor(0,0,0))

                return QtGui.QBrush(QtGui.QColor(255,255,255)) # everything else is white

            ############ TOOLTIPS ###############

            if role == QtCore.Qt.ToolTipRole:

                if "averageprofit" in data: # this is a graph search
                    if columnorder[section] == "profit":
                        ret="Loop average profit: "+str(data["averageprofit"])\
                            +"\nLoop max profit: "+str(data["loopmaxprofit"])\
                            +"\nLoop min profit: "+str(data["loopminprofit"])
                        if "celltype" not in data:
                            ret+= "\nBuy for "+str(data["AexportPrice"])\
                                +"\nSell for "+str(data["BimportPrice"])\
                                +"\nProfit:    "+str(data["profit"])
                        return ret
                    if columnorder[section] == "profitPh":
                        ret="Loop average profit: "+str(data["averageprofit"])\
                            +"\nLoop max profit: "+str(data["loopmaxprofit"])\
                            +"\nLoop min profit: "+str(data["loopminprofit"])
                        if "celltype" not in data:
                            ret+= "\nBuy for "+str(data["AexportPrice"])\
                                  +"\nSell for "+str(data["BimportPrice"])\
                                  +"\nProfit:    "+str(data["profit"])\
                                  +"\nProfit/h:"+str(int(data["profit"]/data["hours"]))
                        return ret
                    else:
                        if "celltype" in data:
                            return None

                if columnorder[section] == "_curdist":
                    if self.mw.currentSystem is None:
                        return
                    else:
                        curname=self.mw.currentSystem.getName() # todo: ship range
                        pos=self.mw.currentSystem.getPosition()
                        dist=( (pos[0]-data["Ax"])**2 + (pos[1]-data["Ay"])**2 + (pos[2]-data["Az"])**2 ) ** 0.5
                        return "Distance from "+curname+" (current system)\n" \
                            "to "+data["Asystemname"]+" (commodity seller) is "+("%.2f" % dist)+"ly " \
                            "("+str("%.2f" % (SpaceTime.BaseToBase(dist)/60))+"min)"
                elif columnorder[section] == "_Bcurdist":
                    if self.mw.currentSystem is None:
                        return
                    else:
                        curname=self.mw.currentSystem.getName() # todo: ship range
                        pos=self.mw.currentSystem.getPosition()
                        dist=( (pos[0]-data["Bx"])**2 + (pos[1]-data["By"])**2 + (pos[2]-data["Bz"])**2 ) ** 0.5
                        return "Distance from "+curname+" (current system)\n" \
                            "to "+data["Bsystemname"]+" (commodity seller) is "+("%.2f" % dist)+"ly " \
                            "("+str("%.2f" % (SpaceTime.BaseToBase(dist)/60))+"min)"

                elif columnorder[section] == "AexportPrice":
                    return "Data "+str("%.2f" %((time.time()-data['AlastUpdated'])/(60*60*24)))+" days old"\
                          +"\nExport sales price: "+str(data["AexportPrice"])+"\nSupply: "+str(data["Asupply"])
                elif columnorder[section] == "BexportPrice":
                    return "Export sales price: "+str(data["BexportPrice"])+"\nSupply: "+str(data["Bsupply"])
                elif columnorder[section] == "commodityname":
                    return "Commodity "+data["commodityname"]\
                           +"\nData "+str("%.2f" %((time.time()-min(data['AlastUpdated'],data['BlastUpdated']))/(60*60*24)))+" days old"\
                           +"\nBuy for "+str(data["AexportPrice"])\
                           +"\nSell for "+str(data["BimportPrice"])\
                           +"\nProfit:    "+str(data["profit"])\
                           +"\nGalactic average price: "+str(data["average"])
                elif columnorder[section] == "Ccommodityname":
                    return "Commodity "+data["Ccommodityname"]\
                           +"\nBuy for "+str(data["BexportPrice"])\
                           +"\nSell for "+str(data["CimportPrice"])\
                           +"\nProfit:    "+str(data["Cprofit"])\
                           +"\nGalactic average price: "+str(data["Caverage"])
                elif columnorder[section] == "BimportPrice":
                    return "Data "+str("%.2f" %((time.time()-data['BlastUpdated'])/(60*60*24)))+" days old"\
                          +"\nImport buy price: "+str(data["BimportPrice"])+"\nDemand: "+str(data["Bdemand"])
                elif columnorder[section] == "CimportPrice":
                    return "Import buy price: "+str(data["CimportPrice"])+"\nDemand: "+str(data["Cdemand"])
                elif columnorder[section] in ["Asystemname","Abasename"]:
                    padsize={
                        None:"unknown",
                        0:'S',
                        1:'M',
                        2:'L'
                    }
                    returnstring=""

                    if data['Acontrolled'] is not None:
                      returnstring+='System controlled by '+Powers.valToName( data['Acontrolled'] ) +'\n'
                    elif data['Aexploited'] is not None and data['Aexploited'] != -1:
                      returnstring+='System exploited by '+Powers.valToName( data['Aexploited'] ) +'\n'
                    elif data['Aexploited'] == -1:
                      returnstring+='System contested by opposing powers\n'

                    if data['Aallegiance'] is  not None and int(data['Aallegiance']) != 0:
                      allegiance={
                        0:'None',
                        1:'Allegiance',
                        2:'Federation',
                        3:'Empire'
                      }
                      returnstring+="Allegiance: "+allegiance[int(data['Aallegiance'])]+"\n"
                    returnstring+="System: "+data["Asystemname"]+"\n"
                    returnstring+="Station: "+data["Abasename"]+"\n"
                    returnstring+="Distance to star: "+str(data["Adistance"] is not None and (str(data["Adistance"])
                    +" ("+str("%.2f" % (SpaceTime.StarToBase(data["Adistance"])/60))+"min)") or "unknown")+"\n"
                    returnstring+="Landing pad size: "+padsize[data["AlandingPadSize"]]
                    return returnstring
                elif columnorder[section] in ["Bsystemname","Bbasename"]:
                    padsize={
                        None:"unknown",
                        0:'S',
                        1:'M',
                        2:'L'
                    }
                    returnstring=""

                    if data['Bcontrolled'] is not None:
                      returnstring+='System controlled by '+Powers.valToName( data['Bcontrolled'] ) +'\n'
                    elif data['Bexploited'] is not None and data['Bexploited'] != -1:
                      returnstring+='System exploited by '+Powers.valToName( data['Bexploited'] ) +'\n'
                    elif data['Bexploited'] == -1:
                      returnstring+='System contested by opposing powers\n'

                    if data['Ballegiance'] is  not None and int(data['Ballegiance']) != 0:
                      allegiance={
                        0:'None',
                        1:'Allegiance',
                        2:'Federation',
                        3:'Empire'
                      }
                      returnstring+="Allegiance: "+allegiance[int(data['Ballegiance'])]+"\n"
                    returnstring+="System: "+data["Bsystemname"]+"\n"
                    returnstring+="Station: "+data["Bbasename"]+"\n"
                    returnstring+="Distance to star: "+str(data["Bdistance"] is not None and (str(data["Bdistance"])
                    + " ("+str("%.2f" %(SpaceTime.StarToBase(data["Bdistance"])/60))+"min)") or "unknown")+"\n"
                    returnstring+="Landing pad size: "+padsize[data["BlandingPadSize"]]
                    return returnstring
                elif columnorder[section] == "DistanceSq":
                    return "Travel distance "+str(data["DistanceSq"]**0.5)+"ly + "+\
                                str(data["Bdistance"] is not None and data["Bdistance"] or "unknown")+"ls from star to station"
                elif columnorder[section] == "SystemDistance":
                    return "Travel distance "+str(data["SystemDistance"])+"ly + "+\
                                str(data["Bdistance"] is not None and data["Bdistance"] or "unknown")+"ls from star to station\n"+\
                                str(data["Bdistance"] is not None and str("%.2f" % (SpaceTime.StarToBase(data["Bdistance"])/60))+"min" or "")
                elif columnorder[section] == "profit":
                    return "Buy for "+str(data["AexportPrice"])\
                                 +"\nSell for "+str(data["BimportPrice"])\
                                 +"\nProfit:    "+str(data["profit"])
                elif columnorder[section] == "Cprofit":
                    return "Buy for "+str(data["BexportPrice"])\
                                 +"\nSell for "+str(data["CimportPrice"])\
                                 +"\nProfit:    "+str(data["Cprofit"])
                elif columnorder[section] == "profitPh":
                    returnstring="Profit:"+str(data["profit"])+"\n"
                    returnstring+="System: "+data["Bsystemname"]+"\n"
                    returnstring+=str(data["SystemDistance"])+"ly\n"
                    returnstring+="Station: "+data["Bbasename"]+"\n"
                    returnstring+=str(data["Bdistance"] is not None and str(data["Bdistance"])+"ls\n" or "")
                    returnstring+=str(data["Bdistance"] is not None and str("%.2f" % (SpaceTime.StarToBase(data["Bdistance"])/60))+"min" or "")
                    return returnstring
                elif columnorder[section] == "CprofitPh":
                    returnstring="Profit:"+str(data["Cprofit"])+"\n"
                    returnstring+="System: "+data["Csystemname"]+"\n"
                    returnstring+=str(data["CSystemDistance"])+"ly\n"
                    returnstring+="Station: "+data["Cbasename"]+"\n"
                    returnstring+=str(data["Cdistance"] is not None and str(data["Cdistance"])+"ls\n" or "")
                    returnstring+=str(data["Cdistance"] is not None and str("%.2f" % (SpaceTime.StarToBase(data["Cdistance"])/60))+"min" or "")
                    return returnstring
                else:
                    return None

            ################# VISIBLE DATA ##################

            if role == QtCore.Qt.DisplayRole:
                if section >=len(columnorder):
                        return None

                if "celltype" in data:
                    if data["celltype"] in ['separatorrow']:
                        if columnorder[section]=='profit':
                            return str(int(data["loopmaxprofit"]))+"cr"
                        elif columnorder[section]=='profitPh':
                            return str(data["totalprofitPh"])+"cr/h"
                        elif columnorder[section] == "hours":
                          return str(int(data["totalhours"]*60*10)/10)
                        else:
                            return None
                    else:
                        return None

                if columnorder[section] == "_curdist":
                    if self.mw.currentSystem is None:
                        return '?'
                    else:
                        pos=self.mw.currentSystem.getPosition()
                        dist=( (pos[0]-data["Ax"])**2 + (pos[1]-data["Ay"])**2 + (pos[2]-data["Az"])**2 ) ** 0.5
                        return "%.2f" % dist # two decimals
                elif columnorder[section] == "_Bcurdist":
                    if self.mw.currentSystem is None:
                        return '?'
                    else:
                        pos=self.mw.currentSystem.getPosition()
                        dist=( (pos[0]-data["Bx"])**2 + (pos[1]-data["By"])**2 + (pos[2]-data["Bz"])**2 ) ** 0.5
                        return "%.2f" % dist # two decimals
                elif columnorder[section] == "_targetdist":
                    if self.mw.targetSystemCombo.currentText() is None:
                        return '?'
                    else:
                        pos=self.mw.targetSystem.getPosition()
                        dist=( (pos[0]-data["Bx"])**2 + (pos[1]-data["By"])**2 + (pos[2]-data["Bz"])**2 ) ** 0.5
                        return "%.2f" % dist # two decimals
                elif columnorder[section] == "DistanceSq":
                    return data["DistanceSq"] ** 0.5
                elif columnorder[section] == "SystemDistance":
                    return data["SystemDistance"]
                elif columnorder[section] == "profitPh":
                    return str(int(data["profit"]/data["hours"]))
                elif columnorder[section] == "hours":
                    return str(int(data["hours"]*60*10)/10)
                else:
                    return data[columnorder[section]]

            return None # default when nothing matches
示例#6
0
        def data(self, index, role):
            if not index.isValid():
                return None
            if index.row() >= len(self.mw.result):
                return None
            data = self.mw.result[index.row()]
            section = index.column()

            columnorder = self.columnorder[self.mw.searchType]

            if section >= len(columnorder):
                return None

            # roles:    http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum

            ########### ICONS ##################

            if role == QtCore.Qt.DecorationRole:
                if "celltype" not in data:
                    if columnorder[section] in ["Asystemname"]:
                        powerid = None
                        if data['Acontrolled'] is not None:
                            powerid = data['Acontrolled']
                        if data['Aexploited'] is not None:
                            powerid = data['Aexploited']
                        if powerid is not None and powerid != -1:
                            return QtGui.QPixmap("img/power_" + str(powerid) +
                                                 ".png")
                    if columnorder[section] in ["Bsystemname"]:
                        powerid = None
                        if data['Bcontrolled'] is not None:
                            powerid = data['Bcontrolled']
                        if data['Bexploited'] is not None:
                            powerid = data['Bexploited']
                        if powerid is not None and powerid != -1:
                            return QtGui.QPixmap("img/power_" + str(powerid) +
                                                 ".png")
                    if columnorder[section] in ["commodityname"]:
                        if data['blackmarket'] == 1:
                            return QtGui.QPixmap("img/illegal.png")

            ########### TEXT COLOR ###########

            if role == QtCore.Qt.TextColorRole:
                if "celltype" not in data:
                    if columnorder[section] in ["AexportPrice"]:
                        if int(data['AlastUpdated']
                               ) < time.time() - 60 * 60 * 24 * int(
                                   Options.get('Market-valid-days', 7)):
                            return QtGui.QBrush(QtGui.QColor(255, 255, 0))
                    if columnorder[section] in ["Asupply"]:
                        if int(data['Asupply'] < 100):
                            return QtGui.QBrush(QtGui.QColor(255, 255, 0))
                    if columnorder[section] in ["BimportPrice"]:
                        if int(data['BlastUpdated']
                               ) < time.time() - 60 * 60 * 24 * int(
                                   Options.get('Market-valid-days', 7)):
                            return QtGui.QBrush(QtGui.QColor(255, 255, 0))
                    if columnorder[section] in ["commodityname"]:
                        if data['blackmarket'] == 1:
                            return QtGui.QBrush(QtGui.QColor(250, 250, 250))

            ########### BACKGROUND COLOR ##########

            if role == QtCore.Qt.BackgroundRole:
                if "celltype" in data:
                    if data["celltype"] == 'emptyrow':
                        return QtGui.QBrush(QtGui.QColor(255, 255, 255))
                    if data["celltype"] == 'separatorrow':
                        return QtGui.QBrush(QtGui.QColor(200, 200, 200))
                if columnorder[section] in ["Asystemname", "Abasename"]:
                    if data['Aallegiance'] == 1:
                        return QtGui.QBrush(QtGui.QColor(200, 255, 200))
                    if data['Aallegiance'] == 2:
                        return QtGui.QBrush(QtGui.QColor(255, 200, 200))
                    if data['Aallegiance'] == 3:
                        return QtGui.QBrush(QtGui.QColor(200, 200, 255))
                    return QtGui.QBrush(QtGui.QColor(255, 255, 230))
                if columnorder[section] in ["Bsystemname", "Bbasename"]:
                    if data['Ballegiance'] == 1:
                        return QtGui.QBrush(QtGui.QColor(200, 255, 200))
                    if data['Ballegiance'] == 2:
                        return QtGui.QBrush(QtGui.QColor(255, 200, 200))
                    if data['Ballegiance'] == 3:
                        return QtGui.QBrush(QtGui.QColor(200, 200, 255))
                    return QtGui.QBrush(QtGui.QColor(255, 255, 230))
                if columnorder[section] in ["AexportPrice"]:
                    r, g, b = self.mw.AgeToColor(data['AlastUpdated'])
                    return QtGui.QBrush(QtGui.QColor(r, g, b))
                if columnorder[section] in ["BimportPrice"]:
                    r, g, b = self.mw.AgeToColor(data['BlastUpdated'])
                    return QtGui.QBrush(QtGui.QColor(r, g, b))
                if columnorder[section] in ["Asupply"]:
                    b = (data['Asupply']) / 5000
                    g = b * 2
                    g = max(min(1, g), 0) * 255
                    b = max(min(1, b), 0) * 255
                    r = 255
                    return QtGui.QBrush(QtGui.QColor(r, g, b))
                if columnorder[section] in [
                        "profit", "Cprofit", "totalprofit"
                ]:
                    return QtGui.QBrush(QtGui.QColor(255, 230, 255))
                if columnorder[section] in ["commodityname"]:
                    if data['blackmarket'] == 1:
                        return QtGui.QBrush(QtGui.QColor(0, 0, 0))

                return QtGui.QBrush(QtGui.QColor(
                    255, 255, 255))  # everything else is white

            ############ TOOLTIPS ###############

            if role == QtCore.Qt.ToolTipRole:

                if "averageprofit" in data:  # this is a graph search
                    if columnorder[section] == "profit":
                        ret="Loop average profit: "+str(data["averageprofit"])\
                            +"\nLoop max profit: "+str(data["loopmaxprofit"])\
                            +"\nLoop min profit: "+str(data["loopminprofit"])
                        if "celltype" not in data:
                            ret+= "\nBuy for "+str(data["AexportPrice"])\
                                +"\nSell for "+str(data["BimportPrice"])\
                                +"\nProfit:    "+str(data["profit"])
                        return ret
                    if columnorder[section] == "profitPh":
                        ret="Loop average profit: "+str(data["averageprofit"])\
                            +"\nLoop max profit: "+str(data["loopmaxprofit"])\
                            +"\nLoop min profit: "+str(data["loopminprofit"])
                        if "celltype" not in data:
                            ret+= "\nBuy for "+str(data["AexportPrice"])\
                                  +"\nSell for "+str(data["BimportPrice"])\
                                  +"\nProfit:    "+str(data["profit"])\
                                  +"\nProfit/h:"+str(int(data["profit"]/data["hours"]))
                        return ret
                    else:
                        if "celltype" in data:
                            return None

                if columnorder[section] == "_curdist":
                    if self.mw.currentSystem is None:
                        return
                    else:
                        curname = self.mw.currentSystem.getName(
                        )  # todo: ship range
                        pos = self.mw.currentSystem.getPosition()
                        dist = ((pos[0] - data["Ax"])**2 +
                                (pos[1] - data["Ay"])**2 +
                                (pos[2] - data["Az"])**2)**0.5
                        return "Distance from "+curname+" (current system)\n" \
                            "to "+data["Asystemname"]+" (commodity seller) is "+("%.2f" % dist)+"ly " \
                            "("+str("%.2f" % (SpaceTime.BaseToBase(dist)/60))+"min)"
                elif columnorder[section] == "_Bcurdist":
                    if self.mw.currentSystem is None:
                        return
                    else:
                        curname = self.mw.currentSystem.getName(
                        )  # todo: ship range
                        pos = self.mw.currentSystem.getPosition()
                        dist = ((pos[0] - data["Bx"])**2 +
                                (pos[1] - data["By"])**2 +
                                (pos[2] - data["Bz"])**2)**0.5
                        return "Distance from "+curname+" (current system)\n" \
                            "to "+data["Bsystemname"]+" (commodity seller) is "+("%.2f" % dist)+"ly " \
                            "("+str("%.2f" % (SpaceTime.BaseToBase(dist)/60))+"min)"

                elif columnorder[section] == "AexportPrice":
                    return "Data "+str("%.2f" %((time.time()-data['AlastUpdated'])/(60*60*24)))+" days old"\
                          +"\nExport sales price: "+str(data["AexportPrice"])+"\nSupply: "+str(data["Asupply"])
                elif columnorder[section] == "BexportPrice":
                    return "Export sales price: " + str(
                        data["BexportPrice"]) + "\nSupply: " + str(
                            data["Bsupply"])
                elif columnorder[section] == "commodityname":
                    return "Commodity "+data["commodityname"]\
                           +"\nData "+str("%.2f" %((time.time()-min(data['AlastUpdated'],data['BlastUpdated']))/(60*60*24)))+" days old"\
                           +"\nBuy for "+str(data["AexportPrice"])\
                           +"\nSell for "+str(data["BimportPrice"])\
                           +"\nProfit:    "+str(data["profit"])\
                           +"\nGalactic average price: "+str(data["average"])
                elif columnorder[section] == "Ccommodityname":
                    return "Commodity "+data["Ccommodityname"]\
                           +"\nBuy for "+str(data["BexportPrice"])\
                           +"\nSell for "+str(data["CimportPrice"])\
                           +"\nProfit:    "+str(data["Cprofit"])\
                           +"\nGalactic average price: "+str(data["Caverage"])
                elif columnorder[section] == "BimportPrice":
                    return "Data "+str("%.2f" %((time.time()-data['BlastUpdated'])/(60*60*24)))+" days old"\
                          +"\nImport buy price: "+str(data["BimportPrice"])+"\nDemand: "+str(data["Bdemand"])
                elif columnorder[section] == "CimportPrice":
                    return "Import buy price: " + str(
                        data["CimportPrice"]) + "\nDemand: " + str(
                            data["Cdemand"])
                elif columnorder[section] in ["Asystemname", "Abasename"]:
                    padsize = {None: "unknown", 0: 'S', 1: 'M', 2: 'L'}
                    returnstring = ""

                    if data['Acontrolled'] is not None:
                        returnstring += 'System controlled by ' + Powers.valToName(
                            data['Acontrolled']) + '\n'
                    elif data['Aexploited'] is not None and data[
                            'Aexploited'] != -1:
                        returnstring += 'System exploited by ' + Powers.valToName(
                            data['Aexploited']) + '\n'
                    elif data['Aexploited'] == -1:
                        returnstring += 'System contested by opposing powers\n'

                    if data['Aallegiance'] is not None and int(
                            data['Aallegiance']) != 0:
                        allegiance = {
                            0: 'None',
                            1: 'Allegiance',
                            2: 'Federation',
                            3: 'Empire'
                        }
                        returnstring += "Allegiance: " + allegiance[int(
                            data['Aallegiance'])] + "\n"
                    returnstring += "System: " + data["Asystemname"] + "\n"
                    returnstring += "Station: " + data["Abasename"] + "\n"
                    returnstring += "Distance to star: " + str(
                        data["Adistance"] is not None and
                        (str(data["Adistance"]) + " (" +
                         str("%.2f" %
                             (SpaceTime.StarToBase(data["Adistance"]) / 60)) +
                         "min)") or "unknown") + "\n"
                    returnstring += "Landing pad size: " + padsize[
                        data["AlandingPadSize"]]
                    return returnstring
                elif columnorder[section] in ["Bsystemname", "Bbasename"]:
                    padsize = {None: "unknown", 0: 'S', 1: 'M', 2: 'L'}
                    returnstring = ""

                    if data['Bcontrolled'] is not None:
                        returnstring += 'System controlled by ' + Powers.valToName(
                            data['Bcontrolled']) + '\n'
                    elif data['Bexploited'] is not None and data[
                            'Bexploited'] != -1:
                        returnstring += 'System exploited by ' + Powers.valToName(
                            data['Bexploited']) + '\n'
                    elif data['Bexploited'] == -1:
                        returnstring += 'System contested by opposing powers\n'

                    if data['Ballegiance'] is not None and int(
                            data['Ballegiance']) != 0:
                        allegiance = {
                            0: 'None',
                            1: 'Allegiance',
                            2: 'Federation',
                            3: 'Empire'
                        }
                        returnstring += "Allegiance: " + allegiance[int(
                            data['Ballegiance'])] + "\n"
                    returnstring += "System: " + data["Bsystemname"] + "\n"
                    returnstring += "Station: " + data["Bbasename"] + "\n"
                    returnstring += "Distance to star: " + str(
                        data["Bdistance"] is not None and
                        (str(data["Bdistance"]) + " (" +
                         str("%.2f" %
                             (SpaceTime.StarToBase(data["Bdistance"]) / 60)) +
                         "min)") or "unknown") + "\n"
                    returnstring += "Landing pad size: " + padsize[
                        data["BlandingPadSize"]]
                    return returnstring
                elif columnorder[section] == "DistanceSq":
                    return "Travel distance "+str(data["DistanceSq"]**0.5)+"ly + "+\
                                str(data["Bdistance"] is not None and data["Bdistance"] or "unknown")+"ls from star to station"
                elif columnorder[section] == "SystemDistance":
                    return "Travel distance "+str(data["SystemDistance"])+"ly + "+\
                                str(data["Bdistance"] is not None and data["Bdistance"] or "unknown")+"ls from star to station\n"+\
                                str(data["Bdistance"] is not None and str("%.2f" % (SpaceTime.StarToBase(data["Bdistance"])/60))+"min" or "")
                elif columnorder[section] == "profit":
                    return "Buy for "+str(data["AexportPrice"])\
                                 +"\nSell for "+str(data["BimportPrice"])\
                                 +"\nProfit:    "+str(data["profit"])
                elif columnorder[section] == "Cprofit":
                    return "Buy for "+str(data["BexportPrice"])\
                                 +"\nSell for "+str(data["CimportPrice"])\
                                 +"\nProfit:    "+str(data["Cprofit"])
                elif columnorder[section] == "profitPh":
                    returnstring = "Profit:" + str(data["profit"]) + "\n"
                    returnstring += "System: " + data["Bsystemname"] + "\n"
                    returnstring += str(data["SystemDistance"]) + "ly\n"
                    returnstring += "Station: " + data["Bbasename"] + "\n"
                    returnstring += str(data["Bdistance"] is not None
                                        and str(data["Bdistance"]) + "ls\n"
                                        or "")
                    returnstring += str(data["Bdistance"] is not None and str(
                        "%.2f" %
                        (SpaceTime.StarToBase(data["Bdistance"]) / 60)) + "min"
                                        or "")
                    return returnstring
                elif columnorder[section] == "CprofitPh":
                    returnstring = "Profit:" + str(data["Cprofit"]) + "\n"
                    returnstring += "System: " + data["Csystemname"] + "\n"
                    returnstring += str(data["CSystemDistance"]) + "ly\n"
                    returnstring += "Station: " + data["Cbasename"] + "\n"
                    returnstring += str(data["Cdistance"] is not None
                                        and str(data["Cdistance"]) + "ls\n"
                                        or "")
                    returnstring += str(data["Cdistance"] is not None and str(
                        "%.2f" %
                        (SpaceTime.StarToBase(data["Cdistance"]) / 60)) + "min"
                                        or "")
                    return returnstring
                else:
                    return None

            ################# VISIBLE DATA ##################

            if role == QtCore.Qt.DisplayRole:
                if section >= len(columnorder):
                    return None

                if "celltype" in data:
                    if data["celltype"] in ['separatorrow']:
                        if columnorder[section] == 'profit':
                            return str(int(data["loopmaxprofit"])) + "cr"
                        elif columnorder[section] == 'profitPh':
                            return str(data["totalprofitPh"]) + "cr/h"
                        elif columnorder[section] == "hours":
                            return str(int(data["totalhours"] * 60 * 10) / 10)
                        else:
                            return None
                    else:
                        return None

                if columnorder[section] == "_curdist":
                    if self.mw.currentSystem is None:
                        return '?'
                    else:
                        pos = self.mw.currentSystem.getPosition()
                        dist = ((pos[0] - data["Ax"])**2 +
                                (pos[1] - data["Ay"])**2 +
                                (pos[2] - data["Az"])**2)**0.5
                        return "%.2f" % dist  # two decimals
                elif columnorder[section] == "_Bcurdist":
                    if self.mw.currentSystem is None:
                        return '?'
                    else:
                        pos = self.mw.currentSystem.getPosition()
                        dist = ((pos[0] - data["Bx"])**2 +
                                (pos[1] - data["By"])**2 +
                                (pos[2] - data["Bz"])**2)**0.5
                        return "%.2f" % dist  # two decimals
                elif columnorder[section] == "_targetdist":
                    if self.mw.targetSystemCombo.currentText() is None:
                        return '?'
                    else:
                        pos = self.mw.targetSystem.getPosition()
                        dist = ((pos[0] - data["Bx"])**2 +
                                (pos[1] - data["By"])**2 +
                                (pos[2] - data["Bz"])**2)**0.5
                        return "%.2f" % dist  # two decimals
                elif columnorder[section] == "DistanceSq":
                    return data["DistanceSq"]**0.5
                elif columnorder[section] == "SystemDistance":
                    return data["SystemDistance"]
                elif columnorder[section] == "profitPh":
                    return str(int(data["profit"] / data["hours"]))
                elif columnorder[section] == "hours":
                    return str(int(data["hours"] * 60 * 10) / 10)
                else:
                    return data[columnorder[section]]

            return None  # default when nothing matches