Esempio n. 1
0
 def __init__(self):
     self.__data = {}
     self.__ignore = []
     self.__buyed = []
     self.__setting = Config()
     self.__tpe = ThreadPoolExecutor(5)
     self.__engine = create_engine(self.__setting.get_DBurl())
Esempio n. 2
0
    def __init__(self):
        super().__init__()
        self.config = Config("config.ini")

        # INIT Controls
        self.wheels = Wheels(self.config.steeringMid, self.config.steeringLeft,
                             self.config.steeringRight)
        self.accelerator = Accelerator(self.config, self)

        self.__initUI()
        self.statusBar().showMessage("Board not connected")

        # Init uds listener
        self._log("Init udp at {}:{}".format(
            get_ip(), self.config.getOption('udp_port')))
        self.udpSocket = QUdpSocket()
        self.udpSocket.setLocalAddress(QHostAddress(get_ip()))
        self.udpSocket.bind(self.config.getOption('udp_port'))
        self.udpSocket.readyRead.connect(self.udpHandler)

        # Init tcp server
        self.tcpServer = QTcpServer(self)
        self._log("Starting TCP at {}:{} ".format(
            get_ip(), str(self.config.getOption('tcp_port'))))
        self.tcpServer.listen(QHostAddress(get_ip()),
                              self.config.getOption('tcp_port'))
        self.tcpServer.newConnection.connect(self.establishBoardConnection)

        self.show()
Esempio n. 3
0
def upload_face():
    male_group_id = 'celebrity_male_test'
    female_group_id = 'celebrity_female_test'

    app_id = Config().get("AipConfig", "APP_ID")
    api_key = Config().get("AipConfig", "API_KEY")
    secret_key = Config().get("AipConfig", "SECRET_KEY")
    client = AipFace(app_id, api_key, secret_key)

    cnx = mysql.connector.connect(user='******', password='******',
                                  host='127.0.0.1',
                                  database='chbb_facecompare')
    cursor = cnx.cursor()
    query_images = 'select c.name, c.gender, ci.imagePath, ci.uid from celebrity c join celebrityImage ci on ci.celebrity_id = c.id;'
    cursor.execute(query_images)

    for (name, gender, imagePath, uid) in cursor:
        group_id = ''
        # print(name, gender, imagePath, uid)
        if gender == '男':
            group_id = male_group_id
        elif gender == '女':
            group_id = female_group_id
        else:
            print(gender)

        image_path = directoryPath + imagePath
        options = {
            "action_type": "replace"
        }
        client.updateUser(uid, name, group_id, get_file_content(image_path), options)
        print(name, gender, 'uploaded.')

    cursor.close()
    cnx.close()
Esempio n. 4
0
def main():
    home = os.path.expanduser("~")
    defaultConfigFile = home + '/.config-stt-watson.yml'
    parser = argparse.ArgumentParser(
        description=
        'Speech to text using watson in python with websocket and record from microphone'
    )

    parser.add_argument('-f',
                        action='store',
                        dest='configFile',
                        default=defaultConfigFile,
                        help='config file',
                        required=False)
    args = parser.parse_args()
    if not os.path.isfile(args.configFile):
        print "Config file '" + args.configFile + "' doesn't exist."
        print "Creating it ..."
        data = pkgutil.get_data('config', 'config.sample.yml')
        Config.Instance().loadConfigFromResource(data)
        watsonConfig = Config.Instance().getWatsonConfig()
        user = raw_input("Watson user: "******"Watson password: "******"user"] = user
        watsonConfig["password"] = password
        f = open(args.configFile, 'w')
        f.write(yaml.dump(Config.Instance().getConfig()))
        f.close()

    Config.Instance().setConfigFile(args.configFile)
    sttWatsonLogListener = SttWatsonLogListener()
    watsonConfig = Config.Instance().getWatsonConfig()
    sttWatson = SttWatson(watsonConfig["user"], watsonConfig["password"])
    sttWatson.addListener(sttWatsonLogListener)
    sttWatson.run()
Esempio n. 5
0
 def __init__(self, stopper):
     threading.Thread.__init__(self)
     self.p = pyaudio.PyAudio()
     self.writer = None
     self.stopper = stopper
     self.channels = Config.Instance().getChannels()
     self.rate = Config.Instance().getAudioRate()
     self.chunk = Config.Instance().getAudioChunk()
     self.pauseRecord = False
Esempio n. 6
0
 def __init__(self):
     self.__config = Config()
     self.__buyedCount = 0
     self.__balance = self.__config.get_t1()['trade']['balance']
     if self.__config.get_t1()['trade']['enable']:
         self.__trade = Trade()
     if self.__config.get_t1()['trade']['enableMock']:
         self.__mockTrade = MockTrade()
     self.__engine = create_engine(self.__config.get_DBurl())
 def __init__(self, db_name):
     con = Config()
     self._db_host = con.get_db("database", "db_host")
     self._db_port = con.get_db("database", "db_port")
     self._db_auth = con.get_db("database", "db_auth")
     self._db_user = con.get_db("database", "db_user")
     self._db_password = con.get_db("database", "db_password")
     self._db_name = db_name
     self._client = None
Esempio n. 8
0
 def __init__(self, codes):
     self.__data = {}
     self.__buyed = []
     self.__selled = []
     self.__setting = Config()
     self.__tpe = ThreadPoolExecutor(5)
     self.__engine = create_engine(self.__setting.get_DBurl())
     if self.__setting.get_t1(
     )['need_recover_data'] and self.needRecoverData():
         self.recoverData(codes)
Esempio n. 9
0
 def __getFilenamesToNormalise(self):
     extensions = tuple(
         Config.getFromSection(
             self.mediaType,
             'normaliser.path.sources.file.extensions').split(','))
     maxNumberOfFiles = int(
         Config.getFromSection(self.mediaType,
                               'normaliser.max.number.of.files'))
     return FileUtils.findFilesRecursivelly(self.sourcePath, extensions,
                                            maxNumberOfFiles)
Esempio n. 10
0
	def __init__(self):
		super(TitleScene, self).__init__()

		# generate bg stars
		self.bgStars = []
		for i in range(0, 100):
			self.bgStars.append(Vector2(random.randrange(0, Config.getScreenSize()[0]), random.randrange(0, Config.getScreenSize()[1])))

		# menu manager
		self.menuManager = MenuManager(MainMenu(), self)

		# bg music
		pygame.mixer.music.load(Config.getFile(Config.titleBgMusic))
		pygame.mixer.music.play(-1) # loop forever
Esempio n. 11
0
def main():
    config = Loggable.get_config_provider()
    config.set_console_log_level(logging.INFO)
    Loggable.set_config_provider(config)

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', dest='config', default='config.json', help='Config which should be used')
    args = parser.parse_args()
    if not os.path.isfile(args.config):
        raise FileNotFoundError('Config not found: ' + str(args.config))

    with open(args.config) as file:
        config = Config(json.load(file))

    dns_watcher = DnsWatcher()
    tunnels = []
    for forwarder in config.forwarders:
        tunnels.append(Tunnel(forwarder, config.dest_addr, dns_watcher))

    for tunnel in tunnels:
        tunnel.start()

    def signal_handler(sig, frame):
        # Gracefully terminate to revert the iptables config
        dns_watcher.stop()
        for t in tunnels:
            t.stop()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    dns_watcher.wait_for_changes()
Esempio n. 12
0
 def __init__(self):
     self.config = Config()
     self.ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
     self.db_filename = os.path.join(self.config.database_location)
     self.schema_filename = os.path.join(self.ROOT_DIR,
                                         'cryptoAlchemist_schema.sql')
     self.createDatabase()
Esempio n. 13
0
def main(argv):
    if len(argv) < 2:
        print("usage: python generate.py <model-config.yaml>")
        exit(1)
    print(argv)
    configs = Config(argv[1])
    generate_dataset(configs)
Esempio n. 14
0
class WebSocket:
    auth_cookie = ''
    uri = 'wss://' + Config.get_host() + '/api/v4/websocket'

    def __init__(self):
        self.auth_cookie = 'MMAUTHTOKEN=' + Config.get_access_token(
        ) + '; MMUSERID=' + Bot.Bot.get_bot().get_bot_id()

    async def listen(self):
        async with websockets.connect(
                uri=self.uri,
                extra_headers=[('Cookie', self.auth_cookie)]) \
                as websocket:
            while True:
                receive = await websocket.recv()
                dump = json.loads(receive)
                if 'data' in dump:
                    if 'post' in dump['data']:
                        post_dump = dump['data']['post']
                        post_dump = post_dump.strip()
                        index = post_dump.index('message')
                        message = post_dump[index + len('message') +
                                            2:post_dump.index(',', index)]
                        message = message[1:len(message) - 1]
                        message = message.strip()
                        if Command.is_command(message):
                            if ' ' in message:
                                command, arg = message.split(' ')
                                CommandManager.check_command(command, arg)
                            else:
                                CommandManager.check_command(message, '')
Esempio n. 15
0
def __normalise():
    for pathSource in Config.get('normaliser.path.sources').split(','):
        try:
            Normaliser(pathSource, 'Pictures').run()
            Normaliser(pathSource, 'Videos').run()
        except Exception as err:
            logging.error(str(err))
Esempio n. 16
0
def __rename():
    for pathSource in Config.get('renamer.path.sources').split(','):
        try:
            Renamer(pathSource, 'Pictures').run()
            Renamer(pathSource, 'Videos').run()
        except Exception as err:
            logging.error(str(err))
Esempio n. 17
0
    def buyLogic(self, emaTracker, connection, currentSelectedCryptoPrice, mainConfig):
        ################################################################################################################
        #################################### Buy #######################################################################
        # See if the conditions are right for a sell limit to be placed

        avgNegVariance = emaTracker.getAvgNegVariance()

        print("Avg Neg Variance: ", (avgNegVariance / mainConfig.order_rate))

        ema = emaTracker.getEMA()

        try:
            last_ema_val = ema[len(ema) - 1]
        except:
            print("Error with getting Ema")
            return

        print("Last EMA Val: ", last_ema_val, '   ', "Current Price: ", currentSelectedCryptoPrice)

        if avgNegVariance is not None:
            print("Min Buy Val: ", last_ema_val - avgNegVariance)

            # Altered buy logic to immediately set buy order
            # The Buy orders are all timed to elapse in 1 hour, with the amount needed scaling towards EMA
            buy_val = float(currentSelectedCryptoPrice) - float(avgNegVariance / mainConfig.order_rate)  # hard-coding offset
            tradeHandler = TradeHandler(connection, Config())
            tradeHandler.buy(buy_val)
Esempio n. 18
0
class Storage:

    def __init__(self):
        self.config = Config()

    def get_storage(self):
        return self.config.get_storage()
Esempio n. 19
0
    def sellLogic(self, emaTracker, connection, currentSelectedCryptoPrice, mainConfig):

        avgPosVariance = emaTracker.getAvgPosVariance()

        print("Avg Pos Variance: ", avgPosVariance)

        ema = emaTracker.getEMA()

        try:
            last_ema_val = ema[len(ema) - 1]
        except:
            print("Error with getting Ema")
            return

        trade_handler = TradeHandler(connection, Config())

        if avgPosVariance is not None:

            print("Last EMA Val: ", last_ema_val, '   ', "Current Price: ", currentSelectedCryptoPrice)
            # print("Step Value decisionMaker.sellLogic(): ", stepValue)
            print("Sell Val: ", last_ema_val + (avgPosVariance / mainConfig.order_rate))

            last_buy_price = self.database.getLastBoughtPrice()
            sell_price = last_buy_price + (avgPosVariance / mainConfig.order_rate)

            if sell_price < last_buy_price:
                sell_price = last_buy_price + .01
                print("Sell Price is currently being calculated below profitability.")
                print("Selling at 1 cent above bought price: ", sell_price)

            trade_handler.sell(sell_price)
Esempio n. 20
0
	def showPauseMenu(self, screen):
		menuRect = pygame.Rect(0,0, 400, 400)
		menuRect.center = screen.get_rect().center

		self.selections = ["RESUME", "SAVE GAME", "MAIN MENU", "QUIT"]
		selectionsTexts = []
		selectionsRects = []

		menuFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 40)
		for index, item in enumerate(self.selections):
			text = menuFont.render(item, True, (255,255,255))
			textRect = text.get_rect()
			textRect.centerx = screen.get_rect().centerx
			textRect.y = menuRect.top + 30 + index * 60
			selectionsTexts.append(text)
			selectionsRects.append(textRect)

		self.selectionsRects = selectionsRects

		highlightRect = selectionsRects[self.currentSelection].copy()
		highlightRect.top = selectionsRects[self.currentSelection].bottom
		highlightRect.height = 2

		pygame.draw.rect(screen, (0,254,253), highlightRect, 0)
		for i, text in enumerate(selectionsTexts):
				screen.blit(text, selectionsRects[i])
Esempio n. 21
0
def __shrink():
    for pathSource in Config.get('shrinker.path.sources').split(','):
        try:
            Shrinker(pathSource, 'Pictures').run()
            Shrinker(pathSource, 'Videos').run()
        except Exception as err:
            logging.error(str(err))
Esempio n. 22
0
    def modify_path_watch(self):

        Config().check_config(path_watch=self.path_watch,
                              file_pattern=self.file_pattern,
                              min_size=self.min_size,
                              timewait=self.timewait)

        list_file = parser_yaml.get_list_file_data()
        path_file_name = parser_yaml.normalize_path(self.path_watch)

        if path_file_name not in list_file:
            logging.error("Path already exists : {} | use ajouter".format(
                self.path_watch))
            return False

        modif_val = parser_yaml.get_read_single_yaml(path_file_name)

        if self.file_pattern is not None:
            modif_val['file_pattern'] = self.file_pattern
        if self.min_size is not None:
            modif_val['min_size'] = self.min_size
        if self.command is not None:
            modif_val['command'] = self.command
        if self.timewait is not None:
            modif_val['timewait'] = self.timewait

        parser_yaml.set_write_yaml(path_file_name, modif_val)

        logging.info('Modify for path {}'.format(self.path_watch))

        return True
Esempio n. 23
0
def __classify():
    for pathSource in Config.get('classifier.path.sources').split(','):
        try:
            Classifier(pathSource, 'Pictures').run()
            Classifier(pathSource, 'Videos').run()
        except Exception as err:
            logging.error(str(err))
Esempio n. 24
0
 def __buildDestinationFilename(self, filename, destinationPath):
     media = MediaBuilder.build(filename)
     partialPath = FileUtils.getDestinationSubdirectory(media)
     filePath = os.path.join(destinationPath, partialPath,
                             media.getNextNewFileName())
     filePathWithoutExtension = os.path.splitext(filePath)[0]
     newExtension = '.' + Config.get('handbrake.destination.extension')
     return filePathWithoutExtension + newExtension
Esempio n. 25
0
    def initialize():
        config = Config()
        log_distributor_builder = LogDistributorBuilder()
        default_log_distributor = log_distributor_builder.build_default()

        logger = Logger()
        logger.setup([default_log_distributor])

        App.__path_provider = PathProvider(logger=logger)

        config.pathes = App.__path_provider.load(load_default=True)

        App.__settings_provider = SettingsProvider(location=config.pathes[PathKeys.SETTINGS].location,
                                                   logger=logger)
        config.settings = App.__settings_provider.load()

        log_distributor_builder.setup(config.settings[SettingsKeys.logging][SettingsKeys.loggers])
        log_distributors = log_distributor_builder.build_all()

        logger.setup(log_distributors=log_distributors)

        delete_excess_files(
            config.pathes[PathKeys.GEN_OUT].location,
            config.settings[SettingsKeys.system][SettingsKeys.out_files_max],
            logger)

        delete_excess_files(
            config.pathes[PathKeys.LOG].location,
            config.settings[SettingsKeys.logging][SettingsKeys.logger_files_max],
            logger)

        App.__gen_settings_provider = SettingsProvider(location=config.pathes[PathKeys.GEN_SETTINGS].location,
                                                       logger=logger)
        config.gen_settings = App.__gen_settings_provider.load()

        App.__logger = logger
        #App.setup_thread_pool(config)

        #App.__data_collector = ReportDataCollector()
        #App.__data_collector.setup()

        App.__reporter = Reporter(App.__data_collector.data)

        #App.__batch_amount = config.gen_settings[GenSettingsKeys.portion_amount]

        return config, logger
Esempio n. 26
0
	def renderNearestPlanetGUI(self, screen, camera):
		# GUI - Object desc
		color = (0,254,253)
		
		# heading
		guiFont = pygame.font.Font(Config.getFile(Config.neuropol), 18)
		heading = guiFont.render("Nearest Planet", True, color)
		headingRect = pygame.Rect(screen.get_rect().left + 10, screen.get_rect().bottom - 200, 400, 30)
		screen.blit(heading, (headingRect.left + 10, headingRect.top + 7))

		#border
		descRect = pygame.Rect(headingRect.left, headingRect.bottom + 10, 400, 150)
		borderRect = descRect.copy()
		borderRect.height = 2
		pygame.draw.rect(screen, color, borderRect, 0)

		# planet name
		closestPlanet = None
		closestDistanceSq = 0
		for planet in self.planets:
			distanceToPlanetSq = (self.probe.position - planet.position).magnitude_squared()
			if closestPlanet is None or distanceToPlanetSq < closestDistanceSq:
				closestPlanet = planet
				closestDistanceSq = distanceToPlanetSq

		font = pygame.font.Font(Config.getFile(Config.ethnocentric), 30)
		text = font.render(closestPlanet.name, True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 10))

		font = pygame.font.Font(Config.getFile(Config.neuropol), 17)

		text = font.render("Distance : " + str(int(math.sqrt(closestDistanceSq))), True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 60))

		hasHumanPresence = "Yes" if closestPlanet.zoneRadius > 0 else "No"
		text = font.render("Human Presence : " + hasHumanPresence, True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 85))

		text = font.render("Distance From Sun: " +  str(int(closestPlanet.distance)) + " AU", True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 110))

		originalImage = closestPlanet.originalImage
		zoomedImage = pygame.transform.smoothscale(originalImage, (100,100))
		probeRect = zoomedImage.get_rect()
		probeRect.topright = (descRect.right - 10, descRect.top + 10)
		screen.blit(zoomedImage, probeRect)
Esempio n. 27
0
    def __init__(self):
        # pull from database
        print("Initializing Exponential Moving Average tracker...")

        # Basic Queue carries unweighted price data

        self.mainConfig = Config()
        self.database = CryptoDatabase()
Esempio n. 28
0
 def __init__(self,
              user,
              password,
              model=None,
              rate=None,
              chunk=None,
              channels=None):
     if not Config.Instance().getConfig():
         Config.Instance().setConfig(self.default_config)
     watsonConfig = Config.Instance().getWatsonConfig()
     watsonConfig["user"] = user
     watsonConfig["password"] = password
     if model is not None:
         watsonConfig["model"] = model
     if chunk is not None:
         Config.Instance().setAudioChunk(chunk)
     if rate is not None:
         Config.Instance().setAudioRate(rate)
     if channels is not None:
         Config.Instance().setChannels(channels)
     Config.Instance().setWatsonConfig(watsonConfig)
     self.listeners = []
     self.stopper = threading.Event()
     self.record = Record(self.stopper)
     self.workers = [self.record]
     self.watsonClient = Client()
     self.handler = SignalHandler(self.stopper, self.workers)
     signal.signal(signal.SIGINT, self.handler)
 def setUp(self):
     driver_path = os.path.realpath('../webdrivers/chromedriver.exe')
     self.driver = webdriver.Chrome(driver_path)
     self.contact_page = ContactPage(self.driver)
     self.driver.maximize_window()
     self.driver.implicitly_wait(5)
     self.data = TestData()
     self.url = Config().get_url(ENV)
     self.enums = ContactPageEnums
Esempio n. 30
0
 def __handleError(self, filename):
     self.numberOfErrors = self.numberOfErrors + 1
     logging.error("Error normalising %s. Error number %s.",
                   filename,
                   str(self.numberOfErrors),
                   exc_info=True)
     if self.numberOfErrors == int(
             Config.get('normaliser.max.number.of.errors')):
         raise ValueError(
             'Too many errors. Something is wrong. Aborting execution.')
Esempio n. 31
0
 def __init__(self):
     self.__config = Config()
     try:
         if self.__config.get_mongo_config()['load_from_mongo']:
             self.__mongo_client = pymongo.MongoClient(
                 self.__config.get_mongo_config()['mongo_url'])
             self.__mongo_client.admin.command('ismaster')
             self.__config.update_proxy(self.get_t1_from_mongo())
             self.__config.get_mongo_config(
             )['load_time'] = dt.datetime.now()
     except Exception as e:
         MyLog.error('can not connect to mongo, %s' % e)
     self.__buyedCount = 0
     self.__balance = self.__config.get_t1()['trade']['balance']
     if self.__config.get_t1()['trade']['enable']:
         self.__trade = Trade()
     if self.__config.get_t1()['trade']['enableMock']:
         self.__mockTrade = MockTrade()
     self.__engine = create_engine(self.__config.get_DBurl())
 def __buildCommand(inputFile, outputFile):
     command = []
     command.append('HandBrakeCLI')
     command.append('-i')
     command.append(inputFile)
     command.append('-o')
     command.append(outputFile)
     command.append('-x')
     command.append(Config.get('handbrake.profile'))
     return command
Esempio n. 33
0
	def __init__(self):
		self.mass = 33300
		self.position = Vector2(0,0)
		self.size = 15

		self.imageSize = Vector2(self.size*2, self.size*2)
		self.zoom = 0
		self.originalImage = pygame.image.load(Config.getFile("img/planets/sun.png")).convert_alpha()
		self.tempImage = pygame.transform.smoothscale(self.originalImage, map(int, (self.imageSize * self.zoom)))
		self.rect = self.tempImage.get_rect()
def action():
    # 定义环境
    env = Consts.API_ENVIRONMENT_DEBUG
    conf = Config()
    host = conf.host_debug
    tester = conf.tester_debug
    allure.environment(environment=env)
    allure.environment(hostname=host)
    allure.environment(tester=tester)
    return env
Esempio n. 35
0
	def renderObjectDescGUI(self, screen):
		# GUI - Object desc
		color = (0,254,253)
		windowSize = Vector2(400, 150)
		
		# heading
		guiFont = pygame.font.Font(Config.getFile(Config.neuropol), 18)
		heading = guiFont.render("Object description", True, color)
		headingRect = pygame.Rect(screen.get_rect().right - 10 - windowSize.x, screen.get_rect().bottom - 200, windowSize.x, 30)
		screen.blit(heading, (headingRect.left + 10, headingRect.top + 7))

		descRect = pygame.Rect(headingRect.left, headingRect.bottom + 10, windowSize.x, windowSize.y)

		# border
		borderRect = descRect.copy()
		borderRect.height = 2
		pygame.draw.rect(screen, color, borderRect, 0)

		# object descriptions
		font = pygame.font.Font(Config.getFile(Config.ethnocentric), 30)
		text = font.render("FR-71", True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 10))

		font = pygame.font.Font(Config.getFile(Config.neuropol), 17)

		text = font.render("Health : " + str(self.probe.health) + "/" + str(self.probe.maxHealth), True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 60))

		text = font.render("Fuel : " + str(round(self.probe.fuel, 1)) + "/" + str(self.probe.fuelCapacity), True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 85))

		text = font.render("Speed: " +  str(int(self.probe.speed.magnitude() * 100)) + "/" + str(self.probe.maxSpeed * 100), True, color)
		screen.blit(text, (descRect.left + 10, descRect.top + 110))

		# object image
		originalImage = pygame.image.load(Config.getFile("img/rocket4.png")).convert_alpha()
		imageSize = Vector2(173, 291) * 0.5
		zoomedImage = pygame.transform.smoothscale(originalImage, map(int, (imageSize)))
		probeRect = zoomedImage.get_rect()
		probeRect.topright = (descRect.right - 10, descRect.top + 10)
		screen.blit(zoomedImage, probeRect)
Esempio n. 36
0
	def __init__(self):
		super(IntroScene, self).__init__()

		# generate bg stars
		self.bgStars = []
		for i in range(0, 100):
			self.bgStars.append(Vector2(random.randrange(0, Config.getScreenSize()[0]), random.randrange(0, Config.getScreenSize()[1])))

		# bg music
		pygame.mixer.music.load(Config.getFile(Config.introBgMusic))
		pygame.mixer.music.play(-1) # loop forever

		# Render Lines
		self.fontColor = (255,255,0)
		self.titleFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 40)
		self.font = pygame.font.Font(Config.getFile(Config.ethnocentric), 20)
		self.lineHeight = 55
		self.lines = [
			"HOME DEFENCE",
			"",
			"It is a period of space war. Alien",
			"spaceships, striking from a hidden base,",
			"have conquered the planets of our solar",
			"system.",
			"",
			"During the battle, alien spies managed",
			"to destroy our colonies of Uranus and",
			"Neptune, using armoured space station",
			"called DEATH STAR.",
			"",
			"We must act fast to stop the aliens from",
			"destroying all of our homeland!"
		]

		# start scrolling from the bottom of the screen
		self.y = Config.getScreenSize()[1]
		self.scrollSpeed = 50
Esempio n. 37
0
	def render(self, screen, camera):
		if self.zoom != camera.zoom:
			self.zoomedImage = pygame.transform.smoothscale(self.originalImage, map(int, (self.imageSize * camera.zoom)))
			self.tempImage = pygame.transform.rotate(self.zoomedImage, self.direction)
			self.rect = self.tempImage.get_rect()

			self.zoom = camera.zoom

		if abs(self.directionChange) > 0:
			oldCenter = self.rect.center
			self.tempImage = pygame.transform.rotate(self.zoomedImage, self.direction)
			self.rect = self.tempImage.get_rect()
			self.rect.center = oldCenter

			self.directionChange = 0

		if self.isHit:
			self.tempImage.fill((255,0,0), special_flags=pygame.BLEND_RGBA_MULT)

		self.rect.center = camera.convertCoordinates(self.position)
		screen.blit(self.tempImage, self.rect)

		if self.isHit:
			self.zoomedImage = pygame.transform.scale(self.originalImage, map(int, (self.imageSize * camera.zoom)))
			self.tempImage = pygame.transform.rotate(self.zoomedImage, self.direction)
			self.isHit = False
			
		for bullet in self.bullets:
			bullet.blit(screen, camera)

		# health bar and info
		maxWidth = 0.02 * camera.zoom  * self.maxHealth
		healthRect = pygame.Rect((self.rect.topleft), (maxWidth, 2))
		healthRect.bottom = self.rect.top - 4
		healthRect.centerx = self.rect.centerx
		oldLeft = healthRect.left

		healthRect.width = maxWidth * self.health / self.maxHealth
		healthRect.left = oldLeft
		pygame.draw.rect(screen, (0,255,0), healthRect, 0)

		font = pygame.font.Font(Config.getFile(Config.ethnocentric), int(round(0.4 * camera.zoom)))
		text = font.render("HP:" + str(self.health), True, (255,255,255))
		textRect = text.get_rect()
		textRect.left = healthRect.left
		textRect.bottom = healthRect.top - 1
		screen.blit(text, textRect)
Esempio n. 38
0
	def render(self, screen):
		screen.fill((0,0,0))

		# render bg stars
		for star in self.bgStars:
			position = map(int, star)
			randomVal = random.randrange(150, 255)
			color = (randomVal,randomVal,randomVal)
			pygame.gfxdraw.pixel(screen, position[0], position[1], (randomVal,randomVal,randomVal))

		# Render Game title
		titleFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 80)
		titleText = titleFont.render("PLANET WARS", True, (255,255,255))
		titleTextRect = titleText.get_rect()
		titleTextRect.centerx = screen.get_rect().centerx
		titleTextRect.y = 40
		screen.blit(titleText, titleTextRect)

		# Render Menu
		self.menuManager.menu.render(screen)
Esempio n. 39
0
	def render(self, screen):
		selectionsTexts = []
		selectionsRects = []
		menuFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 40)

		for i, selection in enumerate(self.selections):
			text = menuFont.render(selection, True, (255,255,255))
			textRect = text.get_rect()
			textRect.centerx = screen.get_rect().centerx
			textRect.y = 180 + i * 60
			selectionsTexts.append(text)
			selectionsRects.append(textRect)

		self.selectionsRects = selectionsRects

		highlightRect = selectionsRects[self.currentSelection].copy()
		highlightRect.height = 2
		highlightRect.top = selectionsRects[self.currentSelection].bottom
		pygame.draw.rect(screen, (0,254,253), highlightRect, 0)

		for i, text in enumerate(selectionsTexts):
			screen.blit(text, selectionsRects[i])
Esempio n. 40
0
	def render(self, screen):
		super(SavedGamesMenu, self).render(screen)

		texts = []
		rects = []
		menuFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 20)
	
		text = menuFont.render("ENTER - Load saved game", True, (255,255,255))
		textRect = text.get_rect()
		textRect.centerx = screen.get_rect().width / 4
		textRect.bottom = screen.get_rect().bottom - 20
		texts.append(text)
		rects.append(textRect)

		text = menuFont.render("BACKSPACE - Delete saved game", True, (255,255,255))
		textRect = text.get_rect()
		textRect.centerx = screen.get_rect().width / 4 * 3
		textRect.bottom = screen.get_rect().bottom - 20
		texts.append(text)
		rects.append(textRect)

		for i, text in enumerate(texts):
			screen.blit(text, rects[i])
Esempio n. 41
0
	def __init__(self, position, speed, direction, imageSize, size, imageFile, health, maxHealth, thrust):
		self.position = position
		self.speed = speed
		self.direction = direction
		self.gravitationalPull = Vector2(0,0)
		self.directionChange = 0
		self.thrust = thrust

		self.imageSize = imageSize
		self.size = size # for collision purpose

		self.originalImage = pygame.image.load(Config.getFile(imageFile)).convert_alpha()
		self.zoom = 0

		self.zoomedImage = pygame.transform.smoothscale(self.originalImage, map(int, (self.imageSize * self.zoom)))
		self.tempImage = pygame.transform.rotate(self.zoomedImage, self.direction)
		self.rect = self.tempImage.get_rect()

		self.maxHealth = maxHealth
		self.health = health
		self.isHit = False

		self.bullets = []
Esempio n. 42
0
	def render(self, screen):
		super(ControlsMenu, self).render(screen)
		controlsTexts = []
		controlsRects = []
		menuFont = pygame.font.Font(Config.getFile(Config.ethnocentric), 15)

		for i, control in enumerate(self.controls1):
			text = menuFont.render(control, True, (255,255,255))
			textRect = text.get_rect()
			textRect.centerx = screen.get_rect().width / 4
			textRect.y = 250 + i * 30
			controlsTexts.append(text)
			controlsRects.append(textRect)

		for i, control in enumerate(self.controls2):
			text = menuFont.render(control, True, (255,255,255))
			textRect = text.get_rect()
			textRect.centerx = screen.get_rect().width / 4 * 3
			textRect.y = 250 + i * 30
			controlsTexts.append(text)
			controlsRects.append(textRect)

		for i, text in enumerate(controlsTexts):
			screen.blit(text, controlsRects[i])
Esempio n. 43
0
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#
import sys
import os
sys.path.append( os.path.join( os.getcwd(), '..' ) )


# Make template classes
from mako.template import Template
from mako.lookup import TemplateLookup
templateLookup = TemplateLookup(directories=['./'])


#local classes for Numb3r L0ck3r
from config.Config import Config


localConfig = Config()
localConfig.parseConfigurationFile()

t = Template(filename='template/frontPage.tmpl',lookup=templateLookup)

#print(page)
print(t.render(templateDir="template",
	       **localConfig.getConfigurationDict()))

from mako.lookup import TemplateLookup
templateLookup = TemplateLookup(directories=['./'])

#local classes for Numb3r L0ck3r
from config.Config import Config

# The database class. Used to escape some sensitive information.
from DataBase import DataBase

# The authorization class to get the password hash for the admin user
from User.Authorize import Authorize



# Create objects from the configuration and database classes
config = Config('../config/config.dat')

# Parse the config file.
if(config.parseConfigurationFile()) :
    # The config file was successfully parsed.
    db = DataBase()                                      # Create the db object
    siteInfo     = config.getConfigurationDict()         # Get the site variables
    databaseInfo = config.getDatabaseConfigurationDict() # get the db variables
    securityInfo = config.getSecurityConfigurationDict() # get the security variables
    siteInfo.update(databaseInfo)                        # Add all the dicts into one master
    siteInfo.update(securityInfo)

    # Set the admin password
    auth = Authorize()
    auth.setPassPhrase(securityInfo['passwordSecurityHash'])
    siteInfo['adminPassword'] = auth.getHash(securityInfo['administratorPassword'])
Esempio n. 45
0
	def __init__(self, savedGame = None):
		super(GameScene, self).__init__()

		self.level = 1
		self.paused = False

		screenSize = Config.getScreenSize()
		self.camera = Camera(Vector2(screenSize[0], screenSize[1]))
		
		# setup solar system
		self.sun = Sun()
		#							size	mass	dist	year	colour						center
		mercury = Planet("Mercury",	0.383, 	3200, 	57.0, 	900, 	"img/planets/mercury.png", 	self.sun, math.radians(random.randrange(0, 359)))
		venus 	= Planet("Venus",	0.95, 	3200, 	108.0, 	2000, 	"img/planets/venus.png", 	self.sun, math.radians(random.randrange(0, 359)))
		earth 	= Planet("Earth",	1.0, 	3200, 	150.0, 	3650, 	"img/planets/earth.png", 	self.sun, math.radians(random.randrange(0, 359)))
		mars 	= Planet("Mars",	0.532, 	3200, 	227.0, 	7000, 	"img/planets/mars.png", 	self.sun, math.radians(random.randrange(0, 359)))
		jupiter = Planet("Jupiter",	11.2, 	12000, 	778.0, 	36000, 	"img/planets/jupiter.png", 	self.sun, math.radians(random.randrange(0, 359)))
		saturn 	= Planet("Saturn",	9.45, 	5000, 	1426.0, 80000, 	"img/planets/saturn.png", 	self.sun, math.radians(random.randrange(0, 359)))

		# moons
		#earth
		moon = Moon(		0.5, 	100, 	15.0, 	80, 	"img/planets/moon.png", 	earth, math.radians(random.randrange(0, 359)))
		earth.moons.append(moon)

		#mars
		phobos = Moon(		0.2, 	100, 	5.0, 	30, 	"img/planets/moon.png", 	mars, math.radians(random.randrange(0, 359)))
		deimos = Moon(		0.2, 	100, 	8.0, 	40, 	"img/planets/moon.png", 	mars, math.radians(random.randrange(0, 359)))
		mars.moons.append(phobos)
		mars.moons.append(deimos)

		#jupiter
		europa 		= Moon(		0.2, 	100, 	20.0, 	60, 	"img/planets/moon.png", 	jupiter, math.radians(random.randrange(0, 359)))
		io 			= Moon(		0.2, 	100, 	25.0, 	80, 	"img/planets/moon.png", 	jupiter, math.radians(random.randrange(0, 359)))
		ganymede 	= Moon(		0.2, 	100, 	30.0, 	100, 	"img/planets/moon.png", 	jupiter, math.radians(random.randrange(0, 359)))
		callisto 	= Moon(		0.2, 	100, 	35.0, 	120, 	"img/planets/moon.png", 	jupiter, math.radians(random.randrange(0, 359)))
		jupiter.moons.append(europa)
		jupiter.moons.append(io)
		jupiter.moons.append(ganymede)
		jupiter.moons.append(callisto)

		self.planets = [mercury, venus, earth, mars, jupiter, saturn]


		# asteroids
		self.asteroids = []
		for i in range(0, 500):
			size = random.randrange(4, 15) / 10.0
			self.asteroids.append(Asteroid(	size, 	1, 	random.randrange(400,600), 	random.randrange(100, 300), (100, 100, 100), 	self.sun, math.radians(random.randrange(0, 359))))

		# setup pointer to probe and aliens
		self.probe = Probe(earth.position + Vector2(20,0), Vector2(0,0))
		self.aliens = []

		# stars
		self.bgStars = []
		for i in range(0, 200):
			self.bgStars.append(Vector2(random.randrange(-Config.getScreenSize()[0]/2, Config.getScreenSize()[0]/2), random.randrange(-Config.getScreenSize()[1]/2, Config.getScreenSize()[1]/2)))

		# Level setup and load game if necessary
		self.levelManager = LevelManager(Level1(), self.planets, self.probe, self.aliens, self)
		
		if savedGame is not None:
			savedGame.load(self.levelManager, self.planets, self.probe, self.aliens)
			self.update(0)
			self.paused = True

		# gui
		self.currentSelection = 0
		self.selectionsRects = []

		self.selectSound = pygame.mixer.Sound("sound/select.ogg")
Esempio n. 46
0
	def save(self):
		s = shelve.open(Config.getFile(Config.savedGamesDB))
		appended = s["savedGames"]
		appended.append(self)
		s["savedGames"] = appended
		s.close()
Esempio n. 47
0
    # TODO - verify the password
    if(authorization.checkUser(formValues['userID'].value,formValues['passwd'].value)):
	# TODO - set cookie
	#authorization.printCookieInformation()
        #print("Authorized: {0}".format(authorization.userAuthorized()))
	print("Location: ../index.cgi\n\n")


    else:
	# The password and username did not match.
	# Need to print an error message
	badUser = True

# Get the configuration information 
from config.Config import Config
localConfig = Config('../')
localConfig.parseConfigurationFile()

# Get the authorization information
authorization = Authorize(localConfig.getPassPhrase())


# get the controler to print the page
from Controller.AccountController import LoginController
mainControl = LoginController('loginPage.tmpl',localConfig.diskOptions['templateDir'])
mainControl.renderPage(loginBox=True,
		       badPassword = badUser,
                       username=authorization.getUserName(),
                       **localConfig.getConfigurationDict())

Esempio n. 48
0
	def saveBulk(savedGames):
		db = shelve.open(Config.getFile(Config.savedGamesDB))
		db["savedGames"] = savedGames
		db.close()
Esempio n. 49
0
import sys, pygame
from config.Config import Config
from scenes.Scene import Scene
from models.SceneManager import SceneMananger
from scenes.TitleScene import TitleScene
from scenes.GameScene import GameScene

pygame.init()
Config.load()
modes = pygame.display.list_modes(32)
size = modes[Config.screenMode]
screen = pygame.display.set_mode(size, Config.getScreenFlags())
pygame.display.set_caption(Config.caption)
clock = pygame.time.Clock()

pygame.mouse.set_visible(True)

manager = SceneMananger(TitleScene())

# bg music
pygame.mixer.init()
pygame.mixer.set_num_channels(8)

def main():
	while True:
		clock.tick(Config.fps)
		deltaTime = clock.get_time() / 1000.0 # in seconds

		events = pygame.event.get()
		for event in events:
			if event.type == pygame.QUIT:
Esempio n. 50
0
	def loadAll():
		db = shelve.open(Config.getFile(Config.savedGamesDB))
		savedGames = db["savedGames"]
		db.close()
		return savedGames