Пример #1
0
def _do_split(p_room, p_split_dir, p_config):
    """
    Internal implementation of _split_room in the specified direction.
    """
    room_dims = p_room.dims
    if p_split_dir == split_types.vertical:
        span = room_dims.w
    else:
        span = room_dims.h

    split_point = _pick_split_point(span, p_config)
    if split_point == -1:
        return None

    topleft = p_room.topleft
    dims = p_room.dims
    first_room = room()  #left or top
    second_room = room()  #bottom or right
    first_room.topleft = point(topleft.x, topleft.y)
    #remaining properties depend on split direction
    if p_split_dir == split_types.vertical:
        first_room.dims = dimensions(split_point, dims.h)
        second_room.topleft = point(topleft.x + split_point, topleft.y)
        second_room.dims = dimensions(dims.w - split_point, dims.h)
    else:
        first_room.dims = dimensions(dims.w, split_point)
        second_room.topleft = point(topleft.x, topleft.y + split_point)
        second_room.dims = dimensions(dims.w, dims.h - split_point)

    return (first_room, second_room)
Пример #2
0
def unit(pid):
    #返回单元中的房间数"building.aspx?id=34914&presellid=41853"
    urlbase = "http://zjj.sz.gov.cn/ris/bol/szfdc/"
    url = "http://zjj.sz.gov.cn/ris/bol/szfdc/" + pid
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    req1 = urllib.request.Request(url=url, headers=headers)
    response1 = urllib.request.urlopen(req1)
    result1 = response1.read().decode('utf-8')
    selector1 = etree.HTML(result1, parser=None, base_url=None)
    test = selector1.xpath('//div[@id="divShowBranch"]/a/@href')
    res = []
    for i in range(0, len(test)):
        urli = urlbase + test[i]
        req = urllib.request.Request(url=urli, headers=headers)
        response = urllib.request.urlopen(req)
        result = response.read().decode('utf-8')
        selector = etree.HTML(result, parser=None, base_url=None)
        unitsum = selector.xpath('//td/div/a/@href')
        for i in range(len(unitsum)):
            line = room.room(unitsum[i])
            line.append('\n')
            res += line
    return res
    def addRoomsToWorld(self):
        roomTypes = [
            "kitchen",
            "dinning",
            "lounge",
            "bathroom",
            "cave",
            "library",
        ]

        descriptionTypes = [
            "kitchen description",
            "dinning description",
            "lounge description",
            "bathroom description",
            "cave description",
            "library description",
        ]

        for i in self.worldMap:

            # randomly select room and description
            roomSelectedRandomly = np.random.choice(roomTypes, replace=False)

            descriptionSelectedRandomly = np.random.choice(descriptionTypes,
                                                           replace=False)

            # make a dictionary of room objects
            self.worldRooms[i] = room.room(
                roomID=i,
                name=roomSelectedRandomly,
                description=descriptionSelectedRandomly,
            )
Пример #4
0
 def where_am_i(self, option="return"):
     # returns the position of the room the person is in
     for y_axis in self.grid:
         for x_axis in y_axis:
             if x_axis.status == room.room().mark_character:
                 if option == "return":
                     return x_axis.coordinate
                 elif option == "print":
                     print(x_axis.coordinate)
Пример #5
0
    def __init__(self, h, w):
        self.width = w
        self.height = h
        visited_rooms = []
        self.rooms = []
        for i in range(h):
            visited_rooms += [[]]
            self.rooms += [[]]
            for j in range(w):
                visited_rooms[i] += [False]
                self.rooms[i] += [
                    room.room([False, False, False, False], [], [])
                ]

        stack = []
        current_x = 0
        current_y = 0
        while True:
            print(len(stack))
            neighbors = []
            if current_x != 0 and not visited_rooms[current_y][current_x - 1]:
                neighbors += [(current_y, current_x - 1)]
            if current_y != 0 and not visited_rooms[current_y - 1][current_x]:
                neighbors += [(current_y - 1, current_x)]
            if current_x != w - 1 and not visited_rooms[current_y][current_x +
                                                                   1]:
                neighbors += [(current_y, current_x + 1)]
            if current_y != h - 1 and not visited_rooms[current_y +
                                                        1][current_x]:
                neighbors += [(current_y + 1, current_x)]

            visited_rooms[current_y][current_x] = True
            if len(neighbors) == 0:
                if len(stack) == 0:
                    break
                current_y, current_x = stack[-1]
                stack.pop()
            else:
                stack += [(current_y, current_x)]
                new_y, new_x = random.choice(neighbors)
                if new_y == current_y + 1:
                    self.rooms[current_y][current_x].doors[2] = True
                    self.rooms[new_y][new_x].doors[0] = True
                elif new_y == current_y - 1:
                    self.rooms[current_y][current_x].doors[0] = True
                    self.rooms[new_y][new_x].doors[2] = True
                elif new_x == current_x + 1:
                    self.rooms[current_y][current_x].doors[1] = True
                    self.rooms[new_y][new_x].doors[3] = True
                elif new_x == current_x - 1:
                    self.rooms[current_y][current_x].doors[3] = True
                    self.rooms[new_y][new_x].doors[1] = True
                current_y, current_x = new_y, new_x
        for row in self.rooms:
            for i in range(len(row)):
                row[i] = copy.deepcopy(
                    random.choice(data_bank.rooms[tuple(row[i].doors)]()))
Пример #6
0
    def fromJSON(self, jobj):

        self.data = jobj["data"]

        for r in jobj["rooms"].keys():

            newroom = room.room(0, 0, "unnamed", jobj["rooms"][r])

            self.rooms.update({newroom.getroomid(): newroom})
Пример #7
0
def roomStart(current_player):
    return room.room(
        "the royal kitchen",
        "you are a young servant known as " + current_player.name +
        ".\nYou have fallen ill to a grave illness and have decided to leave\nyour terrible life and seek fame and fortune.",
        0, [
            itemDict["bread"], itemDict["fish"], itemDict["honey"],
            itemDict["chicken"], itemDict["kitchenknife"], itemDict["caviar"],
            itemDict["oyster"]
        ], ["Go forward", "Take an item"])
Пример #8
0
    def newroom(self, name="unnamed"):

        # acquire new room id
        newroomid = self.data["ridcount"]
        self.data["ridcount"] += 1

        # create new room
        newroom = room.room(self.getid(), newroomid, name)

        # update zone room dict
        self.rooms.update({newroomid: newroom})
Пример #9
0
 def createroom(self, name, icon, maxplayers, matchoverscore, pwd=None):
     r = room()
     r.name = name
     r.icon = icon
     r.maxplayers = maxplayers
     r.matchoverscore = matchoverscore
     r.pwd = pwd
     # r.onclientdisconnected = onclientdisconnected
     self.rooms[r.id] = r
     self.updatesortedrooms()
     return r
	def __init__(self, grid_size, hero_instance):
		self.map_size = grid_size
		self.map = map(grid_size=self.map_size)
		self.hero = hero_instance
		self.ai = AI_class(hero_instance=self.hero, map_instance=self.map)
		self.fight = Fight(hero=self.hero, is_Ai=True)
		self.room = room()
		self.round_count = 0
		self.game_active = True
		self.round_max = 5
		self.stop_value = self.map_size**2
Пример #11
0
    def __init__(self, file_name=None, exclude_list=[]):
        self.elements = []
        # if you have a filename, just fetch the room list from the file
        # else go to the server to fetch it
        if file_name is None:
            # this is the url that is used to figure out the rooms for each of the buildings
            # you may not like it, but this is what peak performance looks like lmao
            # (it's really not peak performance)
            building_search_url = "https://ace.utoronto.ca/ws/f?p=210:1"
            building_request = requests.get(building_search_url)

            # now we have to parse the html
            building_soup = bs(building_request.text, features="html.parser")
            # this list generation compiles all of the building codes to be used to determine the rooms
            building_list = [
                building['value']
                for building in building_soup.find_all('option')
                if 'null' not in building['value']
            ]

            # given all of the building codes, we can determine all of the rooms for a particular building
            # and store every room number and building code combination as a room
            for building in building_list:
                # fetch the rooms for each building from the url
                room_search_url = "https://ace.utoronto.ca/ws/f?p=210:1:::::P1_BLDG:{}".format(
                    building)
                room_number_request = requests.get(room_search_url)
                room_number_soup = bs(room_number_request.text,
                                      features="html.parser")
                # a slightly inefficient way of gathering all of the rooms for a given building
                # should probably be reworked as well to run faster
                room_number_list = [
                    room_number['value']
                    for room_number in room_number_soup.find_all('option')
                    if 'null' not in room_number['value']
                    and room_number['value'] not in building_list
                ]
                # print room_number_list
                # this constructs the rooms from the numbers and adds them to the elements
                for room_number in room_number_list:
                    self.elements.append(room.room(building, room_number))

                # this is just for testing purposes, will be removed soon enough
                # break

            # now we write the results we fetched to a json for caching reasons
            self.store_info_to_file("room_info.json")

        # this is the else, it's a bit easier to follow logically
        else:
            self.load_info_from_file(file_name)
        # sort it before you leave to save yourself some trouble
        self.sort_by_capacity(ascending=False)
Пример #12
0
    def grid_generator(self):
        # one grid with all the room-instances
        # its a two dimensional array, "outer array" is y-axis and the y-axis elements
        # are the x-"axises" and the x-axis elements

        number = self.grid_size + 2
        rooms_grid = []

        for y in range(number):
            row_rooms = []
            for x in range(number):
                if x is not 0 and x is not max(range(number)):
                    if y is not 0 and y is not max(range(number)):
                        z = x + y
                        z = room.room(coordinate=[y, x],
                                      status=room.room().room_character,
                                      edge=False)
                        row_rooms.append(z)
                    else:
                        z = x + y
                        z = room.room(coordinate=[y, x],
                                      status=room.room().edge_character,
                                      edge=True)
                        row_rooms.append(z)
                else:
                    z = x + y
                    z = room.room(coordinate=[y, x],
                                  status=room.room().edge_character,
                                  edge=True)
                    row_rooms.append(z)

            rooms_grid.append(row_rooms)

        return rooms_grid
Пример #13
0
def init_game():
    current_deck = shuffle(original_deck)

    my_room = room.room()
    my_room.publisher(current_status=0,
                      players=[''],
                      player_status='',
                      stack_status=[''],
                      deck_status=list_indices(current_deck))

    time.sleep(1)
    refresh = threading.Thread(target=my_room.refresher)
    refresh.start()
    print("- room initialising -\n")
    return join_room(my_room=my_room, through_init=True)
Пример #14
0
 def loadcontent(self):
     self.map = [[ Tile(False)
     for y in range(self.height) ]
         for x in range(self.width) ]
     for objd in self.objs:
         self.batch.add(objd)
     self.char.roll()
     
     self.tes = room(5, 5, 30, 25)
     enter = self.tes.getEnter()
     # self.char.setLoc([enter[0] + self.tes.getX(), enter[1] + self.tes.getY() - 2])
     self.rooms = []
     self.rooms.append(self.tes)
     self.drawRoom()
     self.char.inventory[item(0,0,'yellow').key] = 0
     self.char.inventory[item(0,0,'green').key] = 0
     self.char.inventory[item(0,0,'red').key] = 0
Пример #15
0
def join_room(my_room=None, through_init=False):
    start = time.time()
    player = input("Enter your name : ")

    if not through_init:
        my_room = room.room(join=True)

        refresh = threading.Thread(target=my_room.refresher)
        refresh.start()

    player_cards, new_deck = pop_cards(deck=my_room.deck, count=5)
    my_player = playa.playa(name=player.lower(), cards=player_cards)

    print("\n- adding you to the ROOM -")
    my_room.add_player(player=my_player, deck=new_deck)

    print(f"JOINED ROOM in : {time.time() - start}s")

    time.sleep(1)
    display_cards(player=my_player)
    return my_room, my_player
Пример #16
0
    def __init__(self, building_id, numRows, *attrs):

        self.rooms = {}
        self.corridors = {}

        if attrs:
            attrs = attrs[0]
            self.id = attrs['id']
            self.stdev = attrs['info']['stdev']
            self.adjustment = attrs['info']['adjustment']

            for roomID in attrs['info']['rooms']:
                room_attributes = {
                    'id': roomID,
                    'info': attrs['info']['rooms'][roomID]
                }
                self.rooms[roomID] = room(0, numRows, room_attributes)

            for corridorID in attrs['info']['corridors']:
                corridor_attributes = {
                    'id': corridorID,
                    'info': attrs['info']['corridors'][corridorID]
                }
                self.corridors[corridorID] = corridor(0, numRows,
                                                      corridor_attributes)

        else:
            num_buildings = np.random.poisson(10, 1)[0]

            self.id = building_id
            self.building_mod = None

            self.stdev = int(np.random.poisson(50, 1)[0])
            self.adjustment = int(np.random.normal(0, 100, 1)[0])
            self.entropy = np.random.normal(0, self.stdev, numRows)

            self.num_rooms = rd.randint(1, 10)
            self.num_corrs = rd.randint(1, 15)

            self.makeRooms(numRows)
Пример #17
0
 def __init__(self, p_dims):
     self.dungeon = bintree()
     root_room = room()
     root_room.dims = p_dims
     self.dungeon.val = root_room
     self.corridors = []
Пример #18
0
    numberNext = index / 3
    j = 1
    while j <= numberNext:
        nextButton.click()
        time.sleep(2)
        j += 1
    i = 1
    while i <= 21:
        if not i in dict:
            i += 1
            continue
        path = "//*[@id='eq-time-grid']/div[2]/div/table/tbody/tr/td[3]/div/div/div/div[1]/div/table/tbody/tr[" + str(
            i) + "]/td/div/div"
        elem = driver.find_element_by_xpath(path)
        columns = elem.find_elements_by_class_name('s-lc-eq-avail')
        r = room(columns, dict[i], startDate)
        rooms.append(r)
        i += 1
    ############test

    ##########################

    #algorithm
    r
    if chosen == 1:
        r = chooseRoom(rooms, startTime)
        if r == None:
            r = chooseRandomroom(rooms, startTime)
            if r != None:
                print(r.get_attribute('title') + "     Random")
Пример #19
0
    def makeRooms(self, numRows):
        for i in range(self.num_rooms):
            self.rooms[i] = room(i, numRows)

        for i in range(self.num_corrs):
            self.corridors[i] = corridor(i, numRows)
Пример #20
0
my_name = raw_input("Name: ")
my_player = player(my_name)

shore_scene= """
shore
"""

forest_scene="""
forest
"""

clif_scene="""
clif
"""

room1 = room("Shoreline", shore_scene)
room2 = room("Forest", forest_scene)
room3 = room("Clif", clif_scene)

print "%s, you were just on an amazing cruise, but the ship was poorly managed. " % my_player.whoami()
print "As a result the crew was not taken care of and in turn did not take work hard"
print "or take care of the ship, the culmination of these efforts, or lack thereof"
print "lead to the ship running into troublesome waters and no one took any of the"
print "appropriate measures, therefore it was destoryed and lost at sea."
print "You somehow managed to get to an deserted island and pass out from exhaustion."
print "There endless %s to your right, a dense %s up ahead, and steep rock %s to your left." % ( room1.getName(), room2.getName(), room3.getName() )

while True:
	print "Which way do you go?"
	next_room = raw_input("> ")
Пример #21
0
 def createRoom(self, userid, room_name):
     self.last_id_room += 1
     self.rooms.append(room.room(self.last_id_room, room_name))
     return self.last_id_room
Пример #22
0
# -*- coding: utf-8 -*-
from client import client
from room import room
from sattlements import sattlements

a1=client(1, 1, 'Иванов', 'Иван', "Иванович", "6514 250550", '-')
b1=room(1, '301', 'Двухместный', 'Трехзвездочный', 4200)
typeOfClient = type(a1)
c1=sattlements(1, a1, b1, '12.11.2017', '14.11.2017', '-')
Пример #23
0
import room

rom = room.room()

rom.frontdoor()
Пример #24
0
 def newRec (self,  code=0, number='', numperson='', comf='', prize=0):self.appendList(room(code, number, numperson, comf, prize))
 def getNumber (self, code):return self.findByCode(code).getNumber()
Пример #25
0
import player
import objects
import room
import menu

if __name__== '__main__':
  pygame.init()
  screen = pygame.display.set_mode((350,350))
  pygame.display.set_caption('Witch')
  #pygame.display.toggle_fullscreen()
  screen.fill((255,255,255))
  mousepos = (0,0)
  mousebutton = 0
  room = room.room((14*64,8*64),('resources/tilemaps/grassmap','resources/tilemaps/fencemap'),(0,0), player.player((100,100),(32,128),(32,8),(0,120),3), {'up':pygame.K_UP, 'down':pygame.K_DOWN, 'left':pygame.K_LEFT, 'right':pygame.K_RIGHT}, [
	objects.obj((20,20),(20,64*5),None,(22,64*8),(0,0)),
	objects.obj((20+64*13,20),(0,0),None,(22,64*8),(0,0)),
	objects.obj((20,40),(64*14,20),None,(64*14,22),(0,0)),
	objects.tile_object((0,64*7),(64*14,64),'resources/tilemaps/fences_v',(64*14,22),(0,40))])

  font = pygame.font.Font('resources/PressStart2P-Regular.ttf',14)

  menu = menu.menu('resources/PressStart2P-Regular.ttf',14,'god is real',[menu.menu_item(),menu.menu_item()])

  debug = False
  
  running = True
  clock = pygame.time.Clock()

  while running:
    clock.tick(50)
Пример #26
0
import json
import room

rooms_file = open("rooms.json", "r")
rooms_json = json.load(rooms_file)

rooms = dict()

for current_room in rooms_json:
    container = rooms_json[current_room]
    descriptions = container["Description"]
    commands = container["Commands"]
    rooms[current_room] = room.room(current_room, descriptions, commands)

current = "Home"

print(rooms[current])
while True:
    current, command = rooms[current].command_rules(current)
    if command != None:
        print(command)
    else:
        print(rooms[current])
Пример #27
0
        self.x = self.next_x
        self.y = self.next_y
        self.appearence = '§§'
        self.current_frame = 0


ennemies = {
    'skull': lambda x, y: ennemy.ennemy('00', (x, y), 1, 50, skull_ai),
    'alien': lambda x, y: ennemy.ennemy(')(', (x, y), 2, 1, alien_ai),
    'mouthless': lambda x, y: ennemy.ennemy('¤¤', (x, y), 1, 1, mouthless_ai),
    'genie': lambda x, y: ennemy.ennemy('§§', (x, y), 2, 2, genie_ai)
}

rooms = {
    (False, False, False, True): [
        room.room((False, False, False, True),
                  [ennemies['skull'](27, 1), ennemies['skull'](27, 8)])
    ],
    (False, False, True, False): [
        room.room((False, False, True, False),
                  [ennemies['genie'](27, 1), ennemies['mouthless'](1, 1)])
    ],
    (False, False, True, True):
    [room.room((False, False, True, True), [ennemies['skull'](27, 1)])],
    (False, True, False, False): [
        room.room((False, True, False, False),
                  [ennemies['mouthless'](1, 1), ennemies['genie'](1, 8)])
    ],
    (False, True, False, True): [
        room.room((False, True, False, True),
                  [ennemies['skull'](13, 1), ennemies['skull'](13, 8)])
    ],
Пример #28
0
def create_room():
	x = random.randint(0, len(rooms) - 2)
	r  = room(rooms[x][0], rooms[x][1], rooms[x][2], rooms[x][3])
	y = create_enemy()
	r.entity.append(y)
	return room
Пример #29
0
def main():
    game_over = False
    game__over=False
    rows, cols = 15, 15
    borders = 0
    dirty_tiles=0
    while(rows >= 15 or cols >= 15 or rows==0 or cols==0 or borders==0 or dirty_tiles==0):
        try:

            layout = [  [sg.Text('Necessary Inputs')],
            [sg.Text('Please enter number of rows as an integer:'), sg.InputText()],
            [sg.Text('Please enter number of cols as an integer:'), sg.InputText()],
            [sg.Text('Please enter number of dirty tiles:'), sg.InputText()],
            [sg.Text('Please enter number of borders:'), sg.InputText()],
            [sg.Text('Speed:'),sg.Slider(range=(1000,30),default_value=1000,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Text('Window dirt Period'),sg.Slider(range=(2,10),default_value=5,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Text('Agent Period'),sg.Slider(range=(2,10),default_value=5,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Spin([i for i in range(1,5)], initial_value=1), sg.Text('Cleaning Agents')],
            [sg.Spin([i for i in range(0,5)], initial_value=0), sg.Text('Dirt Agents')],
            [sg.Frame(layout=[
            [sg.Radio('Case1 (Fully observable map and once generated dirt):', "Case1", default=False)],
            [sg.Radio('Case2 (Fully observable map and continuously added dirt):', "Case1", default=False)],
            [sg.Radio('Case3 (Fully observable borders and unknown dirt positions):', "Case1", default=False)],
            [sg.Radio('Case4 (Unknown borders and dirt positions):', "Case1", default=False)],

            [sg.Checkbox('Alternate Dirt Algorithm',  default=False)],
            [sg.Checkbox('Box In',  default=False)]],

            title='Choose Any of these Cases',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
            [sg.Submit()]]
            window = sg.Window('Vacuum Cleaner Agent', layout)
            event, values = window.Read()
            case1=values[9]
            case2=values[10]
            case3=values[11]
            case4=values[12]
            
            intelligenceDirtFirst=values[13]

            boxIn = values[14]
            
            rows=int(values[0])
            cols=int(values[1])
            dirty_tiles= int(values[2])
            borders=int(values[3])
            globals.globals.speed=int(values[4])
            globals.globals.frequency=int(values[5])
            globals.globals.period=int(values[6])
            globals.globals.cleaning_agents=int(values[7])
            globals.globals.dirt_agents=int(values[8])
            if event in ('Submit'):
                print('Borders are placed randomly')
            window.Close()
        except ValueError:
            print("No valid integer! Please try again ...")
    CELL_SIZE = 40
    window_size = [cols * CELL_SIZE, rows * CELL_SIZE]


    pygame.init()

    window = pygame.display.set_mode(window_size)
    pygame.display.set_caption("Vacuum Cleaner Agent")
    run = True
    clock = pygame.time.Clock()
    r = room(CELL_SIZE, rows, cols, window)
    r.draw_grid()
    r.draw_borders(borders)
    vacuums = []
    dirt_machines = []

    for x in range(globals.globals.cleaning_agents):
        vacuums.append(vacuum(r, window, x))
        print("creating vacuum with ID: ",  x)

    if(globals.globals.dirt_agents > 0):
        for x in range(globals.globals.dirt_agents):
            dirt_machines.append(dirt_machine(r, window, x))
            print("creating dirt machine with ID: ", x)
    else:
        pass
    # print(dirt_machines)
    d = dirt(r, window, dirty_tiles)

    pos = None
    mySolver = solver(r.get_array())

    tempLastLoc = None
    pos2 = None

    globals.globals.start_duration = datetime.now().timestamp()

    

# depending on the Specific case
    if(case1):  # fully observable with set amount of dirt
        while run:

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)
            for event in pygame.event.get():

                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    game_over = True
                    r.clear_room()
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)
                    vacuums[0].move_left()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT:
                        v.move_left()
                    if event.key == pygame.K_RIGHT:
                        v.move_right()
                    if event.key == pygame.K_UP:
                        v.move_up()
                    if event.key == pygame.K_DOWN:
                        v.move_down()
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            if(not game_over):
                
                if(not intelligenceDirtFirst):
                    for x in vacuums:
                        x.move_to_closest_dirt()
                
                
                
                if(globals.globals.dirt_agents != 0):
                    if(intelligenceDirtFirst):
                       #Alternate Algrthm 
                        paths = mySolver.getFirstPathForDirt(r,dirt_machines,vacuums, boxIn)
                       
                        index = -1
                        if(not paths is None):
                            
                            m = len(paths[0])
                            for p in paths:
                                if(len(p) < m):
                                    m = len(p)
                            
                            for idx in range(0,m):
                                for pathX in paths:
                                    index += 1

                                    if( pathX is None or pathX == [] or len(pathX) == 0 or pathX[0] == None):
                                        continue

                                    if(idx >= len(pathX)):
                                        continue    

                                    try:
                                        
                                        didMove = False

                                        if(pathX[idx] == 'L'):
                                            dirt_machines[index].move_left()
                                            didMove = True
                                        if(pathX[idx] == 'U'):
                                            dirt_machines[index].move_up()
                                            didMove = True
                                        if(pathX[idx] == 'D'):
                                            dirt_machines[index].move_down()
                                            didMove = True
                                        if(pathX[idx] == 'R'):
                                            dirt_machines[index].move_right()
                                            didMove = True

                                       # if(idx >= 1):
                                        for x in vacuums:
                                            x.move_to_closest_dirt()
                            
                                        if( intelligenceDirtFirst):
                                            pygame.time.delay(globals.globals.speed)

                                    except Exception:
                                        pass
                                    
                                    

                                
                                
                    else:
                        for x in dirt_machines:
                            x.move_from_closest_dirt()


    elif(case2):  # fully observable and dirt keeps getting added
        count = 0
        while run:
            if(count == globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            
            if(not intelligenceDirtFirst):
                pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():

                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    game_over = True
                    r.clear_room()
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)
                    vacuums[0].move_left()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
            if(not game_over):
                
                if(not intelligenceDirtFirst):
                    for x in vacuums:
                        x.move_to_closest_dirt()
                
                
                
                if(globals.globals.dirt_agents != 0):
                    if(intelligenceDirtFirst):
                       #Alternate Algrthm 
                        paths = mySolver.getFirstPathForDirt(r,dirt_machines,vacuums, boxIn)
                       
                        index = -1
                        if(not paths is None):
                            
                            m = len(paths[0])
                            for p in paths:
                                if(len(p) < m):
                                    m = len(p)
                            
                            for idx in range(0,m):
                                for pathX in paths:
                                    index += 1

                                    if( pathX is None or pathX == [] or len(pathX) == 0 or pathX[0] == None):
                                        continue

                                    if(idx >= len(pathX)):
                                        continue    

                                    try:
                                        
                                        didMove = False

                                        if(pathX[idx] == 'L'):
                                            dirt_machines[index].move_left()
                                            didMove = True
                                        if(pathX[idx] == 'U'):
                                            dirt_machines[index].move_up()
                                            didMove = True
                                        if(pathX[idx] == 'D'):
                                            dirt_machines[index].move_down()
                                            didMove = True
                                        if(pathX[idx] == 'R'):
                                            dirt_machines[index].move_right()
                                            didMove = True

                                       # if(idx >= 1):
                                        for x in vacuums:
                                            x.move_to_closest_dirt()
                            
                                        if( intelligenceDirtFirst):
                                            pygame.time.delay(globals.globals.speed)

                                    except Exception:
                                        pass
                                    
                                    

                                
                                
                    else:
                        for x in dirt_machines:
                            x.move_from_closest_dirt()

            count += 1

    #Partially visible in HERE
    elif(case3):

        dirtMachineIntelligence = 0
        if(intelligenceDirtFirst):
            dirtMachineIntelligence = 1

        path = []
        pathDirt = []

        count = 0

        mySolver.expoloreAllBorders()

        cyclesStuckCount = [1]
        cycleStuckPos = [ [0,0] ]

        cyclesStuckCountDirt = [1]
        cycleStuckPosDirt = [ [0,0] ]

        while run:

            if(count >= globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            #FOR DEBUGGING
            #NOTE TO SELF => REMOVE LATER ON
            #d.rnd_dirt_DEBUG(1)
            count += 1
            #////////////////////////////////////

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():
                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    game__over=True
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    r.clear_room()
                    path=["R","R","R","R"]
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            index = -1
            for v in vacuums:

                index += 1
                if(len(path) < index + 1):
                    path.append([])
                if(len(cyclesStuckCount) < index + 1):
                    cyclesStuckCount.append(1)
                    cycleStuckPos.append( [0,0] )

                if(pos2 is None):
                    pos2 = r.vacuum_position(index)

                pos2 = copy.deepcopy ( r.vacuum_position(index) )
                #pos2 = r.vacuum_position()

                pos2 = mySolver.dirtPathIterator( copy.deepcopy( pos2 ) )

                #print("pos 2")
                #print(pos2)

                if(not game__over):
                    path[index] = mySolver.getLastActualUsedPath()
                    #machine.move_from_closest_dirt()


                # Take care of dynmaic collision

                #if stuck by other agent abort mission
                if(cyclesStuckCount[index] > 1):
                    #print(cycleStuckPos[index])
                    cyclesStuckCount[index] = 1
                    mySolver.escapeFromAgent(r.vacuum_position(index), cycleStuckPos[index] )
                    path[index] = mySolver.getLastActualUsedPath();

            if(dirtMachineIntelligence == 0):
                index = -1
                for _ in dirt_machines:

                    index += 1
                    if(len(pathDirt) < index + 1):
                        pathDirt.append([])
                    if(len(cyclesStuckCountDirt) < index + 1):
                        cyclesStuckCountDirt.append(1)
                        cycleStuckPosDirt.append( [0,0] )

                    if(pos2 is None):
                        pos2 = r.dirt_machine_position(index)

                    pos2 = copy.deepcopy ( r.dirt_machine_position(index) )
                    #pos2 = r.vacuum_position()

                    pos2 = mySolver.addDirtPathIterator( copy.deepcopy( pos2 ) )

                    #print("pos 2")
                    #print(pos2)

                    if(not game__over):
                        pathDirt[index] = mySolver.getLastActualUsedPath()
                        #machine.move_from_closest_dirt()


                    # Take care of dynmaic collision

                    #if stuck by other agent abort mission
                    if(cyclesStuckCountDirt[index] > 1):
                        #print(cycleStuckPos[index])
                        cyclesStuckCountDirt[index] = 1
                        mySolver.escapeFromAgent(r.dirt_machine_position(index), cycleStuckPosDirt[index] )
                        pathDirt[index] = mySolver.getLastActualUsedPath();


            m = len(path[0])
            for p in path:
                if(len(p) < m):
                    m = len(p)

            if(dirtMachineIntelligence == 0):
                for p in pathDirt:
                    if(len(p) < m):
                        m = len(p)



            for idx in range(0,m):

                index = -1
                for pathX in path:

                    index += 1

                    #print(index)
                    #print(idx)

                    p = pathX[idx]

                    # Take care of dynmaic collision
                    if( not p in vacuums[index].get_valid_moves() ):
                        #print("Vacuum Was Gonna Hit")
                        #exit(0)
                        cyclesStuckCount[index] += 1

                        deltX = 0
                        deltaY = 0
                        if(p == "L"):
                            deltX = -1
                        elif(p == "R"):
                            deltX = 1
                        elif(p == "U"):
                            deltaY = -1
                        elif(p == "D"):
                            deltaY = 1

                        cycleStuckPos[index] = [r.vacuum_position(index)[0] + deltaY, r.vacuum_position(index)[1] + deltX, ]

                        continue;


                    if(p == "L"):
                        vacuums[index].move_left()
                    elif(p == "R"):
                        vacuums[index].move_right()
                    elif(p == "U"):
                        vacuums[index].move_up()
                    elif(p == "D"):
                        vacuums[index].move_down()

                    mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )

                    # if(globals.globals.dirt_agents != 0):
                    #     for x in dirt_machines:
                    #         x.move_from_closest_dirt()
                    # else:
                    #     pass

                    #if(not game__over and globals.globals.dirt_agents > 0):
                    #    dirt_machines[0].move_from_closest_dirt()

                if(dirtMachineIntelligence == 0):
                    index = -1
                    for pathX in pathDirt:

                        index += 1

                        if(isVacuumNeghbr(r,vacuums, r.dirt_machine_position(index), boxIn )):
                            continue

                        p = pathX[idx]

                        # Take care of dynmaic collision
                        if( not p in dirt_machines[index].get_valid_moves() ):
                            #print("Vacuum Was Gonna Hit")
                            #exit(0)
                            cyclesStuckCountDirt[index] += 1

                            deltX = 0
                            deltaY = 0
                            if(p == "L"):
                                deltX = -1
                            elif(p == "R"):
                                deltX = 1
                            elif(p == "U"):
                                deltaY = -1
                            elif(p == "D"):
                                deltaY = 1

                            cycleStuckPosDirt[index] = [r.dirt_machine_position(index)[0] + deltaY, r.dirt_machine_position(index)[1] + deltX, ]

                            continue;


                        if(p == "L"):
                            dirt_machines[index].move_left()
                        elif(p == "R"):
                            dirt_machines[index].move_right()
                        elif(p == "U"):
                            dirt_machines[index].move_up()
                        elif(p == "D"):
                            dirt_machines[index].move_down()
                        
                        dirt_machines[index].incrementCountForDirt(8)


                if(dirtMachineIntelligence == 1):
                    for mac in dirt_machines:
                        mac.move_from_closest_dirt()

                pygame.time.delay(globals.globals.speed)

            #pos2 = r.vacuum_position();

            pygame.display.update()

    elif(case4):

        path = []

        count = 0

        dirtMachineIntelligence = 0
        if(intelligenceDirtFirst):
            dirtMachineIntelligence = 1

        cyclesStuckCount = [1]
        cycleStuckPos = [ [0,0] ]

        tempLastLoc = []

        pathDirt = []

        cyclesStuckCountDirt = [1]
        cycleStuckPosDirt = [ [0,0] ]

        while run:

            if(count >= globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            #FOR DEBUGGING
            #NOTE TO SELF => REMOVE LATER ON
            #d.rnd_dirt_DEBUG(1)
            count += 1
            #////////////////////////////////////

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():
                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    game__over=True
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    r.clear_room()
                    path=["R","R","R","R"]
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    v.set_position((rows//2)+1,(cols//2)-3)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                       pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            #EXPLORE MAP CODE

            index = -1
            for v in vacuums:

                index += 1
                if(len(path) < index + 1):
                    path.append([])
                if(len(cyclesStuckCount) < index + 1):
                    cyclesStuckCount.append(1)
                    cycleStuckPos.append( [0,0] )
                if(len(tempLastLoc) < index + 1):
                    tempLastLoc.append( [] )

                #if(index > 1):
                #    print("Impossible Indx")
                #    exit(0)

                if (pos is None or not pos[0] == -1):

                    if(not pos is None):
                        tempLastLoc[index] = copy.deepcopy( pos )


                    pos = mySolver.discoverMapIter( copy.deepcopy(r.vacuum_position(index)) )
                    #print('target pos: ' + str(pos) )


                    if(not game__over):
                        path[index] = mySolver.getLastActualUsedPath()

                    #print('path: ' + str(path) )
                    #print(r.vacuum_position() )


                else:

                    #print("Dirt Phase")

                    if(pos2 is None):
                        pos2 = tempLastLoc[index]



                    pos2 = mySolver.dirtPathIterator( copy.deepcopy( r.vacuum_position(index) ) )

                    #pos2 = mySolver.dirtPathIterator( copy.deepcopy( pos2 ) )


                    #print("pos 2")
                    #print(pos2)
                    if(not game__over):
                        path[index] = mySolver.getLastActualUsedPath()

                pst = [-1,-1]
                #if stuck by other agent abort mission
                if(cyclesStuckCount[index] > 1):
                    #print("getting out")
                    cyclesStuckCount[index] = 1
                    pst = mySolver.escapeFromAgent(r.vacuum_position(index), cycleStuckPos[index] )
                    path[index] = mySolver.getLastActualUsedPath();
                    #print("agent")
                    #print(index)
                    #print(pst)

                #print(index)
                #print("My pos")
                #print(r.vacuum_position(index))
                #print("dest")
                #if(pst[0] == -1):
                #    print(pos2)
                #else:
                #    print(pst)
                #print("path")
                #print(path[index])

            if(dirtMachineIntelligence == 0):
                index = -1
                for _ in dirt_machines:

                    index += 1
                    if(len(pathDirt) < index + 1):
                        pathDirt.append([])
                    if(len(cyclesStuckCountDirt) < index + 1):
                        cyclesStuckCountDirt.append(1)
                        cycleStuckPosDirt.append( [0,0] )

                    if(pos2 is None):
                        pos2 = r.dirt_machine_position(index)

                    pos2 = copy.deepcopy ( r.dirt_machine_position(index) )
                    #pos2 = r.vacuum_position()

                    pos2 = mySolver.addDirtPathIterator( copy.deepcopy( pos2 ) )

                    #print("pos 2")
                    #print(pos2)

                    if(not game__over):
                        pathDirt[index] = mySolver.getLastActualUsedPath()
                        #machine.move_from_closest_dirt()


                    # Take care of dynmaic collision

                    #if stuck by other agent abort mission
                    if(cyclesStuckCountDirt[index] > 1):
                        #print(cycleStuckPos[index])
                        cyclesStuckCountDirt[index] = 1
                        mySolver.escapeFromAgent(r.dirt_machine_position(index), cycleStuckPosDirt[index] )
                        pathDirt[index] = mySolver.getLastActualUsedPath();


            #END OF EXPLORATION

            #print("paths")
            #print(path[0])
            #print(path[1])

            m = len(path[0])
            for p in path:
                if(len(p) < m):
                    m = len(p)

            if(dirtMachineIntelligence == 0):
                for p in pathDirt:
                    if(len(p) < m):
                        m = len(p)

            if(m < 2):
                m = 3

            #print("M value")
            #print(m)

            for idx in range(0,m):

                index = -1
                for pathX in path:

                    index += 1

                    #print(index)
                    #print(idx)

                    if(idx >= len(pathX)):
                        continue


                    p = pathX[idx]

                    #mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )
                    #print("in pathX loop")

                    if( not p in vacuums[index].get_valid_moves() ):
                       # print(p + " Vacuum Was Gonna Hit")
                        #exit(0)

                        cyclesStuckCount[index] += 1

                        deltX = 0
                        deltaY = 0
                        if(p == "L"):
                            deltX = -1
                        elif(p == "R"):
                            deltX = 1
                        elif(p == "U"):
                            deltaY = -1
                        elif(p == "D"):
                            deltaY = 1

                        cycleStuckPos[index] = [r.vacuum_position(index)[0] + deltaY, r.vacuum_position(index)[1] + deltX ]

                        #print(cycleStuckPos[index])

                        #print(cyclesStuckCount[index])

                        continue;

                    if(p == "L"):
                        vacuums[index].move_left()
                    elif(p == "R"):
                        vacuums[index].move_right()
                    elif(p == "U"):
                        vacuums[index].move_up()
                    elif(p == "D"):
                        vacuums[index].move_down()

                    #print("moved vacuum " + str(index) )


                    mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )

                    #if(not game__over):
                    #    machine.move_from_closest_dirt()

                if(dirtMachineIntelligence == 0):
                    index = -1
                    for pathX in pathDirt:

                        index += 1

                        if(isVacuumNeghbr(r,vacuums, r.dirt_machine_position(index) , boxIn)):
                            continue

                        if(idx >= len(pathX)):
                            continue

                        p = pathX[idx]

                        # Take care of dynmaic collision
                        if( not p in dirt_machines[index].get_valid_moves() ):
                            #print("Vacuum Was Gonna Hit")
                            #exit(0)
                            cyclesStuckCountDirt[index] += 1

                            deltX = 0
                            deltaY = 0
                            if(p == "L"):
                                deltX = -1
                            elif(p == "R"):
                                deltX = 1
                            elif(p == "U"):
                                deltaY = -1
                            elif(p == "D"):
                                deltaY = 1

                            cycleStuckPosDirt[index] = [r.dirt_machine_position(index)[0] + deltaY, r.dirt_machine_position(index)[1] + deltX, ]

                            continue;


                        if(p == "L"):
                            dirt_machines[index].move_left()
                        elif(p == "R"):
                            dirt_machines[index].move_right()
                        elif(p == "U"):
                            dirt_machines[index].move_up()
                        elif(p == "D"):
                            dirt_machines[index].move_down()

                        dirt_machines[index].incrementCountForDirt(8)


                        #print("moved machine " + str(index) )

                if(dirtMachineIntelligence == 1):
                    for mac in dirt_machines:
                        mac.move_from_closest_dirt()

                pygame.time.delay(globals.globals.speed)

            path[index] = []
            if(dirtMachineIntelligence == 0):
                pathDirt[index] = []
           

            #print("idx loop")

            pygame.display.update()



    pygame.quit()
Пример #30
0
 def load_info_from_file(self, file_name):
     with open(file_name, 'r') as f:
         self.elements = [room.room(dict_=dict_) for dict_ in json.load(f)]
Пример #31
0
def DN_iteration(nx, ny, theta = 0.7, maxiter = 100, tol = 1e-10, plot = True):
    ## nx & ny = number of interior unknowns per unit length
    temp_wall = 15
    temp_heater = 40
    temp_window = 5
    
    dx, dy = 1/(nx + 1), 1/(ny + 1)
    
    ## set up rooms and their static boundary conditions
    room1 = room(nx + 1, ny , dx, dy)
    room1.add_boundary('D', 'left', temp_heater)    
    room1.add_boundary('D', 'top', temp_wall)    
    room1.add_boundary('D', 'bottom', temp_wall)
    
    room2 = room(nx, 2*ny+1, dx, dy)
    room2.add_boundary('D', 'top', temp_heater)
    room2.add_boundary('D', 'bottom', temp_window)
    
    room3 = room(nx + 1, ny, dx, dy)
    room3.add_boundary('D', 'right', temp_heater)    
    room3.add_boundary('D', 'top', temp_wall)    
    room3.add_boundary('D', 'bottom', temp_wall)
    
    
    ## set initial condition for boundaries in room2
    temp_gamma_1_old = np.ones(ny)*temp_wall
    temp_gamma_2_old = np.ones(ny)*temp_wall
    
    
    updates1, updates2 = [], []
    for k in range(maxiter):
        ## step1: add dirichlet boundaries for room2
        room2.add_boundary('D', 'left',
                           np.pad(temp_gamma_1_old, (0, ny + 1), mode = 'constant', constant_values = temp_wall)) ## pad up values to fit whole wall
        room2.add_boundary('D', 'right',
                           np.pad(temp_gamma_2_old, (ny + 1, 0), mode = 'constant', constant_values = temp_wall)) ## pad up values to fit whole wall
        
        ## step 2: solve room2
        room2.solve()
        
        ## step 3: get heat fluxes
        flux_gamma_1 = room2.get_flux('left')
        flux_gamma_2 = room2.get_flux('right')
        
        ## step 4: cut to length
        flux_gamma_1 = flux_gamma_1[:ny]
        flux_gamma_2 = flux_gamma_2[-ny:]
        
        ## step5: add fluxes as boundaries to room1 and room3
        room1.add_boundary('N', 'right', -flux_gamma_1)
        room3.add_boundary('N', 'left', -flux_gamma_2)
        
        ## step6: solve room1 and room3
        room1.solve()
        room3.solve()
        
        ## step7: get new boundary values
        temp_gamma_1_new = room1.get_solution(where = 'right')
        temp_gamma_2_new = room3.get_solution(where = 'left')
        
        ## step8: relaxation and update solutions
        temp_gamma_1_old = (1-theta)*temp_gamma_1_old + theta*temp_gamma_1_new
        temp_gamma_2_old = (1-theta)*temp_gamma_2_old + theta*temp_gamma_2_new
        
        ## step9: compute updates
        ## TODO: possibly use different norm, e.g., discrete L2 norm?
        updates1.append(np.linalg.norm(temp_gamma_1_old - temp_gamma_1_new, 2))
        updates2.append(np.linalg.norm(temp_gamma_2_old - temp_gamma_2_new, 2))
        
        ## step10: check if iteration has converged via updates
        if (updates1[-1] < tol) and (updates2[-1] < tol):
            break
        
    if plot: ## currently assuming
        if dx != dy:
            raise ValueError('plotting currently not implemented for dx != dy')
        A = np.zeros((3*(nx+1) + 1, 2*(nx+1) + 1))
        n = nx + 1
        
        # Standard walls 
        A[:n+1, 0] = temp_wall
        A[:n+1, n] = temp_wall
        A[n, n:] = temp_wall
        A[2*n:, -1] = temp_wall
        A[2*n:,n] = temp_wall
        A[2*n, :n] = temp_wall
        # Window front
        A[n+1:2*n, 0] = temp_window
        # Heaters
        A[0, 1:n] = temp_heater
        A[-1, n+1:-1] = temp_heater
        A[n+1:2*n, -1] = temp_heater
        ## rooms
        # TODO: make sure these are in the correct shapes
        A[1:n+1, 1:n] = room1.get_solution()
        A[n+1:2*n, 1:-1] = room2.get_solution()
        A[2*n:-1, n+1:-1] = room3.get_solution()
        
        ## boundaries
        A[n, 1:n] = temp_gamma_1_old # left
        A[2*n, n+1:-1] = temp_gamma_2_old # right
        
        pl.subplots(figsize = (8, 4))
        pl.pcolor(A.transpose(), cmap = 'RdBu_r', vmin = 5, vmax = 40)
        pl.title('Heat distribution')
        pl.colorbar()
        pl.axis([0, 3/dx+1, 0, 2/dx+1])
        pl.xticks([])
        pl.yticks([])
        
    return updates1, updates2, k+1
    def close(self):
        try:
            self.connect = False
            self.socket.shutdown(socket.SHUT_RDWR)
            self.socket.close()
        except OSError:
            pass

    def __del__(self):
        print ("User " + self.uname+ " dengan id " + str(self.id) + " logout")


a = Server.Server()
game = game.game()
while True:
    handler, addr = a.socket.accept()
    CL = Client_handler(game,handler,addr)
    print("koneksi pada",addr)
    CL.recv()
    print("added username: "******" dengan id =",CL.id)
    print("Username yang sedang online:",CL.game.existing_names)
    CL.game.rooms.append(room.room(1, "haiiii"))
    CL.recv()
    CL.game.last_id_room += 1
    CL.recv()
    print("joined room: ",CL.game.rooms[CL.room_id-1].rname," dengan id =",CL.room_id)
    CL.recv()
    print("kondisi board sekarang: \n")
    print(CL.game.rooms[CL.game.user_room[CL.id]-1].board.board)
Пример #33
0
            randc('x'), randc('y'), *better_heal_items[rand(0, 2)]),
    lambda: item.HealItem(randc('x'), randc('y'), *best_heal_items[rand(0, 1)])
]

basic_heal_items = [(' Ò', 1), ('-<', 2), ('<3', 3)]

better_heal_items = [('@ ', 4), ('∴ ', 5), ('∞', 6)]

best_heal_items = [('Θ~', 9), ('♡!', 10)]

rooms = {
    (False, False, False, True):
    lambda: [
        room.room((False, False, False, True), [
            ennemies['genie'](5, 1), ennemies['mouthless']
            (7, 1), ennemies['genie'](9, 1), ennemies['genie']
            (5, 8), ennemies['mouthless'](7, 8), ennemies['genie'](9, 8)
        ], [armor_loot_tables[3](), heal_loot_tables[2]()])
    ],
    (False, False, True, False):
    lambda: [
        room.room((False, False, True, False), [
            ennemies['ogre'](27, 1), ennemies['mouthless']
            (1, 1), ennemies['alien'](27, 8)
        ], [armor_loot_tables[3](), armor_loot_tables[2]()])
    ],
    (False, False, True, True):
    lambda: [
        room.room((False, False, True, True), [
            ennemies['mouthless'](27, 1), ennemies['backstabber']
            (1, 1), ennemies['alien'](21, 5)
Пример #34
0
particles = []
A=300#num particles
B=800#y value start
for part in range(1, 300):
    if part % 2 > 0: col = white
    else: col = grey
    particles.append( Particle(100, 800, col, round(B*part/A)) )
    particles.append(Particle(1340, 800, col,round(B*part/A)) )

test_room_code = ['ffffffffffffffff','fffffffffffffffff','fffffffffffffffff',
                  'fffffffffffffffff','fffffffffffffffff','fffffffffffffffff',
                  'fffffffffffffffff','fffffffffffffffff','fffffffffffffffff',
                  'fffffffffffffffff', 'fffffffffffffffff']


test_room = room.room(test_room_code)

pc = player.player(plyr_loc)
HUD = overlays.hud(pc, disp)
hp = overlays.healthbar(pc, HUD)

test_room.addPlayer(pc)

bumper = enemies.bouncer((600, 600))
bumper.set_target(pc)
test_room.enemies.add(bumper)

#test_room.overlays.add(hp)

'''
fleye1 = enemies.fleye((500, 500))
Пример #35
0
	descriptor_index2 = random.randint(0, len(d_list) - 1)
	descriptor_index3 = random.randint(0, len(d_list) - 1)
	name_index = random.randint(0, len(names) - 1)
	new_sword  = sword(names[name_index], d_list[descriptor_index1], d_list[descriptor_index2], d_list[descriptor_index3])
	return new_sword
	
def create_player():
	p = character(creatures[0][0], creatures[0][1], creatures[0][2], creatures[0][3], creatures[0][4], creatures[0][5], creatures[0][6], creatures[0][7])
	return p


#this is the game

player = create_player()

room = room("dungeon", [], [], 0, True)
room.fill_chest()
room.add_enemy()
room.add_exit()
print(room)

print("You pick up a sword.")
new_sword = create_sword()
new_sword.view()
player.equip_sword(new_sword)

print("You have encountered a " + str(room.enemy))

running = True
player_turn = True
Пример #36
0
##### Initialize world
# Room channels
rChans = Channel() * 4
# Room layout:
#  0  1
#  3  2

# Room 0
# Add all player objects
rooms = []
rooms.append(room.room(
    'Room #0',
    rChans[0].reader(),
    {
        'N': None,
        'S': rChans[3].writer(),
        'E': rChans[1].writer(),
        'W': None
    },
    pObjects,
    'Entrance'
    ))

# Room 1
rooms.append(room.room(
    'Room #1',
    rChans[1].reader(),
    {
        'N': None,
        'S': rChans[2].writer(),
        'E': None,
        'W': rChans[0].writer()
Пример #37
0
from room import room

#Baement Stuff
laundry = room("Laundry Room")
cellar = room("Wine Cellar")
butchers = room("Butcher's Quarters")
furnace = room("Furnace Room")
stairs1 = room("Stairs from basement and first floor")

#First Floor
gallery = room("Art Gallery")
dining = room("Dining Room")
kitchen = room("Kitchen")
sunroom = room("Sunroom")
pantry = room("Pantry")
bath1 = room("Bathroom")
stairs2 = room("Down the stairs between first and second floor")

#Second Floor
bed1 = room("Boy Bedroom")
master = room("Master Bedroom")
bed2 = room("Girl Bedroom")
library = room("Library")
bath2 = room("Bathroom")
stairs3 = room("Up the stairs between the first and second floor")

#Outside
maze = room("The Maze")
garden = room("The Garden")
shed = room("Shed")
graveyard = room("Graveyard")
from npc import npc
from room import room

# Create rooms
empty = room('an empty room', 'The stone floors and walls are cold and damp.')
temple = room('a small temple',
              'There are three rows of benches facing a small statue.')
torture = room(
    'a torture chamber',
    'There is a rack and an iron maiden against the wall\nand some chains and thumbscrews on the floor.'
)
bedroom = room('a bedroom',
               'There is a large bed with black, silk sheets on it.')

# Create npcs
priest = npc('priest', 'a priestly figure in long white robes.')
priest.add_line('Hello child.')
priest.add_line('Welcome to the temple.')
priest.add_line('Please take all the time you need.')

maid = npc('maid', 'a short, plump lady with a feather duster in her hand.')
maid.add_line('Oh!')
maid.add_line('Please excuse the mess.')
maid.add_line("Sorry. I'm almost done.")

# Setup rooms
empty.add_adjacent_room('east', bedroom)
empty.add_adjacent_room('north', temple)

temple.add_adjacent_room('east', torture)
temple.add_adjacent_room('south', empty)