def getCustomPath(latitude, longitude, end_place): startCoord = Coordinate() startCoord.latitude = latitude startCoord.longitude = longitude #Get all coordinate in the database for our end place end_coordinates = Coordinate.getAllForBuilding(end_place) if len(end_coordinates) == 0: raise Exception(end_place + " is not a building in our database") #Figure out the two closest coordinates (startCoord, endCoord) = DB.getClosestCoords([startCoord], end_coordinates) #Find all floor plans for our end place #floorPlans = [] #floors = Floor.getAllForBuilding(end_place) #for floor in floors: # floorPlans.append(floor.floor_map) #Get building information for our end place building = Building() building.loadFromID(end_place) #Build path object to pass back path = Path() path.startCoord = startCoord.__dict__ path.endCoord = endCoord.__dict__ path.floorPlans = building.floorPlans path.buildingInfo = building.__dict__ return path.__dict__
def test_elevators(): ELEVATOR_COUNT = 2 theBuilding = Building("Blair Plaza", 17, ELEVATOR_COUNT) theBuilding.start_elevators() print("Elevator status: " + ', '.join(theBuilding.get_elevators_statuses())) theTracker = Elevator_tracker(theBuilding, 0.2) theTracker.start_tracking() sleep(1.5) theBuilding.call_elevator(4, -1) sleep(2.5) # theBuilding.call_elevator(8, 1) sleep(5) # theBuilding.call_elevator(2, 1) # sleep(10) print ("The End") theBuilding.stop_elevators() print("Elevator status: " + ', '.join(theBuilding.get_elevators_statuses())) theTracker.end_tracking() #print("Tracker status: " + theTracker.get_tracker_status()) theTracker.plot_track()
def getBasicState(): state = GameState.getBlankState() # player 1 p1Queen = Ant((0, 0), QUEEN, 0) state.board[0][0].ant = p1Queen state.inventories[0].ants.append(p1Queen) p1Hill = Building((0, 0), ANTHILL, 0) p1Tunnel = Building((9, 0), TUNNEL, 0) state.board[0][0].constr = p1Hill state.board[0][9].contrs = p1Tunnel state.inventories[0].constrs += [p1Hill, p1Tunnel] #player 2 p2Queen = Ant((9, 9), QUEEN, 1) state.board[9][9].ant = p2Queen state.inventories[1].ants.append(p2Queen) p1Hill = Building((9, 9), ANTHILL, 1) p1Tunnel = Building((0, 9), TUNNEL, 1) state.board[9][9].constr = p1Hill state.board[9][0].contrs = p1Tunnel state.inventories[1].constrs += [p1Hill, p1Tunnel] return state
def init(self): # self.arrivesMemoryVariable = "Arrives Freight House" self.departsMemoryVariable = "Departs Freight House" self.freightHouse = Building() self.freightHouse.init(self.arrivesMemoryVariable, self.departsMemoryVariable) self.scheduleTimes = [] self.scheduleTimes.append( memories.provideMemory(self.arrivesMemoryVariable)) self.stove = lights.provideLight("NL120") self.platformLights = lights.provideLight("NL121") self.officeLight = lights.provideLight("NL122") self.dockLight = lights.provideLight("NL123") self.platformIndicator = lights.provideLight("IL121") self.officeIndicator = lights.provideLight("IL122") self.dockIndicator = lights.provideLight("IL123") self.platformLightDimmer = lights.provideLight("NL124") self.officeLightDimmer = lights.provideLight("NL125") self.dockLightDimmer = lights.provideLight("NL126")
def __init__(self): """Initialize the SLSQP algorithm for a specific building. """ print("Initializing the SLSQP Optimizer...") self.opt_prob = [] self.opt = [] self.building = Building()
def calculateRent(self, player, building, dice = None): #Rent for buildings if (building.type == "building"): query = Building.gql("WHERE ANCESTOR IS :1 AND colour = :2 AND owner = :3", self.game, building.colour, player.user) count = query.count(3) if (building.houses == 0 and (((building.colour == "954c23" or building.colour == "284ea1") and count == 2) or count == 3)): return building.rent[0] * 2 elif(0 <= building.houses <= 5): return building.rent[building.houses] else: message = {'error' : 'Invalid number of houses. Contact a game admin.'} self.messageAll(message) sys.exit() #Rent for pubs elif (building.type == "pub"): query = Building.gql("WHERE ANCESTOR IS :1 AND type = 'pub' AND owner = :2", self.game, player.user) count = query.count(4) return building.rent[count-1] #Rent for shops elif (building.type == "shop"): query = Building.gql("WHERE ANCESTOR IS :1 AND type = 'shop' AND owner = :2", self.game, player.user) count = query.count(2) if(count == 1): return 4 * (dice) elif(count ==2): return 10 * (dice) else: message = {'error' : 'Property number error. Contact a game admin.'} self.messagePlayer(player.user, message) else: message = {'error' : 'Invalid building type. Contact a game admin.'} self.messagePlayer(player.user, message) sys.exit()
def printState(self, bestGene): ''' Description: Creates a state with the best gene in a population to print an ascii representation to a file. Parameters: bestGene - best gene in the current population ''' ants1 = [] cons1 = [] ants2 = [] cons2 = [] #Booger Player Buildings cons3 = [] #FOOD #fill state with best gene's placements for i, coord in enumerate(bestGene): if i == 0: cons1.append(Building((coord), ANTHILL, self.playerId)) elif i == 1: cons1.append(Building((coord), TUNNEL, self.playerId)) elif i < 11: cons1.append(Building((coord), GRASS, self.playerId)) else: cons3.append(Building((coord), FOOD, NEUTRAL)) newInventories = [ Inventory(self.playerId, ants1, cons1, 0), Inventory(abs(self.playerId - 1), ants2, cons2, 0), Inventory(NEUTRAL, [], cons3, 0) ] dummyState = GameState(None, newInventories, 2, self.playerId) self.asciiPrintState(dummyState) #print state to file
def test2(): ELEVATOR_COUNT = 2 theBuilding = Building("Blair Plaza", 17, ELEVATOR_COUNT) theBuilding.start_elevators() theTracker = Elevator_tracker(theBuilding, 1) #0.2 theTracker.start_tracking() print ("The End") theTracker.end_tracking()
def getBuildingInfo(building_id): building = Building() building.loadFromID(building_id) #Find all floor plans for our end place floorPlans = [] floors = Floor.getAllForBuilding(building_id) for floor in floors: floorPlans.append(floor.floor_map) buildingInfo = BuildingWithFloor() buildingInfo.loadUp(building.__dict__, floorPlans) return buildingInfo.__dict__
def getTown(numDudes=10): # handle request data req_data = loads(request.data) culture_filters = {} print "~~~~~~~~~~~~~~~~~~~~~\n%s\n###############" % req_data if 'cultureFilter' in req_data: culture_filters = req_data['cultureFilter'] if 'size' in req_data: size = int(req_data['size']) * 10 # get the population of the town blank_npcs = assemble_npc_list(numDudes, culture_filters) npcs = jobs_for_npcs(blank_npcs) # stuff all professions in a dict, to assign to NPCs when the building is created professions = {} profession_distribution = [] for profession in db.get_all_professions(): professions[profession[4]] = {'occupation':profession[0], 'description':profession[1], 'category':profession[2], 'id':profession[4]} # load all possible buildings to get started actualizing our new Town buildings_raw = [] for bld in db.get_all_businesses(): buildings_raw.append( Building(bld[2], bld[4], bld[5]) ) # pull out the buildings actually in our town, based on size buildings = [] for i, bld in enumerate(buildings_raw): #print '\nbld: {}\nsize: {}\nreqPop: {}\nnumThere: {}'.format(bld.name, size, bld.reqPopulation, size / bld.reqPopulation) for x in range( size / bld.reqPopulation ): # need to reinstantiate so each instance has its own worker this_building = Building(bld.name, bld.reqPopulation, bld.requiredProfession) # get an employee for the business worker = npcs.pop() worker.profession = professions[bld.requiredProfession] this_building.worker = worker.__dict__ buildings.append(this_building) # build the final town product retTown = {} # the thing to jsonify and return bld = {} # buildings dict retTown["name"] = choice(db.get_all_places())[0] # put buildings in dict for easy jsonify for x,y in enumerate(buildings): bld[x] = y.__dict__ retTown['buildings'] = bld # populate town with NPCs retTown['npcs'] = [n.__dict__ for n in npcs] return dumps(retTown)
def init(self): # self.arrivesMemoryVariable = "Arrives Freight House" self.departsMemoryVariable = "Departs Freight House" self.freightHouse = Building() self.freightHouse.init(self.arrivesMemoryVariable, self.departsMemoryVariable) self.scheduleTimes = [] self.scheduleTimes.append( memories.provideMemory(self.arrivesMemoryVariable)) #self.stove = lights.provideLight("NL120"); #self.platformLights = lights.provideLight("NL121"); #self.officeLight = lights.provideLight("NL122"); #self.dockLight = lights.provideLight("NL123"); #self.platformIndicator = lights.provideLight("IL121"); #self.officeIndicator = lights.provideLight("IL122"); #self.dockIndicator = lights.provideLight("IL123"); #self.platformLightDimmer = lights.provideLight("NL124"); #self.officeLightDimmer = lights.provideLight("NL125"); #self.dockLightDimmer = lights.provideLight("NL126"); self.freightDock = TriStateSensor( sensors.provideSensor("Freight Dock Dim"), sensors.provideSensor("Freight Dock On"), sensors.provideSensor("Freight Dock Off")) self.freightOffice = TriStateSensor( sensors.provideSensor("Freight Office Dim"), sensors.provideSensor("Freight Office On"), sensors.provideSensor("Freight Office Off")) self.freightPlatform = TriStateSensor( sensors.provideSensor("Freight Platform Dim"), sensors.provideSensor("Freight Platform On"), sensors.provideSensor("Freight Platform Off")) self.freightStove = TriStateSensor( None, sensors.provideSensor("Freight Stove"), None) self.sideDoor = sensors.provideSensor( "Mine Bldg Side Soor") # Mine Bldg Side Door self.lockerRoom = sensors.provideSensor( "Mine Bldg S2") # Mine Bldg Level 2 - Locker Room self.tipple = sensors.provideSensor("Mine Bldg S3") # Mine Bldg Tipple
def make_objs(): Building.create_buildings() i = 0 # 계단끼리 연결 while i < 3: stair_list[i + 3].other_stair = stair_list[i + 6] stair_list[i + 6].other_stair = stair_list[i + 3] stair_list[i + 3 + 12].other_stair = stair_list[i + 6 + 12] stair_list[i + 6 + 12].other_stair = stair_list[i + 3 + 12] i += 1 # Make Obj for j in range(2): for i in range(6): make_random_floor_obj(j, i) random_actor_generator() Player2() # ui ---------------------------- Cursor() ui_mouse = Ui(1) ui_mouse.load_img('img/ui_mouse.png') ui_mouse.set_pos(0, 90) ui_mouse.set_off((-1, 0)) ui_keyboard = Ui(1) ui_keyboard.load_img('img/ui_keyboard.png') ui_keyboard.set_pos(-00, 90) ui_keyboard.set_off((1, 0)) global ui_hp1, ui_hp2 ui_hp1 = PlayerUI(1) ui_hp1.set_pos(-369, 64) ui_hp1.size[0], ui_hp1.size[1] = 0, 35 ui_hp1.init(240, 63, 63, -1.0, ui_keyboard.pos) ui_hp2 = PlayerUI(1) ui_hp2.set_pos(369, 64) ui_hp2.size[0], ui_hp2.size[1] = 0, 35 ui_hp2.init(91, 215, 232, 1.0, ui_mouse.pos) ui_center = Ui(1) ui_center.load_img('img/ui_center.png') ui_center.set_pos(0, 75)
def initializeBuildingsAndPopulation(self): # Initialize Buildings step = self.townSize[0] / 15 for x in range(step, 14 * step, step): for y in range(step, 14 * step, step): self.buildings.append( Building('House', (x, y), [0, random.randint(2, 6)])) mid = len(self.buildings) / 2 self.buildings[mid].type = 'Store' self.buildings[mid].capacity = [0, 0] #Initialize population infective = int(self.parameters.initialProbabilityInfected * 100) susceptible = 100 - infective my_list = ['I'] * infective + ['S'] * susceptible for i in range(self.popSize): for b in self.buildings: if b.capacity[0] < b.capacity[1]: friends = self.findFriends(b) initialCondition = random.choice(my_list) if initialCondition == 'I': self.population.append( Person(i + 1, b.location[0], b.location[1], False, True, b, self.buildings[mid], friends)) else: self.population.append( Person(i + 1, b.location[0], b.location[1], True, False, b, self.buildings[mid], friends)) b.capacity[0] += 1 break
def test_building_placed(self): case_study_town = self.towns[0] test_farm = Building("farm", case_study_town, [0, 0], self.player) case_study_town.holdings.append(test_farm) case_study_town.holdings = [test_farm] assert test_farm in case_study_town.holdings
def make_buildings_from_saved_file( building_data: Dict[str, List]) -> List[Building]: buildings: List[Building] = [] # First, create buildings without their connections for building_data in building_data["data"]: buildings.append( Building(**building_data, annotate_with_text=False)) # then connect them all temp_city = City(buildings, on_change=lambda: None, create_streets_between_buildings=False) def get_building_at_pos(x, y): return temp_city.get_building_at_pos((x, y)) # Convert each building's connections from coordinates to Building objects for building in buildings: building.connections = [ get_building_at_pos(*coords) for coords in building.connections ] return buildings
def unmortgageProperty(self, user, property_id) : if self.game.inProgress : if self.checkPlayerTurn(user) : player = self.getCurrentPlayer() query = Building.gql("WHERE ANCESTOR IS :1 AND position = :2", self.game, int(property_id)) property = query.get() #Unmortgage amount is mortgage cost + 10% interest amount = property.cost/2 amount = amount + amount/10 #Validate if player can unmortgage property (Who owns it, if not mortgaged) if property.owner != user : message = {'error' : 'not your property'} self.messagePlayer(user, message) elif property.mortgaged == False : message = {'error' : 'property already unmortgaged'} self.messagePlayer(user, message) elif self.deductMoney(player, amount) : property.mortgaged = False property.put() message = {'status' : 'unmortgaged', 'player_id' : player.turnNumber, 'property_id' : property.position, 'money_change' : amount, 'money' : player.money} self.messageAll(message) else : message = {'error' : 'not enough money'} self.messagePlayer(user, message) else : message = {'error' : 'It is not your turn'} self.messagePlayer(user, message) else : message = {'error' : 'The game has not started'} self.messagePlayer(user, message)
def addBuilding(angle, distFromCenter, sectorAngle, buildingSize=1): innerLength = max(distFromCenter - ringSize, 0) angleSeperationOuter = ( sectorAngle - (buildingSeperation / distFromCenter)) * buildingSize angleSeperationInner = angleSeperationOuter poly = [ Point(innerLength * math.cos(angle), innerLength * math.sin(angle)), Point(distFromCenter * math.cos(angle), distFromCenter * math.sin(angle)), Point(distFromCenter * math.cos(angle + angleSeperationOuter), distFromCenter * math.sin(angle + angleSeperationOuter)), Point(innerLength * math.cos(angle + angleSeperationInner), innerLength * math.sin(angle + angleSeperationInner)) ] pointsOutOfFrame = 0 for p in poly: pM = p + Point(imageSize[0] / 2, imageSize[1] / 2) if not (pM.x > 0 and pM.x < imageSize[0] and pM.y > 0 and pM.y < imageSize[1]): pointsOutOfFrame += 1 if pointsOutOfFrame < len(poly): objects.append( Building(Point(imageSize[0] / 2, imageSize[1] / 2), poly, 1, fill=(random.randint(50, 255), 0, random.randint(50, 255))))
def mortgageProperty(self, user, position) : if self.game.inProgress : if self.checkPlayerTurn(user) : #Mortgage property #Get property player = self.getCurrentPlayer() query = Building.gql("WHERE ANCESTOR IS :1 AND position = :2", self.game, int(position)) property = query.get() #Validate if player can mortgage property (Who owns it, if has houses on block, already mortgaged) if property.owner != user : message = {'error' : 'not your property'} self.messagePlayer(user, message) elif property.mortgaged == True : message = {'error' : 'property already mortgaged'} self.messagePlayer(user, message) elif not self.checkBlockForHouses(property.colour): #no houses so can mortgage property.mortgaged = True property.put() #Now give the player their money amount = property.cost / 2 self.addMoney(player, amount) message = {'status' : 'mortgaged', 'player_id' : player.turnNumber, 'property_id' : property.position, 'money_change' : amount, 'money' : player.money} self.messageAll(message) else : #Block has houses on message = {'error' : 'too many houses on neighbouring properties'} self.messagePlayer(user, message) else : message = {'error' : 'It is not your turn'} self.messagePlayer(user, message) else : message = {'error' : 'The game has not started'} self.messagePlayer(user, message)
def __init__(self, x, y, terrain, team): Building.__init__(self, x,y,terrain, BUILDING_LIFE, BUILDING_REGENERATION, team, "art/building1.png") if team == 0: self.image = loadImage('art/parathonon.png', (255,255,255)) else: self.image = loadImage('art/Pyramid.png', (255,255,255)) self.swordsman = [] self.numSwordsman = 0 self.maxNumberSwordsman = MAX_NUMBER_SWORDSMAN self.spawTime = SWORDSMAN_SPAWN_TIME self.timer = 0
def __init__( self, building_path="data/building_oib_16linie.xlsx", kWp=1, # PV kWp battery_kWh=1): # Battery kWh ###### Compononets ##### # (Other classes and parts, that form the model) self.building = Building(path=building_path) self.HVAC = HVAC() self.PV = PV(csv="data/pv_1kWp.csv", kWp=1) self.PV.set_kWp(kWp) self.battery = Battery(kWh=battery_kWh) ###### Parameters ##### self.cp_air = 0.34 # spez. Wärme kapazität Luft (Wh/m3K) self.price_grid = 0.19 # €/kWh self.price_feedin = 0.05 # €/kWh ###### Timeseries ##### # load Usage characteristics self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252") # load climate data self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1] # load solar gains self.QS = np.genfromtxt("data/Solar_gains.csv") # W/m²
def create_map(self): for row in range(self.size_rows): self.maps.append([]) for col in range(self.size_columns): self.maps[row].append( Building("building", self.building_types[random.randrange(0, 13)])) while self.number_of_main_road_elements != 0: self.generate_next_element() print("") for line in self.maps: for element in line: if isinstance(element, Building): print("B", end=" ") elif isinstance(element, Street): print(".", end=" ") else: print("*", end=" ") print("") print("") # print(self.road) # print("") return self.maps
def buyProperty(self, user): #Check it is the user's turn if self.game.inProgress : if (self.checkPlayerTurn(user)) : #Action of buying property player = self.getCurrentPlayer() if self.game.numRolls == 0: self.messagePlayer(user, {"error": "You haven't moved yet."}); return #Check if property is available query = Building.gql("WHERE ANCESTOR IS :1 AND owner = NULL AND position = :2" , self.game, player.position) property = query.get() if not property : #property not available message = {'error' : 'property unavailable'} self.messagePlayer(user, message) else : #property is available #Check if the player has the available funds if self.deductMoney(player, property.cost) : property.owner = user property.put() message = {'status' : 'bought', 'player' : player.turnNumber, 'property' : property.position, 'money_change' : -property.cost, 'money' : player.money} self.messageAll(message) else : message = {'error' : 'not enough money'} self.messagePlayer(user, message) else : message = {'error' : 'It is not your turn'} self.messagePlayer(user, message) else : message = {'error' : 'The game has not started'} self.messagePlayer(user, message)
def buyHouse(self, user, propertyPosition): #Check it is the user's turn if self.game.inProgress : if (self.checkPlayerTurn(user)) : #Now time to buy an office/lab player = self.getCurrentPlayer() query = Building.gql("WHERE ANCESTOR IS :1 AND owner = :2 AND position = :3 AND type = 'building' ", self.game, player.user, int(propertyPosition)) property = query.get() #Check if property belongs to player and property is "building" type if property != None : block = self.getBlockDetails(property.colour) #Check if surrounding houses have the minumum number of houses on them #or if one of the properties is mortgaged (as only need to check for one) for houseCheck in block : #Check player owns all in group if houseCheck["owner"] != user: message = {'error' : 'must own all properties'} self.messagePlayer(user, message) return if houseCheck["houses"] < property.houses : message = {'error' : 'not enough houses on neighbouring properties'} self.messagePlayer(user, message) return if houseCheck["mortgaged"] : message = {'error' : 'property in group is mortgaged'} self.messagePlayer(user, message) return if property.houses >= 5 : #Check if the house will exceed the maximum allowed message = {'error' : 'maximum number of houses already'} self.messagePlayer(user, message) return #Check if the player has the available funds if self.deductMoney(player, property.buildCost) : property.houses = property.houses + 1 property.put() message = {'status' : 'addBuilding', 'player' : player.turnNumber, 'property' : property.position, 'money_change' : -property.buildCost, 'money' : player.money} self.messageAll(message) else : message = {'error' : 'not enough money'} self.messageAll(message) else: message = {'error' : 'Cannot build houses here!'} self.messagePlayer(user, message) else : message = {'error' : 'It is not your turn'} self.messagePlayer(user, message) else : message = {'error' : 'The game has not started'} self.messagePlayer(user, message)
def __init__(self, x, y, terrain, team): Building.__init__(self, x,y,terrain, BUILDING_LIFE, BUILDING_REGENERATION, team, "art/building1.png") if team == 0: self.image = loadImage('art/Greek_building.png', (255,255,255)) else: self.image = loadImage('art/egyptian_house.png', (255,255,255)) self.peasants = [] self.numPeasants = 0 self.maxNumPeasants = MAX_NUMBER_PEASANTS self.spawTime = PEASANT_SPAW_TIME self.timer = 0
def __init__(self, x, y, terrain, team): Building.__init__(self, x,y,terrain, BUILDING_LIFE, BUILDING_REGENERATION, team, "art/building1.png") if team == 0: self.image = loadImage('art/greek_temple.png', (255,255,255)) else: self.image = loadImage('art/egyptian_temple.png', (255,255,255)) self.wizards = [] self.numWizards = 0 self.maxNumberWizards = MAX_NUMBER_WIZARDS self.spawTime = WIZARD_SPAWN_TIME self.timer = 0
def __init__(self, x, y, terrain, team): Building.__init__(self, x,y,terrain, BUILDING_LIFE, BUILDING_REGENERATION, team, "art/building1.png") if team == 0: self.image = loadImage('art/armory.png', (255,255,255)) else: self.image = loadImage('art/egyptian_armory.png', (255,255,255)) self.archers = [] self.numArchers = 0 self.maxNumberArchers = MAX_NUMBER_ARCHERS self.spawTime = ARCHER_SPAWN_TIME self.timer = 0
def main(): list = [] while (True): print("1 - add new") print("2 - delete") print("3 - search") print("4 - show all") x = input() if int(x) == 1: print("City name:") city_name = input() print("population:") population = input() print("Street name") street_name = input() print("Building number:") building_number = input() print("Apartment number:") apartment_number = input() if street_name == "" and building_number == "" and apartment_number == "": item = City(city_name, population) elif building_number == "" and apartment_number == "": item = Street(city_name, population, street_name) elif apartment_number == "": item = Building(city_name, population, street_name, building_number) else: item = Apartment(city_name, population, street_name, building_number, apartment_number) list.append(item) elif int(x) == 2: print("1 - City name") print("2 - Population") print("3 - Street name") print("4 - Building number") print("5 - Apartment") field = input() print("What?") what = input() print("DELETED") for m in delete(list, field, what): print(m) elif int(x) == 3: print("1 - City name") print("2 - Population") print("3 - Street name") print("4 - Building number") print("5 - Apartment") field = input() print("What?") what = input() for m in search(list, field, what): print(m) else: for m in list: print(m)
def __init__(self, building_path="data/building.xlsx", # building parameters kWp=0, # PV parameters battery_kWh=0): # battery parameters print("initializing Model") ###### Compononets ##### # (Other classes and parts, that form the model) # your code here... self.building = Building(path=building_path)
def populate_building(self, single_row): """ From each row of an Excel sheet Building,it craetes object of Building and stores it in dictionary. Also populates the dictionary which maps mail codes with corresponding buildings Args: :param single_row: represents one row of the sheet building of an excel file """ b = Building(single_row[0], single_row[1], single_row[2]) self.__node_by_id[single_row[0]] = b self.populate_bulding_mail_code_from_list(single_row[0], single_row[3])
def transferMoney(self, amount, playerFrom, playerTo=None): if(playerFrom.money > amount): playerFrom.money -= amount playerFrom.put() if(playerTo != None): playerTo.money += amount playerTo.put() else: query = Building.gql("WHERE ANCESTOR IS :1 AND owner = :2 AND mortgaged = False", self.game, playerFrom.user) buildings = query.fetch(100) mortgageValue = 0 for building in buildings: mortgageValue += building.houses * (building.buildCost/2) mortgageValue += building.cost/2 playerFrom.money -= amount playerFrom.put() if(mortgageValue > amount): message = {'status' : 'force_mortgage', 'amount' : (-1 * playerFrom.money)+1} self.messagePlayer(playerFrom.user, message) else: playerFrom.bankrupt = True playerFrom.put() message = {'status' : 'bankrupt', 'player' : playerFrom.turnNumber} self.messageAll(message) query = Player.gql("WHERE ANCESTOR IS :1 AND Bankrupt = False", self.game) count = query.count(2) if(count == 1): message = {'status' : 'victory', 'player' : query.get().turnNumber} self.messageAll(message) self.cleanUpDatastore() else: query = Building.gql("WHERE ANCESTOR IS :1 AND owner = :2", self.game, playerFrom.user) buildings = query.fetch(40) for building in buildings: building.owner = playerTo.user building.put()
def __init__(self): """Initialize the GP_SS algorithm for a specific building. """ print("Initializing the GP_SS...") self.building = Building() self.X = [] self.Y = [] self.dynModels = [] # Number of Initial Exploration Simulation self.initExploration = 36 # Number of Samples for witching to Sparse Gaussian Processes self.num_inducing = 2000 # Safety constraint for exploration self.explorationConstraint = 0.03 # Needed to determine the best controller out of all iterations self.costs = [] self.constraints = [] self.policies = [] self.baseline = []
def placeBuilds(self, scene, cityMap, length, width, origin): currX = origin[0] for row in cityMap: currY = origin[1] for cell in row: if cell == "tower": self.tower = Building(scene, "tower", currX, currY, 0) elif type(cell) == list: self.renderBlocks(scene, cell, length / 9, width / 11, (currX, currY)) currY -= width currX -= length
def cleanUpDatastore(self): query = Building.gql("WHERE ANCESTOR IS :1", self.game) db.delete(query.fetch(100)) query = Player.gql("WHERE ANCESTOR IS :1", self.game) db.delete(query.fetch(100)) query = EventCard.gql("WHERE ANCESTOR IS :1", self.game) db.delete(query.fetch(100)) self.game.delete()
def __constructBuildings__(self, buildingNameMap, rawData): idToBuildingPixelMap = {k: [] for k in buildingNameMap} for y in range(Constants.HEIGHT): for x in range(Constants.WIDTH): buildingId = rawData[y * Constants.WIDTH + x] assert (buildingId == 0 or buildingId in buildingNameMap) if (buildingId != 0): idToBuildingPixelMap[buildingId].append(Point(x, y)) return [ Building(buildingNameMap[buildingId], buildingId, pixels) for buildingId, pixels in idToBuildingPixelMap.items() ]
def create_state(self, ai): #create game state for testing self.state = self.setup_state() players = [c.PLAYER_ONE, c.PLAYER_TWO] for player in players: self.state.whoseTurn = player constrsToPlace = [] constrsToPlace += [Building(None, c.ANTHILL, player)] constrsToPlace += [Building(None, c.TUNNEL, player)] constrsToPlace += [ Construction(None, c.GRASS) for i in xrange(0, 9) ] setup = ai.getPlacement(self.state) for piece in setup: self.place_items(piece, constrsToPlace, self.state) self.state.flipBoard() self.state.phase = c.SETUP_PHASE_2 for player in players: self.state.whoseTurn = player constrsToPlace = [] constrsToPlace += [ Construction(None, c.FOOD) for i in xrange(0, 2) ] setup = ai.getPlacement(self.state) for food in setup: self.place_items(food, constrsToPlace, self.state) self.state.flipBoard() self.setup_play(self.state) self.state.whoseTurn = c.PLAYER_ONE return self.state
def buildingArray(browser, buildingSettings): allButtons = browser.find_elements_by_class_name('build_up') buildings = [] k = 0 while k < len(buildingSettings): newBuilding = Building(buildingSettings[k], allButtons[k]) if newBuilding.haveEnoughResources: buildings.append(newBuilding) k += 1 return buildings
def addBuilding(position, otherBuildings, canvas): pool = multiprocessing.Pool(processes=12) polyPoints = [Point(0, 0)] + [ p for p in pool.starmap( findRayCollisions, zip( repeat(position), repeat(otherBuildings), range(0, int((math.pi * 2) * 1000), int((math.pi) * 1000 / NUM_RAYS)))) if p != None ] if len(polyPoints) > 2: #canvas.ellipse((position.x, position.y, position.x + 10, position.y + 10), fill=(255, 0, 0), outline=(0, 0, 0)) objects.append(Building(position, tuple(polyPoints), 1)) else: objects.append( Building(position, [ Point(0, 0), Point(random.randint(-100, 100), random.randint(-100, 100)), Point(random.randint(-100, 100), random.randint(-100, 100)) ]))
def __init__(self): super(MainWindow, self).__init__() self.coll = RuleCollection() self.coll.addRule(Database.LoeWa()) self.coll.addRule(Database.ZuGa()) self.coll.addRule(Database.ZweiGe()) self.coll.addRule(Database.UnterGe()) self.coll.addRule(Database.RettWeg()) self.coll.addRule(Database.CheckBrandabschnittsflaeche()) self.ui = Ui_MainWindow() self.ui.setupUi(self) # self-setup: self.ui.pushStart.clicked.connect(self.check) self.ui.squareSpinBox.valueChanged.connect(self.setSquareMeters) self.ui.topSpinBox.valueChanged.connect(self.setTopFloors) self.ui.subSpinBox.valueChanged.connect(self.setSubFloors) self.ui.heightSpinBox.valueChanged.connect(self.setHeight) self.ui.sicherheitsCombo.currentIndexChanged.connect( self.updateSicherheits) self.ui.baustoffCombo.currentIndexChanged.connect(self.updateBaustoff) self.ui.pushNeu.clicked.connect(self.reloadDatabase) self.ui.pushBeenden.clicked.connect(QtWidgets.QApplication.quit) self.haus = Building(squaremeters=self.ui.squareSpinBox.value(), height=self.ui.heightSpinBox.value(), subfloors=self.ui.subSpinBox.value(), topfloors=self.ui.topSpinBox.value(), sicherheits=strToSicherheitsCategory( self.ui.sicherheitsCombo.currentText()), baustoff=strToBaustoffCategory( self.ui.baustoffCombo.currentText())) print('running...') self.show()
def create_building(self, pos: Tuple[int, int]) -> None: """ Creates a building at the given position """ new_building_pos = (pos[0] - NODE_RADIUS // 4, pos[1] - NODE_RADIUS // 4) new_building = Building(*new_building_pos, connections=[], annotate_with_text=False) self.buildings.append(new_building) self.on_change()
def __clickEvent__(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: global gClickCount global gMapArr isEvenClick = gClickCount % 2 == 0 gClickCount = gClickCount + 1 if isEvenClick: gMapArr = __setUpGMap__() clickBuilding = Building("clickBuilding", -1, [Point(x, y)]) print( __describeComparativePosition__( __getComparativePosition__(gVillage, clickBuilding))) comparativelySimilarPoints = __getComparativelySimilarPoints__( gVillage, clickBuilding) __replacePoints__(gMapArr, comparativelySimilarPoints, Constants.TEAL if isEvenClick else Constants.RED) cv2.imshow("Campus Map", gMapArr)
def displayUndescribedPoints(village): undescribedPoints = [] for x in range(Constants.WIDTH): for y in range(Constants.HEIGHT): point = Point(x, y) dummyBuilding = Building("dummyBuilding", -1, [point]) if all([ len(elem) == 0 for elem in __getComparativePosition__( village, dummyBuilding) ]): undescribedPoints.append(point) print(f'Num of undescribed points: {len(undescribedPoints)}') mapArr = __createEmptyMap__() for building in village.getBuildings(): __replacePoints__(mapArr, building.getPoints(), Constants.WHITE) __replacePoints__(mapArr, undescribedPoints, Constants.RED) __display__(mapArr)
def renderBlocks(self, scene, block, length, width, origin): buildCode = {1:"house1", 2:"house2", 3:"house3", 4:"build", \ 5:"concrete", 6:"r", 7:"cafe", 8:"old"} currX = origin[0] # resets data so to fit key to ZData for row in block: currY = origin[1] # resets data to fit key to ZData for cell in row: try: # try to read z-value from database (x, y) = (int(currX // 100 * 100) - 400, int(currY // 100 * 100)) currZ = self.zData[(x, y)] except: continue if cell in buildCode: name = buildCode[cell] cell = Building(scene, name, currX, currY, currZ) currY -= width currX -= length
def actOnPosition(self, player): pos = player.position #Community Chest if ((pos == 2) or (pos == 17) or (pos == 33)): self.drawCard(False, player) #Chance elif((pos == 7) or (pos == 22) or (pos == 36)): self.drawCard(True, player) #Income Tax elif(pos == 4): self.transferMoney(200, player) self.messageAll({'status' : 'tax', 'player_id' : self.game.turn, 'money_change' : '-200', 'money' : player.money}) #Super Tax elif(pos == 38): self.transferMoney(100, player) self.messageAll({'status' : 'tax', 'player_id' : self.game.turn, 'money_change' : '-100', 'money' : player.money}) #Jail elif(pos == 30): self.goToJail(player) self.messageAll({'status' : 'go_to_jail', 'player_id' : self.game.turn, 'position' : 10}) #Free Parking/Just Visiting/Go elif((pos == 0) or ((pos == 10) and (player.inJail == -1)) or (pos == 20)): pass #Property else: query = Building.gql("WHERE ANCESTOR IS :1 AND position = :2", self.game, pos) building = query.get() if(building.mortgaged == False and building.owner != None and building.owner != player.user): query = Player.gql("WHERE ANCESTOR IS :1 AND user = :2", self.game, building.owner) buildingOwner = query.get() rent = self.calculateRent(buildingOwner, building, self.game.lastDiceTotal) self.transferMoney(rent, player, buildingOwner) #Send a message to the clients that rent is to be paid self.messageAll({'status' : 'rent', 'player_id' : player.turnNumber, 'property_owner' : buildingOwner.turnNumber, 'amount' : rent, 'player_money' : player.money, 'owner_money' : buildingOwner.money})
def getBlockDetails(self, colour) : #Returns a list that contains the properties positions query = Building.gql("WHERE ANCESTOR IS :1 AND colour = :2", self.game, colour) result = query.fetch(3) positions = [] for x in range(0, len(result)) : if colour == 'ffffff' or colour == 'fefefe' : positions.append({ "position": result[x].position, "owner": result[x].owner, "mortgaged": result[x].mortgaged }) else : positions.append({ "position": result[x].position, "houses": result[x].houses, "owner": result[x].owner, "mortgaged": result[x].mortgaged }) return positions
def displaySimilarPointCluster(village, comparison): descriptionMap = {} most = ("", None) for x in range(Constants.WIDTH): for y in range(Constants.HEIGHT): point = Point(x, y) description = __describeComparativePosition__( __getComparativePosition__( village, Building("dummyBuilding", -1, [point]))) if description in descriptionMap.keys(): descriptionMap[description].append(point) else: descriptionMap[description] = [point] for key, val in descriptionMap.items(): if comparison(key, val, most[1]): most = (key, val) print(most[0]) print(f'number of points: {len(most[1])}') mapArr = __createEmptyMap__() for building in village.getBuildings(): __replacePoints__(mapArr, building.getPoints(), Constants.WHITE) __replacePoints__(mapArr, most[1], Constants.RED) __display__(mapArr)
def __getComparativelySimilarPoints__(village, building): description = __getComparativePosition__(village, building) center = building.getCenterForDisplay() checkedPoints = set([center]) pointsToCheck = center.adjacentPoints() pointsToCheckSet = set(pointsToCheck) resultingPoints = [center] while len(pointsToCheck) > 0: otherPoint = pointsToCheck.pop(0) pointsToCheckSet.remove(otherPoint) checkedPoints.add(otherPoint) otherDescription = __getComparativePosition__( village, Building("nearClickBuilding", -2, [otherPoint])) sameDescription = True for i in range(5): if description[i] != otherDescription[i]: sameDescription = False if sameDescription: resultingPoints.append(otherPoint) for newPoint in otherPoint.adjacentPoints(): if newPoint not in checkedPoints and newPoint not in pointsToCheckSet: pointsToCheck.append(newPoint) pointsToCheckSet.add(newPoint) return resultingPoints
def leaveGame(self, player) : #Need logic to test if they are not bankrupt and if so return their properties to the bank propertiesMessage = [] if self.game.inProgress : if not player.bankrupt : #In this case they still in the game so their properties still need to be returned to the bank query = Building.gql("WHERE ANCESTOR IS :1 AND owner = :2", self.game, player.user) properties = query.fetch(30) for property in properties : property.owner = None property.houses = 0 property.mortgaged = False property.put() propertiesMessage.append(property.position) #Remove player from the datastore player.delete() #Notify all players that player has left #Check how many players are left (and delete game possibility) if self.game.inProgress : if self.getNumberOfPlayers() < 2 : #Then the remaining player has won message = {'status' : 'victory', 'player_piece' : Player.gql("WHERE ANCESTOR IS :1 AND bankrupt = False", self.game).get().piece} self.messageAll(message) self.cleanUpDatastore() if self.game.turn == player.turnNumber : self.game.rollRemaining = False self.endPlayerTurn(player.user) #End the players turn self.messageAll({'status' : 'player_disconnected', 'player_piece' : player.piece, 'property_positions_returned_to_bank' : propertiesMessage}) else : #Return the colours and pieces to game to use self.game.pieces.append(player.piece) self.game.colours.append(player.colour) self.game.put() self.messageAll({'status' : 'player_disconnected', 'player_piece' : player.piece})
def __init__(self, x, y, terrain, life, lifeRegenerationRate, team, image_path): Building.__init__(self, x, y, terrain, life, lifeRegenerationRate, team, image_path)
def takeCard(self, card, player, isChance): #Display card.text to player that drew card moneyChange = 0 position = None otherPlayers = [] inJail = False goojf = False if(card.event == 0): #Transfer money self.transferMoney((-1 * card.value),player) moneyChange = card.value elif(card.event == 1): #Move player self.movePlayer(player,card.value) position = player.position elif(card.event == 2): #Move player to stated position self.setPlayerPosition(player, card.value) position = player.position elif(card.event == 3): #Player pays/receives-from all query = Player.gql("WHERE ANCESTOR IS :1",self.game) players = query.fetch(4) for playerX in players: if (player.key() != playerX.key()): #If other player - don't give money to self self.transferMoney(card.value,player,playerX) otherPlayers.append([playerX.turnNumber, card.value, playerX.money]) elif(card.event == 4): #Get out jail free or go to jail if(card.value == 1): #Puts player in jail. No checking for GOOJF cards self.goToJail(player) position = 10 inJail = True else: player.getOutOfJailFree += 1 player.put() goojf = player.getOutOfJailFree elif(card.event == 5): #Move to nearest shop #Currently only moves if player is on a chance/commchest space if (player.position in (2, 7, 33, 36)): #self.setPlayerPosition(player,12) if player.position > 12 : #Will pass go moves = 40 - player.position + card.value self.movePlayer(player, moves) else : self.setPlayerPosition(player, 12) position = 12 elif (player.position in (17, 22)): self.setPlayerPosition(player, 28) position = 28 elif(card.event == 6): #Move to pub #currently only moves if player is on a chance/commchest space if (player.position in (2, 36)): if player.position > 5 : #Will pass go moves = 40 - player.position + card.value self.movePlayer(player, moves) else : self.setPlayerPosition(player, 5) position = 5 if (player.position == 7): self.setPlayerPosition(player,15) position = 15 if (player.position in (17, 22)): self.setPlayerPosition(player,25) position = 25 if (player.position == 33): self.setPlayerPosition(player,35) position = 35 elif(card.event == 7): #NEEDS REVIEW: how does building.houses property work? #also not thoroughly tested. Problem with having hotel/lab #pay per property total_to_pay = 0 #get all buildings with offices/lab query = Building.gql("WHERE ANCESTOR IS :1 AND type = 'building' AND houses > 0",self.game) buildings = query.fetch(40) #find all buildings belonging to player for building in buildings: if (building.owner == player.user): if (building.houses == 5): total_to_pay += card.value2 #pay per hotel/lab else: total_to_pay += (card.value * building.houses) #pay per house/office self.transferMoney(total_to_pay,player) moneyChange = total_to_pay else: message = {'error' : 'Invalid event type. Contact a game admin.'} self.messageAll(message) sys.exit() #Finally send the message regarding the card to all players message = {'status': 'pick_up_card','player': player.turnNumber,'isChance': isChance, 'text': card.text, 'money_change' : moneyChange, 'money' : player.money, 'position' : position, 'otherPlayers' : otherPlayers, 'in_jail' : inJail, 'goojf_card' : goojf} self.messageAll(message)
def getAllBuildings(): buildings = [] for building in Building.getAllBuildings(): buildings.append(building.__dict__) return buildings