コード例 #1
0
def start():
    #Initialize pygame
    pygame.init()

    #Set the window caption
    pygame.display.set_caption("wow! really good!!")

    #Use double buffering for better performance
    flags = DOUBLEBUF
    #Create the screen
    global screen
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), flags)

    #Create the clock
    global clock
    clock = pygame.time.Clock()

    global player_pos
    player_pos = [(SCREEN_WIDTH - PLAYER_WIDTH) / 2,
                  (SCREEN_HEIGHT - PLAYER_HEIGHT) / 2]

    global names
    names = Names.NameGenerator("name_parts.json")

    #Start the game loop
    run()
コード例 #2
0
	def __init__(self, dataSet):
		self.dataSet = dataSet
		
		self.cardType = CardType.createType(self.generateList('type'), self.model)
		self.cardTypes = CardTypes.createTypes(self.generateList('types'), self.model)
		self.cmc = Cmc.createCmc(self.generateList('cmc'), self.model)
		self.colorIdentity = ColorIdentity.createColorIdentity(self.generateList('colorIdentity'), self.model)
		self.colors = Colors.createColors(self.generateList('colors'), self.model)
		self.hand = Hand.createHand(self.generateList('hand'), self.model)
		self.imageName = ImageName.createImageName(self.generateList('imageName'), self.model)
		self.layouts = Layouts.createLayouts(self.generateList('layout'), self.model)
		self.legalities = Legalities.createLegalities(self.generateList('legalities'), self.model)
		self.life = Life.createLife(self.generateList('life'), self.model)
		self.loyalty = Loyalty.createLoyalty(self.generateList('loyalty'), self.model)
		self.manaCost = ManaCost.createManaCost(self.generateList('manaCost'), self.model)
		self.name = Name.createName(self.generateList('name'), self.model)
		self.names = Names.createNames(self.generateList('names'), self.model)
		self.power = Power.createPower(self.generateList('power'), self.model)
		self.printings = Printings.createPrintings(self.generateList('printings'), self.model)
		self.rulings = Rulings.createRulings(self.generateList('rulings'), self.model)
		self.source = Source.createSource(self.generateList('source'), self.model)
		self.starter = Starter.createStarter(self.generateList('starter'), self.model)
		self.cardSubTypes = CardSubTypes.createSubTypes(self.generateList('subtypes'), self.model)
		self.cardSuperTypes = CardSuperTypes.createSuperTypes(self.generateList('supertypes'), self.model)
		self.text = Text.createText(self.generateList('text'), self.model)
		self.toughness = Toughness.createToughness(self.generateList('toughness'), self.model)
コード例 #3
0
def get_count_gdf(geo_df, base_shape, state_code, city, year, avg=False):
    """
    Add incident count data to a GeoDataFrame.
    :param geo_df: The GeoDataFrame
    :param base_shape: The column name of the shape in which to count points.
    :param state_code: Census state code
    :param city: (String) City name (for finding incident logs)
    :param year: The year. If avg=True, this will be the last year over which to average
    :param avg: True if an average (past 5 years) is desired; False will return incident data
    for year specified in 'year' only.
    :return: A GeoDataFrame
    """
    inc_folder = Names.get_inc_log_folder(state_code, city)
    if not isdir(inc_folder):
        print 'Incident data not found at ' + inc_folder
        print 'Exiting...'
        exit(1)

    # Years is a list of the 5 years to average over, or the single year if avg is not indicated
    years = set([str(i) for i in range(int(year) - 4, int(year) + 1)] if avg else [str(year)])
    all_counts, all_inc_types = get_all_counts(geo_df=geo_df, base_shape=base_shape, log_folder=inc_folder, years=years)

    if avg:
        all_counts = average_counts(all_counts, year, all_inc_types)

    geo_df = generate_count_gdf(geo_df=geo_df, base_shape=base_shape, all_counts=all_counts)

    return geo_df
コード例 #4
0
def merge_census_to_taz(census_gdf, taz_gdf, census_level_lbl, taz_level_lbl):
    """
    Reaggregate Census data into TAZ shapes.
    :param census_gdf: Census GeoDataFrame
    :param taz_gdf: TAZ GeoDataFrame
    :param census_level_lbl: Name of the column indicating a unique label for each Census shape
    :param taz_level_lbl: Name of the column indicating a unique label for each TAZ
    :return: A gdf with Census data reaggregated into TAZ shapes
    """
    print("Merging TAZ and Census data")
    # TAZ does not have lat/long of centroids. Add this info for GWR analysis.
    lat_col_name = Names.SF_TAZ_COL_LAT
    long_col_name = Names.SF_TAZ_COL_LONG
    taz_gdf = get_interp_lat_long(taz_gdf,
                                  lat_col_name=lat_col_name,
                                  long_col_name=long_col_name)

    # Get a dataframe with a subset of the taz columns
    sub_df_cols = ['TAZ', taz_level_lbl, lat_col_name, long_col_name
                   ] + taz_to_sum + taz_to_avg + taz_no_mod
    geo_col = taz_gdf.loc[:, 'geometry']
    sub_gdf = taz_gdf.reindex(columns=sub_df_cols)

    # The 'tract' column in the taz file includes state and county code before the tract
    # NOTE: A TAZ can be made up of different census shapes.
    # In Charlotte, NC, TAZs are subdivisions of block groups.
    # However, this may not be the case in other cities.
    sub_gdf.loc[:, taz_level_lbl] = \
        sub_gdf.loc[:, taz_level_lbl].apply(func=lambda x: '"' + x[5:] + '"')

    # Left join because Census is more likely to exclude useless shapes.
    combined_gdf = sub_gdf.merge(right=census_gdf,
                                 how='left',
                                 left_on=taz_level_lbl,
                                 right_on=census_level_lbl)
    combined_gdf.loc[:, 'geometry'] = geo_col

    # -------  Divide population by number of TAZ within tracts
    # NOTE: It might be better to assign populations as a proportion of area, but neither will be perfect

    # Get all census population labels in the TAZ
    census_pop_labels = CodeDicts.get_pop_labels()
    census_pop_labels = filter(lambda x: x in combined_gdf.columns.values,
                               census_pop_labels)

    # Count the number of TAZ to divide by
    combined_gdf['numblks'] = combined_gdf[taz_level_lbl].groupby(
        combined_gdf[taz_level_lbl]).transform('count')

    # Divide each column of Census population by the number of TAZ within the Census shape
    combined_gdf.loc[:, census_pop_labels] = \
        combined_gdf.loc[:, census_pop_labels].divide(combined_gdf.loc[:, 'numblks'], axis='rows')
    combined_gdf.drop(columns='numblks', inplace=True)
    combined_gdf = Names.quote_column(combined_gdf, Names.SF_TAZ_COL_TAZ)

    return combined_gdf
コード例 #5
0
ファイル: Functions.py プロジェクト: Brounredo/Revolution
def next_year():
    """Конец хода (1 ход = 1 год)."""
    Vars.year += 1  # Инкремент текущего года
    for e in Vars.players:  # Для всех игроков
        Vars.players[e].age += 1  # Инкремент возраста
    game_over()  # Проверка на конец игры
    for w in range(5):  # 5 раз
        Vars.MyCountry.min_now[w] = Names.random_name()  # присвоить министру с номером w случайное имя
    for q in range(5):  # 5 раз
        Vars.MyCountry.min_stats[q] = random.randint(1, 11)  # присвоить случайный уровень (от 1 до 10) министру q
コード例 #6
0
ファイル: Identity.py プロジェクト: lyfeinclouds/PyDev
	def __init__(self, gender, age_range):
		# Set Gender
		self.gender = gender
		# Set Name
		self.fullname = Names.Name(gender)
		self.first = self.fullname.first_name
		self.middle = self.fullname.middle_name
		self.last = self.fullname.last_name
		# Set Age
		self.age = random.randrange(age_range[0], age_range[1])
		# Set Password
		self.password = getRandVal(FiletoArray('data/passwords.txt'))
		# Set Website
		word1 = getRandVal(FiletoArray("data/dictionary.txt"))
		word2 = getRandVal(FiletoArray("data/dictionary.txt"))
		commonTLDS = ["com", "edu", "net", "org"]
		self.website = "http://" + word1 + word2 + "." + getRandVal(commonTLDS)
コード例 #7
0
def find_taz_of_addr(base_gdf, mat_df):
    """
    Find the TAZ of each address within the Master Address Table
    :param base_gdf: The TAZ GDF
    :param mat_df: The master address table as a DataFrame
    :return: A GeoDataframe with each address merged with its associated TAZ
    """

    print "Merging address and shapefile data."
    mat_df['geometry'] = mat_df.apply(lambda x: gpd.geoseries.Point(
        (float(x.longitude), float(x.latitude))),
                                      axis=1)
    mat_gdf = gpd.GeoDataFrame(mat_df, geometry='geometry')
    mat_gdf.crs = base_gdf.crs
    merged = gpd.sjoin(mat_gdf, base_gdf, how='inner', op='within')
    merged.drop(['geometry'], axis=1, inplace=True)
    merged = Names.quote_column(df=merged, column=Names.SF_TAZ_COL_TAZ)
    return merged
コード例 #8
0
        def Another():
            global saved_

            if saved_ == False:

                faces = []
                
                
                if len(os.listdir("../Faces/"+str(Details[0]))) > 6:
                    
                    messagebox.showinfo('Delete Extra Images','Kindly delete extra images and keep only 6')
                    return 0
                
                for face in os.listdir("../Faces/"+str(Details[0])):
                    
                    img = cv2.imread("../Faces/"+str(Details[0])+"/"+face)
                    faces.append(ExtractFeatures(img))
                    

                faces = np.array(faces)
                String_Code = faces.__repr__()
                
                
                mydb= connector.connect(host = "localhost", user= "******", passwd = "aayush123", database="testdb")
                cursor = mydb.cursor()
                
                q = "insert into userse (name,age,gender,post,contact,address, encodings) values ( %s , %s , %s , %s , %s , %s , %s )"

                data = [(Details[1], int(Details[2]), Details[3], Details[4], Details[5], Details[6], String_Code ) ]
                print(data)
                cursor.executemany(q,data)
                mydb.commit()
                saved_ = True


            mydb= connector.connect(host = "localhost", user= "******", passwd = "aayush123", database="testdb")
            cursor = mydb.cursor()

            cursor.execute("Select count(ID) from userse")
            result = cursor.fetchall()
            incrementedID = int(result[0][0]) + 1
            top.destroy()

            Names.EnterData(incrementedID)
コード例 #9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'state_code',
        type=str,
        help="The state code (note this is a string and may have a leading 0)")
    args = parser.parse_args()

    state_codes = CensusDicts.us_state_codes

    if args.state_code not in state_codes:
        print("Invalid state code (You can check code with ListStateCodes.py)")
        exit(1)

    census = Census.Census(Names.get_census_key())
    county_dict = census.get_county_dict(args.state_code)

    for code, county in sorted(county_dict.iteritems(),
                               key=lambda (k, v): (v, k)):
        print(code + ': ' + county)
コード例 #10
0
def create_shapefile(state_code,
                     county_code,
                     year,
                     avg=True,
                     level='tract',
                     zone=False,
                     points=None,
                     taz=True,
                     clip=None,
                     intersect=None,
                     nocheck=False,
                     outname='out'):

    all_population_columns = [
    ]  # Keep a list of all population columns for areal interpolation

    bg = (level == 'bg')
    base_shape = Names.SF_CENSUS_COL_BG if bg else Names.SF_CENSUS_COL_TRACT

    if level != 'bg' and level != 'tract':
        print "Invalid Census level"
        exit(1)

    if avg and not points:
        print "Cannot average incidents without counting incidents!"
        exit(1)

    county, state = Names.get_location(state_code, county_code)
    msg = 'You have selected to create a shapefile for {}, {} for {} with the following properties:\n'. \
        format(county, state, year)
    msg += 'Demographics for {} in {}, {}\n'.format(level, county, state)
    if points:
        if avg:
            msg += "Averaged "
        else:
            msg += "Yearly "
        msg += "incident counts\n"
    if taz:
        msg += "Taz data\n"
    if clip:
        msg += "Clipped against {}'s response zone\n".format(clip)
    if intersect:
        msg += "Intersected against {}'s response zone\n".format(intersect)
    if zone:
        msg += "With zoning proportions of each shape\n"
    msg += "Saving as shapefile: {}".format(outname)
    r = ''
    print msg

    while not nocheck and r != 'y':
        r = raw_input("Is this correct? (y/n): ")
        if r == 'n':
            print "Exiting..."
            exit(1)

    gdf = GetDemographics.create_demographic_df(state_code=state_code,
                                                county_code=county_code,
                                                year=year,
                                                bg=bg)
    GetNeighborData.get_neighbor_data(census_gdf=gdf,
                                      target_columns=['bldavg', 'medinc'])
    all_population_columns.extend(CodeDicts.get_pop_labels())

    if taz:
        taz_gdf = get_taz_gdf(state_code, county_code, year)
        gdf = GetTazData.merge_census_to_taz(
            census_gdf=gdf,
            taz_gdf=taz_gdf,
            census_level_lbl=base_shape,
            taz_level_lbl=Names.SF_TAZ_COL_TRACT)

        base_shape = Names.SF_TAZ_COL_TAZ
        all_population_columns.extend(TazCodeList.taz_to_sum)

        # Get employment and population density
        density_cols = ['TPE_TOTEMP', 'TPE_POP']
        area_column = 'TPE_AREA_L'
        gdf = ExtractFeatures.get_densities(gdf=gdf,
                                            target_columns=density_cols,
                                            area_column=area_column,
                                            drop=False)

    # NOTE: population values are interpolated during clipping. Make sure all population features are added
    # before clipping!
    if clip:
        resp_area_fpath = Names.get_response_zone_shapefile(state_code, clip)
        gdf = GetTrimmedSF.clip_shapefile(gdf, resp_area_fpath,
                                          all_population_columns)

    if intersect:
        resp_area_fpath = Names.get_response_zone_shapefile(
            state_code, intersect)
        gdf = GetTrimmedSF.intersect_shapefile(gdf, resp_area_fpath)

    if points:
        gdf = GetIncidentCounts.get_count_gdf(geo_df=gdf,
                                              base_shape=base_shape,
                                              state_code=state_code,
                                              city=points,
                                              year=year,
                                              avg=False)

    if zone:
        zone_gdf = gpd.read_file(
            Names.get_zoning_shapefile(state_code=state_code,
                                       county_code=county_code,
                                       year=year))
        gdf = GetZoningData.append_zone_proportions(base_gdf=gdf,
                                                    zone_gdf=zone_gdf,
                                                    base_shp_col=base_shape)

        zones_to_combine = \
            {
                'RESIDENTIAL': ['SINGLE FAMILY', 'MULTI-FAMILY'],
                'COMMERCIAL': ['OFFICE', 'BUSINESS', 'MIXED USE']
            }

        gdf = CombineFeatures.sum_features(gdf, zones_to_combine)

    print("Creating shapefile as {}".format(outname))
    gdf.to_file(outname, driver='ESRI Shapefile')
    gdf.drop(['geometry'], axis=1, inplace=True)
    gdf.to_csv(outname + '.csv')
コード例 #11
0
def get_taz_gdf(state_code, county_code, year):
    return gpd.read_file(
        Names.get_taz_shapefile(state_code=state_code,
                                county_code=county_code,
                                year=year))
 def ADD():
     window.destroy()
     Names.EnterData(incrementedID)
コード例 #13
0
ファイル: DnDGen.py プロジェクト: ziggi24/DnDRand
		weaponSorc = ["Quarterstaff"]
		weaponWiza = ["Quarterstaff"]


		char['str'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
		char['dex'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
		char['con'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6) 
		char['int'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
		char['wis'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
		char['cha'] = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
		char['alx'] = random.choice(alx)
		char['aly'] = random.choice(aly)

		if( char['str'] > char['dex'] and char['str'] > char['con'] and char['str'] > char['int'] 
		and char['str'] > char['wis'] and char['str'] > char['cha']):
			char['name'] = name + " " + Names.getName() + " The " +  random.choice(nameStr)
			char['class'] = random.choice(classStr)
		elif( char['dex'] > char['str'] and char['dex'] > char['con'] and char['dex'] > char['int'] 
		and char['dex'] > char['wis'] and char['dex'] > char['cha']):
			char['name'] = name + " " + Names.getName() + " The " + random.choice(nameDex)
			char['class'] = random.choice(classDex)
		elif( char['con'] > char['str'] and char['con'] > char['dex'] and char['con'] > char['int'] 
		and char['con'] > char['wis'] and char['con'] > char['cha']):
			char['name'] = name + " " + Names.getName() + " The " + random.choice(nameCon)
			char['class'] = random.choice(classCon)
		elif( char['int'] > char['str'] and char['int'] > char['dex'] and char['int'] > char['con'] 
		and char['int'] > char['wis'] and char['int'] > char['cha']):
			char['name'] = name + " " + Names.getName() + " The " + random.choice(nameInt)
			char['class'] = random.choice(classInt)
		elif( char['wis'] > char['str'] and char['wis'] > char['dex'] and char['wis'] > char['con'] 
		and char['wis'] > char['int'] and char['wis'] > char['cha']):
コード例 #14
0
def get_names(names_file):
    """
    Get the Names object
    :param names_file: the pathname of the names file
    :return: the Names object
    """

    with open(names_file, 'r') as f:
        # Read the names file
        spamreader = list(csv.reader(f, delimiter='='))

    # Add code_dir folder
    sys.path.append(code_dir)
    # Import the Names module
    import Names

    names = Names.Names()

    # For each parameter
    for para_name in names.para_names:
        # For each row in the names file
        for i in range(len(spamreader)):
            # If spamreader[i] is not empty
            if spamreader[i] is not None and len(spamreader[i]) > 0:
                # Get the string on the left-hand side of '='
                str_left = spamreader[i][0]

                # Ignore comments
                if str_left.startswith('#'):
                    continue

                if para_name in str_left:
                    # If there is a value for the parameter
                    if len(spamreader[i]) > 1:
                        # Get the string on the right-hand side of '='
                        str_right = spamreader[i][1]

                        if para_name == 'combine_classes':
                            # Split the string into groups of new-old classes
                            groups = [
                                group.strip() for group in str_right.split(';')
                                if len(group.strip()) > 0
                            ]

                            # If groups is not empty
                            if len(groups) > 0:
                                # Get the combine_classes dictionary
                                combine_classes = {}

                                for group in groups:
                                    # Split the group into new and old classes
                                    new_old_classes = [
                                        new_old_class.strip()
                                        for new_old_class in group.split(':')
                                        if len(new_old_class.strip()) > 0
                                    ]

                                    # If there are both new and old classes
                                    if len(new_old_classes) == 2:
                                        # Get the new class
                                        new_class = new_old_classes[0]

                                        # Get the old classes
                                        old_classes = [
                                            old_class.strip() for old_class in
                                            new_old_classes[1].split(',')
                                            if len(old_class.strip()) > 0
                                        ]

                                        # Update the combine_classes dictionary
                                        combine_classes[
                                            new_class] = old_classes

                                get_para_vals(names, para_name,
                                              combine_classes)
                        else:
                            # Split the string into values
                            vals = [
                                str_.strip() for str_ in str_right.split(',')
                                if len(str_.strip()) > 0
                            ]

                            # If vals is not empty
                            if len(vals) > 0:
                                vals = [
                                    float(val)
                                    if val.isdigit() is True else val
                                    for val in vals
                                ]
                                get_para_vals(names, para_name, vals)

    # Get the features
    names.features = [
        feature for feature in names.columns
        if (feature != names.target and feature not in names.exclude_features)
    ]

    return names
コード例 #15
0
ファイル: main.py プロジェクト: Brounredo/Revolution
if age_temp < 14:
    print("Маленький ещё страной управлять!")
    sys.exit()
elif age_temp > 50:
    print("Староват уже.")
    sys.exit()
Vars.MyPlayer.age = int(age_temp)  # Возраст игрока
Vars.MyCountry = random.choice(AllCountries.allcountries)  # Страна игрока
print("Ваша страна - ", Vars.MyCountry.name)
Vars.MyPlayer.place = Vars.MyCountry.capital  # Местоположение игрока
print("Введите количество ботов: ", end='')
bots = int(input())  # Количество ботов
for j in range(bots):  # Добавление ботов
    Vars.countries.append(random.choice(AllCountries.allcountries))
for q in range(5):  # "Созыв" министров
    Vars.MyCountry.min_now[q] = Names.random_name()
Functions.gen_gamemap()  # Генерация карты


# Цикл игры
while 1:
    # Вывод основной информации
    print("")
    print("Год:", Vars.year)
    print("Ваш возраст:", Vars.MyPlayer.age)
    print("Ваша популярность:", Vars.MyPlayer.popular)
    print("Денег в казне:", Vars.MyCountry.money, "руб.")
    print("Население страны:", Vars.MyCountry.population, "чел.")
    print("Личных денег:", Vars.MyPlayer.money, "руб.")
    print("Вы находитесь в:", Vars.MyPlayer.place)
    print("Новости:", Vars.news)