Exemple #1
0
    def render(self):
        if self.winner is None:
            self.drawing_systems.update(1)

            icon = resources.get("imgAloneIcon")
            position = (50, 650)
            for i in range(0, self.lives[0]):
                self.display.blit(icon, (position[0]+i*icon.get_width(), position[1]))

            icon = resources.get("imgNyancatIcon")
            position = (700, 650)
            for i in range(0, self.lives[1]):
                self.display.blit(icon, (position[0]+i*icon.get_width(), position[1]))

        else:
            #self.display.blit(resources.get("imgBackgroundGO"), (0, 0))

            self.display.blit(resources.get("imgGOString"), (300, 150))

            if self.winner == 0:
                string = "Player1 wins!"
                color = (255, 0, 0)
            elif self.winner == 1:
                string = "Player2 wins!"
                color = (0, 0, 255)
            text_surface = resources.get("basicFont").render(string, True, color)
            text_rect = text_surface.get_rect()
            text_rect.centerx = self.display.get_rect().centerx
            text_rect.centery = self.display.get_rect().centery
            self.display.blit(text_surface, text_rect)
Exemple #2
0
 def __init__(self, display):
     self.display = display
     self.offset = 0
     self.entities = EntityManager()
     prototypes.entities = self.entities
     self.systems = SystemManager(self.entities)
     self.systems.add_system(LinearMotionSystem())
     self.systems.add_system(GravitySystem())
     self.systems.add_system(GroundingSystem())
     self.systems.add_system(DamageSystem())
     self.systems.add_system(CollisionSystem())
     self.systems.add_system(ActorSystem())
     self.drawing_systems = SystemManager(self.entities)
     self.drawing_systems.add_system(DrawingSystem(self.display))
     self.drawing_systems.add_system(DebugDrawingSystem(self.display))
     self.players = (None, None)
     self.lives = [5, 5]
     self.winner = None
     self.player_controllers = resources.get("player_joysticks")
     #resources.get("logfile").write("p1 controller {}\n".format(self.player_controllers[0]))
     #resources.get("logfile").write("that controller id {}\n".format(resources.get("joysticks")[self.player_controllers[0]].get_id()))
     #resources.get("logfile").write("p2 controller {}\n".format(self.player_controllers[1]))
     #resources.get("logfile").write("that controller id {}\n".format(resources.get("joysticks")[self.player_controllers[1]].get_id()))
     self.old_sticks = []
     self.joysticks = [resources.get("joysticks")[resources.get("player_joysticks")[0]], resources.get("joysticks")[resources.get("player_joysticks")[1]]]
     self.maxmin = [0, 0, 0, 0]
     self.logfile = resources.get("logfile")
     self.create_world()
Exemple #3
0
    def update(self, dt):
        for entity, hurtvolume in self.entity_manager.pairs_for_type(Hurtvolume):
            hurtpos = self.entity_manager.component_for_entity(entity, Position)
            for entity2, hitvolume in self.entity_manager.pairs_for_type(Hitvolume):
                if entity == hitvolume.player or not hitvolume.active:
                    continue
                hitpos = self.entity_manager.component_for_entity(entity2, Position)
                collision = collide_shapes((hurtpos, hurtvolume.shape), (hitpos, hitvolume.shape))
                if collision["occured"]:
                    actor = self.entity_manager.component_for_entity(entity, Actor)
                    if actor.shielded:
                        continue
                    else:
                        actor.stunned = hitvolume.stun
                        actor.damage += hitvolume.damage
                        hitaccel = mul(collision["direction"], (hitvolume.damage + actor.damage) * resources.get("hitFactor"))
                        resources.get("logfile").write("dmg {} {} {}\n".format(hitvolume.damage, actor.damage, resources.get("hitFactor")))
                        actor_velocity = self.entity_manager.component_for_entity(entity, Velocity)
                        actor_velocity.dx += hitaccel[0]
                        actor_velocity.dy += hitaccel[1]

        volumes = []
        for entity, hitvolume in self.entity_manager.pairs_for_type(Hitvolume):
            hitvolume.active = False
            volumes.append(entity)

        for ent in volumes:
            pass#self.entity_manager.remove_entity(ent)
Exemple #4
0
    def __init__(self, position, movestep=16, speed=200):
        super(Player, self).__init__()
        # self.image = pygame.image.load("examples/placeholder_player.png")

        self._floor_listeners = set()

        self.layer = 1
        self._z = 0

        self.build_animations()
        self.update_animation()

        self.feet = pygame.Rect(0, 0, self.rect.width * 1.0, 10)

        self.reset_inputs()

        self.movestep = movestep
        self.speed = speed
        self.destination = self.position = position
        self._old_position = self.position
        self._old_destination = self.destination

        self.velocity = (0, 0)

        self._snd_step_concrete = pygame.mixer.Sound(resources.get("assets/step_concrete.wav"))
        self._snd_step_grass = pygame.mixer.Sound(resources.get("assets/step_grass.wav"))
        self._snd_step_water = pygame.mixer.Sound(resources.get("assets/step_water.wav"))
Exemple #5
0
 def update(self, dt):
     for entity, velocity in self.entity_manager.pairs_for_type(Velocity):
         position = self.entity_manager.component_for_entity(entity, Position)
         position.x += velocity.dx * dt
         position.y += velocity.dy * dt
         #speed = length((velocity.dx, velocity.dy))
         velocity.dx -= resources.get("slowFactor") * velocity.dx
         velocity.dy -= resources.get("slowFactor") * velocity.dy
         resources.get("logfile").write("v {} {}\n".format(velocity.dx, velocity.dy))
Exemple #6
0
    def create_world(self):
        p1 = prototypes.create_player((-100, 0), "foreveralone")
        p2 = prototypes.create_player((100, 0), "nyancat")
        self.players = (p1, p2)
        tiled = pygame.Surface((378, 54))
        for i in range(0, 7):
            tiled.blit(resources.get("imgTile"), (54*i, 0))
        prototypes.create_terrain((0, -50), rect((0, 0),378, 54), tiled)
        tiled = pygame.Surface((756, 54))
        for i in range(0, 14):
            tiled.blit(resources.get("imgTile"), (54*i, 0))
        prototypes.create_terrain((0, 300), rect((0, 0),756, 54), tiled)

        prototypes.create_terrain((-400, 200), circle((0, 0),80), resources.get("imgCake"))
        prototypes.create_terrain((400, 200), circle((0, 0),80), resources.get("imgCake"))
Exemple #7
0
 def render(self):
     color = (0, 0, 0)
     textSurface = resources.get("basicFont").render('Credits', True, color, (255, 255, 255))
     textRect = textSurface.get_rect()
     textRect.centerx = self.display.get_rect().centerx
     textRect.centery = self.display.get_rect().centery
     self.display.blit(textSurface, textRect)
Exemple #8
0
 def __init__(self, max_length: int = 128):
     super().__init__()
     # word2idx_path = os.path.join(os.path.dirname(__file__), 'word2idx.json')
     # with open(word2idx_path) as file:
     with resources.get('word2idx.json') as file:
         self.word2idx: typing.Dict[str, int] = json.load(file)
     self.max_length = max_length
Exemple #9
0
def createFont():
    # create font
    for fontName in config.get("general", "fonts").split(","):
        section = "%s font" % fontName
        fontType = config.get(section, "type")
        log.debug("Loading font", fontName, fontType)
        if fontType == "windowsttf":
            if os.name == "nt":
                # get "Fonts" folder location
                handle = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
                path, valueType = winreg.QueryValueEx(handle, 'Fonts')
                handle.Close()
                filename = os.path.join(path, config.get(section, "file"))
            else:
                continue
        elif fontType == "ttf":
            filename = resources.get(config.get(section, "file"))
        elif fontType == "default":
            filename = None
        # load font
        if filename == None or os.path.exists(filename):
            Fonts.initFont('small', filename, config.getint(section, "small"))
            Fonts.initFont('small-bold', filename, config.getint(section, "small"), bold = 1)
            Fonts.initFont('small-italic', filename, config.getint(section, "small"), italic = 1)
            Fonts.initFont('normal', filename, config.getint(section, "normal"))
            Fonts.initFont('normal-bold', filename, config.getint(section, "normal"), bold = 1)
            Fonts.initFont('normal-italic', filename, config.getint(section, "normal"), italic = 1)
            Fonts.initFont('large', filename, config.getint(section, "large"))
            Fonts.initFont('large-bold', filename, config.getint(section, "large"), bold = 1)
            Fonts.initFont('large-italic', filename, config.getint(section, "large"), italic = 1)
            return
Exemple #10
0
    def build_animations(self):
        images = pyganim.getImagesFromSpriteSheet(
            resources.get('examples/placeholder_player_ani.png'),
            rows=4, cols=3, rects=[])

        self.animations = {
            'idle_up': [(images[0], 100)],
            'idle_down': [(images[3], 100)],
            'idle_left': [(images[6], 100)],
            'idle_right': [(images[9], 100)],

            'walk_up': zip([images[x] for x in [1, 0, 2, 0]], [200] * 4),
            'walk_down': zip([images[x] for x in [4, 3, 5, 3]], [200] * 4),
            'walk_left': zip([images[x] for x in [7, 6, 8, 6]], [200] * 4),
            'walk_right': zip([images[x] for x in [10, 9, 11, 9]], [200] * 4),
        }

        self.idle_transitions = {
            'walk_up': 'idle_up',
            'walk_down': 'idle_down',
            'walk_left': 'idle_left',
            'walk_right': 'idle_right',
        }

        for k, v in self.animations.items():
            self.animations[k] = pyganim.PygAnimation(list(v))

        self.animate('idle_up')
def createFont():
    # create font
    for fontName in config.get("general", "fonts").split(","):
        section = "%s font" % fontName
        fontType = config.get(section, "type")
        log.debug("Loading font", fontName, fontType)
        if fontType == "windowsttf":
            if os.name == "nt":
                # get "Fonts" folder location
                handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
                path, valueType = _winreg.QueryValueEx(handle, 'Fonts')
                handle.Close()
                filename = os.path.join(path, config.get(section, "file"))
            else:
                continue
        elif fontType == "ttf":
            filename = resources.get(config.get(section, "file"))
        elif fontType == "default":
            filename = None
        # load font
        if filename == None or os.path.exists(filename):
            Fonts.initFont('small', filename, config.getint(section, "small"))
            Fonts.initFont('small-bold', filename, config.getint(section, "small"), bold = 1)
            Fonts.initFont('small-italic', filename, config.getint(section, "small"), italic = 1)
            Fonts.initFont('normal', filename, config.getint(section, "normal"))
            Fonts.initFont('normal-bold', filename, config.getint(section, "normal"), bold = 1)
            Fonts.initFont('normal-italic', filename, config.getint(section, "normal"), italic = 1)
            Fonts.initFont('large', filename, config.getint(section, "large"))
            Fonts.initFont('large-bold', filename, config.getint(section, "large"), bold = 1)
            Fonts.initFont('large-italic', filename, config.getint(section, "large"), italic = 1)
            return
Exemple #12
0
 def __init__(self, position, floor=0):
     super(RisingPlatform, self).__init__()
     self.position = position
     self.floor = floor
     self.height = floor * 32
     self.rect = pygame.Rect((position[0] - 8, position[1] - 8), (32, 32))
     self.rect = pygame.Rect((position[0], position[1]), (32, 32))
     self.image = pygame.image.load(resources.get("examples/platformgrass.png"))
     self.image_offset = (-8, -8)
Exemple #13
0
 def onSelectTheme(self, widget, action, data):
     items = []
     themeDir = resources.get("themes")
     for term in os.listdir(themeDir):
         if os.path.isfile(os.path.join(themeDir, term, "config.ini")) and not term.startswith("."):
             item = ui.Item(term, tTheme = term)
             items.append(item)
     self.twin.vThemes.items = items
     self.twin.vThemes.itemsChanged()
     self.twin.show()
Exemple #14
0
    def __init__(self, rect):
        super(Switch, self).__init__()
        self.rect = rect
        images = pyganim.getImagesFromSpriteSheet(
            resources.get("assets/stonepad.png"),
            rows=1, cols=2, rects=[])
        self._sound = pygame.mixer.Sound("assets/step_concrete.wav")

        self.image = images[0]
        self.released_image = images[0]
        self.pressed_image = images[1]
        self.active = False
Exemple #15
0
 def onSelectTheme(self, widget, action, data):
     items = []
     themeDir = resources.get("themes")
     for term in os.listdir(themeDir):
         if os.path.isfile(
                 os.path.join(themeDir, term,
                              "config.ini")) and not term.startswith("."):
             item = ui.Item(term, tTheme=term)
             items.append(item)
     self.twin.vThemes.items = items
     self.twin.vThemes.itemsChanged()
     self.twin.show()
Exemple #16
0
 def __init__(self, config):
     super(Actor, self).__init__()
     self.direction = "neutral"
     self.orientation = "right"
     self.impact = None
     self.acting = 0
     self.stunned = 0
     self.shielded = 0
     self.air_actions = resources.get("airActions")
     self.commands = []
     self.damage = 0
     self.config = config
Exemple #17
0
 def onSelectLanguage(self, widget, action, data):
     items = []
     items.append(ui.Item(self.languages['en'],tLanguage = 'en'))
     langDir = resources.get('translations')
     for term in os.listdir(langDir):
         if os.path.isfile(os.path.join(langDir, term,"LC_MESSAGES", "OSPACE.mo")) and not term.startswith("."):
             if self.languages.has_key(term):
                 item = ui.Item(self.languages[term], tLanguage = term)
             else:
                 item = ui.Item(term, tLanguage = term)
             items.append(item)
     self.lwin.vLanguages.items = items
     self.lwin.vLanguages.itemsChanged()
     self.lwin.show()
Exemple #18
0
    def __init__(self, rect):
        super(Keystone, self).__init__()
        self._floor_listeners = set()

        self.rect = rect
        self.images = pyganim.getImagesFromSpriteSheet(resources.get('examples/keystone.png'),
            rows=1, cols=5, rects=[])
        self.animation = pyganim.PygAnimation(zip([self.images[x] for x in [0, 1, 2, 3, 4, 3, 2, 1]], [200] * 8))
        self.animate()
        self.image = self.images[0]

        self.won = False

        self.font = pygame.font.SysFont('Courier', 48, True, True)
Exemple #19
0
 def onSelectLanguage(self, widget, action, data):
     items = []
     items.append(ui.Item(self.languages['en'], tLanguage='en'))
     langDir = resources.get('translations')
     for term in os.listdir(langDir):
         if os.path.isfile(
                 os.path.join(langDir, term, "LC_MESSAGES",
                              "OSPACE.mo")) and not term.startswith("."):
             if self.languages.has_key(term):
                 item = ui.Item(self.languages[term], tLanguage=term)
             else:
                 item = ui.Item(term, tLanguage=term)
             items.append(item)
     self.lwin.vLanguages.items = items
     self.lwin.vLanguages.itemsChanged()
     self.lwin.show()
Exemple #20
0
 def onLanguageSelected(self, widget, action, data):
     self.recipientObjID = []
     text = ""
     if not self.lwin.vLanguages.selection:
         return
     self.curLang = self.lwin.vLanguages.selection[0].tLanguage
     self.lwin.hide()
     if self.curLang == 'en':
         tran = gettext.NullTranslations()
     else:
         tran = gettext.translation('OSPACE', resources.get('translations'), languages = [self.curLang])
     tran.install(unicode = 1)
     try:
         self.win.vLangSel.text = self.languages[self.curLang]
     except:
         self.win.vLangSel.text = self.curLang
     self.win.setStatus(_("You should restart client to change the language."))
Exemple #21
0
def getNetworkDistribution(user_ID, op1, op1Percentage,op2,  op2Percentage,op3, op3Percentage):
	
	n1 = get3MostFrequentlyCalledNumbers(user_ID).get('number1')
	op1Percentage = getTrafficPercentageForNumber(n1)
	n2 = get3MostFrequentlyCalledNumbers(user_ID).get('number2')
	op2Percentage= getTrafficPercentageForNumber(n1)
	n3 = get3MostFrequentlyCalledNumbers(user_ID).get('number3')
	op3Percentage = getTrafficPercentageForNumber(n1)
	results = {}
	top3TotalPercentage =getTrafficPercentageTop3Numbers(user_ID)
	results[op1] = op1Percentage + (100-top3TotalPercentage)*resources.network_distribution.get(op1)
	results[op2] = op2Percentage + (100-top3TotalPercentage)*resources.network_distribution.get(op2)
	results[op3] = op3Percentage + (100-top3TotalPercentage)*resources.network_distribution.get(op3)
	for o in resources.network_distribution:
		if o==op1 or o==op2 or o==op3:
			continue
		results[o] = resources.get(o)
	return results
Exemple #22
0
def setSkinTheme(gdata, ui):
    theme = "green"
    if gdata.config.client.theme != None:
            theme = gdata.config.client.theme
    ui.SkinableTheme.enableMusic(gdata.config.defaults.music == "yes")
    ui.SkinableTheme.enableSound(gdata.config.defaults.sound == "yes")
    ui.SkinableTheme.setSkin(os.path.join(resources.get("themes"), theme))
    ui.SkinableTheme.loadMusic(gdata.config.defaults.mymusic)
    if gdata.config.defaults.musicvolume:
            ui.SkinableTheme.setMusicVolume(float(gdata.config.defaults.musicvolume)/ 100.0)
    if gdata.config.defaults.soundvolume:
            ui.SkinableTheme.setVolume(float(gdata.config.defaults.soundvolume) / 100.0)

    gdata.sevColors[gdata.CRI] = (ui.SkinableTheme.themeCritical)
    gdata.sevColors[gdata.MAJ] = (ui.SkinableTheme.themeMajor)
    gdata.sevColors[gdata.MIN] = (ui.SkinableTheme.themeMinor)
    gdata.sevColors[gdata.NONE] = (ui.SkinableTheme.themeNone)
    gdata.sevColors[gdata.DISABLED] = (ui.SkinableTheme.themeDisabled)
Exemple #23
0
    def render(self):
        #self.display.blit(resources.get("imgBackgroundMenu"), (0, 0))

        self.display.blit(resources.get("imgMenuTitle"), (self.display.get_rect().centerx - resources.get("imgMenuTitle").get_width()/2, self.display.get_rect().centery - resources.get("imgMenuTitle").get_height()/2 - 200))

        if self.fsm.current == "start":
            color = (0, 0, 0)
        else:
            color = (220, 220, 220)
        text_surface = resources.get("basicFont").render('Start', True, color)
        text_rect = text_surface.get_rect()
        text_rect.right = self.display.get_rect().centerx -  10
        text_rect.centery = self.display.get_rect().centery - 100
        self.display.blit(text_surface, text_rect)

        if self.fsm.current == "credits":
            color = (0, 0, 0)
        else:
            color = (220, 220, 220)
        text_surface = resources.get("basicFont").render('Credits', True, color)
        text_rect = text_surface.get_rect()
        text_rect.left = self.display.get_rect().centerx + 10
        text_rect.centery = self.display.get_rect().centery - 100
        self.display.blit(text_surface, text_rect)

        text_surface = resources.get("basicFont").render('Register controllers by pressing start', True, (100, 100, 100))
        text_rect = text_surface.get_rect()
        text_rect.centerx = self.display.get_rect().centerx
        text_rect.centery = self.display.get_rect().centery +50
        self.display.blit(text_surface, text_rect)

        if self.player_controllers[0] is None:
            text = "P1 open"
        else:
            text = ""
        text_surface = resources.get("basicFont").render(text, True, (0, 0, 0))
        text_rect = text_surface.get_rect()
        text_rect.right = self.display.get_rect().centerx -  10
        text_rect.centery = self.display.get_rect().centery + 100
        self.display.blit(text_surface, text_rect)

        if self.player_controllers[1] is None:
            text = "P2 open"
        else:
            text = ""
        text_surface = resources.get("basicFont").render(text, True, (0, 0, 0))
        text_rect = text_surface.get_rect()
        text_rect.left = self.display.get_rect().centerx +  10
        text_rect.centery = self.display.get_rect().centery + 100
        self.display.blit(text_surface, text_rect)
Exemple #24
0
def drawBackground():
    global background, backgroundOffset
    global sponsorLogo, sponsorLogoOffset
    if not background:
        image = random.choice([
            resources.get('bck1_1024x768.jpg'),
            resources.get('bck2_1024x768.jpg'),
            resources.get('bck3_1024x768.jpg'),
            resources.get('bck4_1024x768.jpg'),
            resources.get('bck5_1024x768.jpg'),
        ])
        background = pygame.image.load(image).convert_alpha()
        backgroundOffset = (
            (gdata.screen.get_width() - background.get_width()) / 2,
            (gdata.screen.get_height() - background.get_height()) / 2,
        )
    if not sponsorLogo:
        sponsorLogo = pygame.image.load(resources.get("sponsor_logo.png")).convert_alpha()
        sponsorLogoOffset = (
            (gdata.screen.get_width() - 5 - sponsorLogo.get_width()),
            (gdata.screen.get_height() - 5 - sponsorLogo.get_height()),
        )
    font = pygame.font.Font(resources.get('fonts/DejaVuLGCSans.ttf'), 12)
    font.set_bold(1)
    color = 0x40, 0x70, 0x40
    #
    gdata.screen.blit(background, backgroundOffset)
    gdata.screen.blit(sponsorLogo, sponsorLogoOffset)
    img = font.render(_("Server sponsored by:"), 1, (0xc0, 0xc0, 0xc0))
    gdata.screen.blit(img, (sponsorLogoOffset[0], sponsorLogoOffset[1] - img.get_height() - 2))
    # screen.fill((0x00, 0x00, 0x00))
    # OSCI version
    img = font.render(_('Outer Space %s') % ige.version.versionString, 1, color)
    gdata.screen.blit(img, (5, gdata.screen.get_height() - 4 * img.get_height() - 5))
    # Pygame version
    img = font.render(_('Pygame %s') % pygame.version.ver, 1, color)
    gdata.screen.blit(img, (5, gdata.screen.get_height() - 3 * img.get_height() - 5))
    # Python version
    img = font.render(_('Python %s') % sys.version, 1, color)
    gdata.screen.blit(img, (5, gdata.screen.get_height() - 2 * img.get_height() - 5))
    # Video driver
    w, h = pygame.display.get_surface().get_size()
    d = pygame.display.get_surface().get_bitsize()
    img = font.render(_('Video Driver: %s [%dx%dx%d]') % (pygame.display.get_driver(), w, h, d), 1, color)
    gdata.screen.blit(img, (5, gdata.screen.get_height() - 1 * img.get_height() - 5))
Exemple #25
0
 def onLanguageSelected(self, widget, action, data):
     self.recipientObjID = []
     text = ""
     if not self.lwin.vLanguages.selection:
         return
     self.curLang = self.lwin.vLanguages.selection[0].tLanguage
     self.lwin.hide()
     if self.curLang == 'en':
         tran = gettext.NullTranslations()
     else:
         tran = gettext.translation('OSPACE',
                                    resources.get('translations'),
                                    languages=[self.curLang])
     tran.install(unicode=1)
     try:
         self.win.vLangSel.text = self.languages[self.curLang]
     except:
         self.win.vLangSel.text = self.curLang
     self.win.setStatus(
         _("You should restart client to change the language."))
Exemple #26
0
 def onThemeSelected(self, widget, action, data):
     self.recipientObjID = []
     text = ""
     if not self.twin.vThemes.selection:
         return
     curTheme = self.twin.vThemes.selection[0].tTheme
     # set theme for ui
     ui.SkinableTheme.setSkin(os.path.join(resources.get("themes"), curTheme))
     ui.SkinableTheme.loadMusic(gdata.config.defaults.mymusic)
     ui.SkinableTheme.playMusic()
     # update foreground colors
     gdata.sevColors[gdata.CRI] = (ui.SkinableTheme.themeCritical)
     gdata.sevColors[gdata.MAJ] = (ui.SkinableTheme.themeMajor)
     gdata.sevColors[gdata.MIN] = (ui.SkinableTheme.themeMinor)
     gdata.sevColors[gdata.NONE] = (ui.SkinableTheme.themeNone)
     gdata.sevColors[gdata.DISABLED] = (ui.SkinableTheme.themeDisabled)
     # all OK? (no exception) -> store settings
     gdata.config.client.theme = curTheme
     self.win.vTheme2.text = curTheme
     self.twin.hide()
Exemple #27
0
def setSkinTheme(gdata, ui):
    theme = "green"
    if gdata.config.client.theme != None:
        theme = gdata.config.client.theme
    ui.SkinableTheme.enableMusic(gdata.config.defaults.music == "yes")
    ui.SkinableTheme.enableSound(gdata.config.defaults.sound == "yes")
    ui.SkinableTheme.setSkin(os.path.join(resources.get("themes"), theme))
    ui.SkinableTheme.loadMusic(gdata.config.defaults.mymusic)
    if gdata.config.defaults.musicvolume:
        ui.SkinableTheme.setMusicVolume(
            float(gdata.config.defaults.musicvolume) / 100.0)
    if gdata.config.defaults.soundvolume:
        ui.SkinableTheme.setVolume(
            float(gdata.config.defaults.soundvolume) / 100.0)

    gdata.sevColors[gdata.CRI] = (ui.SkinableTheme.themeCritical)
    gdata.sevColors[gdata.MAJ] = (ui.SkinableTheme.themeMajor)
    gdata.sevColors[gdata.MIN] = (ui.SkinableTheme.themeMinor)
    gdata.sevColors[gdata.NONE] = (ui.SkinableTheme.themeNone)
    gdata.sevColors[gdata.DISABLED] = (ui.SkinableTheme.themeDisabled)
Exemple #28
0
def main():
    # set up pygame
    pygame.init()
    # set up the window
    window_surface = pygame.display.set_mode((1024, 768), pygame.DOUBLEBUF | pygame.HWSURFACE) #pygame.FULLSCREEN
    pygame.display.set_caption(title)
    fps_clock = pygame.time.Clock()
    joysticks = []
    for i in range(0, pygame.joystick.get_count()):
            joysticks.append(pygame.joystick.Joystick(i))
            joysticks[-1].init()
    resources.set("joysticks", joysticks)
    app = Application(window_surface)
    resources.load()
    window_active = True
    # run the game loop
    while True:
        #read input
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == ACTIVEEVENT:
                if event.state == 2:
                    window_active = False
                elif event.state == 1:
                    window_active = True
                elif event.state == 6:
                    window_active = False
                #print event
            else:
                if window_active:
                    app.input(event)
        if window_active:
            app.update()
            window_surface.fill(clearColor)
            app.render()
            pygame.display.update()
        fps_clock.tick(resources.get("fps"))
Exemple #29
0
 def onThemeSelected(self, widget, action, data):
     self.recipientObjID = []
     text = ""
     if not self.twin.vThemes.selection:
         return
     curTheme = self.twin.vThemes.selection[0].tTheme
     # set theme for ui
     ui.SkinableTheme.setSkin(
         os.path.join(resources.get("themes"), curTheme))
     res.prepareUIIcons(ui.SkinableTheme.themeIcons)
     ui.SkinableTheme.loadMusic(gdata.config.defaults.mymusic)
     ui.SkinableTheme.playMusic()
     # update foreground colors
     gdata.sevColors[gdata.CRI] = (ui.SkinableTheme.themeCritical)
     gdata.sevColors[gdata.MAJ] = (ui.SkinableTheme.themeMajor)
     gdata.sevColors[gdata.MIN] = (ui.SkinableTheme.themeMinor)
     gdata.sevColors[gdata.NONE] = (ui.SkinableTheme.themeNone)
     gdata.sevColors[gdata.DISABLED] = (ui.SkinableTheme.themeDisabled)
     # all OK? (no exception) -> store settings
     gdata.config.client.theme = curTheme
     self.win.vTheme2.text = curTheme
     self.twin.hide()
Exemple #30
0
def getNetworkDistribution(user_ID, op1, op1Percentage, op2, op2Percentage,
                           op3, op3Percentage):

    n1 = get3MostFrequentlyCalledNumbers(user_ID).get('number1')
    op1Percentage = getTrafficPercentageForNumber(n1)
    n2 = get3MostFrequentlyCalledNumbers(user_ID).get('number2')
    op2Percentage = getTrafficPercentageForNumber(n1)
    n3 = get3MostFrequentlyCalledNumbers(user_ID).get('number3')
    op3Percentage = getTrafficPercentageForNumber(n1)
    results = {}
    top3TotalPercentage = getTrafficPercentageTop3Numbers(user_ID)
    results[op1] = op1Percentage + (
        100 - top3TotalPercentage) * resources.network_distribution.get(op1)
    results[op2] = op2Percentage + (
        100 - top3TotalPercentage) * resources.network_distribution.get(op2)
    results[op3] = op3Percentage + (
        100 - top3TotalPercentage) * resources.network_distribution.get(op3)
    for o in resources.network_distribution:
        if o == op1 or o == op2 or o == op3:
            continue
        results[o] = resources.get(o)
    return results
Exemple #31
0
def defineBackground():
    surface = pygame.Surface.copy(gdata.screen)
    image = random.choice([
        resources.get('bck1_1024x768.jpg'),
        resources.get('bck2_1024x768.jpg'),
        resources.get('bck3_1024x768.jpg'),
        resources.get('bck4_1024x768.jpg'),
        resources.get('bck5_1024x768.jpg'),
    ])
    background = pygame.image.load(image).convert_alpha()
    backgroundOffset = (
        (surface.get_width() - background.get_width()) / 2,
        (surface.get_height() - background.get_height()) / 2,
    )
    try:
        font = pygame.ftfont.Font(resources.get('fonts/DejaVuLGCSans.ttf'), 12)
    except IOError:
        # this can happen on windows during update process, when directory
        # is moved already
        # TODO: proper fix is to use pygameui and caching
        font = pygame.ftfont.Font(None, 12)
    font.set_bold(1)
    color = 0x40, 0x70, 0x40
    #
    surface.blit(background, backgroundOffset)
    # screen.fill((0x00, 0x00, 0x00))
    # OSCI version
    img = font.render(
        _('Outer Space %s') % ige.version.versionString, 1, color)
    surface.blit(img, (5, surface.get_height() - 4 * img.get_height() - 5))
    # Pygame version
    img = font.render(_('Pygame %s') % pygame.version.ver, 1, color)
    surface.blit(img, (5, surface.get_height() - 3 * img.get_height() - 5))
    # Python version
    img = font.render(_('Python %s') % sys.version, 1, color)
    surface.blit(img, (5, surface.get_height() - 2 * img.get_height() - 5))
    # Video driver
    w, h = pygame.display.get_surface().get_size()
    d = pygame.display.get_surface().get_bitsize()
    img = font.render(
        _('Video Driver: %s [%dx%dx%d]') %
        (pygame.display.get_driver(), w, h, d), 1, color)
    surface.blit(img, (5, surface.get_height() - 1 * img.get_height() - 5))
    return surface
Exemple #32
0
def defineBackground():
    surface = pygame.Surface.copy(gdata.screen)
    image = random.choice([
        resources.get('bck1_1024x768.jpg'),
        resources.get('bck2_1024x768.jpg'),
        resources.get('bck3_1024x768.jpg'),
        resources.get('bck4_1024x768.jpg'),
        resources.get('bck5_1024x768.jpg'),
    ])
    background = pygame.image.load(image).convert_alpha()
    backgroundOffset = (
        (surface.get_width() - background.get_width()) / 2,
        (surface.get_height() - background.get_height()) / 2,
    )
    try:
        font = pygame.ftfont.Font(resources.get('fonts/DejaVuLGCSans.ttf'), 12)
    except IOError:
        # this can happen on windows during update process, when directory
        # is moved already
        # TODO: proper fix is to use pygameui and caching
        font = pygame.ftfont.Font(None, 12)
    font.set_bold(1)
    color = 0x40, 0x70, 0x40
    #
    surface.blit(background, backgroundOffset)
    # screen.fill((0x00, 0x00, 0x00))
    # OSCI version
    img = font.render(_('Outer Space %s') % ige.version.versionString, 1, color)
    surface.blit(img, (5, surface.get_height() - 4 * img.get_height() - 5))
    # Pygame version
    img = font.render(_('Pygame %s') % pygame.version.ver, 1, color)
    surface.blit(img, (5, surface.get_height() - 3 * img.get_height() - 5))
    # Python version
    img = font.render(_('Python %s') % sys.version, 1, color)
    surface.blit(img, (5, surface.get_height() - 2 * img.get_height() - 5))
    # Video driver
    w, h = pygame.display.get_surface().get_size()
    d = pygame.display.get_surface().get_bitsize()
    img = font.render(_('Video Driver: %s [%dx%dx%d]') % (pygame.display.get_driver(), w, h, d), 1, color)
    surface.blit(img, (5, surface.get_height() - 1 * img.get_height() - 5))
    return surface
Exemple #33
0
def runClient(options):

    # log initialization
    log.message("Starting Outer Space Client", ige.version.versionString)
    log.debug("sys.path =", sys.path)
    log.debug("os.name =", os.name)
    log.debug("sys.platform =", sys.platform)
    log.debug("os.getcwd() =", os.getcwd())
    log.debug("sys.frozen =", getattr(sys, "frozen", None))

    # create required directories
    if not os.path.exists(options.configDir):
        os.makedirs(options.configDir)
    log.debug("options.configDir =", options.configDir)

    running = 1
    first = True
    #while running:
    if not first:
        reload(osci)
    # parse configuration
    if first:
        import osci.gdata as gdata
    else:
        reload(gdata)

    gdata.config = Config(
        os.path.join(options.configDir, options.configFilename))
    gdata.config.game.server = options.server

    setDefaults(gdata, options)

    language = gdata.config.client.language
    import gettext
    log.debug('OSCI', 'Installing translation for:', language)
    if language == 'en':
        log.debug('OSCI', 'English is native - installing null translations')
        tran = gettext.NullTranslations()
    else:
        try:
            tran = gettext.translation('OSPACE',
                                       resources.get('translations'),
                                       languages=[language])
        except IOError:
            log.warning('OSCI', 'Cannot find catalog for', language)
            log.message('OSCI', 'Installing null translations')
            tran = gettext.NullTranslations()

    tran.install(unicode=1)

    #initialize pygame and prepare screen
    if (gdata.config.defaults.sound == "yes") or (gdata.config.defaults.music
                                                  == "yes"):
        pygame.mixer.pre_init(44100, -16, 2, 4096)

    os.environ['SDL_VIDEO_ALLOW_SCREENSAVER'] = '1'
    os.environ['SDL_DEBUG'] = '1'
    pygame.init()

    flags = pygame.SWSURFACE

    DEFAULT_SCRN_SIZE = (800, 600)
    gdata.scrnSize = DEFAULT_SCRN_SIZE
    if gdata.config.display.resolution == "FULLSCREEN":
        gdata.scrnSize = (0, 0)
        flags |= pygame.FULLSCREEN
    elif gdata.config.display.resolution is not None:
        width, height = gdata.config.display.resolution.split('x')
        gdata.scrnSize = (int(width), int(height))

    if gdata.config.display.depth == None:
        # guess best depth
        bestdepth = pygame.display.mode_ok(gdata.scrnSize, flags)
    else:
        bestdepth = int(gdata.config.display.depth)

    # initialize screen
    try:
        screen = pygame.display.set_mode(gdata.scrnSize, flags, bestdepth)
        # gdata.scrnSize is used everywhere to setup windows
        gdata.scrnSize = screen.get_size()
    except pygame.error:
        # for example if fullscreen is selected with resolution bigger than display
        # TODO: as of now, fullscreen has automatic resolution
        gdata.scrnSize = DEFAULT_SCRN_SIZE
        screen = pygame.display.set_mode(gdata.scrnSize, flags, bestdepth)
    gdata.screen = screen
    log.debug('OSCI', 'Driver:', pygame.display.get_driver())
    log.debug('OSCI', 'Using depth:', bestdepth)
    log.debug('OSCI', 'Display info:', pygame.display.Info())

    pygame.mouse.set_visible(1)

    pygame.display.set_caption(_('Outer Space %s') % ige.version.versionString)

    # set icon
    pygame.display.set_icon(
        pygame.image.load(resources.get('icon48.png')).convert_alpha())

    # UI stuff
    if first:
        import pygameui as ui
    else:
        reload(ui)

    setSkinTheme(gdata, ui)

    app = ui.Application(update, theme=ui.SkinableTheme)
    app.background = defineBackground()
    app.draw(gdata.screen)
    app.windowSurfaceFlags = pygame.SWSURFACE | pygame.SRCALPHA
    gdata.app = app

    pygame.event.clear()

    # resources
    import osci.res

    osci.res.initialize()

    # load resources
    import osci.dialog
    dlg = osci.dialog.ProgressDlg(gdata.app)
    osci.res.loadResources(dlg)
    dlg.hide()
    osci.res.prepareUIIcons(ui.SkinableTheme.themeIcons)

    while running:
        if first:
            import osci.client, osci.handler
            from igeclient.IClient import IClientException
        else:
            reload(osci.client)
            reload(osci.handler)
        osci.client.initialize(gdata.config.game.server, osci.handler, options)

        # create initial dialogs
        if first:
            import osci.dialog
        else:
            reload(osci.dialog)
        gdata.savePassword = gdata.config.game.lastpasswordcrypted != None

        if options.login and options.password:
            gdata.config.game.lastlogin = options.login
            gdata.config.game.lastpassword = options.password
            gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(
                options.password).strip()
            gdata.config.game.autologin = '******'
            gdata.savePassword = '******'

        loginDlg = osci.dialog.LoginDlg(gdata.app)
        updateDlg = osci.dialog.UpdateDlg(gdata.app)

        # event loop
        update()

        lastSave = time.clock()
        # set counter to -1 to trigger Update dialog (see "if" below)
        counter = -1
        needsRefresh = False
        session = 1
        first = False
        while running and session:
            try:
                counter += 1
                if counter == 0:
                    # display initial dialog in the very first cycle
                    updateDlg.display(caller=loginDlg, options=options)
                # process as many events as possible before updating
                evt = pygame.event.wait()
                evts = pygame.event.get()
                evts.insert(0, evt)

                forceKeepAlive = False
                saveDB = False

                for evt in evts:
                    if evt.type == pygame.QUIT:
                        running = 0
                        break
                    if evt.type == (
                            ui.USEREVENT) and evt.action == "localExit":
                        session = False
                        break
                    if evt.type == pygame.ACTIVEEVENT:
                        if evt.gain == 1 and evt.state == 6:
                            # pygame desktop window focus event
                            needsRefresh = True
                    if evt.type == pygame.KEYUP and evt.key == pygame.K_F12:
                        if not pygame.key.get_mods() & pygame.KMOD_CTRL:
                            running = 0
                            break
                    if evt.type == pygame.KEYUP and evt.key == pygame.K_F9:
                        forceKeepAlive = True
                    evt = gdata.app.processEvent(evt)

                if gdata.app.needsUpdate() or needsRefresh:
                    needsRefresh = False
                    update()
                # keep alive connection
                osci.client.keepAlive(forceKeepAlive)

                # save DB every 4 hours in case of a computer crash
                # using "counter" to limit calls to time.clock() to approximately every 10-15 minutes
                if counter > 5000:
                    # set this to zero so we don't display Update dialog
                    counter = 0
                    if time.clock() - lastSave > 14400:
                        saveDB = True
                if saveDB:
                    osci.client.saveDB()
                    lastSave = time.clock()

            except IClientException, e:
                osci.client.reinitialize()
                gdata.app.setStatus(e.args[0])
                loginDlg.display(message=e.args[0])
            except Exception, e:
                log.warning('OSCI', 'Exception in event loop')
                if not isinstance(e, SystemExit) and not isinstance(
                        e, KeyboardInterrupt):
                    log.debug("Processing exception")
                    # handle exception
                    import traceback, StringIO
                    fh = StringIO.StringIO()
                    exctype, value, tb = sys.exc_info()
                    funcs = [entry[2] for entry in traceback.extract_tb(tb)]
                    faultID = "%06d-%03d" % (
                        hash("/".join(funcs)) % 1000000,
                        traceback.extract_tb(tb)[-1][1] % 1000,
                    )
                    del tb
                    # high level info
                    print >> fh, "Exception ID:", faultID
                    print >> fh
                    print >> fh, "%s: %s" % (exctype, value)
                    print >> fh
                    print >> fh, "--- EXCEPTION DATA ---"
                    # dump exception
                    traceback.print_exc(file=fh)
                    excDlg = osci.dialog.ExceptionDlg(gdata.app)
                    excDlg.display(faultID, fh.getvalue())
                    del excDlg  # reference to the dialog holds app's intance
                    fh.close()
                    del fh
                else:
                    break
Exemple #34
0
def initialize():
    # needed for progress dlg
    global loginLogoImg
    loginLogoImg = pygame.image.load(
        resources.get('logo-login.png')).convert_alpha()
Exemple #35
0
def loadResources(progress_dlg=None):
    curr = 0
    max = len(glob.glob(resources.get('galaxy/*.png'))) \
        + len(glob.glob(resources.get('techs/*.png'))) \
        + len(glob.glob(resources.get('system/*.png'))) \
        + len(glob.glob(resources.get('icons/*.png'))) \
        + len(glob.glob(resources.get('buttons/*.png')))
    if progress_dlg:
        progress_dlg.display(_('Loading resources'), 0, max)
    # load star imgs
    global smallStarImgs
    smallStarImgs = {}
    for filename in glob.glob(resources.get('galaxy/star_*.png')):
        name = re.search("star_([^.]+).png", filename).group(1)
        smallStarImgs[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load tech imgs
    global techImgs
    techImgs = {}
    white = pygame.Surface((37, 37))
    white.fill((255, 255, 255))
    white.set_alpha(64)
    red = pygame.Surface((37, 37))
    red.fill((255, 0, 0))
    red.set_alpha(64)
    for filename in glob.glob(resources.get('techs/????.png')):
        name = os.path.splitext(os.path.basename(filename))[0]
        imgID = int(name)
        techImgs[imgID] = pygame.image.load(filename).convert_alpha()
        copyImg = techImgs[imgID].convert_alpha()
        copyImg.blit(white, (0, 0))
        techImgs[imgID + whiteShift] = copyImg
        copyImg = techImgs[imgID].convert_alpha()
        copyImg.blit(red, (0, 0))
        techImgs[imgID + redShift] = copyImg
        curr += 1
        updateProgress(curr, progress_dlg)
    # load big star imgs
    global bigStarImgs
    bigStarImgs = {}
    for filename in glob.glob(resources.get('system/star_*.png')):
        name = re.search("star_([^.]+).png", filename).group(1)
        bigStarImgs[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load planet images
    global planetImgs
    global planetImgCnt
    planetImgs = {}
    planetImgCnt = {}
    for filename in glob.glob(resources.get('system/planet_*.png')):
        matchobj = re.search("planet_((.)[^.]+).png", filename)
        name = matchobj.group(1)
        pltype = matchobj.group(2)
        if pltype in planetImgCnt:
            planetImgCnt[pltype] += 1
        else:
            planetImgCnt[pltype] = 1
        planetImgs[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load ship imgs
    global shipImgs
    shipImgs = {}
    for filename in glob.glob(resources.get('ships/??.png')):
        name = os.path.splitext(os.path.basename(filename))[0]
        shipImgs[int(name)] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load star imgs
    global icons
    icons = {}
    for filename in glob.glob(resources.get('icons/[!ui_]*.png')):
        name = os.path.splitext(os.path.basename(filename))[0]
        icons[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load UI icons
    global ui_icons
    ui_icons = {}
    for filename in glob.glob(resources.get('icons/ui_*.png')):
        name = os.path.splitext(os.path.basename(filename))[0]
        ui_icons[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # load buttons
    global buttonImgs
    buttonImgs = {}
    for filename in glob.glob(resources.get('buttons/*.png')):
        name = os.path.splitext(os.path.basename(filename))[0]
        buttonImgs[name] = pygame.image.load(filename).convert_alpha()
        curr += 1
        updateProgress(curr, progress_dlg)
    # other icons
    global cmdInProgressImg
    cmdInProgressImg = pygame.image.load(
        resources.get('cmdInProgress.png')).convert_alpha()
    global structProblemImg
    structProblemImg = pygame.image.load(
        resources.get('struct_problem.png')).convert_alpha()
    global structOffImg
    structOffImg = pygame.image.load(
        resources.get('struct_off.png')).convert_alpha()
Exemple #36
0
def initialize():
    # needed for progress dlg
    global loginLogoImg
    loginLogoImg = pygame.image.load(resources.get('logo-login.png')).convert_alpha()
Exemple #37
0
def loadResources():
    import dialog
    dlg = dialog.ProgressDlg(gdata.app)
    curr = 0
    max = len(glob.glob(resources.get('galaxy/*.png'))) + len(glob.glob(resources.get('techs/*.png'))) + \
        len(glob.glob(resources.get('system/*.png'))) + len(glob.glob(resources.get('icons/*.png'))) + len(glob.glob(resources.get('buttons/*.png')))
    dlg.display(_('Loading resources'), 0, max)
    # load star imgs
    global smallStarImgs
    smallStarImgs = {}
    for filename in glob.glob(resources.get('galaxy/star_*.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = re.search("star_([^.]+).png", filename).group(1)
        smallStarImgs[name] = pygame.image.load(filename).convert_alpha()
    # load tech imgs
    global techImgs
    techImgs = {}
    white = pygame.Surface((37,37))
    white.fill((255, 255, 255))
    white.set_alpha(64)
    red = pygame.Surface((37,37))
    red.fill((255, 0, 0))
    red.set_alpha(64)
    for filename in glob.glob(resources.get('techs/????.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = os.path.splitext(os.path.basename(filename))[0]
        imgID = int(name)
        techImgs[imgID] = pygame.image.load(filename).convert_alpha()
        copyImg = techImgs[imgID].convert_alpha()
        copyImg.blit(white, (0,0))
        techImgs[imgID + whiteShift] = copyImg
        copyImg = techImgs[imgID].convert_alpha()
        copyImg.blit(red, (0,0))
        techImgs[imgID + redShift] = copyImg
    # load big star imgs
    global bigStarImgs
    bigStarImgs = {}
    for filename in glob.glob(resources.get('system/star_*.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = re.search("star_([^.]+).png", filename).group(1)
        bigStarImgs[name] = pygame.image.load(filename).convert_alpha()
    # load planet images
    global planetImgs
    global planetImgCnt
    planetImgs = {}
    planetImgCnt = {}
    for filename in glob.glob(resources.get('system/planet_*.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        matchobj = re.search("planet_((.)[^.]+).png", filename)
        name = matchobj.group(1)
        pltype = matchobj.group(2)
        if pltype in planetImgCnt:
            planetImgCnt[pltype] += 1
        else:
            planetImgCnt[pltype] = 1
        planetImgs[name] = pygame.image.load(filename).convert_alpha()
    # load ship imgs
    global shipImgs
    shipImgs = {}
    for filename in glob.glob(resources.get('ships/??.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = os.path.splitext(os.path.basename(filename))[0]
        shipImgs[int(name)] = pygame.image.load(filename).convert_alpha()
    # load star imgs
    global icons
    icons = {}
    for filename in glob.glob(resources.get('icons/*.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = os.path.splitext(os.path.basename(filename))[0]
        icons[name] = pygame.image.load(filename).convert_alpha()
    # load buttons
    global buttonImgs
    buttonImgs = {}
    for filename in glob.glob(resources.get('buttons/*.png')):
        curr += 1
        if curr % 10 == 0:
            dlg.setProgress(_('Loading resources...'), curr)
        name = os.path.splitext(os.path.basename(filename))[0]
        buttonImgs[name] = pygame.image.load(filename).convert_alpha()
    # other icons
    global cmdInProgressImg
    cmdInProgressImg = pygame.image.load(resources.get('cmdInProgress.png')).convert_alpha()
    global structProblemImg
    structProblemImg = pygame.image.load(resources.get('struct_problem.png')).convert_alpha()
    global structOffImg
    structOffImg = pygame.image.load(resources.get('struct_off.png')).convert_alpha()
    dlg.hide()
Exemple #38
0
    gdata.config.defaults.minfleetsymbolsize = 4
    gdata.config.defaults.minplanetsymbolsize = 5
    gdata.config.defaults.maxfleetsymbolsize = 0
    gdata.config.defaults.maxplanetsymbolsize = 0

    options.heartbeat = 60
    osci.client.initialize('localhost:9080', dummyHandler, options)
    osci.client.login(options.game, 'admin', password)
    osci.client.cmdProxy.selectAdmin()
    osci.client.updateDatabase()

    pygame.init()
    screen = pygame.display.set_mode((10,10))
    osci.res.initialize()
    osci.res.loadResources()
    pygameui.SkinableTheme.setSkin(os.path.join(resources.get("themes"), 'green'))
    control_modes = {}  # mutable, thus updating here will update StarMap
    control_modes['systems'] = 1
    control_modes['planets'] = 1
    control_modes['fleets'] = 1
    control_modes['civilian_fleets'] = 1
    control_modes['pirate_areas'] = 1
    control_modes['hotbuttons'] = 0
    control_modes['minimap'] = 0
    control_modes['redirects'] = 0
    control_modes['map_grid_coords'] = 1
    control_modes['map_grid'] = 1
    control_modes['scanners'] = 0
    control_modes['fleet_lines'] = 1
    control_modes['gate_systems'] = 1
    control_modes['alternative_mode'] = 1
Exemple #39
0
    def __init__(self, filename=None):
        self._running = True
        self._display_surf = None
        self.size = self.width, self.height = 1280, 720

        if filename is None:
            filename = resources.get('examples/map_0.tmx')

        self.camera = Rect(0, 0, self.width, self.height)

        self._clock = pygame.time.Clock()
        self.fps = 60

        self.updateables = []
        self.drawables = []

        pygame.init()
        self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
        self.ignore_walls = False

        # Load map data
        tmx_data = load_pygame(filename)

        pygame.mixer.init()
        musicfile = tmx_data.properties.get('music')
        if musicfile:
            self.play_music(musicfile)

        map_data = pyscroll.data.TiledMapData(tmx_data)
        self.map_layer = pyscroll.BufferedRenderer(map_data, self._display_surf.get_size())
        self.map_layer.zoom = 4
        self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2)
        # really the group can be added as a gameobject

        self.teleport_group = pygame.sprite.Group()

        # setup level geometry with simple pygame rects, loaded from pytmx
        self.walls = {} # key is floor, value is list of wall rects

        self.trigger_targets = {}  # targets by target ID
        self.waiting_triggers = {} # lists of trigger targets by target ID
        self.triggers = []

        # Find known object types and attach behavior
        for o in tmx_data.objects:
            if hasattr(gameobjects, o.type):
                klass = getattr(gameobjects, o.type)
                if hasattr(klass, 'from_tmx'):
                    game_object = klass.from_tmx(o)
                    game_object.id = int(o.id)
                    game_object.z = 0
                    game_object.h = 0
                    floor = int(o.properties.get('floor', 0))
                    game_object.floor = floor
                    if hasattr(o, 'target_id'):
                        game_object.target_id = getattr(o, 'target_id')
                    self.group.add(game_object)

                    if o.name == 'Player':
                        self.player = game_object
                        self.player.h = 16
                        self.player.add_floor_listener(self.sprite_layer_handler)

                    if isinstance(game_object, gameobjects.TriggerMixin):
                        self.add_trigger(game_object)

                    self.save_trigger_target(game_object)

            elif o.type == 'Wall':
                floor = int(o.properties.get('floor', 0))
                if not self.walls.has_key(floor):
                    self.walls[floor] = []

                self.walls[floor].append(pygame.Rect(
                    o.x, o.y,
                    o.width, o.height))
            else:
                logger.error('Unrecognized object type: {0}'.format(o.type))

        self.group.center(self.player.rect.center)

        self.camera_shakes = 0
        self.camera_shake_dist = 0
Exemple #40
0
 def __init__(self):
     super(Gravity, self).__init__()
     self.g_factor = resources.get("gravity")
Exemple #41
0
    gdata.config.defaults.minplanetsymbolsize = 5
    gdata.config.defaults.maxfleetsymbolsize = 0
    gdata.config.defaults.maxplanetsymbolsize = 0

    options.heartbeat = 60
    osci.client.initialize('localhost:9080', dummyHandler, options)
    osci.client.login(options.game, 'admin', password)
    osci.client.cmdProxy.selectAdmin()
    osci.client.updateDatabase()

    pygame.init()
    screen = pygame.display.set_mode((10, 10))
    osci.res.initialize()
    osci.res.loadResources()
    pygameui.SkinableTheme.setSkin(
        os.path.join(resources.get("themes"), 'green'))
    control_modes = {}  # mutable, thus updating here will update StarMap
    control_modes['systems'] = 1
    control_modes['planets'] = 1
    control_modes['fleets'] = 1
    control_modes['civilian_fleets'] = 1
    control_modes['pirate_areas'] = 1
    control_modes['hotbuttons'] = 0
    control_modes['minimap'] = 0
    control_modes['redirects'] = 0
    control_modes['map_grid_coords'] = 1
    control_modes['map_grid'] = 1
    control_modes['scanners'] = 0
    control_modes['fleet_lines'] = 1
    control_modes['gate_systems'] = 1
    control_modes['alternative_mode'] = 1
Exemple #42
0
def get_resource():
    return jsonify(resources.get()), 200
Exemple #43
0
def runClient(options):

    # log initialization
    log.message("Starting Outer Space Client", ige.version.versionString)
    log.debug("sys.path =", sys.path)
    log.debug("os.name =", os.name)
    log.debug("sys.platform =", sys.platform)
    log.debug("os.getcwd() =", os.getcwd())
    log.debug("sys.frozen =", getattr(sys, "frozen", None))

    # create required directories
    if not os.path.exists(options.configDir):
        os.makedirs(options.configDir)

    running = 1
    first = True
    while running:
            if not first:
                    reload(osci)
            # parse configuration
            if first:
                    import osci.gdata as gdata
            else:
                    reload(gdata)
            #from ConfigParser import ConfigParser

            gdata.config = Config(os.path.join(options.configDir, options.configFilename))

            # default configuration
            if not options.local:
                    gdata.config.game.server = options.server
                    gdata.config.galaxer.server = options.galaxer
            else:
                    gdata.config.game.server = "localhost:9080"
                    gdata.config.galaxer.server = "http://localhost:9081"

            if gdata.config.client.language == None:
                    gdata.config.client.language = 'en'

            language = gdata.config.client.language

            if gdata.config.defaults.minfleetsymbolsize == None:
                    gdata.config.defaults.minfleetsymbolsize = 4

            if gdata.config.defaults.minplanetsymbolsize == None:
                    gdata.config.defaults.minplanetsymbolsize = 5

            if gdata.config.defaults.maxfleetsymbolsize == None:
                    gdata.config.defaults.maxfleetsymbolsize = 0

            if gdata.config.defaults.maxplanetsymbolsize == None:
                    gdata.config.defaults.maxplanetsymbolsize = 0

            import gettext
            log.debug('OSCI', 'Installing translation for:', language)
            if language == 'en':
                log.debug('OSCI', 'English is native - installing null translations')
                tran = gettext.NullTranslations()
            else:
                try:
                    tran = gettext.translation('OSPACE', resources.get('translations'), languages = [language])
                except IOError:
                    log.warning('OSCI', 'Cannot find catalog for', language)
                    log.message('OSCI', 'Installing null translations')
                    tran = gettext.NullTranslations()

            tran.install(unicode = 1)

            # read Highlights
            if gdata.config.defaults.colors != None:
                    for coldef in gdata.config.defaults.colors.split(' '):
                        m = re.match('(\d+):(0[xX].*?),(0[xX].*?),(0[xX].*)',coldef)
                        if m != None :
                            id = int(m.group(1))
                            red = min(int(m.group(2),16),255)
                            green = min(int(m.group(3),16),255)
                            blue = min(int(m.group(4),16),255)
                            gdata.playersHighlightColors[id] = (red,green,blue)
                        else:
                            log.warning('OSCI','Unrecognized highlight definition :',coldef)
            # read Object Keys
            if gdata.config.defaults.objectkeys != None:
                    for objectkey in gdata.config.defaults.objectkeys.split(' '):
                        m = re.match('(\d+):(\d+)',objectkey)
                        if m != None :
                            key = int(m.group(1))
                            objid = int(m.group(2))
                            gdata.objectFocus[key] = objid
                        else:
                            log.warning('OSCI','Unrecognized object key definition :',objectkey)

            #initialize pygame and prepare screen
            if (gdata.config.defaults.sound == "yes") or (gdata.config.defaults.music == "yes"):
                    pygame.mixer.pre_init(44100, -16, 2, 4096)

            os.environ['SDL_VIDEO_ALLOW_SCREENSAVER'] = '1'
            os.environ['SDL_DEBUG'] = '1'
            pygame.init()

            # step by step initialization
            #pygame.display.init()
            #pygame.font.init()

            # flags = HWSURFACE | DOUBLEBUF | FULLSCREEN
            # flags = HWSURFACE | FULLSCREEN
            flags = SWSURFACE

            gdata.isHWSurface = 0

            if gdata.config.display.flags != None:
                    strFlags = gdata.config.display.flags.split(' ')
                    flags = 0
                    if 'swsurface' in strFlags: flags |= SWSURFACE
                    if 'hwsurface' in strFlags:
                        flags |= HWSURFACE
                        gdata.isHWSurface = 1
                    if 'doublebuf' in strFlags: flags |= DOUBLEBUF
                    if 'fullscreen' in strFlags: flags |= FULLSCREEN

            gdata.scrnSize = (800, 600)
            if gdata.config.display.resolution != None:
                    width, height = gdata.config.display.resolution.split('x')
                    gdata.scrnSize = (int(width), int(height))

            if gdata.config.display.depth == None:
                    # guess best depth
                    bestdepth = pygame.display.mode_ok(gdata.scrnSize, flags)
            else:
                    bestdepth = int(gdata.config.display.depth)

            # initialize screen
            screen = pygame.display.set_mode(gdata.scrnSize, flags, bestdepth)
            gdata.screen = screen
            log.debug('OSCI', 'Driver:', pygame.display.get_driver())
            log.debug('OSCI', 'Using depth:', bestdepth)
            log.debug('OSCI', 'Display info:', pygame.display.Info())

            pygame.mouse.set_visible(1)

            pygame.display.set_caption(_('Outer Space %s') % ige.version.versionString)

            # set icon
            pygame.display.set_icon(pygame.image.load(resources.get('icon48.png')).convert_alpha())

            # load cursor
            cursorImg = pygame.image.load(resources.get('cursor.png')).convert_alpha()


            pygame.event.clear()
            drawBackground()
            pygame.display.flip()

            # UI stuff
            if first:
                    import pygameui as ui
            else:
                    reload(ui)

            theme = "green"
            if gdata.config.client.theme != None:
                    theme = gdata.config.client.theme
            ui.SkinableTheme.enableMusic(gdata.config.defaults.music == "no")
            ui.SkinableTheme.enableSound(gdata.config.defaults.sound == "yes")
            ui.SkinableTheme.setSkin(os.path.join(resources.get("themes"), theme))
            ui.SkinableTheme.loadMusic(gdata.config.defaults.mymusic)
            if gdata.config.defaults.musicvolume:
                    ui.SkinableTheme.setMusicVolume(float(gdata.config.defaults.musicvolume)/ 100.0)
            if gdata.config.defaults.soundvolume:
                    ui.SkinableTheme.setVolume(float(gdata.config.defaults.soundvolume) / 100.0)

            gdata.sevColors[gdata.CRI] = (ui.SkinableTheme.themeCritical)
            gdata.sevColors[gdata.MAJ] = (ui.SkinableTheme.themeMajor)
            gdata.sevColors[gdata.MIN] = (ui.SkinableTheme.themeMinor)
            gdata.sevColors[gdata.NONE] = (ui.SkinableTheme.themeNone)
            gdata.sevColors[gdata.DISABLED] = (ui.SkinableTheme.themeDisabled)

            app = ui.Application(update, theme = ui.SkinableTheme)
            app.windowSurfaceFlags = SWSURFACE | SRCALPHA
            gdata.app = app

            # resources
            import osci.res

            osci.res.initialize()

            # load resources
            osci.res.loadResources()


            # client
            if first:
                    import osci.client, osci.handler
                    from igeclient.IClient import IClientException
            else:
                    reload(osci.client)
                    reload(osci.handler)
            osci.client.initialize(gdata.config.game.server, osci.handler, options)

            # create initial dialogs
            if first:
                    import osci.dialog
            else:
                    reload(osci.dialog)
            gdata.savePassword = gdata.config.game.lastpasswordcrypted != None

            if options.login and options.password:
                    gdata.config.game.lastlogin = options.login
                    gdata.config.game.lastpassword = options.password
                    gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(options.password).strip()
                    gdata.config.game.autologin = '******'
                    gdata.savePassword = '******'

            if not first:
                    gdata.config.game.autologin = '******'




            loginDlg = osci.dialog.LoginDlg(gdata.app)
            updateDlg = osci.dialog.UpdateDlg(gdata.app)

            # event loop
            update()

            lastSave = time.clock()
            # set counter to -1 to trigger Update dialog (see "if" below)
            counter = -1
            needsRefresh = False
            session = 1
            first = False
            while running and session:
                    try:
                            counter += 1
                            if counter == 0:
                                    # display initial dialog in the very first cycle
                                    updateDlg.display(caller = loginDlg, options = options)
                            # process as many events as possible before updating
                            evt = pygame.event.wait()
                            evts = pygame.event.get()
                            evts.insert(0, evt)

                            forceKeepAlive = False
                            saveDB = False

                            for evt in evts:
                                    if evt.type == QUIT:
                                            running = 0
                                            break
                                    if evt.type == (USEREVENT + 1):
                                            if getattr(evt, 'action', None) == 'localExit':
                                                    session = 0
                                                    break
                                    if evt.type == ACTIVEEVENT:
                                            if evt.gain == 1 and evt.state == 6:
                                                    # pygame desktop window focus event
                                                    needsRefresh = True
                                    if evt.type == KEYUP and evt.key == K_F12:
                                            running = 0
                                            break
                                    if evt.type == KEYUP and evt.key == K_F9:
                                            forceKeepAlive = True
                                    evt = gdata.app.processEvent(evt)

                            if gdata.app.needsUpdate() or gdata.isHWSurface or needsRefresh:
                                    needsRefresh = False
                                    update()
                            # keep alive connection
                            osci.client.keepAlive(forceKeepAlive)

                            # save DB every 4 hours in case of a computer crash
                            # using "counter" to limit calls to time.clock() to approximately every 10-15 minutes
                            if counter > 5000:
                                    # set this to zero so we don't display Update dialog
                                    counter = 0
                                    if time.clock() - lastSave > 14400:
                                            saveDB = True
                            if saveDB:
                                    osci.client.saveDB()
                                    lastSave = time.clock();

                    except IClientException, e:
                            osci.client.reinitialize()
                            gdata.app.setStatus(e.args[0])
                            loginDlg.display(message = e.args[0])
                    except Exception, e:
                            log.warning('OSCI', 'Exception in event loop')
                            if not isinstance(e, SystemExit) and not isinstance(e, KeyboardInterrupt):
                                    log.debug("Processing exception")
                                    # handle exception
                                    import traceback, StringIO
                                    fh = StringIO.StringIO()
                                    exctype, value, tb = sys.exc_info()
                                    funcs = [entry[2] for entry in traceback.extract_tb(tb)]
                                    faultID = "%06d-%03d" % (
                                            hash("/".join(funcs)) % 1000000,
                                            traceback.extract_tb(tb)[-1][1] % 1000,
                                    )
                                    del tb
                                    # high level info
                                    print >>fh, "Exception ID:", faultID
                                    print >>fh
                                    print >>fh, "%s: %s" % (exctype, value)
                                    print >>fh
                                    print >>fh, "--- EXCEPTION DATA ---"
                                    # dump exception
                                    traceback.print_exc(file = fh)
                                    excDlg = osci.dialog.ExceptionDlg(gdata.app)
                                    excDlg.display(faultID, fh.getvalue())
                                    del excDlg # reference to the dialog holds app's intance
                                    fh.close()
                                    del fh
                            else:
                                    break
Exemple #44
0
    def update(self, commands):
        #self.logfile.write("frame\n")
        impact = [False, False]
        direction = [None, None]

        stick_0 = self.evaluate_joystick(0)
        stick_1 = self.evaluate_joystick(1)
        if self.old_sticks != []:
            change1 = length(sub(self.old_sticks[0]["stick"], stick_0["stick"]))
            if change1 > resources.get("impactThreshold"):
                impact[0] = True
            #self.logfile.write("p1 {}\n".format(stick_0["stick"]))
            position = length(stick_0["stick"])
            if position < 0.2:
                direction[0] = "neutral"
            else:
                stickdir = utils.normalized(stick_0["stick"])
                if stickdir[0] > 0.7:
                    direction[0] = "right"
                elif stickdir[0] < -0.7:
                    direction[0] = "left"
                elif stickdir[1] > 0.7:
                    direction[0] = "down"
                elif stickdir[1] < -0.7:
                    direction[0] = "up"
                #self.logfile.write("p1 dir {}\n".format(direction[0]))

            change2 = length(sub(self.old_sticks[1]["stick"], stick_1["stick"]))
            if change2 > resources.get("impactThreshold"):
                impact[1] = True
            position = length(stick_1["stick"])
            if position < 0.2:
                direction[1] = "neutral"
            else:
                stickdir = utils.normalized(stick_1["stick"])
                if stickdir[0] > 0.7:
                    direction[1] = "right"
                elif stickdir[0] < -0.7:
                    direction[1] = "left"
                elif stickdir[1] > 0.7:
                    direction[1] = "down"
                elif stickdir[1] < -0.7:
                    direction[1] = "up"

            #self.logfile.write("p2 dir {}\n".format(direction[1]))

            actor = self.entities.component_for_entity(self.players[0], Actor)
            actor.direction = direction[0]
            actor.impact = impact[0]

            actor2 = self.entities.component_for_entity(self.players[1], Actor)
            actor2.direction = direction[1]
            actor2.impact = impact[1]
        else:
            self.old_sticks = [None, None]

        self.old_sticks[0] = stick_0
        self.old_sticks[1] = stick_1

        for command in commands:
            if command == "exit":
                return "finish"
            if len(command) == 2:
                if command[1] == "A":
                    self.add_command(command[0], "attack")
                if command[1] == "L":
                    self.add_command(command[0], "shield")

        self.systems.update(1.0/resources.get("fps"))

        position = self.entities.component_for_entity(self.players[0], Position)
        if position.x < -512 or position.x > 512 or position.y < -500 or position.y > 384:
            self.lives[0] -= 1
            position.x = 0
            position.y = 0
            velocity = self.entities.component_for_entity(self.players[0], Velocity)
            velocity.dx = 0
            velocity.dy = 0
            if self.lives[0] == 0:
                self.winner = 1
        position2 = self.entities.component_for_entity(self.players[1], Position)
        if position2.x < -512 or position2.x > 512 or position2.y < -500 or position2.y > 384:
            self.lives[1] -= 1
            position2.x = 0
            position2.y = 0
            velocity2 = self.entities.component_for_entity(self.players[1], Velocity)
            velocity2.dx = 0
            velocity2.dy = 0
            if self.lives[1] == 0:
                self.winner = 0
        return None