Example #1
0
def main():
    ferengi = Planet(distance=500, speed=-1)
    betasoide = Planet(distance=2000, speed=-3)
    vulcan = Planet(distance=1000, speed=5)

    star_trek_galaxy = Galaxy([ferengi, betasoide, vulcan])

    draft_days = 0
    perfect_days = 0
    rainy_day = 0
    most_rain_day = -1
    most_rain_perimeter = 0

    for day in range(3650):
        alignment = star_trek_galaxy.planets_are_aligned(day)
        if alignment is PlanetsPosition.ALIGNED_WITH_THE_SUN:
            draft_days += 1
        elif alignment is PlanetsPosition.ALIGNED_WITH_EACHOTHER:
            perfect_days += 1
        else:
            # if we are here, planets are forming a polygon
            (sunsPosition, per) = star_trek_galaxy.calculate_suns_position(day)
            if sunsPosition is PlanetsPosition.SUN_INSIDE_POLYGON:
                rainy_day += 1
                if per > most_rain_perimeter:
                    most_rain_day = day
                    most_rain_perimeter = per

    print('Draft:', draft_days)
    print('Perfect:', perfect_days)
    print('Rainy:', rainy_day)
    print('Most rain:', most_rain_day)
Example #2
0
class World(object):
    """
    Describes everything in the in-game world
    
    - players: not users, but in-game players, that can be either avatars of users or NPCs
    - galaxy: the galaxy that contains planets and fleets
    """
    def __init__(self):
        self._players = []
        self._galaxy = Galaxy()
        self._time = 0

    def sim(self):
        """Simulate in-game world"""
        self._galaxy.sim()
        self._time += 1

    def get_time(self):
        """Return in-game time"""
        return self._time

    def set_time(self, time_):
        """Set in-game time"""
        self._time = time_
        return self._time
Example #3
0
class World(object):
    """
    Describes everything in the in-game world
    
    - players: not users, but in-game players, that can be either avatars of users or NPCs
    - galaxy: the galaxy that contains planets and fleets
    """
    
    def __init__(self):
        self._players = []
        self._galaxy = Galaxy()
        self._time = 0
    
    def sim(self):
        """Simulate in-game world"""
        self._galaxy.sim()
        self._time += 1
    
    def get_time(self):
        """Return in-game time"""
        return self._time
    
    def set_time(self, time_):
        """Set in-game time"""
        self._time = time_
        return self._time
Example #4
0
    def __init__(self, client, *args, **kwargs):
        logger.debug("Lobby instantiating.")
        BaseClass.__init__(self, *args, **kwargs)

        self.setupUi(self)

        self.client = client
        #self.client.galacticwarTab.setStyleSheet(util.readstylesheet("galacticwar/galacticwar.css"))

        self.COLOR_FACTIONS = {}
        self.mapTransparency = 10
        self.AA = True
        self.rotation = True
        self.stars = 25

        self.GWOptions = GWOptions(self)
        self.GWOptions.loadSettings()

        self.client.galacticwarTab.layout().addWidget(self)

        self.downloader = QNetworkAccessManager(self)
        self.downloader.finished.connect(self.finishRequest)

        self.shaderlist = []
        self.texturelist = {}
        self.shaders = {}

        self.infoPanel = None
        self.OGLdisplay = None

        self.galaxy = Galaxy(self)
        self.channel = None

        self.initDone = False

        self.uid = None
        self.faction = None
        self.name = None
        self.rank = None
        self.credits = 0
        self.victories = 0
        self.enslavedBy = None

        self.attacks = {}

        self.state = ClientState.NONE

        ## Network initialization

        self.socket = QtNetwork.QTcpSocket()
        self.socket.readyRead.connect(self.readFromServer)
        self.socket.disconnected.connect(self.disconnectedFromServer)
        self.socket.error.connect(self.socketError)
        self.blockSize = 0

        self.progress = QtGui.QProgressDialog()
        self.progress.setMinimum(0)
        self.progress.setMaximum(0)
Example #5
0
class GalaxyCanvas(Canvas):
    def __init__(self):
        Canvas.__init__(self, size=[800, 800], close_keys='ESCAPE', show=True,
                        title='Galaxy')
        self.galaxy = Galaxy(35000)
        self.galaxy.reset(13000, 4000, 0.0004, 0.90, 0.90, 0.5, 200, 300)
        program = gloo.Program(vertex, fragment, count=len(self.galaxy))
        view = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        program['u_view'] = view
        program['u_model'] = np.eye(4, dtype=np.float32)
        program['u_projection'] = np.eye(4, dtype=np.float32)

        from PIL import Image
        from specrend import (SMPTEsystem, spectrum_to_xyz, norm_rgb,
                              xyz_to_rgb, bb_spectrum)
        image = Image.open("particle.bmp")
        program['u_texture'] = np.array(image)/255.0
        t0 = 1000.
        t1 = 10000.
        n = 256
        dt = (t1 - t0) / n
        colors = np.zeros((1, n, 3), dtype=np.float32)
        for i in range(n):
            cs = SMPTEsystem
            temperature = t0 + i*dt
            x, y, z = spectrum_to_xyz(bb_spectrum, temperature)
            r, g, b = xyz_to_rgb(cs, x, y, z)
            colors[0, i] = norm_rgb(r, g, b)
        program['u_colormap'] = gloo.Texture2D(colors)
        program['a_size'] = self.galaxy['size']
        program['a_type'] = self.galaxy['type']
        self.program = program

    def on_initialize(self):
        gloo.set_clear_color((0.0, 0.0, 0.0, 1.0))
        gloo.set_state(blend=True, depth_test=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))

    def on_paint(self, region):
        self.galaxy.update(100000)  # in years !
        self.program['a_size'] = self.galaxy['size']
        gloo.clear()
        t0 = 1000.
        t1 = 10000.
        gloo.set_state(blend=True, blend_func=('src_alpha', 'one'))
        self.program['a_position'] = self.galaxy['position'] / 15000.0
        self.program['a_temperature'] = ((self.galaxy['temperature'] - t0)
                                         / (t1-t0))
        self.program['a_brightness'] = self.galaxy['brightness']
        self.program.draw('points')

    def on_resize(self, width, height):
        gloo.set_viewport(0, 0, width, height)
        projection = perspective(45.0, width / float(height), 1.0, 1000.0)
        self.program['u_projection'] = projection
Example #6
0
def main():

    t = 0
    milky_way = Galaxy(
        num_stars=NUM_STARS_MILKY_WAY,
        pos=vector(-5, 0, 0) * DIST_SCALE,
        vel=vector(0, 0, 0),
        radius=MAX_ORBITAL_RADIUS,
        thickness=MILKY_WAY_GALAXY_THICKNESS,
        color=vector(0.9, 0.9, 1)
    )
    andromeda = Galaxy(
        num_stars=NUM_STARS_ANDROMEDA,
        pos=vector(3, 0, 0) * DIST_SCALE,
        vel=vector(0, 3, 0),
        radius=MAX_ORBITAL_RADIUS,
        thickness=ANDROMEDA_GALAXY_THICKNESS,
        color=vector(0, 0.5, 1)
    )

    while True:
        rate(100)

        mag_difference = milky_way.pos.mag - andromeda.pos.mag


        for i in range(len(milky_way.stars)):
            star = milky_way.stars[i]
            star.vel += accel(star, andromeda) * dt
            star.vel += accel(star, milky_way) * dt
            star.pos += star.vel * dt
            # if(mag_difference == -6+18):
            #     star.obj.color = vector(1, 0.5, 0)
            if(andromeda.pos.mag < 1.1920057081525512e+20):
                star.obj.color = vector(1, 0.5, 0)

        andromeda_mask = np.zeros(len(andromeda.stars))

        for star in andromeda.stars:
            star.vel += accel(star, milky_way) * dt
            star.vel += accel(star, andromeda) * dt
            star.pos += star.vel * dt
            # if(mag_difference < -6+18 and mag_difference > -5e+18):
            #     star.obj.color = vector(1, 0.5, 0)
            if(andromeda.pos.mag < 1.1920057081525512e+20):
                star.obj.color = vector(1, 0.5, 0)

        milky_way.vel += accel(milky_way, andromeda) * dt
        milky_way.pos += milky_way.vel * dt

        andromeda.vel += accel(andromeda, milky_way) * dt
        andromeda.pos += andromeda.vel * dt

        t += dt
Example #7
0
    def __init__(self):
        Canvas.__init__(self, size=[800, 800], close_keys='ESCAPE', show=True,
                        title='Galaxy')
        self.galaxy = Galaxy(35000)
        self.galaxy.reset(13000, 4000, 0.0004, 0.90, 0.90, 0.5, 200, 300)
        program = gloo.Program(vertex, fragment, count=len(self.galaxy))
        view = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        program['u_view'] = view
        program['u_model'] = np.eye(4, dtype=np.float32)
        program['u_projection'] = np.eye(4, dtype=np.float32)

        from PIL import Image
        from specrend import (SMPTEsystem, spectrum_to_xyz, norm_rgb,
                              xyz_to_rgb, bb_spectrum)
        image = Image.open("particle.bmp")
        program['u_texture'] = np.array(image)/255.0
        t0 = 1000.
        t1 = 10000.
        n = 256
        dt = (t1 - t0) / n
        colors = np.zeros((1, n, 3), dtype=np.float32)
        for i in range(n):
            cs = SMPTEsystem
            temperature = t0 + i*dt
            x, y, z = spectrum_to_xyz(bb_spectrum, temperature)
            r, g, b = xyz_to_rgb(cs, x, y, z)
            colors[0, i] = norm_rgb(r, g, b)
        program['u_colormap'] = gloo.Texture2D(colors)
        program['a_size'] = self.galaxy['size']
        program['a_type'] = self.galaxy['type']
        self.program = program
Example #8
0
    def __init__(self, client, *args, **kwargs):
        logger.debug("Lobby instantiating.")
        BaseClass.__init__(self, *args, **kwargs)

        self.setupUi(self)

        self.client = client
        # self.client.galacticwarTab.setStyleSheet(util.readstylesheet("galacticwar/galacticwar.css"))

        self.COLOR_FACTIONS = {}
        self.mapTransparency = 10
        self.AA = True
        self.rotation = True
        self.stars = 25

        self.GWOptions = GWOptions(self)
        self.GWOptions.loadSettings()

        self.client.galacticwarTab.layout().addWidget(self)

        self.downloader = QNetworkAccessManager(self)
        self.downloader.finished.connect(self.finishRequest)

        self.shaderlist = []
        self.texturelist = {}
        self.shaders = {}

        self.infoPanel = None
        self.OGLdisplay = None

        self.galaxy = Galaxy(self)
        self.channel = None

        self.initDone = False

        self.uid = None
        self.faction = None
        self.name = None
        self.rank = None
        self.credits = 0
        self.victories = 0
        self.enslavedBy = None

        self.attacks = {}

        self.state = ClientState.NONE

        ## Network initialization

        self.socket = QtNetwork.QTcpSocket()
        self.socket.readyRead.connect(self.readFromServer)
        self.socket.disconnected.connect(self.disconnectedFromServer)
        self.socket.error.connect(self.socketError)
        self.blockSize = 0

        self.progress = QtGui.QProgressDialog()
        self.progress.setMinimum(0)
        self.progress.setMaximum(0)
    def __init__(self, screen_width=120, screen_height=70):
        self.screen_width = screen_width
        self.screen_height = screen_height

        libtcod.console_init_root(self.screen_width, self.screen_height, 'Heliopause', False)

        self.buffer = libtcod.ConsoleBuffer(self.screen_width, self.screen_height)
        self.console = libtcod.console_new(self.screen_width, self.screen_height)

        self.galaxy_map_console = libtcod.console_new(self.screen_width, self.screen_height)

        self.set_minimap(20)

        self.targeting_width = 20
        self.targeting_height = 26
        self.targeting_buffer  = libtcod.ConsoleBuffer(self.targeting_width, self.targeting_height)
        self.targeting_console = libtcod.console_new(self.targeting_width, self.targeting_height)
        libtcod.console_set_default_foreground(self.targeting_console, libtcod.white)
        libtcod.console_set_default_background(self.targeting_console, libtcod.black)

        self.ship_info_width = 20
        self.ship_info_height = 8
        self.ship_info_buffer  = libtcod.ConsoleBuffer(self.ship_info_width, self.ship_info_height)
        self.ship_info_console = libtcod.console_new(self.ship_info_width, self.ship_info_height)
        libtcod.console_set_default_foreground(self.ship_info_console, libtcod.white)
        libtcod.console_set_default_background(self.ship_info_console, libtcod.black)

        self.message_height = 4
        self.message_width = self.screen_width
        self.messages = collections.deque([])
        self.message_console = libtcod.console_new(self.message_width, self.message_height)
        libtcod.console_set_default_foreground(self.message_console, libtcod.white)
        libtcod.console_set_default_background(self.message_console, libtcod.black)

        self.landing_screen_width = self.screen_width / 2 - 2
        self.landing_screen_height = self.screen_height - 4
        self.landing_console = libtcod.console_new(self.landing_screen_width, self.landing_screen_height)
        libtcod.console_set_default_foreground(self.landing_console, libtcod.white)
        libtcod.console_set_default_background(self.landing_console, libtcod.black)

        self.mouse = libtcod.Mouse()
        self.key = libtcod.Key()

        galaxy_seed, ship_value = self.title_screen_loop()

        # Loading Screen
        libtcod.console_set_default_background(self.console, libtcod.black)
        libtcod.console_clear(self.console)

        self.galaxy = Galaxy(self.screen_width, self.screen_height, seed=galaxy_seed)
        self.sector, self.starfield, self.nebula = self.galaxy.sectors[self.galaxy.current_sector].load_sector(self.console, self.buffer)

        starting_planet = self.sector.planets[randrange(1, len(self.sector.planets))]
        self.player_ship = Ship(self.sector, starting_planet.sector_position_x, starting_planet.sector_position_y, ship_value=ship_value)
        self.add_message("Taking off from {0}".format(starting_planet.name))

        self.current_screen = 'flight'
Example #10
0
def main():
    # Initialize the db
    db_config = {}
    with open(os.path.dirname(os.path.realpath(__file__)) + "\\db-config.json") as db_config_file:
        db_config = json.load(db_config_file)
    db.init(db_config['db-name'],
            user=db_config['user'],
            password=db_config['password'],
            host=db_config['host'],
            port=db_config['port'])
    db.connect()
    tables = db.get_tables()
    if 'Weather' in tables:
        db.drop_tables(Weather)
    db.create_tables([Weather])

    # Create the galaxy we are gonna store
    ferengi = Planet(distance=500, speed=-1)
    betasoide = Planet(distance=2000, speed=-3)
    vulcan = Planet(distance=1000, speed=5)

    star_trek_galaxy = Galaxy([ferengi, betasoide, vulcan])
    weather = {}

    with db.atomic():
        for day in range(3650):
            weather['day'] = day
            alignment = star_trek_galaxy.planets_are_aligned(day)
            if alignment is PlanetsPosition.ALIGNED_WITH_THE_SUN:
                weather['weather'] = 'draft'
            elif alignment is PlanetsPosition.ALIGNED_WITH_EACHOTHER:
                weather['weather'] = 'perfect'
            else:
                # if we are here, planets are forming a polygon
                (sunsPosition, per) = star_trek_galaxy.calculate_suns_position(day)
                if sunsPosition is PlanetsPosition.SUN_INSIDE_POLYGON:
                    weather['weather'] = 'rain'
                else:
                    weather['weather'] = 'sunny'
            Weather.create(**weather)
Example #11
0
def run_game():
    """ initialize game """

    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption('Alien Invasion')

    # create a gamestats instance
    stats = GameStats(settings)

    # create game background
    galaxy = Galaxy(screen)

    # create a ship
    ship = Ship(settings, screen)

    # create bullets group
    bullets = Group()

    # create aliens group
    aliens = Group()

    # create the play button
    play_button = Button(settings, screen, 'Play')

    # create a score board
    scoreboard = Scoreboard(settings, screen, stats)

    # create sound buffer
    sound = Sound()

    # begin game main while
    while True:
        check_events(settings, screen, stats, ship,
                     bullets, aliens, play_button, scoreboard, sound)

        if stats.game_active:
            ship.update_location()
            update_bullets(settings, screen, stats, ship,
                           bullets, aliens, scoreboard, sound)
            update_aliens(settings, screen, stats, ship,
                          bullets, aliens, scoreboard, sound)

        update_screen(settings, screen, stats, galaxy, ship,
                      bullets, aliens, play_button, scoreboard)
Example #12
0
def load_galaxy(galpath, galname, star_class_perc):
    """Loads the galaxy loacated at galpath and returns a Galaxy object""" 
    gal_dict = OrderedDict()
    for color in ('g', 'i', 'r', 'u', 'z'):
        p = os.path.join(galpath, color + '.fits')
        if os.path.exists(p):
            gal_dict.update({color: fits.open(p, ignore_missing_end = True)})
            continue
    
        p2 = os.path.join(galpath, galname + '_' + color + '.fits')    
        if os.path.exists(p2):
            gal_dict.update({color: fits.open(p2, ignore_missing_end = True)})
            continue

        p3 = os.path.join(galpath, galname + '-' + color + '.fits')
        if os.path.exists(p3):
            gal_dict.update({color: fits.open(p3, ignore_missing_end = True)})
            continue

    # if no images were found
    if not gal_dict: return galpath
        
    # find the stars in the galaxies
    star_dict = OrderedDict()
    for color in gal_dict.keys():
        try:
            p = os.path.join(galpath, color + '.fits')
            if os.path.exists(p):
                star_dict.update({color: get_sextractor_points(p)})
                continue

            p2 = os.path.join(galpath, galname + '_' + color + '.fits')
            if os.path.exists(p2):    
                star_dict.update({color: get_sextractor_points(p2)})
                continue

            p3 = os.path.join(galpath, galname + '-' + color + '.fits')
            if os.path.exists(p3):
                star_dict.update({color: get_sextractor_points(p3)})
                continue
        except SextractorError:
            return galpath

    return Galaxy(gal_dict, star_dict, star_class_perc, galname)
Example #13
0
        'color': (35, 217, 89),
        'init_amount': random.randint(500, 600),
        'instances': 0,
        'total_amount': 0
    }
}

# Plots systems on a scatter for visuals
pygame.init()
FPS = 24
GALAXY_SIZE = 800
clock = pygame.time.Clock()
screen = pygame.display.set_mode([GALAXY_SIZE, GALAXY_SIZE])
galaxy = Galaxy(game_screen=screen,
                galaxy_size=GALAXY_SIZE,
                system_count=10,
                allocation=RES_ALLOCATION,
                resource_deviation=.1,
                resource_variation=5,
                price_modifier=10)
running = True
while running:
    screen.fill((255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    galaxy.step()
    pygame.display.flip()
    clock.tick(FPS)
pygame.quit()
Example #14
0
class LobbyWidget(FormClass, BaseClass):
    planetClicked                   = QtCore.pyqtSignal(int)
    hovering                        = QtCore.pyqtSignal()
    creditsUpdated                  = QtCore.pyqtSignal(int)
    rankUpdated                     = QtCore.pyqtSignal(int)
    creditsUpdated                  = QtCore.pyqtSignal(int)
    victoriesUpdated                = QtCore.pyqtSignal(int)
    attacksUpdated                  = QtCore.pyqtSignal()
    planetUpdated                   = QtCore.pyqtSignal(int)
    attackProposalUpdated           = QtCore.pyqtSignal(int)
    ReinforcementUpdated            = QtCore.pyqtSignal(dict)
    planetaryDefenseUpdated         = QtCore.pyqtSignal(dict)
    ReinforcementsGroupUpdated      = QtCore.pyqtSignal(dict)
    ReinforcementsGroupDeleted      = QtCore.pyqtSignal(dict)
    dominationUpdated               = QtCore.pyqtSignal(int)
    playersListUpdated              = QtCore.pyqtSignal(dict)
    teamUpdated                     = QtCore.pyqtSignal(dict)
    searchingUpdated                = QtCore.pyqtSignal(bool)

    def __init__(self, client, *args, **kwargs):
        logger.debug("Lobby instantiating.")
        BaseClass.__init__(self, *args, **kwargs)
        
        self.setupUi(self)
        
        
        self.client = client
        #self.client.galacticwarTab.setStyleSheet(util.readstylesheet("galacticwar/galacticwar.css"))
        
        self.COLOR_FACTIONS = {}
        self.mapTransparency = 10
        self.AA = True
        self.rotation = True
        self.stars = 25
        
        self.GWOptions = GWOptions(self)
        self.GWOptions.loadSettings()                     
                
        self.client.galacticwarTab.layout().addWidget(self)
   
        self.downloader     = QNetworkAccessManager(self)
        self.downloader.finished.connect(self.finishRequest)
        
        self.shaderlist     =   []
        self.texturelist    =   {}        
        self.shaders    =   {}
        
        
        
        self.infoPanel  = None
        self.OGLdisplay = None
        
        self.galaxy     = Galaxy(self)
        self.channel    = None
        
        self.initDone   = False
        
        self.uid        = None
        self.faction    = None
        self.name       = None
        self.rank       = None
        self.credits    = 0
        self.victories  = 0
        self.enslavedBy = None
   
        self.attacks = {}
   
        self.state = ClientState.NONE
        
        ## Network initialization
        
        self.socket = QtNetwork.QTcpSocket()
        self.socket.readyRead.connect(self.readFromServer)
        self.socket.disconnected.connect(self.disconnectedFromServer)
        self.socket.error.connect(self.socketError)
        self.blockSize = 0     


        self.progress = QtGui.QProgressDialog()
        self.progress.setMinimum(0)
        self.progress.setMaximum(0)

#    def focusEvent(self, event):
#        return BaseClass.focusEvent(self, event)
    
    def showEvent(self, event):
        if self.state != ClientState.ACCEPTED :
            fa.exe.check("gw")
            if self.doConnect():
                logger.info("connection done")
                self.doLogin()                   
        
        else :
            if not self.initDone :
                logger.info("init not done")
                self.doLogin()
            else :
                if self.faction == None :
                    logger.info("not faction")
                    self.doLogin()

        return BaseClass.showEvent(self, event)
    
    def updateOptions(self):
        ''' settings galactic wars options'''
        self.GWOptions.show()
        
    
    def createChannel(self, chat, name):
        self.channel = gwChannel(chat, name, True)        

    def finishRequest(self, reply):
        filename = reply.url().toString().rsplit('/',1)[1]
        root, _ = os.path.splitext(filename)
        
        toFile = os.path.join(GW_TEXTURE_DIR, filename)
        writeFile = QtCore.QFile(toFile)
        if(writeFile.open(QtCore.QIODevice.WriteOnly)) :
                writeFile.write(reply.readAll())
                writeFile.close()                
        else:
            logger.warn("%s is not writeable in in %s. Skipping." % (filename, GW_TEXTURE_DIR))

        if root in self.texturelist :
            del self.texturelist[root]
            
        if len(self.texturelist) == 0:
            self.setup()
            self.progress.close()


    def doConnect(self):
        logger.debug("Connecting to server")
        if self.client.state == ClientState.ACCEPTED :

            self.progress.setCancelButtonText("Cancel")
            self.progress.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint)
            self.progress.setAutoClose(False)
            self.progress.setAutoReset(False)
            self.progress.setModal(1)
            self.progress.setWindowTitle("Galactic War Network...")
            self.progress.setLabelText("Gating in ...")
            self.progress.show()                
                      
             
#            self.login = self.client.login.strip()      
#            logger.info("Attempting to gate as: " + str(self.client.login))
            self.state = ClientState.NONE

            # Begin connecting.        
            self.socket.connectToHost(LOBBY_HOST, LOBBY_PORT)
            
            
            
            while (self.socket.state() != QtNetwork.QAbstractSocket.ConnectedState) and self.progress.isVisible():
                QtGui.QApplication.processEvents()                                        
    
    #        #Perform Version Check first        
            if not self.socket.state() == QtNetwork.QAbstractSocket.ConnectedState:
                
                self.progress.close() # in case it was still showing...
                # We either cancelled or had a TCP error, meaning the connection failed..
                if self.progress.wasCanceled():
                    logger.warn("doConnect() aborted by user.")
                else:
                    logger.error("doConnect() failed with clientstate " + str(self.state) + ", socket errorstring: " + self.socket.errorString())
                return False
            else:     
      
                return True  


    def doLogin(self):
        ''' login in the GW server 
            We are using the main login and session to check legitimity of the client.
        '''
        
        self.progress.setLabelText("Gating in...")
        self.progress.reset()
        self.progress.show()                       
   
        logger.info("Attempting to gate as: " + str(self.client.login))
        self.state = ClientState.NONE

        self.send(dict(command="hello", version=util.VERSION_STRING, port= self.client.gamePort, login=self.client.login, session = self.client.session))
        
        while (not self.state) and self.progress.isVisible():
            QtGui.QApplication.processEvents()
            

        if self.progress.wasCanceled():
            logger.warn("Gating aborted by user.")
            return False
        
        self.progress.close()

        if self.state == ClientState.ACCEPTED:
            logger.info("Gating accepted.")
            self.progress.close()
            self.client.actionGalacticWar.triggered.connect(self.updateOptions)
            self.client.actionGalacticWar.setEnabled(True)
            return True   
            #self.connected.emit()            
          
        elif self.state == ClientState.REJECTED:
            logger.warning("Gating rejected.")
            return False
        else:
            # A more profound error has occurrect (cancellation or disconnection)
            return False



    def setup(self):
        self.galaxy.computeVoronoi()
        from glDisplay import GLWidget
        from infopanel import InfoPanelWidget
        from newsTicker import NewsTicker
        from reinforcements import PlanetaryWidget
        from reinforcements import ReinforcementWidget

        #items panels 
        self.teams = Teams(self)
        self.planetaryItems = PlanetaryWidget(self)
        self.reinforcementItems = ReinforcementWidget(self)
        self.OGLdisplay = GLWidget(self)
        self.newsTicker = NewsTicker(self)
        self.galaxyLayout.addWidget(self.OGLdisplay)
        self.galaxyLayout.addWidget(self.newsTicker)
        self.newsTicker.setMaximumHeight(20)
        self.infoPanel = InfoPanelWidget(self)
        self.info_Panel.layout().addWidget(self.infoPanel)

        self.send(dict(command = "init_done", status=True))
        self.infoPanel.setup()
        
    def get_rank(self, faction, rank):
        return RANKS[faction][rank]


    def handle_welcome(self, message):
        self.state = ClientState.ACCEPTED

    def handle_planetary_defense_info(self, message):
        '''populate planetary defense lists'''
        self.planetaryDefenseUpdated.emit(message)
        
    def handle_group_reinforcements_info(self, message):
        '''populate current group reinforcements '''
        self.ReinforcementsGroupUpdated.emit(message)            
    
    def handle_group_reinforcements_deleted (self, message):
        self.ReinforcementsGroupDeleted.emit(message)
        
    def handle_reinforcement_item_info(self, message):
        '''populate reinforcement lists'''
        self.ReinforcementUpdated.emit(message)

    def handle_resource_required(self, message):
        if message["action"] == "shaders" :
            self.shaderlist = message["data"]
            self.send(dict(command = "request", action ="shaders"))
        elif message["action"] == "textures" :
            for tex in message["data"] :
                if not tex in self.texturelist :
                    self.texturelist[tex] = message["data"][tex]

        

    def handle_shader(self, message):
        name             = message["name"]
        shader_fragment  = message["shader_fragment"]
        shader_vertex    = message["shader_vertex"]
        if not name in self.shaders :
            self.shaders[name] = {}
            self.shaders[name]["fragment"]  = shader_fragment
            self.shaders[name]["vertex"]    = shader_vertex
        
        if name in self.shaderlist :
            self.shaderlist.remove(name)
        self.check_resources()
            
            #we have all our shader.
            
    
    def get_texture_name(self, tex):
        return os.path.join(GW_TEXTURE_DIR, tex + ".png")
    
    def download_textures(self):
        self.progress.show()
        self.progress.setLabelText("Downloading resources ...")
        
        textInCache = []
        
        for tex in self.texturelist : 
            if os.path.exists(self.get_texture_name(tex)) :
                if util.md5(self.get_texture_name(tex)) == self.texturelist[tex] :
                    #logger.debug(tex + ".png in cache.")
                    textInCache.append(tex)
                    continue
            #logger.debug("Downloading " + tex + ".png")
            self.downloader.get(QNetworkRequest(QtCore.QUrl(TEXTURE_SERVER + tex + ".png")))    
        
        for tex in textInCache :
            del self.texturelist[tex]
        
        if len(self.texturelist) == 0 :
            self.progress.close()
            self.setup()
             

    def check_resources(self):
        '''checking if we have everything we need'''
        if len(self.shaderlist) == 0 and self.initDone :
            self.download_textures()
    
    def handle_remove_team(self, message):
        self.teamUpdated.emit(dict(leader=None, members=[]))
    
    def handle_team(self, message):
        self.teamUpdated.emit(message)
    
    def handle_request_team(self, message):
        ''' We have a team invitation from someone '''
        who = message["who"]
        uid = message["uid"]

        self.infoPanel.formTeam()
        self.infoPanel.teamwidget.addProposal(who, uid)
    
    def handle_news_feed(self, message):
        '''Adding news to news feed'''
        if hasattr(self, "newsTicker"):
            if self.newsTicker:
                self.newsTicker.addNews(message["news"])
    
    def handle_player_info(self, message):
        ''' Update Player stats '''
        
        self.uid        = int(message["uid"])
        self.faction    = message["faction"]
        self.name       = message["name"]        
        self.rank       = message["rank"]
        self.credits    = message["credits"]
        self.victories  = message["victories"]        
        
        logger.debug("Received player info : victories %i, credits %i" % (self.victories, self.credits))
       
        self.rankUpdated.emit(self.rank)
        self.creditsUpdated.emit(self.credits)
        self.victoriesUpdated.emit(self.victories)
    
       
    def handle_game_upgrades(self, message):
        '''writing reinforcement list'''
        upgrades = message["upgrades"]
        fa.gwgametable.writeTable(upgrades, "gwReinforcementList.gw")
   
        # and we empty the unit reinforcement list
        self.reinforcementItems.reset()
    
    def handle_domination(self, message):
        master = message["master"]
        self.enslavedBy = master
        self.dominationUpdated.emit(master)
    
    def handle_attack_result(self, message):
        self.progress.close()
        result = message["result"]
        if result == "won" :
            QtGui.QMessageBox.information(self, "War report", "You win !" , QtGui.QMessageBox.Close)
            
            
    def handle_attack_proposal(self, message):
        planetuid = message["planetuid"]
        self.attackProposalUpdated.emit(planetuid)
    
    def handle_attacks_info(self, message):
        if self.OGLdisplay == None:
            return
        
        attacks = message["attacks"]
        self.attacks = {}
        
        for playeruid in attacks :
            playeruid_int = int(playeruid)
            if not playeruid_int in self.attacks :
                self.attacks[playeruid_int] = {}
            
            for planetuid in attacks[playeruid] :
                planetuid_int = int(planetuid)
                self.attacks[playeruid_int][planetuid_int] = attacks[playeruid][planetuid]
        self.attacksUpdated.emit()

    def handle_planet_defense_remove(self, message):
        '''handling removing defenses for a planet'''
        planetuid = message["planetuid"]
        self.galaxy.removeDefenses(planetuid)
            
    def handle_planet_defense_info(self, message):
        '''handling defenses for planets'''
        planetuid = message["planetuid"]
        self.galaxy.updateDefenses(planetuid, message)

    def handle_planet_info(self, message):
        uid = message['uid'] 
        if not uid in self.galaxy.control_points :
            display     = message['visible']
            x           = message['posx']
            y           = message['posy']
            size        = message['size']
            textureMd5  = message['md5tex']
            name        = message['name']
            desc        = message['desc']
            sector      = message['sector']
            if display:
                texture     = message['texture']
                mapname     = message['mapname']
                maxplayer   = message['maxplayer']
                if not texture in self.texturelist :
                    self.texturelist[texture] = textureMd5 
            else:
                mapname = ""
                texture = 0
                maxplayer = 0

            self.galaxy.addPlanet(uid, sector, name, desc, x, y, size, maxplayer=maxplayer, mapname=mapname,texture = texture, init=True, display = display) 
            self.galaxy.update(message)
            
            if not uid in self.galaxy.links :
                self.galaxy.links[uid] = message['links']
        else :
            self.galaxy.update(message)
            self.planetUpdated.emit(message['sector'])

    def handle_logged_in(self, message):
       
        self.handle_player_info(message)
        if self.faction != None :
            self.client.galacticwarTab.setStyleSheet(util.readstylesheet("galacticwar/galacticwar.css").replace("%FACTION%", FACTIONS[self.faction]))   
            
        self.attacksUpdated.emit()

    def handle_create_account(self, message):
        if message["action"] == 0 :
            
            accountCreator = loginwizards.gwSelectFaction(self)
            accountCreator.exec_()
            if self.faction != None :
                self.send(dict(command = "account_creation", action = 0, faction = self.faction))
            else :
                self.client.mainTabs.setCurrentIndex(0)
                QtGui.QMessageBox.warning(self, "No faction :(", "You need to pledge allegiance to a faction in order to play Galactic War !")

        elif message["action"] == 1 :
            name = message["name"]
            self.faction = message["faction"]

            self.rank = message["rank"]
            
            question = QtGui.QMessageBox.question(self, "Avatar name generation", "Your avatar name will be : <br><br>" + self.get_rank(self.faction, self.rank) + " " + name + ".<br><br>Press Reset to generate another, Ok to accept.", QtGui.QMessageBox.Reset, QtGui.QMessageBox.Ok)
            if question ==  QtGui.QMessageBox.Reset :
                self.send(dict(command = "account_creation", action = 1))
            else :
                self.name = name
                self.send(dict(command = "account_creation", action = 2))
    
    def handle_faction_player_list(self, message):
        '''players online'''
        self.playersListUpdated.emit(message["players"])
    
    def handle_init_done(self, message):
        if message['status'] == True :
            self.initDone = True
            self.check_resources()

    def handle_social(self, message):      
        if "autojoin" in message :
            if message["autojoin"] == 0 :
                self.client.autoJoin.emit(["#UEF"])
            elif message["autojoin"] == 1 :         
                self.client.autoJoin.emit(["#Aeon"])
            elif message["autojoin"] == 2 :
                self.client.autoJoin.emit(["#Cybran"])
            elif message["autojoin"] == 3 :
                self.client.autoJoin.emit(["#Seraphim"])

    def handle_searching(self, message):
        state = message["state"]
        if state == "on":
            self.searchingUpdated.emit(True)
        else:
            self.searchingUpdated.emit(False)

    def handle_notice(self, message):
        self.client.handle_notice(message)
       

    def handle_update(self, message):
        update = message["update"]
        if not util.developer():
            logger.warn("Server says that Updating is needed.")
            self.progress.close()
            self.state = ClientState.OUTDATED
            fa.updater.fetchClientUpdate(update)        

    def process(self, action, stream):
        if action == "PING":
            self.writeToServer("PONG")
        else :
            self.dispatchJSON(action, stream)
            
    
    def dispatchJSON(self, data_string, stream):
        '''
        A fairly pythonic way to process received strings as JSON messages.
        '''
        message = json.loads(data_string)
        cmd = "handle_" + message['command']
        #logger.debug("Incoming JSON Command: " + data_string)
        if hasattr(self, cmd):
            getattr(self, cmd)(message)  
        else:
            logger.error("command unknown : %s", cmd)
 

    def send(self, message):
        data = json.dumps(message)
        logger.info("Outgoing JSON Message: " + data)
        self.writeToServer(data)

    @QtCore.pyqtSlot()
    def readFromServer(self):
        ins = QtCore.QDataStream(self.socket)        
        ins.setVersion(QtCore.QDataStream.Qt_4_2)
        
        while ins.atEnd() == False :
            if self.blockSize == 0:
                if self.socket.bytesAvailable() < 4:
                    return
                self.blockSize = ins.readUInt32()            
            if self.socket.bytesAvailable() < self.blockSize:
                return
            
            action = ins.readQString()
            self.process(action, ins)
            self.blockSize = 0
                                
            
    @QtCore.pyqtSlot()
    def disconnectedFromServer(self):
        logger.warn("Disconnected from lobby server.")
        
        if self.state == ClientState.ACCEPTED:
            QtGui.QMessageBox.warning(QtGui.QApplication.activeWindow(), "Disconnected from Galactic War", "The lobby lost the connection to the Galactic War server.<br/><b>You might still be able to chat.<br/>To play, try reconnecting a little later!</b>", QtGui.QMessageBox.Close)
            self.initDone   = False
            self.client.mainTabs.setCurrentIndex(0)

            self.client.mainTabs.setTabEnabled(self.client.mainTabs.indexOf(self.client.galacticwarTab  ), False)
            self.client.mainTabs.setTabText(self.client.mainTabs.indexOf(self.client.galacticwarTab  ), "offline")
                
        self.state = ClientState.DROPPED             
            
    def writeToServer(self, action, *args, **kw):
        '''
        This method is the workhorse of the client, and is used to send messages, queries and commands to the server.
        '''
        logger.debug("Client: " + action)
        
        block = QtCore.QByteArray()
        out = QtCore.QDataStream(block, QtCore.QIODevice.ReadWrite)
        out.setVersion(QtCore.QDataStream.Qt_4_2)

        out.writeUInt32(0)
        out.writeQString(action)
   
        
        for arg in args :
            if type(arg) is IntType:
                out.writeInt(arg)
            elif isinstance(arg, basestring):
                out.writeQString(arg)
            elif type(arg) is FloatType:
                out.writeFloat(arg)
            elif type(arg) is ListType:
                out.writeQVariantList(arg)
            elif type(arg) is DictType:
                out.writeQString(json.dumps(arg))                                
            elif type(arg) is QtCore.QFile :       
                arg.open(QtCore.QIODevice.ReadOnly)
                fileDatas = QtCore.QByteArray(arg.readAll())
                #seems that that logger doesn't work
                #logger.debug("file size ", int(fileDatas.size()))
                out.writeInt(fileDatas.size())
                out.writeRawData(fileDatas)

                # This may take a while. We display the progress bar so the user get a feedback
                self.sendFile = True
                self.progress.setLabelText("Sending file to server")
                self.progress.setCancelButton(None)
                self.progress.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint)
                self.progress.setAutoClose(True)
                self.progress.setMinimum(0)
                self.progress.setMaximum(100)
                self.progress.setModal(1)
                self.progress.setWindowTitle("Uploading in progress")
 
                self.progress.show()
                arg.close()
            else:
                logger.warn("Uninterpreted Data Type: " + str(type(arg)) + " sent as str: " + str(arg))
                out.writeQString(str(arg))

        out.device().seek(0)        
        out.writeUInt32(block.size() - 4)
        self.bytesToSend = block.size() - 4
    
        self.socket.write(block)

    @QtCore.pyqtSlot(QtNetwork.QAbstractSocket.SocketError)
    def socketError(self, error):
        logger.error("TCP Socket Error: " + self.socket.errorString())
        if self.state > ClientState.NONE:   # Positive client states deserve user notification.
            QtGui.QMessageBox.critical(None, "TCP Error", "A TCP Connection Error has occurred:<br/><br/><b>" + self.socket.errorString()+"</b>", QtGui.QMessageBox.Close)        
Example #15
0
    projection = perspective(45.0, width / float(height), 1.0, 1000.0)
    program['u_projection'] = projection


def keyboard(key, x, y):
    if key == '\033': sys.exit()


def timer(fps):
    galaxy.update(100000)  # in years !
    program['a_size'] = galaxy['size']
    glut.glutTimerFunc(1000 / fps, timer, fps)
    glut.glutPostRedisplay()


galaxy = Galaxy(35000)
galaxy.reset(13000, 4000, 0.0004, 0.90, 0.90, 0.5, 200, 300)

glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
glut.glutCreateWindow('Galaxy')
glut.glutReshapeWindow(800, 800)
glut.glutReshapeFunc(reshape)
glut.glutKeyboardFunc(keyboard)
glut.glutDisplayFunc(display)
glut.glutTimerFunc(1000 / 60, timer, 60)

program = gloo.Program(vertex, fragment, count=len(galaxy))
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
Example #16
0
def parse_options():
   parser = OptionParser()
   parser.add_option("", "--force", action="store_true", dest="force_update", help="force update of feeds", default=False),
   parser.add_option("", "--no-update", action="store_true", dest="no_update", help="prevent feed updates", default=False),
   parser.add_option('', '--delete-missing', dest="delete_missing", help="delete planets from db if they are not in file system", action="store_true", default=False)
   parser.add_option('', '--clean', dest="clean", help="remove missing planets, unused feeds", action="store_true", default=False)
   (options, args) = parser.parse_args()

   opt['force_check'] = options.force_update
   opt['no_update'] = options.no_update

   if len(args) >= 1:
      global planets
      planets.extend(args)

   if options.clean:
      log.debug("Cleaning databse.")
      galaxy = Galaxy(planets)
      galaxy.load()
      galaxy.delete_missing_planets()
      galaxy.delete_unused_feeds()
   elif options.delete_missing:
      log.debug("Deleting missing planets.")
      galaxy = Galaxy(planets)
      galaxy.load()
      galaxy.delete_missing_planets()
   else:
      return

   sys.exit()
Example #17
0
      galaxy.delete_unused_feeds()
   elif options.delete_missing:
      log.debug("Deleting missing planets.")
      galaxy = Galaxy(planets)
      galaxy.load()
      galaxy.delete_missing_planets()
   else:
      return

   sys.exit()

if __name__ == "__main__":
   parse_options()

   print "Options parsed."
   import templates
   for p,t in {'copyright':templates.Copyright,
               'thanks':templates.Thanks,
               'tos':templates.TOS,
               'index':templates.Main_Page,
               }.items():
      t(opt).write(cfg.OUTPUT_DIR, "%s.html" % p)
   galaxy = Galaxy(planets)
   galaxy.load()
   print "Galaxies loaded"
   #galaxy.dump()
   if not opt['no_update']:
      galaxy.update()
   galaxy.generate()

Example #18
0
 def __init__(self):
     self._players = []
     self._galaxy = Galaxy()
     self._time = 0
    #Create a generation error log
    errorlog = []
    errorlocation = []

    #Check for presence of galactic data file.
    try:
        with open('galactic_data.pkl', 'rb') as input:
            galaxy = pickle.load(input)
    except:
        # Break down input arguments
        if options.testflag is True:
            filename = "Test.csv"
            seed = 0.1234567890
            random.seed(seed)
            galaxy = Galaxy(1000)  #Number of particles
            galaxy.reset(13000, 4000, 0.0004, 0.85, 0.90, 0.5, 200, 300)
            galaxy.update(100000)
        else:
            # random.seed('earth')
            filename = "Production Run.csv"
            seed = 0.1234567890
            random.seed(seed)
            if seed:
                random.seed(seed)
            galaxy = Galaxy(35000)  #Number of particles
            galaxy.reset(13000, 4000, 0.0004, 0.85, 0.90, 0.5, 200, 300)
            galaxy.update(100000)

        exo = 0
        # Loop to produce all planets for stars
Example #20
0
#!/usr/bin/env python

import sys
from galaxy import Galaxy
from dictgraphviz import dict_to_digraph

def load_warps(path):
  sectors = {}
  with open(sys.argv[1]) as fh:
    fh.readline()
    for l in fh:
      line = l.strip().split()
      if len(line) < 2:
        break
      sectors[line[0]] = line[1:]
  return sectors


if __name__ == "__main__":
  galaxy = Galaxy(load_warps(sys.argv[1]))
  start = int(sys.argv[2])
  depth = int(sys.argv[3])
  output = galaxy.get_map(start, depth)
  print dict_to_digraph(output, "sector{0}depth{1}".format(start, depth))

Example #21
0
def reshape(width, height):
    gl.glViewport(0, 0, width, height)
    projection = perspective(45.0, width / float(height), 1.0, 1000.0)
    program['u_projection'] = projection

def keyboard(key, x, y):
    if key == '\033': sys.exit()

def timer(fps):
    galaxy.update(100000) # in years !
    program['a_size'] = galaxy['size']
    glut.glutTimerFunc(1000 / fps, timer, fps)
    glut.glutPostRedisplay()


galaxy = Galaxy(35000)
galaxy.reset(13000, 4000, 0.0004, 0.90, 0.90, 0.5, 200, 300)

glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
glut.glutCreateWindow('Galaxy')
glut.glutReshapeWindow(800,800)
glut.glutReshapeFunc(reshape)
glut.glutKeyboardFunc(keyboard)
glut.glutDisplayFunc(display)
glut.glutTimerFunc(1000 / 60, timer, 60)

program = gloo.Program(vertex, fragment, count = len(galaxy))
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
Example #22
0
class LobbyWidget(FormClass, BaseClass):
    planetClicked = QtCore.pyqtSignal(int)
    hovering = QtCore.pyqtSignal()
    creditsUpdated = QtCore.pyqtSignal(int)
    rankUpdated = QtCore.pyqtSignal(int)
    creditsUpdated = QtCore.pyqtSignal(int)
    victoriesUpdated = QtCore.pyqtSignal(int)
    attacksUpdated = QtCore.pyqtSignal()
    depotUpdated = QtCore.pyqtSignal()
    planetUpdated = QtCore.pyqtSignal(int)
    attackProposalUpdated = QtCore.pyqtSignal(int)
    ReinforcementUpdated = QtCore.pyqtSignal(dict)
    planetaryDefenseUpdated = QtCore.pyqtSignal(dict)
    ReinforcementsGroupUpdated = QtCore.pyqtSignal(dict)
    ReinforcementsGroupDeleted = QtCore.pyqtSignal(dict)
    dominationUpdated = QtCore.pyqtSignal(int)
    playersListUpdated = QtCore.pyqtSignal(dict)
    teamUpdated = QtCore.pyqtSignal(dict)
    searchingUpdated = QtCore.pyqtSignal(bool)

    def __init__(self, client, *args, **kwargs):
        logger.debug("Lobby instantiating.")
        BaseClass.__init__(self, *args, **kwargs)

        self.setupUi(self)

        self.client = client
        #self.client.galacticwarTab.setStyleSheet(util.readstylesheet("galacticwar/galacticwar.css"))

        self.COLOR_FACTIONS = {}
        self.mapTransparency = 10
        self.AA = True
        self.rotation = True
        self.stars = 25

        self.GWOptions = GWOptions(self)
        self.GWOptions.loadSettings()

        self.client.galacticwarTab.layout().addWidget(self)

        self.downloader = QNetworkAccessManager(self)
        self.downloader.finished.connect(self.finishRequest)

        self.shaderlist = []
        self.texturelist = {}
        self.shaders = {}

        self.infoPanel = None
        self.OGLdisplay = None

        self.galaxy = Galaxy(self)
        self.channel = None

        self.initDone = False

        self.uid = None
        self.faction = None
        self.name = None
        self.rank = None
        self.credits = 0
        self.victories = 0
        self.enslavedBy = None

        self.attacks = {}

        self.state = ClientState.NONE

        ## Network initialization

        self.socket = QtNetwork.QTcpSocket()
        self.socket.readyRead.connect(self.readFromServer)
        self.socket.disconnected.connect(self.disconnectedFromServer)
        self.socket.error.connect(self.socketError)
        self.blockSize = 0

        self.progress = QtGui.QProgressDialog()
        self.progress.setMinimum(0)
        self.progress.setMaximum(0)

#    def focusEvent(self, event):
#        return BaseClass.focusEvent(self, event)

    def showEvent(self, event):
        if self.state != ClientState.ACCEPTED:
            fa.exe.check("gw")
            if self.doConnect():
                logger.info("connection done")
                self.doLogin()

        else:
            if not self.initDone:
                logger.info("init not done")
                self.doLogin()
            else:
                if self.faction == None:
                    logger.info("not faction")
                    self.doLogin()

        return BaseClass.showEvent(self, event)

    def updateOptions(self):
        ''' settings galactic wars options'''
        self.GWOptions.show()

    def createChannel(self, chat, name):
        self.channel = gwChannel(chat, name, True)

    def finishRequest(self, reply):
        filename = reply.url().toString().rsplit('/', 1)[1]
        root, _ = os.path.splitext(filename)

        toFile = os.path.join(GW_TEXTURE_DIR, filename)
        writeFile = QtCore.QFile(toFile)
        if (writeFile.open(QtCore.QIODevice.WriteOnly)):
            writeFile.write(reply.readAll())
            writeFile.close()
        else:
            logger.warn("%s is not writeable in in %s. Skipping." %
                        (filename, GW_TEXTURE_DIR))

        if root in self.texturelist:
            del self.texturelist[root]

        if len(self.texturelist) == 0:
            self.setup()
            self.progress.close()

    def doConnect(self):
        logger.debug("Connecting to server")
        if self.client.state == ClientState.ACCEPTED:

            self.progress.setCancelButtonText("Cancel")
            self.progress.setWindowFlags(QtCore.Qt.CustomizeWindowHint
                                         | QtCore.Qt.WindowTitleHint)
            self.progress.setAutoClose(False)
            self.progress.setAutoReset(False)
            self.progress.setModal(1)
            self.progress.setWindowTitle("Galactic War Network...")
            self.progress.setLabelText("Gating in ...")
            self.progress.show()

            #            self.login = self.client.login.strip()
            #            logger.info("Attempting to gate as: " + str(self.client.login))
            self.state = ClientState.NONE

            # Begin connecting.
            self.socket.connectToHost(LOBBY_HOST, LOBBY_PORT)

            while (self.socket.state() !=
                   QtNetwork.QAbstractSocket.ConnectedState
                   ) and self.progress.isVisible():
                QtGui.QApplication.processEvents()

    #        #Perform Version Check first
            if not self.socket.state(
            ) == QtNetwork.QAbstractSocket.ConnectedState:

                self.progress.close()  # in case it was still showing...
                # We either cancelled or had a TCP error, meaning the connection failed..
                if self.progress.wasCanceled():
                    logger.warn("doConnect() aborted by user.")
                else:
                    logger.error("doConnect() failed with clientstate " +
                                 str(self.state) + ", socket errorstring: " +
                                 self.socket.errorString())
                return False
            else:

                return True

    def doLogin(self):
        ''' login in the GW server 
            We are using the main login and session to check legitimity of the client.
        '''

        self.progress.setLabelText("Gating in...")
        self.progress.reset()
        self.progress.show()

        logger.info("Attempting to gate as: " + str(self.client.login))
        self.state = ClientState.NONE

        self.send(
            dict(command="hello",
                 version=util.VERSION_STRING,
                 port=self.client.gamePort,
                 login=self.client.login,
                 session=self.client.session))

        while (not self.state) and self.progress.isVisible():
            QtGui.QApplication.processEvents()

        if self.progress.wasCanceled():
            logger.warn("Gating aborted by user.")
            return False

        self.progress.close()

        if self.state == ClientState.ACCEPTED:
            logger.info("Gating accepted.")
            self.progress.close()
            self.client.actionGalacticWar.triggered.connect(self.updateOptions)
            self.client.actionGalacticWar.setEnabled(True)
            return True
            #self.connected.emit()

        elif self.state == ClientState.REJECTED:
            logger.warning("Gating rejected.")
            return False
        else:
            # A more profound error has occurrect (cancellation or disconnection)
            return False

    def setup(self):
        self.galaxy.computeVoronoi()
        from glDisplay import GLWidget
        from infopanel import InfoPanelWidget
        from newsTicker import NewsTicker
        from reinforcements import PlanetaryWidget
        from reinforcements import ReinforcementWidget

        #items panels
        self.teams = Teams(self)
        self.planetaryItems = PlanetaryWidget(self)
        self.reinforcementItems = ReinforcementWidget(self)
        self.OGLdisplay = GLWidget(self)
        self.newsTicker = NewsTicker(self)
        self.galaxyLayout.addWidget(self.OGLdisplay)
        self.galaxyLayout.addWidget(self.newsTicker)
        self.newsTicker.setMaximumHeight(20)
        self.infoPanel = InfoPanelWidget(self)
        self.info_Panel.layout().addWidget(self.infoPanel)

        self.send(dict(command="init_done", status=True))
        self.infoPanel.setup()

    def get_rank(self, faction, rank):
        return RANKS[faction][rank]

    def handle_welcome(self, message):
        self.state = ClientState.ACCEPTED

    def handle_planetary_defense_info(self, message):
        '''populate planetary defense lists'''
        self.planetaryDefenseUpdated.emit(message)

    def handle_group_reinforcements_info(self, message):
        '''populate current group reinforcements '''
        self.ReinforcementsGroupUpdated.emit(message)

    def handle_group_reinforcements_deleted(self, message):
        self.ReinforcementsGroupDeleted.emit(message)

    def handle_reinforcement_item_info(self, message):
        '''populate reinforcement lists'''
        self.ReinforcementUpdated.emit(message)

    def handle_resource_required(self, message):
        if message["action"] == "shaders":
            self.shaderlist = message["data"]
            self.send(dict(command="request", action="shaders"))
        elif message["action"] == "textures":
            for tex in message["data"]:
                if not tex in self.texturelist:
                    self.texturelist[tex] = message["data"][tex]

    def handle_shader(self, message):
        name = message["name"]
        shader_fragment = message["shader_fragment"]
        shader_vertex = message["shader_vertex"]
        if not name in self.shaders:
            self.shaders[name] = {}
            self.shaders[name]["fragment"] = shader_fragment
            self.shaders[name]["vertex"] = shader_vertex

        if name in self.shaderlist:
            self.shaderlist.remove(name)
        self.check_resources()

        #we have all our shader.

    def get_texture_name(self, tex):
        return os.path.join(GW_TEXTURE_DIR, tex + ".png")

    def download_textures(self):
        self.progress.show()
        self.progress.setLabelText("Downloading resources ...")

        textInCache = []

        for tex in self.texturelist:
            if os.path.exists(self.get_texture_name(tex)):
                if util.md5(
                        self.get_texture_name(tex)) == self.texturelist[tex]:
                    #logger.debug(tex + ".png in cache.")
                    textInCache.append(tex)
                    continue
            #logger.debug("Downloading " + tex + ".png")
            self.downloader.get(
                QNetworkRequest(QtCore.QUrl(TEXTURE_SERVER + tex + ".png")))

        for tex in textInCache:
            del self.texturelist[tex]

        if len(self.texturelist) == 0:
            self.progress.close()
            self.setup()

    def check_resources(self):
        '''checking if we have everything we need'''
        if len(self.shaderlist) == 0 and self.initDone:
            self.download_textures()

    def handle_remove_team(self, message):
        self.teamUpdated.emit(dict(leader=None, members=[]))

    def handle_team(self, message):
        self.teamUpdated.emit(message)

    def handle_request_team(self, message):
        ''' We have a team invitation from someone '''
        who = message["who"]
        uid = message["uid"]

        self.infoPanel.formTeam()
        self.infoPanel.teamwidget.addProposal(who, uid)

    def handle_news_feed(self, message):
        '''Adding news to news feed'''
        if hasattr(self, "newsTicker"):
            if self.newsTicker:
                self.newsTicker.addNews(message["news"])

    def handle_player_info(self, message):
        ''' Update Player stats '''

        self.uid = int(message["uid"])
        self.faction = message["faction"]
        self.name = message["name"]
        self.rank = message["rank"]
        self.credits = message["credits"]
        self.victories = message["victories"]

        logger.debug("Received player info : victories %i, credits %i" %
                     (self.victories, self.credits))

        self.rankUpdated.emit(self.rank)
        self.creditsUpdated.emit(self.credits)
        self.victoriesUpdated.emit(self.victories)

    def handle_game_upgrades(self, message):
        '''writing reinforcement list'''
        upgrades = message["upgrades"]
        fa.gwgametable.writeTable(upgrades, "gwReinforcementList.gw")

        # and we empty the unit reinforcement list
        self.reinforcementItems.reset()

    def handle_domination(self, message):
        master = message["master"]
        self.enslavedBy = master
        self.dominationUpdated.emit(master)

    def handle_attack_result(self, message):
        self.progress.close()
        result = message["result"]
        if result == "won":
            QtGui.QMessageBox.information(self, "War report", "You win !",
                                          QtGui.QMessageBox.Close)

    def handle_attack_proposal(self, message):
        planetuid = message["planetuid"]
        self.attackProposalUpdated.emit(planetuid)

    def handle_attacks_info(self, message):
        if self.OGLdisplay == None:
            return

        attacks = message["attacks"]
        self.attacks = {}

        for playeruid in attacks:
            playeruid_int = int(playeruid)
            if not playeruid_int in self.attacks:
                self.attacks[playeruid_int] = {}

            for planetuid in attacks[playeruid]:
                planetuid_int = int(planetuid)
                self.attacks[playeruid_int][planetuid_int] = attacks[
                    playeruid][planetuid]
        self.attacksUpdated.emit()

    def handle_planet_defense_remove(self, message):
        '''handling removing defenses for a planet'''
        planetuid = message["planetuid"]
        self.galaxy.removeDefenses(planetuid)

    def handle_planet_depot_info(self, message):
        '''handling depots'''
        planetuid = message["planetuid"]
        self.galaxy.updateDepot(planetuid, message)
        self.depotUpdated.emit()

    def handle_planet_defense_info(self, message):
        '''handling defenses for planets'''
        planetuid = message["planetuid"]
        self.galaxy.updateDefenses(planetuid, message)

    def handle_planet_info(self, message):
        uid = message['uid']
        if not uid in self.galaxy.control_points:
            display = message['visible']
            x = message['posx']
            y = message['posy']
            size = message['size']
            textureMd5 = message['md5tex']
            name = message['name']
            desc = message['desc']
            sector = message['sector']
            if display:
                texture = message['texture']
                mapname = message['mapname']
                maxplayer = message['maxplayer']
                if not texture in self.texturelist:
                    self.texturelist[texture] = textureMd5
            else:
                mapname = ""
                texture = 0
                maxplayer = 0

            self.galaxy.addPlanet(uid,
                                  sector,
                                  name,
                                  desc,
                                  x,
                                  y,
                                  size,
                                  maxplayer=maxplayer,
                                  mapname=mapname,
                                  texture=texture,
                                  init=True,
                                  display=display)
            self.galaxy.update(message)

            if not uid in self.galaxy.links:
                self.galaxy.links[uid] = message['links']
        else:
            self.galaxy.update(message)
            self.planetUpdated.emit(message['sector'])

    def handle_logged_in(self, message):

        self.handle_player_info(message)
        if self.faction != None:
            self.client.galacticwarTab.setStyleSheet(
                util.readstylesheet("galacticwar/galacticwar.css").replace(
                    "%FACTION%", FACTIONS[self.faction]))

        self.attacksUpdated.emit()

    def handle_create_account(self, message):
        if message["action"] == 0:

            accountCreator = loginwizards.gwSelectFaction(self)
            accountCreator.exec_()
            if self.faction != None:
                self.send(
                    dict(command="account_creation",
                         action=0,
                         faction=self.faction))
            else:
                self.client.mainTabs.setCurrentIndex(0)
                QtGui.QMessageBox.warning(
                    self, "No faction :(",
                    "You need to pledge allegiance to a faction in order to play Galactic War !"
                )

        elif message["action"] == 1:
            name = message["name"]
            self.faction = message["faction"]

            self.rank = message["rank"]

            question = QtGui.QMessageBox.question(
                self, "Avatar name generation",
                "Your avatar name will be : <br><br>" +
                self.get_rank(self.faction, self.rank) + " " + name +
                ".<br><br>Press Reset to generate another, Ok to accept.",
                QtGui.QMessageBox.Reset, QtGui.QMessageBox.Ok)
            if question == QtGui.QMessageBox.Reset:
                self.send(dict(command="account_creation", action=1))
            else:
                self.name = name
                self.send(dict(command="account_creation", action=2))

    def handle_faction_player_list(self, message):
        '''players online'''
        self.playersListUpdated.emit(message["players"])

    def handle_init_done(self, message):
        if message['status'] == True:
            self.initDone = True
            self.check_resources()

    def handle_social(self, message):
        if "autojoin" in message:
            if message["autojoin"] == 0:
                self.client.autoJoin.emit(["#UEF"])
            elif message["autojoin"] == 1:
                self.client.autoJoin.emit(["#Aeon"])
            elif message["autojoin"] == 2:
                self.client.autoJoin.emit(["#Cybran"])
            elif message["autojoin"] == 3:
                self.client.autoJoin.emit(["#Seraphim"])

    def handle_searching(self, message):
        state = message["state"]
        if state == "on":
            self.searchingUpdated.emit(True)
        else:
            self.searchingUpdated.emit(False)

    def handle_notice(self, message):
        self.client.handle_notice(message)

    def handle_update(self, message):
        update = message["update"]
        if not util.developer():
            logger.warn("Server says that Updating is needed.")
            self.progress.close()
            self.state = ClientState.OUTDATED
            fa.updater.fetchClientUpdate(update)

    def process(self, action, stream):
        if action == "PING":
            self.writeToServer("PONG")
        else:
            self.dispatchJSON(action, stream)

    def dispatchJSON(self, data_string, stream):
        '''
        A fairly pythonic way to process received strings as JSON messages.
        '''
        message = json.loads(data_string)
        cmd = "handle_" + message['command']
        #logger.debug("Incoming JSON Command: " + data_string)
        if hasattr(self, cmd):
            getattr(self, cmd)(message)
        else:
            logger.error("command unknown : %s", cmd)

    def send(self, message):
        data = json.dumps(message)
        logger.info("Outgoing JSON Message: " + data)
        self.writeToServer(data)

    @QtCore.pyqtSlot()
    def readFromServer(self):
        ins = QtCore.QDataStream(self.socket)
        ins.setVersion(QtCore.QDataStream.Qt_4_2)

        while ins.atEnd() == False:
            if self.blockSize == 0:
                if self.socket.bytesAvailable() < 4:
                    return
                self.blockSize = ins.readUInt32()
            if self.socket.bytesAvailable() < self.blockSize:
                return

            action = ins.readQString()
            self.process(action, ins)
            self.blockSize = 0

    @QtCore.pyqtSlot()
    def disconnectedFromServer(self):
        logger.warn("Disconnected from lobby server.")

        if self.state == ClientState.ACCEPTED:
            QtGui.QMessageBox.warning(
                QtGui.QApplication.activeWindow(),
                "Disconnected from Galactic War",
                "The lobby lost the connection to the Galactic War server.<br/><b>You might still be able to chat.<br/>To play, try reconnecting a little later!</b>",
                QtGui.QMessageBox.Close)
            self.initDone = False
            self.client.mainTabs.setCurrentIndex(0)

            self.client.mainTabs.setTabEnabled(
                self.client.mainTabs.indexOf(self.client.galacticwarTab),
                False)
            self.client.mainTabs.setTabText(
                self.client.mainTabs.indexOf(self.client.galacticwarTab),
                "offline")

        self.state = ClientState.DROPPED

    def writeToServer(self, action, *args, **kw):
        '''
        This method is the workhorse of the client, and is used to send messages, queries and commands to the server.
        '''
        logger.debug("Client: " + action)

        block = QtCore.QByteArray()
        out = QtCore.QDataStream(block, QtCore.QIODevice.ReadWrite)
        out.setVersion(QtCore.QDataStream.Qt_4_2)

        out.writeUInt32(0)
        out.writeQString(action)

        for arg in args:
            if type(arg) is IntType:
                out.writeInt(arg)
            elif isinstance(arg, basestring):
                out.writeQString(arg)
            elif type(arg) is FloatType:
                out.writeFloat(arg)
            elif type(arg) is ListType:
                out.writeQVariantList(arg)
            elif type(arg) is DictType:
                out.writeQString(json.dumps(arg))
            elif type(arg) is QtCore.QFile:
                arg.open(QtCore.QIODevice.ReadOnly)
                fileDatas = QtCore.QByteArray(arg.readAll())
                #seems that that logger doesn't work
                #logger.debug("file size ", int(fileDatas.size()))
                out.writeInt(fileDatas.size())
                out.writeRawData(fileDatas)

                # This may take a while. We display the progress bar so the user get a feedback
                self.sendFile = True
                self.progress.setLabelText("Sending file to server")
                self.progress.setCancelButton(None)
                self.progress.setWindowFlags(QtCore.Qt.CustomizeWindowHint
                                             | QtCore.Qt.WindowTitleHint)
                self.progress.setAutoClose(True)
                self.progress.setMinimum(0)
                self.progress.setMaximum(100)
                self.progress.setModal(1)
                self.progress.setWindowTitle("Uploading in progress")

                self.progress.show()
                arg.close()
            else:
                logger.warn("Uninterpreted Data Type: " + str(type(arg)) +
                            " sent as str: " + str(arg))
                out.writeQString(str(arg))

        out.device().seek(0)
        out.writeUInt32(block.size() - 4)
        self.bytesToSend = block.size() - 4

        self.socket.write(block)

    @QtCore.pyqtSlot(QtNetwork.QAbstractSocket.SocketError)
    def socketError(self, error):
        logger.error("TCP Socket Error: " + self.socket.errorString())
        if self.state > ClientState.NONE:  # Positive client states deserve user notification.
            QtGui.QMessageBox.critical(
                None, "TCP Error",
                "A TCP Connection Error has occurred:<br/><br/><b>" +
                self.socket.errorString() + "</b>", QtGui.QMessageBox.Close)
class Game:
    def __init__(self, screen_width=120, screen_height=70):
        self.screen_width = screen_width
        self.screen_height = screen_height

        libtcod.console_init_root(self.screen_width, self.screen_height, 'Heliopause', False)

        self.buffer = libtcod.ConsoleBuffer(self.screen_width, self.screen_height)
        self.console = libtcod.console_new(self.screen_width, self.screen_height)

        self.galaxy_map_console = libtcod.console_new(self.screen_width, self.screen_height)

        self.set_minimap(20)

        self.targeting_width = 20
        self.targeting_height = 26
        self.targeting_buffer  = libtcod.ConsoleBuffer(self.targeting_width, self.targeting_height)
        self.targeting_console = libtcod.console_new(self.targeting_width, self.targeting_height)
        libtcod.console_set_default_foreground(self.targeting_console, libtcod.white)
        libtcod.console_set_default_background(self.targeting_console, libtcod.black)

        self.ship_info_width = 20
        self.ship_info_height = 8
        self.ship_info_buffer  = libtcod.ConsoleBuffer(self.ship_info_width, self.ship_info_height)
        self.ship_info_console = libtcod.console_new(self.ship_info_width, self.ship_info_height)
        libtcod.console_set_default_foreground(self.ship_info_console, libtcod.white)
        libtcod.console_set_default_background(self.ship_info_console, libtcod.black)

        self.message_height = 4
        self.message_width = self.screen_width
        self.messages = collections.deque([])
        self.message_console = libtcod.console_new(self.message_width, self.message_height)
        libtcod.console_set_default_foreground(self.message_console, libtcod.white)
        libtcod.console_set_default_background(self.message_console, libtcod.black)

        self.landing_screen_width = self.screen_width / 2 - 2
        self.landing_screen_height = self.screen_height - 4
        self.landing_console = libtcod.console_new(self.landing_screen_width, self.landing_screen_height)
        libtcod.console_set_default_foreground(self.landing_console, libtcod.white)
        libtcod.console_set_default_background(self.landing_console, libtcod.black)

        self.mouse = libtcod.Mouse()
        self.key = libtcod.Key()

        galaxy_seed, ship_value = self.title_screen_loop()

        # Loading Screen
        libtcod.console_set_default_background(self.console, libtcod.black)
        libtcod.console_clear(self.console)

        self.galaxy = Galaxy(self.screen_width, self.screen_height, seed=galaxy_seed)
        self.sector, self.starfield, self.nebula = self.galaxy.sectors[self.galaxy.current_sector].load_sector(self.console, self.buffer)

        starting_planet = self.sector.planets[randrange(1, len(self.sector.planets))]
        self.player_ship = Ship(self.sector, starting_planet.sector_position_x, starting_planet.sector_position_y, ship_value=ship_value)
        self.add_message("Taking off from {0}".format(starting_planet.name))

        self.current_screen = 'flight'

        # self.add_message("Nebula Colors: r:{0} g:{1} b:{2}".format(
        #     round(self.nebula.r_factor,2),
        #     round(self.nebula.g_factor,2),
        #     round(self.nebula.b_factor,2)))

    def title_screen_loop(self):
        self.current_screen = 'title'
        self.sector = Sector(self.screen_width, self.screen_height, self.buffer)
        self.starfield = Starfield(self.sector, max_stars=50)
        self.nebula = Nebula(self.sector, r_factor=random(), g_factor=random(), b_factor=random(), seed=randrange(1,1000000))
        self.ships = [ [ Ship(self.sector, 0, 0), [self.screen_width/2-16, self.screen_height/2-8] ] for i in range(1) ]

        done = False
        xpos = 0.0
        speed = 3
        galaxy_starting_seed = str(randrange(1,1000000))
        cursor_blinked = 0.0
        cursor = collections.deque(['|', ''])

        title = [
            ' _    _      _ _',
            '| |  | |    | (_)',
            '| |__| | ___| |_  ___  _ __   __ _ _   _ ___  ___',
            '|  __  |/ _ \\ | |/ _ \\| \'_ \\ / _` | | | / __|/ _ \\',
            '| |  | |  __/ | | (_) | |_) | (_| | |_| \\__ \\  __/',
            '|_|  |_|\\___|_|_|\\___/| .__/ \\__,_|\\__,_|___/\\___|',
            '                      | |',
            '                      |_|',
        ]

        while not done:
            libtcod.sys_check_for_event(libtcod.KEY_PRESSED|libtcod.KEY_RELEASED|libtcod.EVENT_MOUSE, self.key, self.mouse)

            self.starfield.scroll(0.0, speed)
            self.starfield.draw()

            self.sector.update_visibility(xpos, 0)
            xpos += speed

            self.nebula.draw()

            for ship, position in self.ships:
                # ship.heading += math.radians(10)
                # if math.degrees(ship.heading) > 350:
                #     ship.heading = 0
                ship.draw(startx=position[0], starty=position[1], hq2x=True)

            self.buffer.blit(self.console)

            t = time.clock()
            if t > cursor_blinked + 0.5:
                cursor_blinked = t
                cursor.rotate()

            for index, line in enumerate(title):
                libtcod.console_print_ex(self.console, (self.screen_width/2)-26, 10+index, libtcod.BKGND_NONE, libtcod.LEFT, line)

            libtcod.console_print_ex(self.console, 1, self.screen_height-2, libtcod.BKGND_NONE, libtcod.LEFT, "Starting Seed: {0}{1}".format(galaxy_starting_seed, cursor[0]))
            libtcod.console_blit(self.console, 0, 0, self.screen_width, self.screen_height, 0, 0, 0)

            libtcod.console_flush()

            self.buffer.clear(self.sector.background[0], self.sector.background[1], self.sector.background[2])

            # player_action = self.handle_keys_titlescreen()
            if self.key.pressed and self.key.vk == libtcod.KEY_ESCAPE:
                exit(0)
            elif self.key.pressed and self.key.vk == libtcod.KEY_ENTER:
                done = True
            elif self.key.pressed and self.key.vk == libtcod.KEY_BACKSPACE:
                if galaxy_starting_seed:
                    galaxy_starting_seed = galaxy_starting_seed[:-1]
            elif self.key.pressed:
                key_character = chr(self.key.c)
                if key_character in '1234567890':
                    galaxy_starting_seed += key_character
                elif key_character == 'G':
                    for ship, position in self.ships:
                        ship.ship_value = getrandbits(32)
                        ship.load_ship_sprites()

        ship_value = self.ships[0][0].ship_value
        del(self.ships)
        return int(galaxy_starting_seed), ship_value

    def set_minimap(self, size):
        self.minimap_width  = size+3
        self.minimap_height = size+3
        self.minimap_buffer  = libtcod.ConsoleBuffer(self.minimap_width, self.minimap_height)
        self.minimap_console = libtcod.console_new(self.minimap_width, self.minimap_height)
        libtcod.console_set_default_foreground(self.minimap_console, libtcod.white)
        libtcod.console_set_default_background(self.minimap_console, libtcod.black)

    def new_sector(self):
        index, distance = self.sector.closest_planet(self.player_ship)
        # if self.sector.distance_from_center(self.player_ship) > 500:
        if distance > 500:
            fade_speed = 10
            # Fade out
            for fade in range(255,0,-1*fade_speed):
                libtcod.console_set_fade(fade,libtcod.black)
                libtcod.console_flush()

            self.sector.clear_selected_planet()

            self.galaxy.current_sector = self.galaxy.sectors[self.galaxy.current_sector].neighbors[self.galaxy.targeted_sector_index]
            self.galaxy.targeted_sector_index = 0
            self.sector, self.starfield, self.nebula = self.galaxy.sectors[self.galaxy.current_sector].load_sector(self.console, self.buffer)

            self.player_ship.sector = self.sector
            self.player_ship.dead_stop()
            self.player_ship.velocity = int(self.player_ship.speed_limit / 2)
            self.player_ship.face_system_center()
            self.player_ship.about_face()
            self.player_ship.velocity_angle = self.player_ship.heading
            self.player_ship.apply_thrust()

            self.clear_messages()
            self.add_message("Arriving in {0}".format(self.galaxy.sectors[self.galaxy.current_sector].name))
            # self.add_message("Nebula Colors: r:{0} g:{1} b:{2}".format(
            #     round(self.nebula.r_factor,2),
            #     round(self.nebula.g_factor,2),
            #     round(self.nebula.b_factor,2)))

            # Fade in
            libtcod.console_set_fade(0,libtcod.black)
            self.render_all()
            for fade in range(0,255,fade_speed):
                libtcod.console_set_fade(fade,libtcod.black)
                libtcod.console_flush()

        else:
            self.add_message("You are not far enough from the nearest planet to jump")

    def check_for_collisions(self):
        asteroid_to_delete = None
        for index, asteroid in enumerate(self.sector.asteroids):
            for p in self.sector.particles:
                if p.bullet:
                    if asteroid.sector_position_x < p.sector_position_x < asteroid.sector_position_x+asteroid.width and \
                       asteroid.sector_position_y+1 < p.sector_position_y < asteroid.sector_position_y+1+asteroid.width:
                        asteroid.hp -= p.damage
                        if asteroid.hp < 0:
                            for a in range(0, 60):
                                self.sector.add_particle(
                                    ExplosionFireBall(
                                        starting_index       = a/10,
                                        sector               = self.sector,
                                        x                    = p.x,
                                        y                    = p.y,
                                        sector_position_x    = p.sector_position_x,
                                        sector_position_y    = p.sector_position_y,
                                        angle                = randrange(0, 359),
                                        velocity             = random() * randrange(1,3)))
                            # self.sector.asteroids.remove(asteroid)
                            asteroid_to_delete = index
                        else:
                            self.sector.add_particle(
                                Fire(
                                    sector               = self.sector,
                                    x                    = p.x,
                                    y                    = p.y,
                                    sector_position_x    = p.sector_position_x,
                                    sector_position_y    = p.sector_position_y))
                        # delete the bullet that hit
                        self.sector.particles.remove(p)
        if asteroid_to_delete is not None:
            self.sector.asteroids.pop(asteroid_to_delete)

    def render_all(self):
        if self.player_ship.velocity > 0.0:
            self.starfield.scroll( self.player_ship.velocity_angle, self.player_ship.velocity )

        self.starfield.draw()

        self.sector.update_particle_positions()
        self.sector.scroll_particles( self.player_ship.velocity_angle, self.player_ship.velocity )

        self.sector.update_visibility(self.player_ship.sector_position_x, self.player_ship.sector_position_y)

        self.nebula.draw()

        for planet in self.sector.planets:
            planet.draw()

        for asteroid in self.sector.asteroids:
            asteroid.draw()
        self.check_for_collisions()

        for particle in self.sector.particles:
            particle.draw()

        self.player_ship.draw()

        if self.sector.selected_planet is not None or self.sector.selected_asteroid is not None:
            self.sector.update_selected_planet_distance(self.player_ship)
            if self.sector.selected_planet_distance() > (self.screen_height/2.0):
                self.player_ship.draw_target_arrow(self.sector.selected_planet_angle)
                # self.sector.draw_target_arrow(self.player_ship)

        self.buffer.blit(self.console)
        libtcod.console_blit(self.console, 0, 0, self.screen_width, self.screen_height, 0, 0, 0)

        if self.sector.selected_planet is not None or self.sector.selected_asteroid is not None:
            # Target window
            planet = self.sector.get_selected_planet()
            planet.draw_target_picture(self.targeting_buffer, 4, 2)
            self.targeting_buffer.blit(self.targeting_console)
            libtcod.console_print_frame(self.targeting_console, 0, 0, self.targeting_width, self.targeting_height, clear=False, flag=libtcod.BKGND_SET, fmt=0)

            name = textwrap.wrap(" Name: {0}".format(planet.name), width=self.targeting_width-4)
            libtcod.console_print_ex(self.targeting_console, 1, 16, libtcod.BKGND_SET, libtcod.LEFT,
                "\n  ".join(name)+"\n"
            )

            planet_class = planet.planet_class.title()
            if planet.star_class:
                planet_class += " ({0})".format(planet.star_class)

            extra_info = ""
            if planet.star_temp:
                extra_info = "\n Temp: {0} K\n".format(planet.star_temp)
            elif planet.planet_class == 'asteroid':
                extra_info = "\n HP: {0} \n".format(planet.hp)

            libtcod.console_print_ex(self.targeting_console, 1, 17+len(name), libtcod.BKGND_SET, libtcod.LEFT,
                ( " Class: {0}\n{1}\n"
                  " Distance: {2}\n"
                ).format(
                    planet_class,
                    extra_info,
                    int(self.sector.selected_planet_distance()),
                )
            )
            libtcod.console_blit(self.targeting_console, 0, 0, self.targeting_width, self.targeting_height, 0, 0, 0, 1.0, 0.25)

        # Ship Info
        libtcod.console_print_frame(self.ship_info_console, 0, 0, self.ship_info_width, self.ship_info_height, clear=True, flag=libtcod.BKGND_SET, fmt=0)
        libtcod.console_print_ex(self.ship_info_console, 1, 1, libtcod.BKGND_SET, libtcod.LEFT,
                ( "  Heading: {0}\n"
                  " Velocity: {1}\n"
                  " VelAngle: {2}\n"
                  "Particles: {3}\n"
                  "Ship\nSeed: {4}\n"
                  # "Nebula Position:\n"
                  # "l:{4} r:{5}\n"
                  # "t:{6} b:{7}\n"
                ).format(
                    round(math.degrees(self.player_ship.heading),2),
                    round(self.player_ship.velocity,2),
                    round(math.degrees(self.player_ship.velocity_angle),2),
                    len(self.sector.particles),
                    hex(self.player_ship.ship_value)
                    # self.nebula.left, self.nebula.right, self.nebula.top, self.nebula.bottom
            ).ljust(self.ship_info_width-2)
        )
        libtcod.console_blit(self.ship_info_console, 0, 0, self.ship_info_width, self.ship_info_height, 0, self.screen_width-self.ship_info_width, self.screen_height-self.ship_info_height-self.message_height, 1.0, 0.25)

        # Bottom Messages
        if len(self.messages) > 0:
            libtcod.console_print_ex(self.message_console, 0, 0, libtcod.BKGND_SET, libtcod.LEFT,
                    "\n".join([message.ljust(self.message_width) for message in self.messages]) )
            libtcod.console_blit(self.message_console, 0, 0, self.message_width, self.message_height, 0, 0, self.screen_height-self.message_height, 1.0, 0.25)

        # Minimap
        self.sector.draw_minimap(self.minimap_buffer, self.minimap_width, self.minimap_height, self.player_ship)
        self.minimap_buffer.blit(self.minimap_console)
        libtcod.console_print_frame(self.minimap_console, 0, 0, self.minimap_width, self.minimap_height, clear=False, flag=libtcod.BKGND_SET, fmt=0)
        libtcod.console_print_ex(self.minimap_console, 1, self.minimap_height-1, libtcod.BKGND_SET, libtcod.LEFT,
            ("[ {0} {1} ]").format(
                int(self.player_ship.sector_position_x),
                int(self.player_ship.sector_position_y),
            ).center(self.minimap_width-2, chr(196))
        )
        libtcod.console_blit(self.minimap_console, 0, 0, self.minimap_width, self.minimap_height, 0, self.screen_width-self.minimap_width, 0, 1.0, 0.25)

        libtcod.console_flush()
        self.buffer.clear(self.sector.background[0], self.sector.background[1], self.sector.background[2])

    def handle_keys(self):
        if self.key.vk == libtcod.KEY_UP:
            self.player_ship.throttle_open = self.key.pressed
        if self.key.vk == libtcod.KEY_DOWN:
            self.player_ship.reversing = self.key.pressed
        if self.key.vk == libtcod.KEY_LEFT:
            self.player_ship.turning_left = self.key.pressed
        if self.key.vk == libtcod.KEY_RIGHT:
            self.player_ship.turning_right = self.key.pressed

        if self.key.vk == libtcod.KEY_SPACE:
            self.player_ship.laser_firing = self.key.pressed

        if self.key.pressed and self.key.vk == libtcod.KEY_ENTER and self.key.lalt:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
        elif self.key.pressed and self.key.vk == libtcod.KEY_ESCAPE:
            return 1  #exit game
        elif self.key.pressed:
            key_character = chr(self.key.c)
            if key_character == 'l' and self.current_screen == 'flight':
                landed, message, planet_index = self.sector.land_at_closest_planet(self.player_ship)
                if message:
                    self.add_message(message)
                if landed:
                    self.landed_loop(planet_index)

            elif key_character == 'G':
                self.player_ship.ship_value = getrandbits(32)
                self.player_ship.load_ship_sprites()
            elif self.key.vk == libtcod.KEY_TAB:
                if self.current_screen == 'flight':
                    self.galaxy_map_loop()
                else:
                    return 1 # exit galaxy loop
            elif key_character == '\\' and self.current_screen == 'galaxy':
                self.galaxy.cycle_sector_target()

            elif key_character == 'm':
                if self.minimap_width == self.screen_height:
                    self.set_minimap(20)
                elif self.minimap_width == 23:
                    self.set_minimap(20 + (self.screen_height-20)/2)
                else:
                    self.set_minimap(self.screen_height-3)

            elif key_character == 'p':
                self.sector.cycle_planet_target(self.player_ship)
            elif key_character == 'P':
                self.sector.target_nearest_planet(self.player_ship)

            elif key_character == 't':
                self.sector.cycle_target(self.player_ship)
            elif key_character == 'T':
                self.sector.target_nearest_asteroid(self.player_ship)

            elif key_character == 'j' and self.current_screen == 'flight':
                self.new_sector()

            elif key_character == 'S':
                libtcod.sys_save_screenshot()
                self.add_message("Saved screenshot")


    def clear_messages(self):
        self.messages.clear()

    def add_message(self, message):
        if len(self.messages) == self.message_height:
            self.messages.popleft()
        self.messages.append(message)

    def galaxy_map_loop(self):
        self.current_screen = 'galaxy'
        done = False
        while not done:
            libtcod.sys_check_for_event(libtcod.KEY_PRESSED|libtcod.KEY_RELEASED|libtcod.EVENT_MOUSE, self.key, self.mouse)
            libtcod.console_clear(self.galaxy_map_console)

            self.starfield.draw()
            self.nebula.draw()
            self.galaxy.draw(self.buffer)
            self.buffer.blit(self.console)
            libtcod.console_blit(self.console, 0, 0, self.screen_width, self.screen_height, 0, 0, 0)

            # Galaxy Map Border/Frame
            libtcod.console_print_frame(self.galaxy_map_console, 0, 0, self.screen_width, self.screen_height,
                    clear=False, flag=libtcod.BKGND_SET, fmt=0)

            # Title in the center of the top border
            top_title = "[ Galaxy Map ]"
            libtcod.console_print_ex(self.galaxy_map_console,
                    (self.screen_width/2) - (len(top_title)/2),
                    0, libtcod.BKGND_SET, libtcod.LEFT, top_title)

            # Title in the center of the bottom border
            bottom_title = "[ Seed: {0} ]".format( self.galaxy.seed )
            libtcod.console_print_ex(self.galaxy_map_console,
                    (self.screen_width/2) - (len(bottom_title)/2),
                    self.screen_height-1, libtcod.BKGND_SET, libtcod.LEFT, bottom_title)

            # Extra info in upper right
            info = ("Current Sector: {0}\n"
                    "Target  Sector: {1}\n").format(
                self.galaxy.sectors[self.galaxy.current_sector].name,
                self.galaxy.sectors[ self.galaxy.sectors[self.galaxy.current_sector].neighbors[self.galaxy.targeted_sector_index] ].name
            )
            libtcod.console_print_ex(self.galaxy_map_console,
                    1, 1, libtcod.BKGND_SET, libtcod.LEFT, info)

            libtcod.console_blit(self.galaxy_map_console, 0, 0, self.screen_width, self.screen_height, 0, 0, 0, 1.0, 0.25)
            libtcod.console_flush()

            self.buffer.clear(self.sector.background[0], self.sector.background[1], self.sector.background[2])

            player_action = self.handle_keys()
            if player_action == 1:
                done = True

        self.current_screen = 'flight'

    def landed_loop(self, planet_index):
        self.current_screen = 'landed'
        done = False
        planet = self.sector.planets[planet_index]
        while not done:
            libtcod.sys_check_for_event(libtcod.KEY_PRESSED|libtcod.KEY_RELEASED|libtcod.EVENT_MOUSE, self.key, self.mouse)

            self.starfield.draw()
            self.nebula.draw()

            planet.render_detail()
            self.buffer.blit(self.console)

            libtcod.console_blit(self.console, 0, 0, self.screen_width, self.screen_height, 0, 0, 0)

            libtcod.console_print_frame(self.landing_console, 0, 0, self.landing_screen_width, self.landing_screen_height, clear=True, flag=libtcod.BKGND_SET, fmt=0)
            title = "[ Landed at {0} ]".format(planet.name)
            libtcod.console_print_ex(self.landing_console,
                    (self.landing_screen_width/2) - (len(title)/2),
                    0, libtcod.BKGND_SET, libtcod.LEFT, title)
            libtcod.console_print_ex(self.landing_console,
                    2, 2, libtcod.BKGND_SET, libtcod.LEFT,
                    "Class: {0}".format(planet.planet_class.title()))
            libtcod.console_print_ex(self.landing_console,
                    2, 3, libtcod.BKGND_SET, libtcod.LEFT,
                    "Diameter: {0}".format(planet.width))
            libtcod.console_print_ex(self.landing_console,
                    2, 4, libtcod.BKGND_SET, libtcod.LEFT,
                    "Seed: {0}".format(planet.seed))
            libtcod.console_blit(self.landing_console, 0, 0, self.landing_screen_width, self.landing_screen_height, 0, self.screen_width/2, 2, 1.0, 0.25)

            libtcod.console_flush()
            self.buffer.clear(self.sector.background[0], self.sector.background[1], self.sector.background[2])

            player_action = self.handle_keys()
            if player_action == 1:
                self.add_message("Taking off from {0}".format(planet.name))
                self.current_screen = 'flight'
                done = True

    def main_loop(self):
        while not libtcod.console_is_window_closed():
            libtcod.sys_check_for_event(libtcod.KEY_PRESSED|libtcod.KEY_RELEASED|libtcod.EVENT_MOUSE, self.key, self.mouse)

            self.render_all()

            player_action = self.handle_keys()
            if player_action == 1:
                break

            if self.player_ship.throttle_open:
                self.player_ship.apply_thrust()

            if self.player_ship.laser_firing:
                self.player_ship.fire_laser()

            if self.player_ship.reversing:
                self.player_ship.reverse_direction()
            elif self.player_ship.turning_left:
                self.player_ship.turn_left()
            elif self.player_ship.turning_right:
                self.player_ship.turn_right()
Example #24
0
def execute_this_fn(worker, *args, **kwargs):
    progress_signal = kwargs['progress_callback']

    galaxy = Galaxy(target='release', api_host=API_HOST, api_key=API_KEY)

    def galaxy_eval(mouse):
        global last_frame_data
        if mouse[0] < -100:
            mouse = (mouse[0] + WorldSize[0], mouse[1])
        galaxy.eval_step(mouse)
        frame_data = galaxy.frame
        if frame_data:
            galaxy.frame = None
            last_frame_data = frame_data
            im = render_frame(frame_data, scale=WorldScale)
            progress_signal.emit(im)

    boot_sequence = [
        (0, 0),
        (0, 0),
        (0, 0),
        (0, 0),
        (0, 0),
        (0, 0),
        (0, 0),
        (0, 0),
        (8, 4),
        (2, -8),
        (3, 6),
        (0, -14),
        (-4, 10),
        (9, -3),
        (-4, 10),
        (1, 4),
    ]
    for mouse in boot_sequence:
        galaxy_eval(mouse)

    while not worker.cancelled:
        if worker.set_state:
            state = worker.set_state
            worker.set_state = None
            if state:
                galaxy.state = state

        if worker.ocr:
            worker.ocr = None
            im = render_frame(last_frame_data, scale=1)
            for symbol, box in ocr_image(im):
                print('  ', repr(symbol), repr(box))

        if worker.redraw:
            worker.redraw = None
            if last_frame_data:
                im = render_frame(last_frame_data, scale=WorldScale)
                progress_signal.emit(im)

        mouse = worker.mouse_click
        if not mouse:
            time.sleep(0.1)
            continue

        worker.mouse_click = None
        print('mouse', mouse)
        galaxy_eval(mouse)
Example #25
0
 def __init__(self):
     self._players = []
     self._galaxy = Galaxy()
     self._time = 0