コード例 #1
0
	def _create_building(self, orientation):
		WELL_OUTER = (Vec3(0,0,0), Vec3(-5,0,-5))
		WELL_CORE = (Vec3(-1,0,-1), Vec3(-4,0,-4))
		WELL_INNER = (Vec3(-2,0,-2), Vec3(-3,0,-3))
		WELL_WIDTH = 6

		WELL_BASE = []
		WELL_BASE.append(BuildingBlock(WELL_CORE[0], block.COBBLESTONE, WELL_CORE[1]))

		WELL_WATER = []
		WELL_WATER.append(BuildingBlock(WELL_CORE[0], block.COBBLESTONE, WELL_CORE[1]))
		WELL_WATER.append(BuildingBlock(WELL_INNER[0], block.WATER, WELL_INNER[1]))

		WELL_GROUND = []
		WELL_GROUND.append(BuildingBlock(WELL_OUTER[0], block.GRAVEL, WELL_OUTER[1]))
		WELL_GROUND.append(BuildingBlock(WELL_CORE[0], block.COBBLESTONE, WELL_CORE[1]))
		WELL_GROUND.append(BuildingBlock(WELL_INNER[0], block.WATER, WELL_INNER[1]))

		WELL_WALLS = []
		WELL_WALLS.append(BuildingBlock(WELL_CORE[0], block.COBBLESTONE, WELL_CORE[1]))
		WELL_WALLS.append(BuildingBlock(WELL_INNER[0], block.AIR, WELL_INNER[1]))

		WELL_SUPPORT = []
		WELL_SUPPORT.append(BuildingBlock(Vec3(-1,0,-1), block.FENCE))
		WELL_SUPPORT.append(BuildingBlock(Vec3(-1,0,-4), block.FENCE))
		WELL_SUPPORT.append(BuildingBlock(Vec3(-4,0,-4), block.FENCE))
		WELL_SUPPORT.append(BuildingBlock(Vec3(-4,0,-1), block.FENCE))
		
		bl = Building(orientation, WELL_WIDTH)
		bl.layers.append(BuildingLayer(WELL_BASE, -3))
		bl.layers.append(BuildingLayer(WELL_WATER, -2))
		bl.layers.append(BuildingLayer(WELL_GROUND, -1))
		bl.layers.append(BuildingLayer(WELL_WALLS, 0))
		bl.layers.append(BuildingLayer(WELL_SUPPORT, 1))
		bl.layers.append(BuildingLayer(WELL_SUPPORT, 2))
		bl.layers.append(BuildingLayer(WELL_BASE, 3))
		
		# set_direction needs to be called after adding layers to building
		bl._set_orientation()

		# rotate offset for test:
		if orientation == Building.EAST:
			self.default_offset.rotateRight()
		elif orientation == Building.SOUTH:
			self.default_offset.rotateRight()
			self.default_offset.rotateRight()
		elif orientation == Building.WEST:
			self.default_offset.rotateLeft()

		return bl
コード例 #2
0
ファイル: game.py プロジェクト: MartinWho2/Game-Project
 def save_load_events(self):
     for e in pygame.event.get():
         # quitter le jeu de force
         if e.type == pygame.QUIT:
             self.run = False
             pygame.quit()
         # récupérer les coordonnées de clic de la souris
         if e.type == pygame.MOUSEBUTTONDOWN:
             x = pygame.mouse.get_pos()[0]
             # False to save and True to load
             if x < self.bg.w / 2:
                 self.s_l_choice = False
             else:
                 self.s_l_choice = True
         # vérification du point de relâchement du clic de la souris
         if e.type == pygame.MOUSEBUTTONUP:
             x = pygame.mouse.get_pos()[0]
             # charger les données de sauvegarde
             if self.s_l_choice and x > self.bg.w / 2:
                 infos = decoding()
                 print(infos)
                 self.buildings.empty()
                 self.gold.quantity, self.stuff.quantity = infos[0]
                 self.gold.add(0)
                 self.stuff.add(0)
                 self.bg.x, self.bg.y, self.bg.zoom = infos[1]
                 for b in infos[2]:
                     type = self.dict_loading[b[0][0]]
                     image = self.pictures[type]
                     batiment = Building(image, b[1], b[2], self.bg, type)
                     self.buildings.add(batiment)
                 self.s_l = False
                 self.win.fill((0, 0, 0))
             # sauvegarder les données de sauvegarde
             elif not self.s_l_choice and x < self.bg.w / 2:
                 resources = [self.gold.quantity, self.stuff.quantity]
                 building = []
                 for b in self.buildings:
                     building.append([b.type, b.gap_x, b.gap_y])
                 data = [
                     resources, [self.bg.x, self.bg.y, self.bg.zoom],
                     building
                 ]
                 encode(data)
                 self.s_l = False
                 self.win.fill((0, 0, 0))
         # si la touche escape est pressée, le menu save/load est fermé
         if e.type == pygame.KEYDOWN:
             if e.key == pygame.K_ESCAPE:
                 self.s_l = False
                 self.win.fill((0, 0, 0))
コード例 #3
0
def run_game():
    #游戏初始化,创建一个屏幕对象
    pygame.init()

    g_settings = Settings()

    screen = pygame.display.set_mode((g_settings.screen_width,g_settings.screen_height),pygame.RESIZABLE)
    pygame.display.set_caption("Flappy Bird")

    bird = Bird(g_settings,screen)

    building = Building(g_settings, screen)

    building1 = Building(g_settings, screen)
    building1.rect1.x = building1.rect1.x + 200
    building1.rect2.x = building1.rect2.x + 200

    building2 = Building(g_settings, screen)
    building2.rect1.x = building1.rect1.x + 400
    building2.rect2.x = building1.rect2.x + 400

    building3 = Building(g_settings, screen)
    building3.rect1.x = building1.rect1.x + 600
    building3.rect2.x = building1.rect2.x + 600

    building4 = Building(g_settings, screen)
    building4.rect1.x = building1.rect1.x + 800
    building4.rect2.x = building1.rect2.x + 800


    while True:
        # 监测键盘事件和鼠标事件
        gf.check_events(bird)

        #屏幕刷新相关函数
        gf.update_screen(screen,g_settings,bird,building,building1,building2,building3,building4)
コード例 #4
0
 def handle_build_action(self, civ, action):
     """Handle incoming build actions and update game state."""
     if self._civs[civ].id != action.unit._civ_id:
         return ([], ServerError(4))
     building_type = action.building_type
     tile = self.validate_tile(action.unit.position)
     unit = self.validate_unit(civ, action.unit)
     bld_id = database_API.Building.insert(self._session,
                                           self._civs[civ]._id,
                                           True, Building.get_type
                                           (building_type),
                                           tile.x, tile.y, tile.z)
     self._civs[civ].build_structure(unit,
                                     building_type,
                                     bld_id)
     return ([tile], bld_id)
コード例 #5
0
ファイル: main.py プロジェクト: garciajg/excel-objects
def get_buildings_from_file():
    d = pd.read_excel("building_data.xlsx",
                      sheet_name="Sheet1",
                      names=[
                          "date_added", "occupancy", "lease_signed",
                          "building", "building_class", "city", "deal_size",
                          "tenant", "new_renewal_expansion", "term",
                          "base_rent", "rent_structure", "esc", "t_i",
                          "rent_abatement", "tenant_broker", "ll_broker",
                          "t_o", "comments"
                      ])
    od = d.where((pd.notnull(d)), None).to_dict(orient="index",
                                                into=OrderedDict)
    buildings = []
    for i in range(len(od)):
        building = Building(**od[i])
        buildings.append(building)
    return buildings
コード例 #6
0
ファイル: game.py プロジェクト: MAKASiNer/projectAntiyoy
 def renderBuilding(self, screen):
     # отрисовка окружения поля
     for y in range(self.size[1]):
         for x in range(self.size[0]):
             # строения
             if self.building[x][y].type != Type(
             ).void and self.building[x][y].type != Type().road:
                 image = self.imageBuilding[self.building[x][y].type -
                                            1][self.building[x][y].team - 1]
                 rect = (int(x * self.plates_size[0]) + self.sideShift,
                         int(y * self.plates_size[1]))
                 screen.blit(image, rect)
             # дорога
             elif self.building[x][y].type == Type().road:
                 # матрица с ситуацией на поле
                 piece = [[False, False, False], [False, True, False],
                          [False, False, False]]
                 try:
                     if self.building[x][y - 1].type == Type().road:
                         piece[0][1] = True
                 except:
                     pass
                 try:
                     if self.building[x - 1][y].type == Type().road:
                         piece[1][0] = True
                 except:
                     pass
                 try:
                     if self.building[x + 1][y].type == Type().road:
                         piece[1][2] = True
                 except:
                     pass
                 try:
                     if self.building[x][y + 1].type == Type().road:
                         piece[2][1] = True
                 except:
                     pass
                 # принимаем тип дороги
                 rect = (int(x * self.plates_size[0]) + self.sideShift,
                         int(y * self.plates_size[1]))
                 screen.blit(
                     self.imageRoad[Building().indexOfRoadPiece(piece)],
                     rect)
コード例 #7
0
ファイル: gorillas.py プロジェクト: MatthewGoff/CSC245
 def init(cls):
     pygame.init()
     cls.buildings.add(Building(-100, 0, 100, cls.height, 1, 1))
     cls.buildings.add(Building(0, 280, 100, 200, 5, 5))
     cls.buildings.add(Building(100, 380, 200, 100, 5, 3))
     cls.buildings.add(Building(300, 330, 150, 150, 10, 10))
     cls.buildings.add(Building(450, 200, 190, 280, 10, 8))
     cls.buildings.add(Building(cls.width, 0, cls.width+100, cls.height, 1, 1))
     cls.player1 = Gorilla(50,50)
     cls.player1.set_vel(10,10)
     cls.player2 = Gorilla(cls.width-50-50,50)
     cls.players.add(cls.player1)
     cls.players.add(cls.player2)
     cls.curr_player = cls.player1
コード例 #8
0
def run_game():
    #游戏初始化,创建一个屏幕对象
    pygame.init()

    g_settings = Settings()

    screen = pygame.display.set_mode((g_settings.screen_width,g_settings.screen_height),pygame.RESIZABLE)
    pygame.display.set_caption("Flappy Bird")

    bird = Bird(g_settings,screen)

    building = Building(g_settings, screen)


    while True:
        # 监测键盘事件和鼠标事件
        gf.check_events(bird)

        #屏幕刷新相关函数
        gf.update_screen(screen,g_settings,bird,building)
コード例 #9
0
    def nextState(self, building_proj, mrow, mcol):
        new_map = deepcopy(self.map)
        new_buildings = deepcopy(self.buildings)
        building_id = len(self.buildings) + 1
        new_buildings.append(Building(building_proj, mrow, mcol, building_id))

        for prow in range(building_proj.rows):
            for pcol in range(building_proj.cols):
                if building_proj.plan[prow][pcol] == '#':
                    if mrow + prow >= len(new_map) or mcol + pcol >= len(
                            new_map[mrow + prow]):
                        return False
                    if new_map[mrow + prow][mcol + pcol] == '.':
                        new_map[mrow + prow][mcol + pcol] = building_id
                    else:
                        return False
        new_score = self.calculateScore(self.city.walk_dist, self.score,
                                        self.map, building_proj, mrow, mcol,
                                        new_buildings)
        new_buildings[-1].score = new_score - self.score
        return State(self.city, new_buildings, new_map, new_score)
コード例 #10
0
 def framePaint(self, event):
     # When called for the first time, instantiates player and 3 buildings
     if self.buildings == None:
         self.buildings = [Building(self.frame) for x in range(3)]
     if self.player == None:
         self.player = Bruin(self.frame)
     # Constructs painter for the central frame
     painter = QtGui.QPainter(self.frame)
     # Sets focus on self whenever focus is True
     if self.focus:
         self.setFocus()
     else:
         self.focus = True
     # If active, calls paintBuilding and paintBruin functions
     if self.active:
         painter.drawImage(
             5, 5,
             self.graphic.scaled(self.frame.geometry().width() - 10,
                                 self.frame.geometry().height() - 10))
         for b in self.buildings:
             b.paintBuilding(painter)
         self.player.paintBruin(painter)
コード例 #11
0
    def load_buildings(self, filename):
        """"  Load building parameters """

        buildings = []
        with open(filename) as json_file:
            data = json.load(json_file)

            for s in data['buildings']:
                k = s.keys()
                for i in k:
                    t = s[i]

                    name = t['name']
                    value = t['value']
                    width = t['width']
                    length = t['length']
                    extra = t['extra']
                    bonus = t['bonus']

                    buildings.append(
                        Building(name, value, width, length, extra, bonus))

        return buildings
コード例 #12
0
ファイル: node.py プロジェクト: czebrose/ML_Projects
 def __init__(self, x, y, node_type):
     Location.__init__(self, x, y)
     self.important = False
     if node_type == 'N' or node_type == 'M':
         self.owner = PlayerColor.NEUTRAL
         self.building = Building(BuildingType.EMPTY, UnitType.EMPTY)
         self.important = node_type == 'M'
     elif node_type == 'B':
         self.owner = PlayerColor.BLUE
         self.building = Building(BuildingType.HOME, UnitType.PIKEMAN)
         self.important = True
     elif node_type == 'R':
         self.owner = PlayerColor.RED
         self.building = Building(BuildingType.HOME, UnitType.PIKEMAN)
         self.important = True
     self.spawn_timer = 0
     self.exit_direction = {PlayerColor.RED: None, PlayerColor.BLUE: None}
     self.unit_in_loc = self.unit_in_loc
コード例 #13
0
ファイル: player.py プロジェクト: alvlam/WidgetFactories
    def update(self, keys):

        self.message = "" # clear any previous message

        for control in self.controls:
            if keys[control]:
                if self.controls[control][0] == "move":
                    #self.rect.move_ip(self.controls[control][1])
                    self.move(self.controls[control][1])
                if self.controls[control][0] == "speed":
                    self.changeSpeed(self.controls[control][1])
                if self.controls[control][0] == "place":
                    newBuilding = Building(FACTORY_FILENAME, (self.rect.centerx, GROUND))
                    # check if there is room to place new factory
                    if pg.sprite.spritecollide(newBuilding, BUILDINGS, False):
                        self.message = "No room!"
                    else:
                        BUILDINGS.add(newBuilding)
                        ALL_SPRITES.add(newBuilding, layer=1) # buildings = layer 1

        vector = self.target - self.pos
        move_length = vector.length()

        if move_length < self.speed:
            self.pos = self.target
            self.autoMoving = False
        elif move_length != 0:
            vector.normalize_ip()
            vector = vector * self.speed
            self.pos += vector
        else:
            self.autoMoving = False

        self.rect.topleft = list(int(v) for v in self.pos)

        self.updateCam()
コード例 #14
0
ファイル: test_building.py プロジェクト: tebriel/codelift
    def setup(self):
        settings = {
            'bot_name': 'unittest',
            'email': '*****@*****.**',
            'registration_id': 'test_123'
        }
        self.building = Building('training_1', settings)
        self.building.floors = 10

        state = {
            'elevators': [
                {
                    'id': 0,
                    'floor': 0
                },
                {
                    'id': 1,
                    'floor': 0
                }
            ],
            'floors': 10
        }

        self.building.build_elevators(state)
コード例 #15
0
ファイル: main.py プロジェクト: amirmohammadraei/Python-Royal
def building_name(code):
    for cc in buildings.buildings:
        if code == cc['code']:
            return cc['name']


def tropp_name(code):
    for tr in troops.troops:
        if code == tr['code']:
            return tr['name']


if __name__ == '__main__':
    print("Hi everyone!")
    buildings = Building()
    troops = Troop()
    while True:
        nickname1 = input("Player1 please enter your nickname: ")
        if len(nickname1) == 0:
            continue
        else:
            break
    while True:
        nickname2 = input("Player2 please enter your nickname: ")
        if len(nickname2) == 0:
            continue
        else:
            break
    player1 = Player(nickname1, 50000)
    player2 = Player(nickname2, 50000)
コード例 #16
0
# 1) В началото създаваме сградите, които искаме да продаваме
# 2) След това създаваме нашите брокери, които ще продават
# 3) И накрая създаваме компанията си, в която работят напите брокери
# -----------
# Всеки ден има различни брокери, които са на смяна. След като сме казали, кои искаме
# да са на смяна, добавяме и кои сгради искаме всеки един да продаде. 
# При продаването на сградата има значение тя колко струва. В зависомост от това се 
# трупат точки и нашите брокери получват бонус в края на смяната си. 
# 

from broker import Broker
from building import Building
from company import Company

# [Сгради] - Създаваме ОБЕКТИ за сградите (buildin_1, buildin_2....):
building_1 = Building("Arholl Arena", 7, 500601.71)
building_2 = Building("DSK Bank", 8, 3000000)
building_3 = Building("Maria's diner", 1, 5732.97)
building_4 = Building("Matt Hann",4, 4242)
building_5 = Building("Balkan Hotel", 6, 1500000.00)
building_6 = Building("Disko BG", 2, 430034)

# [Брокери] - създаваме ОБЕКТИ за брокерите (broker_1, broker_2...):
broker_1 = Broker("Natali", "45")
broker_2 = Broker("George", "27")
broker_3 = Broker("Jasmin", "30")
broker_4 = Broker("Stefan", "43")

#Създаваме ОБЕКТ company
company = Company("MATTAHAN")
コード例 #17
0
ファイル: main.py プロジェクト: TrinityChristiana/py-classes
# **************************** Challenge: Urban Planner II ****************************
"""
Author: Trinity Terry
pyrun: python main.py
"""

from building import Building
from city import City
from random_names import random_name

# Create a new city instance and add your building instances to it. Once all buildings are in the city, iterate the city's building collection and output the information about each building in the city.
megalopolis = City("Megalopolis", "Trinity", "2020")

buildings = [
    Building("333 Commerce Street", 33),
    Building("Strada General Traian Moșoiu 24", 5),
    Building("5 Avenue Anatole France", 276),
    Building("1600 Pennsylvania Ave NW", 6),
    Building("48009 Bilbo", 3)
]

for building in buildings:
    person = random_name()
    building.purchase(person)
    building.construct()
    megalopolis.add_building(building)

megalopolis.print_building_details()
コード例 #18
0
class Village:
    def __init__(self):
        self.hq = Building({
            'level': 1,
            'name': 'hq',
            'maxLevel': 30,  # 30,
            'cost': [90, 80, 70, 5],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 7 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 10,
            'pointFactor': pointFactor,
        })

        self.woodMine = Building({
            'level': 1,
            'name': 'wm',
            'maxLevel': 30,  # 30,
            'cost': [50, 60, 40, 5],
            'costFactor': [1.25, 1.275, 1.245, 1.155],
            'buildTime': 7 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 6,
            'pointFactor': pointFactor,
            'production': 30,
            'productionFactor': productionFactor
        })

        self.clayMine = Building({
            'level': 1,
            'name': 'cm',
            'maxLevel': 30,  # 30,
            'cost': [65, 50, 40, 10],
            'costFactor': [1.27, 1.265, 1.24, 1.14],
            'buildTime': 7 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 6,
            'pointFactor': pointFactor,
            'production': 30,
            'productionFactor': productionFactor
        })

        self.ironMine = Building({
            'level': 1,
            'name': 'im',
            'maxLevel': 30,  # 30,
            'cost': [75, 65, 70, 10],
            'costFactor': [1.252, 1.275, 1.24, 1.17],
            'buildTime': 9 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 6,
            'pointFactor': pointFactor,
            'production': 30,
            'productionFactor': productionFactor
        })

        self.farm = Building({
            'level': 1,
            'name': 'fm',
            'maxLevel': 30,  # 30,
            'cost': [45, 40, 30, 0],
            'costFactor': [1.3, 1.32, 1.29, 1],
            'buildTime': 10 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 5,
            'pointFactor': pointFactor,
            'population': 240,
            'populationFactor': populationFactor
        })

        self.warehouse = Building({
            'level': 1,
            'name': 'wh',
            'maxLevel': 30,  # 30,
            'cost': [60, 50, 40, 0],
            'costFactor': [1.265, 1.27, 1.245, 1.15],
            'buildTime': 8 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 6,
            'pointFactor': pointFactor,
            'capacity': 1000,
            'capacityFactor': capacityFactor
        })

        self.barracks = Building({
            'level': 0,
            'name': 'br',
            'maxLevel': 25,  # 25,
            'cost': [200, 170, 90, 7],
            'costFactor': [1.26, 1.28, 1.26, 1.17],
            'buildTime': 15 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 16,
            'pointFactor': pointFactor
        })

        self.stable = Building({
            'level': 0,
            'name': 'sb',
            'maxLevel': 20,  # 20,
            'cost': [270, 240, 260, 8],
            'costFactor': [1.26, 1.28, 1.26, 1.17],
            'buildTime': 50 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 20,
            'pointFactor': pointFactor
        })

        self.garage = Building({
            'level': 0,
            'name': 'gr',
            'maxLevel': 15,
            'cost': [300, 240, 260, 8],
            'costFactor': [1.26, 1.28, 1.26, 1.17],
            'buildTime': 50 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 24,
            'pointFactor': pointFactor
        })

        self.snob = Building({
            'level': 0,
            'name': 'SN',
            'maxLevel': 1,
            'cost': [15000, 25000, 10000, 80],
            'costFactor': [2, 2, 2, 1.17],
            'buildTime': 4890 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 512,
            'pointFactor': pointFactor
        })

        self.smith = Building({
            'level': 0,
            'name': 'sm',
            'maxLevel': 20,
            'cost': [220, 180, 240, 20],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 50 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 19,
            'pointFactor': pointFactor
        })

        self.place = Building({
            'level': 1,
            'name': 'pl',
            'maxLevel': 1,
            'cost': [10, 40, 30, 0],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 90 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 0,
            'pointFactor': pointFactor
        })

        self.statue = Building({
            'level': 0,
            'name': 'st',
            'maxLevel': 1,
            'cost': [220, 220, 220, 10],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 12 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 24,
            'pointFactor': pointFactor
        })

        self.market = Building({
            'level': 0,
            'name': 'mk',
            'maxLevel': 25,
            'cost': [100, 100, 100, 20],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 22 * 60 + 30,
            'buildTimeFactor': buildTimeFactor,
            'points': 10,
            'pointFactor': pointFactor
        })

        self.hide = Building({
            'level': 0,
            'name': 'hd',
            'maxLevel': 10,
            'cost': [50, 60, 50, 2],
            'costFactor': [1.25, 1.25, 1.25, 1.17],
            'buildTime': 15 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 5,
            'pointFactor': pointFactor
        })

        self.wall = Building({
            'level': 0,
            'name': 'wl',
            'maxLevel': 20,
            'cost': [50, 100, 20, 5],
            'costFactor': [1.26, 1.275, 1.26, 1.17],
            'buildTime': 30 * 60,
            'buildTimeFactor': buildTimeFactor,
            'points': 8,
            'pointFactor': pointFactor
        })

        self.buildings = []
        self.buildings += [self.hq]
        self.buildings += [self.woodMine]
        self.buildings += [self.clayMine]
        self.buildings += [self.ironMine]
        self.buildings += [self.farm]
        self.buildings += [self.warehouse]
        self.buildings += [self.barracks]
        self.buildings += [self.stable]
        self.buildings += [self.garage]
        self.buildings += [self.snob]
        self.buildings += [self.smith]
        self.buildings += [self.place]
        self.buildings += [self.statue]
        self.buildings += [self.market]
        self.buildings += [self.hide]
        self.buildings += [self.wall]

    def get_buildings(self):
        return self.buildings

    def get_wood_yield(self):
        return self.woodMine.get_production()

    def get_clay_yield(self):
        return self.clayMine.get_production()

    def get_iron_yield(self):
        return self.ironMine.get_production()

    def get_yield(self, i):
        if i == 0:
            return self.get_wood_yield()
        elif i == 1:
            return self.get_clay_yield()
        elif i == 2:
            return self.get_iron_yield()

    def get_population(self):
        return sum(map(lambda b: b.get_population(), self.buildings))

    def get_pop_limit(self):
        return self.farm.get_population()

    def get_capacity(self):
        return self.warehouse.get_capacity()
コード例 #19
0
def readDOE(serialize_output=True):
    """
    Read csv files of DOE buildings
    Sheet 1 = BuildingSummary
    Sheet 2 = ZoneSummary
    Sheet 3 = LocationSummary
    Sheet 4 = Schedules
    Note BLD8 & 10 = school


    Then make matrix of ref data as nested nested lists [16, 3, 16]:
    matrix refDOE = Building objs
    matrix Schedule = SchDef objs
    matrix refBEM (16,3,16) = BEMDef
    where:
        [16,3,16] is Type = 1-16, Era = 1-3, climate zone = 1-16
        i.e.
        Type: FullServiceRestaurant, Era: Pre80, Zone: 6A Minneapolis
    Nested tree:
    [TYPE_1:
        ERA_1:
            CLIMATE_ZONE_1
            ...
            CLIMATE_ZONE_16
        ERA_2:
            CLIMATE_ZONE_1
            ...
            CLIMATE_ZONE_16
        ...
        ERA_3:
            CLIMATE_ZONE_1
            ...
            CLIMATE_ZONE_16]

    """

    #Nested, nested lists of Building, SchDef, BEMDef objects
    refDOE = map(lambda j_: map(lambda k_: [None] * 16, [None] * 3),
                 [None] * 16)  #refDOE(16,3,16) = Building;
    Schedule = map(lambda j_: map(lambda k_: [None] * 16, [None] * 3),
                   [None] * 16)  #Schedule (16,3,16) = SchDef;
    refBEM = map(lambda j_: map(lambda k_: [None] * 16, [None] * 3),
                 [None] * 16)  #refBEM (16,3,16) = BEMDef;

    #Purpose: Loop through every DOE reference csv and extract building data
    #Nested loop = 16 types, 3 era, 16 zones = time complexity O(n*m*k) = 768

    for i in xrange(16):

        #i = 16 types of buildings
        #print "\tType: {} @i={}".format(BLDTYPE[i], i)

        # Read building summary (Sheet 1)
        file_doe_name_bld = os.path.join(
            "{}".format(DIR_DOE_PATH), "BLD{}".format(i + 1),
            "BLD{}_BuildingSummary.csv".format(i + 1))
        list_doe1 = read_csv(file_doe_name_bld)
        #listof(listof 3 era values)
        nFloor = str2fl(
            list_doe1[3][3:6]
        )  # Number of Floors, this will be list of floats and str if "basement"
        glazing = str2fl(list_doe1[4][3:6])  # [?] Total
        hCeiling = str2fl(list_doe1[5][3:6])  # [m] Ceiling height
        ver2hor = str2fl(list_doe1[7][3:6])  # Wall to Skin Ratio
        AreaRoof = str2fl(
            list_doe1[8][3:6])  # [m2] Gross Dimensions - Total area

        # Read zone summary (Sheet 2)
        file_doe_name_zone = os.path.join(
            "{}".format(DIR_DOE_PATH), "BLD{}".format(i + 1),
            "BLD{}_ZoneSummary.csv".format(i + 1))
        list_doe2 = read_csv(file_doe_name_zone)
        #listof(listof 3 eras)
        AreaFloor = str2fl([list_doe2[2][5], list_doe2[3][5],
                            list_doe2[4][5]])  # [m2]
        Volume = str2fl([list_doe2[2][6], list_doe2[3][6],
                         list_doe2[4][6]])  # [m3]
        AreaWall = str2fl([list_doe2[2][8], list_doe2[3][8],
                           list_doe2[4][8]])  # [m2]
        AreaWindow = str2fl(
            [list_doe2[2][9], list_doe2[3][9], list_doe2[4][9]])  # [m2]
        Occupant = str2fl(
            [list_doe2[2][11], list_doe2[3][11],
             list_doe2[4][11]])  # Number of People
        Light = str2fl([list_doe2[2][12], list_doe2[3][12],
                        list_doe2[4][12]])  # [W/m2]
        Elec = str2fl([list_doe2[2][13], list_doe2[3][13],
                       list_doe2[4][13]])  # [W/m2] Electric Plug and Process
        Gas = str2fl([list_doe2[2][14], list_doe2[3][14],
                      list_doe2[4][14]])  # [W/m2] Gas Plug and Process
        SHW = str2fl([list_doe2[2][15], list_doe2[3][15],
                      list_doe2[4][15]])  # [Litres/hr] Peak Service Hot Water
        Vent = str2fl([list_doe2[2][17], list_doe2[3][17],
                       list_doe2[4][17]])  # [L/s/m2] Ventilation
        Infil = str2fl([list_doe2[2][20], list_doe2[3][20], list_doe2[4][20]
                        ])  # Air Changes Per Hour (ACH) Infiltration

        # Read location summary (Sheet 3)
        file_doe_name_location = os.path.join(
            "{}".format(DIR_DOE_PATH), "BLD{}".format(i + 1),
            "BLD{}_LocationSummary.csv".format(i + 1))
        list_doe3 = read_csv(file_doe_name_location)
        #(listof (listof 3 eras (listof 16 climate types)))
        TypeWall = [
            list_doe3[3][4:20], list_doe3[14][4:20], list_doe3[25][4:20]
        ]  # Construction type
        RvalWall = str2fl(
            [list_doe3[4][4:20], list_doe3[15][4:20],
             list_doe3[26][4:20]])  # [m2*K/W] R-value
        TypeRoof = [
            list_doe3[5][4:20], list_doe3[16][4:20], list_doe3[27][4:20]
        ]  # Construction type
        RvalRoof = str2fl(
            [list_doe3[6][4:20], list_doe3[17][4:20],
             list_doe3[28][4:20]])  # [m2*K/W] R-value
        Uwindow = str2fl(
            [list_doe3[7][4:20], list_doe3[18][4:20],
             list_doe3[29][4:20]])  # [W/m2*K] U-factor
        SHGC = str2fl(
            [list_doe3[8][4:20], list_doe3[19][4:20],
             list_doe3[30][4:20]])  # [-] coefficient
        HVAC = str2fl(
            [list_doe3[9][4:20], list_doe3[20][4:20],
             list_doe3[31][4:20]])  # [kW] Air Conditioning
        HEAT = str2fl(
            [list_doe3[10][4:20], list_doe3[21][4:20],
             list_doe3[32][4:20]])  # [kW] Heating
        COP = str2fl(
            [list_doe3[11][4:20], list_doe3[22][4:20],
             list_doe3[33][4:20]])  # [-] Air Conditioning COP
        EffHeat = str2fl(
            [list_doe3[12][4:20], list_doe3[23][4:20],
             list_doe3[34][4:20]])  # [%] Heating Efficiency
        FanFlow = str2fl(
            [list_doe3[13][4:20], list_doe3[24][4:20],
             list_doe3[35][4:20]])  # [m3/s] Fan Max Flow Rate

        # Read Schedules (Sheet 4)
        file_doe_name_schedules = os.path.join(
            "{}".format(DIR_DOE_PATH), "BLD{}".format(i + 1),
            "BLD{}_Schedules.csv".format(i + 1))
        list_doe4 = read_csv(file_doe_name_schedules)

        #listof(listof weekday, sat, sun (list of 24 fractions)))
        SchEquip = str2fl(
            [list_doe4[1][6:30], list_doe4[2][6:30],
             list_doe4[3][6:30]])  # Equipment Schedule 24 hrs
        SchLight = str2fl(
            [list_doe4[4][6:30], list_doe4[5][6:30],
             list_doe4[6][6:30]])  # Light Schedule 24 hrs; Wkday=Sat=Sun=Hol
        SchOcc = str2fl(
            [list_doe4[7][6:30], list_doe4[8][6:30],
             list_doe4[9][6:30]])  # Occupancy Schedule 24 hrs
        SetCool = str2fl(
            [list_doe4[10][6:30], list_doe4[11][6:30],
             list_doe4[12][6:30]])  # Cooling Setpoint Schedule 24 hrs
        SetHeat = str2fl([
            list_doe4[13][6:30], list_doe4[14][6:30], list_doe4[15][6:30]
        ])  # Heating Setpoint Schedule 24 hrs; summer design
        SchGas = str2fl(
            [list_doe4[16][6:30], list_doe4[17][6:30],
             list_doe4[18][6:30]])  # Gas Equipment Schedule 24 hrs; wkday=sat
        SchSWH = str2fl(
            [list_doe4[19][6:30], list_doe4[20][6:30], list_doe4[21][6:30]]
        )  # Solar Water Heating Schedule 24 hrs; wkday=summerdesign, sat=winterdesgin

        for j in xrange(3):

            # j = 3 built eras
            #print"\tEra: {} @j={}".format(BUILTERA[j], j)

            for k in xrange(16):

                # k = 16 climate zones
                #print "\tClimate zone: {} @k={}".format(ZONETYPE[k], k)

                B = Building(
                    hCeiling[j],  # floorHeight by era
                    1,  # intHeatNight
                    1,  # intHeatDay
                    0.1,  # intHeatFRad
                    0.1,  # intHeatFLat
                    Infil[j],  # infil (ACH) by era
                    Vent[j] /
                    1000.,  # vent (m^3/s/m^2) by era, converted from liters
                    glazing[j],  # glazing ratio by era
                    Uwindow[j][k],  # uValue by era, by climate type
                    SHGC[j][k],  # SHGC, by era, by climate type
                    'AIR',  # cooling condensation system type: AIR, WATER
                    COP[j][k],  # cop by era, climate type
                    297,  # coolSetpointDay = 24 C
                    297,  # coolSetpointNight
                    293,  # heatSetpointDay = 20 C
                    293,  # heatSetpointNight
                    (HVAC[j][k] * 1000.0) / AreaFloor[
                        j],  # coolCap converted to W/m2 by era, climate type
                    EffHeat[j][k],  # heatEff by era, climate type
                    293)  # initialTemp at 20 C

                #Not defined in the constructor
                B.heatCap = (HEAT[j][k] * 1000.0) / AreaFloor[
                    j]  # heating Capacity converted to W/m2 by era, climate type
                B.Type = BLDTYPE[i]
                B.Era = BUILTERA[j]
                B.Zone = ZONETYPE[k]
                refDOE[i][j][k] = B

                # Define wall, mass(floor), roof
                # Reference from E+ for conductivity, thickness (reference below)

                # Material: (thermalCond, volHeat = specific heat * density)
                Concrete = Material(1.311, 836.8 * 2240, "Concrete")
                Insulation = Material(0.049, 836.8 * 265.0, "Insulation")
                Gypsum = Material(0.16, 830.0 * 784.9, "Gypsum")
                Wood = Material(0.11, 1210.0 * 544.62, "Wood")
                Stucco = Material(0.6918, 837.0 * 1858.0, "Stucco")

                # Wall (1 in stucco, concrete, insulation, gypsum)
                # Check TypWall by era, by climate
                if TypeWall[j][k] == "MassWall":
                    #Construct wall based on R value of Wall from refDOE and properties defined above
                    # 1" stucco, 8" concrete, tbd insulation, 1/2" gypsum
                    Rbase = 0.271087  # R val based on stucco, concrete, gypsum
                    Rins = RvalWall[j][k] - Rbase  #find insulation value
                    D_ins = Rins * Insulation.thermalCond  # depth of ins from m2*K/W * W/m*K = m
                    if D_ins > 0.01:
                        thickness = [
                            0.0254, 0.0508, 0.0508, 0.0508, 0.0508, D_ins,
                            0.0127
                        ]
                        layers = [
                            Stucco, Concrete, Concrete, Concrete, Concrete,
                            Insulation, Gypsum
                        ]
                    else:
                        #if it's less then 1 cm don't include in layers
                        thickness = [
                            0.0254, 0.0508, 0.0508, 0.0508, 0.0508, 0.0127
                        ]
                        layers = [
                            Stucco, Concrete, Concrete, Concrete, Concrete,
                            Gypsum
                        ]

                    wall = Element(0.08, 0.92, thickness, layers, 0., 293., 0.,
                                   "MassWall")

                    # If mass wall, assume mass floor (4" concrete)
                    # Mass (assume 4" concrete);
                    alb = 0.2
                    emis = 0.9
                    thickness = [0.054, 0.054]
                    concrete = Material(1.31, 2240.0 * 836.8)
                    mass = Element(alb, emis, thickness, [concrete, concrete],
                                   0, 293, 1, "MassFloor")

                elif TypeWall[j][k] == "WoodFrame":
                    # 0.01m wood siding, tbd insulation, 1/2" gypsum
                    Rbase = 0.170284091  # based on wood siding, gypsum
                    Rins = RvalWall[j][k] - Rbase
                    D_ins = Rins * Insulation.thermalCond  #depth of insulatino

                    if D_ins > 0.01:
                        thickness = [0.01, D_ins, 0.0127]
                        layers = [Wood, Insulation, Gypsum]
                    else:
                        thickness = [0.01, 0.0127]
                        layers = [Wood, Gypsum]

                    wall = Element(0.22, 0.92, thickness, layers, 0., 293., 0.,
                                   "WoodFrameWall")

                    # If wood frame wall, assume wooden floor
                    alb = 0.2
                    emis = 0.9
                    thickness = [0.05, 0.05]
                    wood = Material(1.31, 2240.0 * 836.8)
                    mass = Element(alb, emis, thickness, [wood, wood], 0.,
                                   293., 1., "WoodFloor")

                elif TypeWall[j][k] == "SteelFrame":
                    # 1" stucco, 8" concrete, tbd insulation, 1/2" gypsum
                    Rbase = 0.271087  # based on stucco, concrete, gypsum
                    Rins = RvalWall[j][k] - Rbase
                    D_ins = Rins * Insulation.thermalCond
                    if D_ins > 0.01:
                        thickness = [
                            0.0254, 0.0508, 0.0508, 0.0508, 0.0508, D_ins,
                            0.0127
                        ]
                        layers = [
                            Stucco, Concrete, Concrete, Concrete, Concrete,
                            Insulation, Gypsum
                        ]
                    else:  # If insulation is too thin, assume no insulation
                        thickness = [
                            0.0254, 0.0508, 0.0508, 0.0508, 0.0508, 0.0127
                        ]
                        layers = [
                            Stucco, Concrete, Concrete, Concrete, Concrete,
                            Gypsum
                        ]
                    wall = Element(0.15, 0.92, thickness, layers, 0., 293., 0.,
                                   "SteelFrame")

                    # If mass wall, assume mass foor
                    # Mass (assume 4" concrete),
                    alb = 0.2
                    emis = 0.93
                    thickness = [0.05, 0.05]
                    mass = Element(alb, emis, thickness, [Concrete, Concrete],
                                   0., 293., 1., "MassFloor")

                elif TypeWall[j][k] == "MetalWall":
                    # metal siding, insulation, 1/2" gypsum
                    alb = 0.2
                    emis = 0.9
                    D_ins = max(
                        (RvalWall[j][k] * Insulation.thermalCond) / 2, 0.01
                    )  #use derived insul thickness or 0.01 based on max
                    thickness = [D_ins, D_ins, 0.0127]
                    materials = [Insulation, Insulation, Gypsum]
                    wall = Element(alb, emis, thickness, materials, 0, 293, 0,
                                   "MetalWall")

                    # Mass (assume 4" concrete);
                    alb = 0.2
                    emis = 0.9
                    thickness = [0.05, 0.05]
                    concrete = Material(1.31, 2240.0 * 836.8)
                    mass = Element(alb, emis, thickness, [concrete, concrete],
                                   0., 293., 1., "MassFloor")

                # Roof
                if TypeRoof[j][k] == "IEAD":  #Insulation Entirely Above Deck
                    # IEAD-> membrane, insulation, decking
                    alb = 0.2
                    emis = 0.93
                    D_ins = max(RvalRoof[j][k] * Insulation.thermalCond / 2.,
                                0.01)
                    roof = Element(alb, emis, [D_ins, D_ins],
                                   [Insulation, Insulation], 0., 293., 0.,
                                   "IEAD")

                elif TypeRoof[j][k] == "Attic":
                    # IEAD-> membrane, insulation, decking
                    alb = 0.2
                    emis = 0.9
                    D_ins = max(RvalRoof[j][k] * Insulation.thermalCond / 2.,
                                0.01)
                    roof = Element(alb, emis, [D_ins, D_ins],
                                   [Insulation, Insulation], 0., 293., 0.,
                                   "Attic")

                elif TypeRoof[j][k] == "MetalRoof":
                    # IEAD-> membrane, insulation, decking
                    alb = 0.2
                    emis = 0.9
                    D_ins = max(RvalRoof[j][k] * Insulation.thermalCond / 2.,
                                0.01)
                    roof = Element(alb, emis, [D_ins, D_ins],
                                   [Insulation, Insulation], 0., 293., 0.,
                                   "MetalRoof")

                # Define bulding energy model, set fraction of the urban floor space of this typology to zero
                refBEM[i][j][k] = BEMDef(B, mass, wall, roof, 0.0)
                refBEM[i][j][k].building.FanMax = FanFlow[j][
                    k]  # max fan flow rate (m^3/s) per DOE

                Schedule[i][j][k] = SchDef()

                Schedule[i][j][
                    k].Elec = SchEquip  # 3x24 matrix of schedule for fraction electricity (WD,Sat,Sun)
                Schedule[i][j][
                    k].Light = SchLight  # 3x24 matrix of schedule for fraction light (WD,Sat,Sun)
                Schedule[i][j][
                    k].Gas = SchGas  # 3x24 matrix of schedule for fraction gas (WD,Sat,Sun)
                Schedule[i][j][
                    k].Occ = SchOcc  # 3x24 matrix of schedule for fraction occupancy (WD,Sat,Sun)
                Schedule[i][j][
                    k].Cool = SetCool  # 3x24 matrix of schedule for fraction cooling temp (WD,Sat,Sun)
                Schedule[i][j][
                    k].Heat = SetHeat  # 3x24 matrix of schedule for fraction heating temp (WD,Sat,Sun)
                Schedule[i][j][
                    k].SWH = SchSWH  # 3x24 matrix of schedule for fraction SWH (WD,Sat,Sun

                Schedule[i][j][k].Qelec = Elec[
                    j]  # W/m^2 (max) for electrical plug process
                Schedule[i][j][k].Qlight = Light[j]  # W/m^2 (max) for light
                Schedule[i][j][k].Nocc = Occupant[j] / AreaFloor[
                    j]  # Person/m^2
                Schedule[i][j][k].Qgas = Gas[j]  # W/m^2 (max) for gas
                Schedule[i][j][k].Vent = Vent[j] / 1000.0  # m^3/m^2 per person
                Schedule[i][j][k].Vswh = SHW[j] / AreaFloor[
                    j]  # litres per hour per m^2 of floor

    # if not test serialize refDOE,refBEM,Schedule and store in resources
    if serialize_output:

        # create a binary file for serialized obj
        pkl_file_path = os.path.join(DIR_CURR, '..', 'resources',
                                     'readDOE.pkl')
        pickle_readDOE = open(pkl_file_path, 'wb')

        # dump in ../resources
        # Pickle objects, protocol 1 b/c binary file
        cPickle.dump(refDOE, pickle_readDOE, 1)
        cPickle.dump(refBEM, pickle_readDOE, 1)
        cPickle.dump(Schedule, pickle_readDOE, 1)

        pickle_readDOE.close()

    return refDOE, refBEM, Schedule
コード例 #20
0
class TestBuildingClass(unittest.TestCase):

    """Class used to test builing is populated and allocates rooms."""

    def setUp(self):
        self.build = Building("input.txt")
        self.build.allocate_to_office()

    def test_building_is_populated_with_data(self):

        self.assertIsNone(self.build.populate_rooms(), msg="room_directory should be poplated with data from list.")

        self.assertIsNone(self.build.get_fellows(), msg="data from returned parser class should be callable")

    def test_data_allocation_function_returns_None(self):

        self.assertIsNone(self.build.allocate_to_office(), msg="method should return any value")

        self.assertIsNone(self.build.allocate_to_livingspace(), msg="method should not return any value")

    def test_data_is_printed(self):

        self.assertIsNone(self.build.allocated_members_list(), msg="method should print data and not return a value.")

        self.assertIsNone(self.build.unallocated_members_list(), msg="method should print data and not return a value.")

        self.assertIsNone(self.build.maleroom_members("opal"), msg="should print data and not return a value")

        self.assertIsNone(self.build.femaleroom_members("ruby"), msg="should print data and not return a value")

        self.assertIsNone(self.build.officeroom_members("Mint"), msg="should print data and not return a value")
コード例 #21
0
ファイル: codelift.py プロジェクト: tebriel/codelift
#!/usr/bin/env python3

import sys
import json
import coloredlogs
import logging
from building import Building

coloredlogs.install()
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

PLANS = ['training_1', 'training_2', 'training_3', 'ch_rnd_500_1',
         'ch_rnd_500_2', 'ch_rnd_500_3', 'ch_clu_500_1', 'ch_clu_500_2',
         'ch_clu_500_3', 'ch_rea_1000_1', 'ch_rea_1000_2', 'ch_rea_1000_3']

if __name__ == '__main__':
    plan_id = 0
    if sys.argv[1] is not None:
        plan_id = int(sys.argv[1])

    with open('codeliftsettings.json') as settings:
        cl_settings = json.load(settings)

    building = Building(PLANS[plan_id], cl_settings)
    building.connect()
    building.start()
    logger.info("Finished plan: %s", PLANS[plan_id])
コード例 #22
0
def create_institutions():
    '''Creates all institutions in the simulation, setting institution names, infection probabilities, positions, 
    and door positions. Adds all institutions to INSTITUTION_INT_MAP.'''

    campus_outdoors = CampusOutdoors(name= 'campus_outdoors',infec_prob=0.0, posn=[0, 0, 0, 0])


    # With old door posns. (flush w/ rest of building)
    #disc =          Building(name= 'disc',infec_prob=0.0, posn=[528, 574, 256, 393], door_posns=[[574, 296], [574,345], [565, 393]])   # , [528,345]
    #uw1 =           Building(name= 'uw1',infec_prob=0.0, posn=[364, 575, 478, 515], door_posns=[[364,496], [495, 478], [575, 493], [494, 515],[480, 515]])
    #uw2 =           Building(name= 'uw2',infec_prob=0.0, posn=[400, 527, 355, 393], door_posns=[[400, 390], [429, 393], [433, 393]])


    # With new door posns. protruding from building walls.
    disc = Building(name='disc', infec_prob=0.0, posn=[528, 574, 256, 393],
                    door_posns=[[575, 296], [576, 296], [575, 345], [576, 345],[565, 394], [565, 395],[527,345], [526,345], \
                                [555, 255 ], [555, 254 ] ] )  # , [528,345]
    uw1 = Building(name='uw1', infec_prob=0.0, posn=[364, 575, 478, 515],
                   door_posns=[[363, 496], [495, 477], [576, 493], [494, 516], [480, 516], \
                               [362, 496], [495, 476], [577, 493], [494, 517], [480, 517]])
    uw2 = Building(name='uw2', infec_prob=0.0, posn=[400, 527, 355, 393],
                   door_posns=[[399, 390], [429, 394], [433, 394], \
                               [398, 390], [429, 395], [433, 395], [520, 354], [520, 353], [410, 354], [410, 353],])


    lb1 =           Building(name= 'lb1',infec_prob=0.0, posn=[621, 752, 421, 470], door_posns=[[664,470]])
    lb2 =           Building(name= 'lb2',infec_prob=0.0, posn=[725, 780, 486, 570], door_posns=[[725, 486]])
    #uwbb =          Building(name= 'uwbb',infec_prob=0.0, posn=[1590, 1686, 330, 400], door_posns=[[1630, 400]])
    #arc =           Building(name= 'arc',infec_prob=0.0, posn=[665, 711, 569, 633], door_posns=[[711,585]])
    #subway =        Building(name= '',infec_prob=0.0, posn=[604, 620, 432, 468], door_posns=[[611, 470]])
    #bus_stop =      BusStop(name= 'bus_stop',infec_prob=0.0, posn=[1070, 1144, 340, 447], door_posns=[[1144, 340]])
    #bus_stop =      BusStop(name= 'bus_stop',infec_prob=0.0, posn=[ - 15, size_x - 10, float(size_y) * 2/3, float(size_y) * 3/4], door_posns=[[840, 480]])
    bus_stop = BusStop(name='bus_stop', infec_prob=0.0,
                       posn=[840, 880, 460, 500], door_posns=[[840, 480]])

    #husky_village = StudentHousing(name= 'husky_village',infec_prob=0.0, posn=[1290, 1390, 160, 300], door_posns=[[1290, 160], [1390, 160], [1390, 300]])

    # With old door posns. flush with institution boundaries.
    #parking_area_1 =ParkingArea(name= 'parking_area_1',infec_prob=0.0, posn=[467, 674, y_offset + 1, 215], door_posns=[[590, 215]])
    #parking_area_2 =ParkingArea(name= 'parking_area_2',infec_prob=0.0, posn=[x_offset + 1, 300, y_offset + 1, 525], door_posns=[[300,395]])


    # With new door posns. protruding from institution boundaries.
    parking_area_1 = ParkingArea(name='parking_area_1', infec_prob=0.0, posn=[467, 674, y_offset + 1, 215],
                                 door_posns=[[590, 216], [590, 217]])
    parking_area_2 = ParkingArea(name='parking_area_2', infec_prob=0.0, posn=[x_offset + 1, 300, y_offset + 1, 525],
                                 door_posns=[[301, 395], [302, 395]])

    #parking_area_3 =ParkingArea(name= 'parking_area_3',infec_prob=0.0, posn=[996, 1154, 563, 616], door_posns=[[1150, 563]])
    #ccc_1_2 =       Building(name= 'ccc_1_2',infec_prob=0.0, posn=[818, 1020, 484, 525])
    #ccc_3 =         Building(name= 'ccc_3',infec_prob=0.0, posn=[892, 1030, 343, 408])

    global INSTITUTION_INT_MAP
    INSTITUTION_INT_MAP = {0: campus_outdoors, \
                           1: disc, \
                           2: uw1, \
                           3: uw2, \
                           4: lb1, \
                           5: lb2, \
                           #6: uwbb, \
                           #7: arc, \
                           #8: subway, \
                           9: bus_stop, \
                           #10: husky_village, \
                           11: parking_area_1, \
                           12: parking_area_2, \
                           #13: parking_area_3, \
                           #14: ccc_1_2, \
                           #15: ccc_3
                            }


    # Adjust x and y, mins and maxes, and door positions, according to selected size_x and size_y
    for instit_int in INSTITUTION_INT_MAP.keys():
        instit = INSTITUTION_INT_MAP[instit_int]

        for i in range(len(instit.posn)):
            if i in [0, 1]:     # If it's either x_min or x_max
                instit.posn[i] -= x_offset
            else:
                instit.posn[i] -= y_offset
            instit.posn[i] *= (float(size_y)/ orig_img_size_y)
            instit.posn[i] = int(math.floor(INSTITUTION_INT_MAP[instit_int].posn[i]))


        if INSTITUTION_INT_MAP[instit_int].__class__.__name__ in ['Building', 'ParkingArea', 'BusStop']:

            for i in range(len(instit.door_posns)):
                instit.door_posns[i][0] -= x_offset
                instit.door_posns[i][1] -= y_offset
                instit.door_posns[i][0] *= (float(size_y)/ orig_img_size_y)
                instit.door_posns[i][1] *= (float(size_y)/ orig_img_size_y)
                instit.door_posns[i][0] = int(math.floor(instit.door_posns[i][0]))
                instit.door_posns[i][1] = int(math.floor(instit.door_posns[i][1]))


        if instit.name in ['uw1', 'uw2', 'disc']:
            cols = 5
            rows = 2
            if instit.name == 'disc':
                cols = 2
                rows = 5
            x_min = instit.posn[0]
            x_max = instit.posn[1]
            y_min = instit.posn[2]
            y_max = instit.posn[3]
            width = x_max - x_min
            height = y_max - y_min
            width_of_one_classroom = (float(width - 2) / cols) - 2 # 2 rows between each classroom and between classrooms and building boundaries
            width_of_one_classroom = int(width_of_one_classroom)
            height_of_one_classroom = (float(height - 2) / rows) - 2
            height_of_one_classroom = int(height_of_one_classroom)

            for col in range(cols):
                for row in range(rows):
                    instit.classrooms.append(Classroom(posn=[x_min + 2 + col*(2 + width_of_one_classroom),
                                                          x_min + 2 + col*(2 + width_of_one_classroom) + width_of_one_classroom,
                                                          y_min + 2 + row * (2 + height_of_one_classroom),
                                                          y_min + 2 + row * (2 + height_of_one_classroom) + height_of_one_classroom]))


        add_institution_to_grid(instit_int, campus)
コード例 #23
0
from building import Building
from city import City

eight_hundred_eighth = Building("800 8th Street", 12)
eight_hundred_eighth.purchase("Fred Flintstone")
eight_hundred_eighth.construct()
# print(eight_hundred_eighth)

three_hundred = Building("300 Plus Park Blvd", 6)
three_hundred.purchase("Barney Rubble")
three_hundred.construct()
# print(three_hundred)

five_hundred = Building("500 Interstate Blvd", 3)
five_hundred.purchase("Wilma Flintstone")
five_hundred.construct()
# print(five_hundred)

two_hundred = Building("200 28th Street", 20)
two_hundred.purchase("Betty Rubble")
two_hundred.construct()
# print(two_hundred)

megalopolis = City()
megalopolis.add_building(eight_hundred_eighth)
megalopolis.add_building(three_hundred)
megalopolis.add_building(five_hundred)
megalopolis.add_building(two_hundred)

for building in megalopolis.buildings:
    print(building)
コード例 #24
0
from building import Building
from domain import Domain
from bson.objectid import ObjectId
# danzi.tn@20160312 import solo delle PK di riferimento sui building
# create main logger
logger = logging.getLogger('smt_main')
logger.setLevel(logging.INFO)
# create a rotating file handler which logs even debug messages 
fh = logging.handlers.RotatingFileHandler('import_building_pks.log',maxBytes=5000000, backupCount=5)
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
# reading config file
sCFGName = 'smt.cfg'
smtConfig = ConfigParser.RawConfigParser()
smtConfig.read(sCFGName)
# setup DB parameter
host = smtConfig.get('MONGODB','host')
database = smtConfig.get('MONGODB','database')
source_database = smtConfig.get('MONGODB','source_database')
username = smtConfig.get('MONGODB','username')
password = smtConfig.get('MONGODB','password')
# connect to MongoDB
client = MongoClient()
db = client[database]
# DB authentication
db.authenticate(username,password,source=source_database)
# IMPORT BUILDINGS PKS
Building.import_building_pks(db,"../data/Edifici_Analizzati_Attributi.csv")
コード例 #25
0
ファイル: test_building.py プロジェクト: tebriel/codelift
class TestBuilding:
    """Test the Building class and its internal methods"""
    def setup(self):
        settings = {
            'bot_name': 'unittest',
            'email': '*****@*****.**',
            'registration_id': 'test_123'
        }
        self.building = Building('training_1', settings)
        self.building.floors = 10

        state = {
            'elevators': [
                {
                    'id': 0,
                    'floor': 0
                },
                {
                    'id': 1,
                    'floor': 0
                }
            ],
            'floors': 10
        }

        self.building.build_elevators(state)

    def test_build_elevators(self):
        """Tests that we build all the elevator objects"""
        # This is testing that the setup method worked
        assert_equals(len(self.building.elevators), 2)

    def test_process_elevators(self):
        """Processes the new elevator states"""
        state = {
            'elevators': [
                {
                    'id': 0,
                    'floor': 2
                },
                {
                    'id': 1,
                    'floor': 4
                }
            ]
        }
        self.building.process_elevators(state)
        assert_equals(self.building.elevators[0].location, 2)
        assert_equals(self.building.elevators[1].location, 4)

    def test_process_requests(self):
        """Processes the new elevator requests"""
        state = {
            'requests': [
                {
                    "direction": -1,
                    "floor": 3
                }
            ],
            'floors': 10
        }

        self.building.process_requests(state)
        [e.get_command() for e in self.building.elevators]
        elevator = self.building.elevators[0]
        assert_equals(elevator.next_direction, -1)

        state = {
            'requests': [
                {
                    "direction": -1,
                    "floor": 3
                },
                {
                    "direction": 1,
                    "floor": 5
                }
            ],
            'floors': 10
        }

        self.building.process_requests(state)
        [e.get_command() for e in self.building.elevators]
        elevator1 = self.building.elevators[0]
        elevator2 = self.building.elevators[1]
        assert_equals(elevator1.cur_direction, 1)
        assert_equals(elevator1.next_direction, -1)
        assert_equals(elevator2.cur_direction, 1)
        assert_equals(elevator2.next_direction, 1)

    def test_add_acked(self):
        """Adds a request to the acked list"""
        state = {
            'requests': [
                {
                    "direction": -1,
                    "floor": 3
                }
            ],
            'floors': 10
        }
        self.building.process_requests(state)
        expected = Request(3, -1)
        assert_equals(expected, self.building.acked[0])

    def test_remove_acked(self):
        """Removes a finished request from the acked list"""
        state = {
            'requests': [
                {
                    "direction": -1,
                    "floor": 3
                }
            ],
            'floors': 10
        }
        self.building.process_requests(state)
        assert_equals(len(self.building.acked), 1)

        state = {
            'elevators': [
                {
                    'id': 0,
                    'floor': 3
                }
            ]
        }
        self.building.process_elevators(state)
        self.building.generate_commands()
        assert_equals(len(self.building.acked), 0)

    def test_find_cheapest_elevator_equal(self):
        request = Request(floor=9, direction=-1)
        result = self.building.find_cheapest_elevator(request, 10)
        assert_equals(result, self.building.elevators[0])

    def test_find_cheapest_elevator_closer(self):
        state = {'elevators': [{'id': 1, 'floor': 5}], 'floors': 10}
        self.building.process_elevators(state)

        request = Request(floor=9, direction=-1)
        result = self.building.find_cheapest_elevator(request, 10)
        assert_equals(result, self.building.elevators[1])

    def test_manage_idle_elevators(self):
        self.building.elevators[0].wait_count = 3
        self.building.elevators[0].playing = True
        self.building.elevators[1].wait_count = 3
        self.building.elevators[1].playing = True
        commands = self.building.generate_commands()
        self.building.manage_idle_elevators(commands)
        for command in commands:
            assert_equals(command.direction, 1)
            assert_equals(command.speed, 1)

        state = {'requests': [{'floor': 5, 'direction': -1}]}
        self.building.process_requests(state)
        commands = self.building.generate_commands()
        for command in commands:
            assert_equals(command.direction, 1)
            assert_equals(command.speed, 1)

    def test_manage_idle_elevators_more(self):
        state = {'elevators': [{'id': 0, 'floor': 6}]}
        self.building.process_elevators(state)
        self.building.elevators[0].wait_count = 3
        self.building.elevators[0].playing = True
        self.building.elevators[1].wait_count = 3
        self.building.elevators[1].playing = True

        state = {'requests': [{'floor': 5, 'direction': -1}]}
        self.building.process_requests(state)
        commands = self.building.generate_commands()
        assert_equals(commands[0].direction, -1)
        assert_equals(commands[0].speed, 1)
        assert_equals(commands[1].direction, 1)
        assert_equals(commands[1].speed, 1)
コード例 #26
0
 def setUp(self):
     self.build = Building("input.txt")
     self.build.allocate_to_office()
コード例 #27
0
 def finder(file_name, test):
     """"Функция составляет базу данных из OSM-кого формата"""
     try:
         if not test:
             coord_path = os.path.join("./test_base",
                                       "Russia_coordinates.db")
             buildings_path = os.path.join("./test_base",
                                           "Russia_buildings.db")
         else:
             coord_path = os.path.join("./test_base", "test_coordinates.db")
             buildings_path = os.path.join("./test_base",
                                           "test_buildings.db")
         con1 = sqlite3.connect(coord_path)
         cur1 = con1.cursor()
         cur1.execute(
             'CREATE TABLE IF NOT EXISTS coordinates_base(Link INTEGER, Lat REAL, Lon REAL)'
         )
         con2 = sqlite3.connect(buildings_path)
         cur2 = con2.cursor()
         cur2.execute(
             'CREATE TABLE IF NOT EXISTS address_base(City TEXT,Address TEXT,House_number TEXT,Links TEXT)'
         )
         with open(file_name, encoding='utf-8') as f:
             buffer = []
             counter = 0
             current_city = ""
             for string in f:
                 string = string.lstrip()[:-1]
                 buffer.append(string)
                 if counter <= 0:
                     if re.match(r'<node id="', string) is not None:
                         try:
                             s = re.findall(r'[0-9]{2}.[0-9]+', string)
                             coordinates = ([
                                 int(s[0]),
                                 float(s[4]),
                                 float(s[5])
                             ])
                             cur1.execute(
                                 "INSERT INTO coordinates_base VALUES(?,?,?)",
                                 coordinates)
                         except IndexError:
                             continue
                     if re.match(r'<tag k="addr:street" v="',
                                 string) is not None:
                         j = 0
                         is_house = False
                         for j in range(len(buffer) - 1, -1, -1):
                             if re.match(r'<way id="',
                                         buffer[j]) is not None:
                                 is_house = True
                                 break
                         if is_house:
                             references = []
                             street = string[24:-3]
                             house_number = None
                             city = current_city
                             for i in range(j, len(buffer)):
                                 if re.match(
                                         r'<tag k="addr:housenumber" v=',
                                         buffer[i]) is not None:
                                     house_number = buffer[i][29:-3]
                                     continue
                                 if re.match(r'<tag k="addr:city" v=',
                                             buffer[i]) is not None:
                                     city = buffer[i][22:-3].capitalize()
                                     current_city = city
                                 if re.match(r'<nd ref="',
                                             buffer[i]) is not None:
                                     references.append(buffer[i][9:-3])
                             if house_number is not None:
                                 build = Building(street, house_number,
                                                  references, city)
                                 references = " ".join(build.references)
                                 cur2.execute(
                                     "INSERT INTO address_base VALUES(?,?,?,?)",
                                     [
                                         build.city, build.address,
                                         build.house_number, references
                                     ])
                             elif house_number is None:
                                 counter = 5
                 elif counter > 0:
                     counter -= 1
                     if re.match(r'<tag k="addr:housenumber" v=',
                                 string) is not None:
                         counter = 0
                         j = 0
                         is_house = False
                         for j in range(len(buffer) - 1, -1, -1):
                             if re.match(r'<way id="',
                                         buffer[j]) is not None:
                                 is_house = True
                                 break
                         if is_house:
                             references = []
                             house_number = string[29:-3]
                             city = current_city
                             street = None
                             for i in range(j, len(buffer)):
                                 if re.match(r'<tag k="addr:street"',
                                             buffer[i]) is not None:
                                     street = buffer[i][24:-3]
                                     continue
                                 if re.match(r'<nd ref="',
                                             buffer[i]) is not None:
                                     references.append(buffer[i][9:-3])
                                 if re.match(r'<tag k="addr:city" v=',
                                             buffer[i]) is not None:
                                     city = buffer[i][22:-3].capitalize()
                                     current_city = city
                             if street is not None:
                                 build = Building(street, house_number,
                                                  references, city)
                                 references = " ".join(build.references)
                                 cur2.execute(
                                     "INSERT INTO address_base VALUES(?,?,?,?)",
                                     [
                                         build.city, build.address,
                                         build.house_number, references
                                     ])
                 if len(buffer) == 40:
                     buffer.pop(0)
         con1.commit()
         con2.commit()
     except FileNotFoundError:
         raise FileNotFoundError("База OSM не загружена!")
コード例 #28
0
ファイル: elevator.py プロジェクト: claudiahoogwerf/lift
from building import Building, Customer, Elevator

while True:
    num_floors = input("Please give the number of floors:")
    num_customers = input("Please give the number of customers:")
    try:
        floors = int(num_floors)
        customers = int(num_customers)
    except ValueError:
        print("You didn't enter a valid number")
        continue

    if floors <= 0:
        print("Please enter a number of floors that is above 0")
        continue
    if customers <= 0:
        print("Please enter a number of customers that is above 0")
        continue

    b = Building(floors, customers)
    print('Made a building with customers', b)
    b.elevator.go_up()
    b.elevator.go_down()
    break
コード例 #29
0
 def __init__(self, name: str, address: str):
     """Constructor"""
     Building.__init__(self, name, address)
     self.__menu = []
     self.__orders = []
     self.__waiters = []
コード例 #30
0
ファイル: main.py プロジェクト: NealJones/rocketu-201401
from person import Person

print "Welcome to the building manager application!"
response = raw_input("Would you like to add a (b)uilding, (a)partment, (r)enter, or (q)uit? ")

while response != "q":
    if response == "b":
        name = raw_input("What is the name of this building? ")
        address = raw_input("What is the address? ")
        num_floors = raw_input("How many floors are in the building? ")
        doorman = raw_input("Does the building have a doorman? (t/f)")
        if doorman == "t":
            doorman = True
        else:
            doorman = False
        building = Building(name=name, address=address, num_floors=num_floors, doorman=doorman)
        print "Thanks for adding building {0}".format(building)

    if response == "a":
        unit = raw_input("What is the unit number? ")
        rent = raw_input("What is the monthly rent? ")
        sqft = raw_input("How many sq feet are in the apartment? ")
        num_bedrooms = raw_input("How many bedrooms does it have? ")
        num_bathrooms = raw_input("How many bathrooms does it have? ")
        apartment = Apartment(unit=unit, rent=rent, sqft=sqft, num_bedrooms=num_bedrooms, num_bathrooms=num_bathrooms)
        try:
            building.apartments[unit] = apartment
            print "Thanks for adding unit {0} to building {1}".format(apartment.unit, building.name)
        except NameError:
            print "You have to add a building first"
コード例 #31
0
ファイル: main.py プロジェクト: biki-cloud/DragonQuest_pygame
if __name__ == '__main__':

    pygame.init()
    logging = get_log.get_logger()

    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('Dragon quest monster')

    icon = pygame.image.load(SLIME_IMG_PATH)
    pygame.display.set_icon(icon)

    field = BackGround(FIELD_IMG_PATH, screen.get_height(), screen.get_width())
    combat = BackGround(COMBAT_IMG_PATH, screen.get_height(), screen.get_width())

    carve = Building(CARVE_IMG_PATH, screen.get_height(), screen.get_width())

    braver = Braver('mike', BRAVER_IMG_PATH, screen.get_height(), screen.get_width())

    slime = Slime('kororo', SLIME_IMG_PATH, screen.get_height(), screen.get_width())

    is_running: bool = True
    while is_running:
        screen.fill((0, 0, 0))
        back_ground = field.pg_img
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    logging.debug('key up')
コード例 #32
0
# -*- coding: utf-8 -*-
from building import Building

if __name__ == '__main__':
    chartreuse = Building('m', "8C - Chartreuse")
コード例 #33
0
from building import Building
from city import City

westin = Building("Westin", "807 Clark Place", 26)
jw = Building("JW", "201 8th Ave S", 28)
hilton = Building("Hilton", "121 4th Ave S", 18)
sheraton = Building("Sheraton", "623 Union St", 33)
union_station = Building("Union Station", "1001 Broadway", 9)

westin.purchase("Mama Bear")
jw.purchase("Papa Bear")
hilton.purchase("Sister Bear")
sheraton.purchase("Brother Bear")
union_station.purchase("Honey Bear")

westin.construct()
jw.construct()
hilton.construct()
sheraton.construct()
union_station.construct()

megalopolis = City("Megalopolis", "Kitty Baby", 2012)

megalopolis.add_building(westin)
megalopolis.add_building(jw)
megalopolis.add_building(hilton)
megalopolis.add_building(sheraton)
megalopolis.add_building(union_station)

print(f'{megalopolis.mayor} is the mayor of the wonderful city of {megalopolis.name}, which was founded in {megalopolis.year}. The following lavish building are located in {megalopolis.name}:')
print()
コード例 #34
0
def create_building(world, scenario_state, sound_system):
    up_door = world.entity()
    up_door.add_components(
        Positionable(0, 0, 50, 100),
        Renderable(
            lambda brush: brush.draw_image("door2_t.png"),
            3
        ),
        TilePositionable("wall", (8, 1), 1),
        Activable(False)
    )

    left_door = world.entity()
    left_door.add_components(
        Positionable(0, 0, 50, 100),
        Renderable(
            lambda brush: brush.draw_image("door2_l.png"),
            3
        ),
        TilePositionable("wall", (0, 6), 3),
        Activable(False)
    )

    down_door = world.entity()
    down_door.add_components(
        Positionable(0, 0, 50, 100),
        Renderable(
            lambda brush: brush.draw_image("door2_b.png"),
            3
        ),
        TilePositionable("wall", (8, 10), 3),
        Activable(False)
    )

    right_door = world.entity()
    right_door.add_components(
        Positionable(0, 0, 100, 50),
        Renderable(
            lambda brush: brush.draw_image("door2_r.png"),
            3
        ),
        TilePositionable("wall", (12, 6), 3),
        Activable(False)
    )

    up_window = world.entity()
    up_window.add_components(
        Positionable(0, 0, 100, 100),
        Renderable(
            lambda brush: brush.draw_image("window_t.png"),
            1
        ),
        TilePositionable("wall", (7, 1), 1),
        Activable(False)
    )

    left_window = world.entity()
    left_window.add_components(
        Positionable(0, 0, 100, 100),
        Renderable(
            lambda brush: brush.draw_image("window_l.png"),
            1
        ),
        TilePositionable("wall", (0, 3), 1),
        Activable(False)
    )

    down_window_renderable = Renderable(
        lambda brush: brush.draw_image("window_b.png"),
        1
    )

    down_window_toggled = [False]

    def toggle_down_window():
        down_window_renderable.render_image(
            "window_b.png" if down_window_toggled[0] else "window_semiopen_b.png",
            (0, 0) if down_window_toggled[0] else (-24, 0)
        )
        down_window_toggled[0] = not down_window_toggled[0]
        sound_system.play("window")

    down_window = world.entity()
    down_window.add_components(
        Positionable(0, 0, 100, 100),
        down_window_renderable,
        TilePositionable("wall", (4, 10), 1),
        Clickable(
            toggle_down_window,
            Button.LEFT
        ),
        Activable(False)
    )
    add_cursor_change_hoverable(down_window)

    def is_activated(entity):
        return entity.get_component(Activable).activated

    scenario_state["has_window"] = lambda: is_activated(up_window)
    scenario_state["has_down_door"] = lambda: is_activated(down_door)
    scenario_state["has_up_door"] = lambda: is_activated(up_door)
    scenario_state["has_right_door"] = lambda: is_activated(right_door)

    scenario_state["window"] = up_window

    building = Building(
        [
            Room((0, 0), [left_door, right_door, down_door, left_window]),
            Room((0, 30), [up_door, left_window]),
            Room((30, 0), [left_door, down_door, up_window]),
            Room((30, 30), [up_door, down_window])
        ],
        (30, 30)
    )

    scenario_state["minimap"] = create_minimap(world, (700, 50), building)

    for i in range(2, 5):
        bookshelf = world.entity()
        bookshelf.add_components(
            Positionable(0, 0, 50, 100),
            Renderable(
                lambda brush: brush.draw_image("bookshelf.png"),
                1
            ),
            TilePositionable("ground", (i, 1), 1)
        )

        if i == 2:
            def bookshelf_move(animable, scenario_state, direction, duration):
                def move():
                    animable.add_animation(
                        TileMoveAnimation(direction, duration)
                    )
                    scenario_state["bookshelf_moved"] =\
                        not scenario_state["bookshelf_moved"]
                    sound_system.play("furniture")

                return move

            animable = Animable()
            scenario_state["bookshelf_moved"] = False
            scenario_state["bookshelf_move_left"] =\
                bookshelf_move(animable, scenario_state, (-2, 0), 1)
            scenario_state["bookshelf_move_right"] =\
                bookshelf_move(animable, scenario_state, (2, 0), 1)
            scenario_state["bookshelf_can_move"] = True

            def toggle_bookshelf(bookshelf):
                def toggle():
                    if scenario_state["bookshelf_can_move"]:
                        if scenario_state["bookshelf_moved"]:
                            scenario_state["bookshelf_move_right"]()
                        else:
                            scenario_state["bookshelf_move_left"]()

                return toggle

            bookshelf.add_components(
                animable,
                Clickable(
                    toggle_bookshelf(bookshelf),
                    Button.LEFT
                ),
                Frightening()
            )

            add_cursor_change_hoverable(bookshelf)

    fireplace_anim = Animable()
    fireplace_anim.add_animation(
        FlickerAnimation(6, 0.3)
    )

    fireplace = world.entity()
    fireplace.add_components(
        Positionable(0, 0, 100, 100),
        Renderable(
            lambda brush: brush.draw_image("fireplace.png"),
            1
        ),
        TilePositionable("ground", (8, 1), 1),
        Lightable(
            Positionable(-130, 60, 360, 120),
            Positionable(-230, 30, 560, 200),
            (205, 155, 29, 64)
        ),
        fireplace_anim
    )

    scenario_state["fireplace"] = fireplace
コード例 #35
0
ファイル: main.py プロジェクト: dkrusch/python
from building import Building, big_building
from city import City

# Name of the city.
# The mayor of the city.
# Year the city was established.
# A collection of all of the buildings in the city.
# A method to add a building to the city.

megalopolis = City()

# Awesome code here

for building in megalopolis.buildings:
    print(building)

megalopolis.name = "Big Town"
megalopolis.city = ["Wuts up"]
megalopolis.mayor = "Bob Jones"
megalopolis.year = "1815"

small_building = Building("700 7th Street", 13)
small_building.construct()
small_building.purchase("Cob")

megalopolis.add_building(small_building)
megalopolis.add_building(big_building)
megalopolis.destroy_city()
for building in megalopolis.buildings:
    print(building.address)
コード例 #36
0
'''Script use to view result of allocation.'''
from building import Building
from fileparser import Parser

amity = Building('input.txt');
amity.populate_rooms()
amity.get_fellows()

amity.allocate_to_office()
amity.allocate_to_livingspace()

amity.allocated_members_list()
amity.unallocated_members_list()

amity.maleroom_members('opal')
amity.femaleroom_members('ruby')
amity.officeroom_members('Mint')
コード例 #37
0
from building import Building
from city import City

three_o_one = Building("301 Plus Park", 4)
five_hundred = Building("500 Interstate Blvd S", 5)
executive_south = Building("1 Executive South", 10)
curts_house = Building("100 Curt's House", 2)
large_skyscraper = Building("3030 Oprah Rd", 100)

three_o_one.purchase("Dr. Phil")
five_hundred.purchase("Joe Shep")
executive_south.purchase("Drew Pazola")
curts_house.purchase("Curt Cato")
large_skyscraper.purchase("Oprah")

three_o_one.construct()
five_hundred.construct()
executive_south.construct()
curts_house.construct()
large_skyscraper.construct()

megalopolis = City()

megalopolis.add_building(three_o_one)
megalopolis.add_building(five_hundred)
megalopolis.add_building(executive_south)
megalopolis.add_building(curts_house)
megalopolis.add_building(large_skyscraper)

for building in megalopolis.buildings:
    print(building)
コード例 #38
0
ファイル: bbl_query.py プロジェクト: hvtuananh/nyc_acris
    def query_bbl(self, bbl):
        borough = bbl.borough
        block = bbl.block
        lot = bbl.lot
        bbl_repr = bbl.bbl_repr
        print "BBL:", bbl
        
        #This is the output
        building = Building(bbl)
        
        print "=== STEP 1: ==="
        lot_records = list(self.db.lot_records.find({'Borough':borough,'Block':block,'Lot':lot}))
        print "Found", len(lot_records), "records in lot_records..."
        unique_keys = list()
        for lot_record in lot_records:
            unique_keys.append(lot_record['Unique_Key'])

        master_records = list(self.db.master_records.find({'Unique_Key':{'$in':unique_keys}}))
        print "Found", len(master_records), "records in master_records..."
        latest_unique_key = None
        latest_doc_date = datetime.strptime('1970-01-01', '%Y-%m-%d')
        for master_record in master_records:
            if master_record['Document_Date'] == "":
                continue
            if master_record['Doc_type'][0:4] == 'DEED':
                if datetime.strptime(master_record['Document_Date'], '%Y-%m-%d') > latest_doc_date:
                    latest_unique_key = master_record['Unique_Key']
                    latest_doc_date = datetime.strptime(master_record['Document_Date'], '%Y-%m-%d')

        if latest_unique_key is None:
            print "Nothing found!"
            return None
        elif str(latest_unique_key)[0:3] == "BK_" or str(latest_unique_key)[0:3] == "FT_":
            print "Latest UK is", latest_unique_key
            print "We're not interested in this type of property!"
            return None
        else:
            print "Latest UK is", latest_unique_key

        #FINISH STEP 1

        print "=== STEP 2: ==="
        party_records = list(self.db.party_records.find({'Unique_Key':latest_unique_key}))
        print "Found", len(party_records), "records in party_records..."
        primary_party = None
        for party_record in party_records:
            if party_record['Party_type'] == 2:
                primary_party = Owner({
                    'name': self.normalize_str(party_record['Name']),
                    'addr1': self.normalize_str(party_record['Addr1']),
                    'addr2': self.normalize_str(party_record['Addr2']),
                    'city': party_record['City'],
                    'state': party_record['State'],
                    'zip': party_record['Zip']
                })

        if primary_party is None:
            print "No name found!"
            return None
        else:
            print "Primary party is ", primary_party['name']
        print primary_party
        
        building.primary = primary_party
    
        #FINISH STEP 2

        print "=== STEP 3: ==="
        secondary_unique_keys = list()
        for master_record in master_records:
            if master_record['Document_Date'] == "":
                continue
            if datetime.strptime(master_record['Document_Date'], '%Y-%m-%d') < latest_doc_date:
                continue
            #if master_record['doc_type'][0:4] == 'MTGE' or master_record['doc_type'][0:4] == 'AGMT':
            if master_record['Doc_type'][0:4] == 'MTGE': #Not consider AGMT right now
                secondary_unique_keys.append(master_record['Unique_Key'])
        
        print "Found", len(secondary_unique_keys), "secondary UKs: ", secondary_unique_keys

        #FINISH STEP 3

        print "=== STEP 4: ==="
        party_records = list(self.db.party_records.find({'Unique_Key':{'$in': secondary_unique_keys}}))
        print "Found", len(party_records), "records in party_records..."
        secondary_parties = set()
        for party_record in party_records:
            if party_record['Party_type'] == 1:
                secondary_party = Owner({
                    'name': self.normalize_str(party_record['Name']),
                    'addr1': self.normalize_str(party_record['Addr1']),
                    'addr2': self.normalize_str(party_record['Addr2']),
                    'city': party_record['City'],
                    'state': party_record['State'],
                    'zip': party_record['Zip']
                })
                secondary_parties.add(secondary_party)
        
        print "Found", len(secondary_parties), "secondary parties..."
        for secondary_party in secondary_parties:
            print "Name:", secondary_party['name']
    
        print secondary_parties
        
        building.secondary = secondary_parties
    
        #FINISH STEP 4

        print "=== STEP 5: ==="
        lot_records = list(self.db.lot_records.find({'Unique_key':{'$in': secondary_unique_keys}}))
        print "Found", len(lot_records), "records in lot_records..."
        cache_bbls = set([bbl])
        for lot_record in lot_records:
            secondary_bbl = BBL(lot_record['Borough'], lot_record['Block'], lot_record['Lot'])
            cache_bbls.add(secondary_bbl)
            
        secondary_bbls = cache_bbls.difference(set([bbl]))
        print "These are secondary BBLs:"
        for secondary_bbl in secondary_bbls:
            print secondary_bbl
            
        building.linkedbbls = secondary_bbls
        
        #FINISH STEP 5

        print "=== STEP 6: HPD ==="
        hpd_records = list(self.db.hpd.find({'bbl':bbl_repr}))
        print "Found", len(hpd_records), "records in hpd..."
        #Get the first one
        if len(hpd_records) == 0:
            print "No HPD records!"
        else:
            hpd_record = hpd_records[0]
            hpd_reg_id = hpd_record['RegistrationID']
            #FINISH STEP 6

            print "=== STEP 7: HPD Contacts ==="
            hpd_contact_records = list(self.db.hpd_contact.find({'RegistrationID': hpd_reg_id}))
            print "Found", len(hpd_contact_records), "records in hpd_contacts..."
            hpd_parties = set()
            for hpd_contact_record in hpd_contact_records:
                hpd_party = Owner({
                    'name': str(hpd_contact_record['LastName']) + ', ' + str(hpd_contact_record['FirstName']),
                    'addr1': str(hpd_contact_record['BusinessHouseNumber']) + ' ' + str(hpd_contact_record['BusinessStreetName']),
                    'addr2': hpd_contact_record['BusinessApartment'],
                    'city': hpd_contact_record['BusinessCity'],
                    'state': hpd_contact_record['BusinessState'],
                    'zip': hpd_contact_record['BusinessZip'],
                    'description': hpd_contact_record['ContactDescription'],
                    'corporation_name': hpd_contact_record['CorporationName']
                })
                hpd_parties.add(hpd_party)
    
            print hpd_parties
            
            building.hpd = hpd_parties

        #FINISH STEP 7

        print "=== STEP 8: DOF Tax Bills ==="
        tax_records = list(self.db.dof_taxes.find({'id-boro':borough, 'id-block':block, 'id-lot':lot}))
        print "Found", len(tax_records), "records in DOF tax bills..."
        #Extract information
        tax_parties = set()
        for tax_record in tax_records:
            tax_party = Owner({
                'name': str(tax_record['nm-recipient-1']) + ' ' + str(tax_record['nm-recipient-2']) + ' ' + str(tax_record['ad-name-attention']),
                'addr1': str(tax_record['ad-street-no']) + ' ' + str(tax_record['ad-street-1']),
                'addr2': tax_record['ad-street-2'],
                'city': tax_record['ad-city'],
                'state': tax_record['cd-addr-state'],
                'zip': tax_record['cd-addr-zip']
            })
            tax_parties.add(tax_party)

        print tax_parties
        
        building.tax = tax_parties

        #FINISH STEP 8

        print "STEP 9: DOS"
        #Need to do it fuzzily by matching name?
        
        return building
コード例 #39
0
    def get_t_zco_from_registers(self):
        return self.holding_register_block.getValues(t_zco_address, 1)


if __name__ == '__main__':
    # start new server
    server = Server('', PORT)
    # add a callback function which will be called with new timestamp each time new time is received
    server.set_time_flag_callback(step)
    # run the server
    server.run()
    print('Server is running')

    water_flow_controller = WaterFlowController()
    logger = Logger()
    building = Building()
    close = False
    while not close:
        try:
            time.sleep(10)
            input_str = input()
            if input_str == 'close':
                close = True
        except KeyboardInterrupt:
            close = True

    print('Server is closing')
    # remember to stop server while closing your application
    server.stop()

    print('finished!')
コード例 #40
0
def export_buildings_data(authenticate, csv_path, shp_path):
    '''
    funzione che fa il vero lavoro
    '''
    logger = init_logger('smt_main', 'export_building_data.log')
    smt_config = get_config('smt.cfg')
    # connect to MongoDB
    client = MongoClient()
    mongodb = client[smt_config.get('MONGODB', 'database')]
    # DB authentication if required
    if authenticate:
        logged_in = mongodb.authenticate(smt_config.get('MONGODB', 'username'),
                                         smt_config.get('MONGODB', 'password'),
                                         source=smt_config.get('MONGODB', 'source_database'))
    else:
        logged_in = True
    if logged_in:
        dati = [{"field":"bldg_code", "csv_field":"ID_bati", "shp_field":"bldg_code", "multiplier":0},
                {"field":"pk_min-tun", "csv_field":"PK début", "shp_field":"pk_min-tun", "multiplier":1},
                {"field":"pk_max-tun", "csv_field":"PK fin", "shp_field":"pk_max-tun", "multiplier":1},
                {"field":"d_min-tun", "csv_field":"Distance horizontale minimale à l'axe du tunnel", "shp_field":"d_min-tun", "multiplier":1},
                {"field":"d_max-tun", "csv_field":"Distance horizontale maximale à l'axe du tunnel", "shp_field":"d_max-tun", "multiplier":1},
                {"field":"pk_min-smi", "csv_field":"PK début", "shp_field":"pk_min-smi", "multiplier":1},
                {"field":"pk_max-smi", "csv_field":"PK fin", "shp_field":"pk_max-smi", "multiplier":1},
                {"field":"d_min-smi", "csv_field":"Distance horizontale minimale à l'axe du tunnel", "shp_field":"d_min-smi", "multiplier":1},
                {"field":"d_max-smi", "csv_field":"Distance horizontale maximale à l'axe du tunnel", "shp_field":"d_max-smi", "multiplier":1},
                {"field":"sc_lev", "csv_field":"Classe de sensibilité", "shp_field":"sc_lev", "multiplier":1},
                {"field":"damage_class", "csv_field":"Classe de dommage", "shp_field":"dmg_cls", "multiplier":1},
                {"field":"vulnerability", "csv_field":"Vulnérablité", "shp_field":"vuln", "multiplier":1},
                {"field":"settlement_max", "csv_field":"Settlement max", "shp_field":"sett_max", "multiplier":1000},
                {"field":"tilt_max", "csv_field":"Tilt max", "shp_field":"tilt_max", "multiplier":1000},
                {"field":"esp_h_max", "csv_field":"Esp h max", "shp_field":"esph_max", "multiplier":1000},
                {"field":"damage_class_base", "csv_field":"Classe de dommage base", "shp_field":"dmg_cls_b", "multiplier":1},
                {"field":"vulnerability_base", "csv_field":"Vulnérablité base", "shp_field":"vuln_b", "multiplier":1},
                {"field":"settlement_max_base", "csv_field":"Settlement max base", "shp_field":"sett_max_b", "multiplier":1000},
                {"field":"tilt_max_base", "csv_field":"Tilt max base", "shp_field":"tilt_max_b", "multiplier":1000},
                {"field":"esp_h_max_base", "csv_field":"Esp h max base", "shp_field":"esph_max_b", "multiplier":1000}, 
                {"field":"damage_class_vibration", "csv_field":"Classe de dommage - Vibration", "shp_field":"dmg_cls_vbr", "multiplier":1},
                {"field":"vulnerability_class_vibration", "csv_field":"Vulnérablité - Vibration", "shp_field":"vuln_vbr", "multiplier":1},
                {"field":"vibration_speed_mm_s", "csv_field":"Vitessse de vibration", "shp_field":"vbr_speed", "multiplier":1}]
       # EXPORT BUILDINGS CALCULATED DATA
        with open(csv_path, 'wb') as out_csvfile:
            writer = csv.writer(out_csvfile, delimiter=";")
            writer.writerow([x["csv_field"] for x in dati])
            bcurr = Building.find(mongodb, {"PK_INFO":{"$exists":True}})
            if bcurr.count == 0:
                logger.error("No Buildings found!")
            else:
                shape_data = open_shapefile(shp_path, logger)
                if shape_data:
                    layer = append_fields_to_shapefile(shape_data,
                                                       [x["shp_field"] for x in dati[1:]], logger)
                for item in bcurr:
                    building = Building(mongodb, item)
                    building.load()
                    bldg_code = building.item["bldg_code"]
                    if layer:
                        bldg_feature = find_first_feature(layer, "bldg_code", bldg_code)
                        if not bldg_feature:
                            logger.warn("No feature with bldg_code %s found", bldg_code)
                    logger.debug("Processing building %s", bldg_code)
                    row = []
                    for dato in dati:
                        if dato["field"] == "bldg_code":
                            field_value = building.item["bldg_code"]
                        elif dato["field"].split("_", 1)[0] in ["d", "pk"]:
                            field, align = dato["field"].split("-", 1)
                            pk_array = building.item["PK_INFO"]["pk_array"]
                            if align == "smi":
                                field_value = next((l[field] for l in pk_array if l['pk_min'] > 2150000), None)
                            else:
                                field_value = next((l[field] for l in pk_array if l['pk_min'] < 2150000), None)
                        else:
                            field_value = building.item.get(dato["field"], 0) * dato["multiplier"]
                        row.append(str(field_value))
                        if bldg_feature and field_value and dato["field"] != "bldg_code":
                            logger.debug("Trying to set field %s of building %s to value %0.10f",
                                         dato["shp_field"][:10], bldg_code, field_value)
                            bldg_feature.SetField(dato["shp_field"][:10], field_value)
                    writer.writerow(row)
                    if layer and bldg_feature:
                        layer.SetFeature(bldg_feature)
                if shape_data:
                    shape_data.Destroy()
                logger.info("Buildings data Exported")
コード例 #41
0
from building import Building
from city import City

# Create a new city instance and add your building instances to it.
# Once all buildings are in the city, iterate the city's building
# collection and output the information about each building in the city.

eight_hundred_eighth = Building("800 8th Street", 12)
seven_hundred_seventh = Building("700 7th Street", 44)
six_hundred_sixth = Building("600 6th Street", 13)
five_hundred_fifth = Building("500 5th Street", 99)
four_hundred_forth = Building("400 4th Street", 88)

eight_hundred_eighth.purchase("Kid Frost")
seven_hundred_seventh.purchase("MC Eight")
six_hundred_sixth.purchase("Dr. Dre")
five_hundred_fifth.purchase("B. Real")
four_hundred_forth.purchase("Mr. Cartoon")

eight_hundred_eighth.construct()
seven_hundred_seventh.construct()
six_hundred_sixth.construct()
five_hundred_fifth.construct()
four_hundred_forth.construct()

megalopolis = City()

megalopolis.add_building(eight_hundred_eighth)
megalopolis.add_building(seven_hundred_seventh)
megalopolis.add_building(six_hundred_sixth)
megalopolis.add_building(five_hundred_fifth)
コード例 #42
0
def print_menu(): #prints terminal menu
  while True:
    to_do = raw_input("What do you want to do?\n--Add (N)ew building\n--Review the (B)uilding information\n--add new (A)partment\n--(L)ook up apartment information\n--add new (R)enter\n--check apartment (O)ccupancy\n--(Q)uit\n ").lower()
    if to_do == 'n': #adds new building
      number = int(raw_input("\nWhat is the building number? "))
      address = raw_input("\nWhat is the building address? ")
      doorman = raw_input("\nDoes the building have a doorman? (T) or (F)") #work on, convert to boolean
      number_units = int(raw_input("\nHow many units does the building have?"))

      building = Building(number,address,number_units, doorman)

      print "\nBuilding Number: %s Added\n" % (building.building_number)
    elif to_do == 'b': #asks for building information
      building_number = int(raw_input("\nWhich building number do you want information on? "))
      building = Building.building_list[building_number]
      building_info = raw_input("\nWhat do you want to look up?\n--(A)ddress\n--(D)oorman\n--(N)umber of Units?\n ").lower()

      if building_info == 'a':
        print building.address
      elif building_info == 'd':
        print building.doorman
      elif building_info == 'n':
        print building.number_units
      else:
        print "\nSorry I could not understand\n"
    elif to_do == 'a': #adds new apartment
      building_number = int(raw_input("What is the building number? "))
      building = Building.building_list[building_number]

      unit_number = int(raw_input("What is the unit number? "))
      rent = int(raw_input("What is the rent per month? "))
      square_footage = int(raw_input("What is the square_footage? "))
      bathrooms = int(raw_input("Number of bathrooms? "))


      apartment = building.add_apartment(unit_number, rent, square_footage, bathrooms)

      print "\nApartment Number: %s added to building number %s\n" % (apartment.unit_number,building)

    elif to_do == 'l': #requests apartment information
      building_number = int(raw_input("Which building number is the apartment located in? "))
      unit_number = int(raw_input("Which apartment number? "))

      print "unit number %s" %(unit_number)

      building = Building.building_list[building_number]
      apartment = building.apartment_dict[unit_number]

      apt_info = raw_input("What do you want to look up?\n--(R)ent\n--(S)quare footage\n--(N)umber of bathrooms\n--Ren(T)er\n--(O)ccupied? ").lower()

      if apt_info == 'r':
        print apartment.rent
      elif apt_info == 's':
        print apartment.square_footage
      elif apt_info == 'n':
        print apartment.number_bathrooms
      elif apt_info == 't':
        print apartment.renter
      elif apt_info == 'o':
        print apartment.occupied
      else:
        print "\nSorry I could not understand\n"
        #finish loop here

    elif to_do =='r': #adds renter
      building_number = int(raw_input("Which building number is the renter located in? "))
      building = Building.building_list[building_number]

      unit_number = int(raw_input("Which apartment number? "))

      apartment = building.apartment_dict[unit_number]

      name = raw_input("What is the renter's name? ")

      renter = apartment.add_renter(name)

      print "\nRenter: %s, added to building number: %s and unit number %s\n" % (renter.name, renter.building_number, renter.apartment_number)
    elif to_do == 'o': #checks apartment occupancy
      building_number = int(raw_input("Which building number is the apartment located in? "))
      unit_number = int(raw_input("Which apartment number? "))

      building = Building.building_list[building_number]
      apartment = building.apartment_dict[unit_number]

      result = apartment.check_occupied()
      if True:
        print "\nOCCUPIED\n"
      else:
        print "\nUNOCCUPIED\n"
    elif to_do == 'q': #quits the program
        print "\nThanks for using Manager Client!\n"
        return False
    else:
        print "\nSorry, I don't understand what you want.\n"