Esempio n. 1
0
 def __init__(self, command, owner):
     self.owner = owner
     self.subj = None
     self.verb = None
     self.target = None
     targeted_commands = r"[a-zA-V]\d+ (mov|atk|spt|inf) [a-zA-V]\d+"
     info_command = r"info [a-zA-V]\d{1,2}"
     unary_commands = r"^[A-Za-z]*$"
     if type(command) == type(b'a'):
         command = command.decode('ascii')
     if command in World.verbs:
         self.verb = command
     elif re.search(info_command, command) != None:
         #command is of the form
         #info a1
         #info z31
         #info A1
         #info V31
         words = command.split(" ")
         self.verb = "inf"
         self.subj = location(words[1])
         #self.target = None
     elif re.search(targeted_commands, command) != None:
         #command is targeted
         #a1 atk A1
         #V31 mov a1
         words = command.split(" ")
         self.subj = location(words[0])
         self.verb = words[1]
         self.target = location(words[2])
Esempio n. 2
0
 def move(
     self, moves
 ):  #location of peice to move from to each spot in array, removes pieces in way
     if moves == None:
         return 0
     if len(moves) < 2:
         #Not enough moves entered
         return 0
     peice = self.realBoard.get(moves[0])  #gets peice that is moving
     startingLocation = moves[0]
     for i in range(1, len(moves)):  #to account for starting move
         currentLocation = moves[i]
         direction = currentLocation - startingLocation  #Direction of piece moved converted to numpy for division ease
         for i in range(2):
             direction[i] = round(direction[i] / 2)
         checkLocation = p.location(
             currentLocation -
             p.location(direction))  #Location of piece hopped over
         if not np.prod(direction) == 0:  #If hopped
             if not self.realBoard.get(checkLocation)[0] == peice:
                 self.realBoard.set(checkLocation,
                                    " ")  #set blank where hopped
             else:
                 print("Move not allowed")  #Can't hop your own peice type
                 return 0
         self.realBoard.set(startingLocation, " ")  #Set old spot blank
         self.realBoard.set(currentLocation,
                            peice)  #Set new spot with piece
         startingLocation = currentLocation  #Update for next tick
     return 1
Esempio n. 3
0
    def load_game(self, file_name):
        self.players = []
        current_team_name = None
        current_team_obj = None
        with open(file_name, "r") as f:
            first_line = f.readline()
            if first_line[0] == "M":
                self.map_name = first_line.split(":")[1].rstrip()

                self.world = World(self.map_name)
                print("creating map from " + self.map_name)
                self.set_color_prefs(Game.default_prefs)
            for line in f:
                # print(line[0])
                if line[0] == "t":
                    current_team_name = line.split("-")[1].split("@")[0]
                    host, port = line.split("-")[1].split("@")[1].split(":")
                    port = int(port)
                    print("creating new team: " + current_team_name)
                    current_team_obj = Team(self.world, current_team_name)
                    self.add_player(Server_Facing_Networked_Player(self, current_team_obj, host, port))
                elif line[0] == "m":
                    loc = location(line.split("@")[1][:-1])
                    current_team_obj.create_mech(line[2:6], loc)
                elif line[0] == "s":
                    loc = location(line.split("@")[1][:-1])
                    self.world.create_station_at(loc, current_team_obj)
Esempio n. 4
0
 def updateToKings(self, board):
     for j in range(8):
         checkB = p.location(0, j)
         checkW = p.location(7, j)
         if board.get(checkB) == "b":
             board.set(checkB, "bk")
         if board.get(checkW) == "w":
             board.set(checkW, "wk")
Esempio n. 5
0
 def checkForHops(self, board):
     for i in range(8):
         for j in range(8):
             pos = p.location(i, j)
             e = board.get(pos)
             if e[0] == self.piece:
                 temp = self.findHops(e, p.location(i, j), board)
                 if temp: return temp
     return None
Esempio n. 6
0
 def do(self, turn):
     if turn.get_subj_loc() is None:
         turn.subj = location("n0")
     if turn.get_target_loc() is None:
         turn.target = location("n0")
     m = self.world.at(turn.get_subj_loc())
     if m is Mech and not m.prepped:
         m.prep()
     self.world.verbs[turn.verb](m, turn.get_target_loc())
Esempio n. 7
0
 def possibleMoves(self, startLocation, piece):
     #used to find possible moves in order to find valid moves
     #Don't directly call
     if piece == "w":
         Moves = list()
         Moves.append(
             p.location(startLocation.row() + 1,
                        startLocation.column() - 1))
         Moves.append(
             p.location(startLocation.row() + 1,
                        startLocation.column() + 1))
     elif piece == "b":
         Moves = list()
         Moves.append(
             p.location(startLocation.row() - 1,
                        startLocation.column() - 1))
         Moves.append(
             p.location(startLocation.row() - 1,
                        startLocation.column() + 1))
     else:
         Moves = list()
         Moves.append(
             p.location(startLocation.row() - 1,
                        startLocation.column() - 1))
         Moves.append(
             p.location(startLocation.row() - 1,
                        startLocation.column() + 1))
         Moves.append(
             p.location(startLocation.row() + 1,
                        startLocation.column() - 1))
         Moves.append(
             p.location(startLocation.row() + 1,
                        startLocation.column() + 1))
     return Moves
Esempio n. 8
0
    def test_location_equality_tests(self):
        a = location("chr1:1000-2000")
        b = location("chr1:1001-2000")
        c = location("chr1:1000-2001")
        d = location("chr2:1000-2000")
        e = location("chr1:1000-2000")

        self.assertEqual(a == b, False)  # internal
        self.assertEqual(a == c, False)  # internal
        self.assertEqual(a == d, False)  # internal
        self.assertEqual(a == e, True)  # internal
        self.assertEqual(a == b, False)  # internal
        self.assertEqual(a == "chr1:1000-2000", True)
        self.assertEqual(a == "chr1:1000-2001", False)
Esempio n. 9
0
    def __init__(self,name,new):
        """
        Constructor

        Uses algorithm to turn string data from txt file into a player object.
        ...
        
        Parameters
        ----------
        :param name: Name of user
        :type name: str
        :param new: if the game is a new or must be loaded
        :type new: Bool
        """
        if new == True:
            self.user = player(level=1, name = name, EXP=0, gold= 150, items ={})
        else:
            x = name.lower() + ".txt" # create string with name matching one used to create savegames
            with open(x, 'r') as f: # open file in read mode and parse through lines in same order as data was stored
                name = f.readline().rstrip('\n') # strip of \n
                level = int(f.readline()) # turn strings into int
                gold = int(f.readline())
                items_keys = f.readline()
                item_am = f.readline()
                cl_map = f.readline().rstrip('\n')
                cl_row = int(f.readline())
                cl_col = int(f.readline())
                exp = int(f.readline())
                exp_n = int(f.readline())
                st = int(f.readline())
            curr_map = None # emptry var to be assigned current map
            for i in all_maps:
                if i.key == cl_map:
                    curr_map = i

            non_pot_items = []        # items that are not pots
            try:
                bag = self.get_items(items_keys,item_am) # bag containing all items
                for i in bag:
                    if i.key != "hpo" and i.key != "mpo" and i.key != "upo":# if itst not a pot then remove from bag and add via add_item method to ensure stats are updated
                        non_pot_items.append(i)
                for i in non_pot_items:
                    del bag[i]
            except:
                bag = {}
            user1 = player(location(curr_map,cl_row,cl_col),location(curr_map,cl_row,cl_col), level,name,exp,exp_n,gold, bag,st)
            for i in non_pot_items:
                user1.add_item(i)

            self.user = user1
Esempio n. 10
0
    def test_loading(self):
        a = location(loc="Chr1:10-20")
        self.assertEqual(str(a), "chr1:10-20")

        a = location(chr="1", left=1000, right=2000)
        self.assertEqual(str(a), "chr1:1000-2000")

        a = location(chr=1, left=1000, right=2000)
        self.assertEqual(str(a), "chr1:1000-2000")

        a = location(chr="X", left=1000, right=2000)
        self.assertEqual(str(a), "chrX:1000-2000")

        a = location(loc="Chr2_RANDOM:100-200")  # should still load...
        self.assertEqual(str(a), "chr2_RANDOM:100-200")
Esempio n. 11
0
 def __init__(self, listofplaces, listofplaces2):
     self.locations = []
     self.locations2 = []
     for place in listofplaces:
         try:
             self.locations.append(
                 location.location(place['geometry'], name=place['name']))
         except:
             print('error')
     for place in listofplaces2:
         try:
             self.locations2.append(
                 location.location(place['geometry'], name=place['name']))
         except:
             print('error')
Esempio n. 12
0
    def savegame(self):
        """
        Creates a savegame txt 

        Return
        ------
        :return True: To inform completion without error
        :type True: Bools
        """
        x = self.name.lower(
        ) + ".txt"  # create var string with name of user and txt at end
        things = []  # to store item keys
        amount = []  # to store item quantities
        for i, j in self.items.items():  # Fill things and amount
            things.append(i.key)
            amount.append(j)
        with open(x, 'w') as f:  # Opens file x and writes or overwrites data
            f.write(
                f"{self.name}\n{self.level}\n{self.gold}\n{things}\n{amount}\n{self.current_location.map.key}\n{self.current_location.row}\n{self.current_location.col}\n{self.EXP}\n{self.exp_needed}\n{self.story_tracker}"
            )
        self.last_save_location = location(
            self.current_location.map, self.current_location.row,
            self.current_location.col)  # Changes last save location

        return True
Esempio n. 13
0
    def __init__(self, info_dict=dict()):
        self.name = ""
        self.phone = ""
        self.location = location()

        if len(info_dict) != 0:
            self.load_info_from_dict(info_dict)
Esempio n. 14
0
 def TFoutput(self):  #Converts board into T/F table to simulate board
     output = [[0 for i in range(8)] for j in range(8)]
     for i in range(8):
         for j in range(8):
             if not self.realBoard.get(p.location(i, j)) == " ":
                 output[i][j] = 1
     return output
Esempio n. 15
0
    def left_right_pointify(self):
        a = location("chr1:1000-2000")
        l = a.pointLeft()
        r = a.pointRight()

        self.assertEqual(l, "chr1:1000-1000")
        self.assertEqual(r, "chr1:2000-2000")
Esempio n. 16
0
    def test_location_modifications(self):
        a = location(loc="chr1:1000-2000")

        a = a.expand(100)  # answer = chr1:900-2100
        self.assertEqual(str(a), "chr1:900-2100")

        a = a.expandLeft(10)  # answer = chr1:890-2100
        self.assertEqual(str(a), "chr1:890-2100")

        a = a.expandRight(10)  # answer = chr1:890-2110
        self.assertEqual(str(a), "chr1:890-2110")

        a = a.shrinkLeft(10)  # answer = chr1:900-2110
        self.assertEqual(str(a), "chr1:900-2110")

        a = a.shrinkRight(10)  # answer = chr1:900-2100
        self.assertEqual(str(a), "chr1:900-2100")

        a = a.shrink(
            100)  # should be back where it started answer = chr1:1000-2000
        self.assertEqual(str(a), "chr1:1000-2000")

        a = a.pointify()  # get the middle # answer = chr1:1500-1500
        self.assertEqual(str(a), "chr1:1500-1500")

        a = a.expand(100)  # and make a 200bp window answer = chr1:1400-1600
        self.assertEqual(str(a), "chr1:1400-1600")
Esempio n. 17
0
def bot():
    print(self_intro())
    print(get_time())
    name = input("Please Enter your Name :")
    print(welcome(name))
    # print(get_time())
    choice = showmenu()

    while choice != 5:
        if (choice == 1):
            print(location())
        elif choice == 2:
            print(college())
        elif choice == 3:
            print('1.ECE',
                  '2.CSE',
                  '3.EEE',
                  '4.MECH',
                  '5.CIVIL',
                  '6.IT',
                  sep='\n')
            print("Enter your choice")
            c = (int(input()))
            print(branch(c))
        elif choice == 4:
            print("AC or Non AC")

            print(hostel(input()))
        elif choice >= 5:
            print("I can't understand... sorry")
        else:
            return 0
        choice = showmenu()
Esempio n. 18
0
def locations():
    # API Call to Dataframe
    # Parse Data frame if need
    # Return data to template

    worksheet = gc.open("p3database").sheet1
    dataFrame = pandas.DataFrame(worksheet.get_all_records())

    latList = pandas.Series(dataFrame["latitude"]).tolist()
    lngtList = pandas.Series(dataFrame["longitude"]).tolist()
    nameList = pandas.Series(dataFrame["name"]).tolist()
    idList = pandas.Series(dataFrame["id"]).tolist()

    locationDic = []
    for i in range(len(latList)):
        locationDic.append(
            location.location(latList[i], lngtList[i], nameList[i],
                              idList[i]).hotspot)

    locations = Map(identifier="locations",
                    lat=32.7157,
                    lng=-117.1611,
                    zoom=13,
                    style="height:300px;width:600px;margin:0;",
                    markers=locationDic)

    return render_template('locations.html', locations=locations)
Esempio n. 19
0
 def getMove(self, board):
     #first get all allowed moves then choose one at random
     allowed_moves = []
     for i in range(board.getSize()):
         for j in range(board.getSize()):
             if board.get(p.location(i, j)) == " ":
                 allowed_moves.append([i, j])
     output = []
     for move in allowed_moves:
         tempBoard = board.getGrid()
         """For each open square check if either player can win next turn"""
         tempBoard[move[0]][move[1]] = self.piece
         if self.checkForWin(tempBoard) == self.piece:
             output = move
             tempBoard[move[0]][move[1]] = " "  #Reset since python things
             break
         tempBoard[move[0]][move[1]] = self.oppopiece
         if self.checkForWin(tempBoard) == self.oppopiece:
             output = move
             tempBoard[move[0]][move[1]] = " "  #Reset since python things
             break
         tempBoard[move[0]][move[1]] = " "  #Reset since python things
     else:
         output = random.choice(allowed_moves)
     return output
Esempio n. 20
0
 def getMove(self, board):
     #first get all allowed moves then choose one at random
     allowed_moves = []
     for i in range(board.getSize()):
         for j in range(board.getSize()):
             if board.get(p.location(i, j)) == " ":
                 allowed_moves.append([i, j])
     return random.choice(allowed_moves)
Esempio n. 21
0
def stopJourney(chasis, ssos_passenger, lat, lng):
    p1 = load_file(ssos_passenger, passenger.Passenger)
    locationStop = location.location(str(time.strftime("%c")), lat, lng)
    t1 = p1.get_travels()
    t1 = t1[len(t1) - 1]
    t1.set_timeStop(locationStop)
    p1.set_travels(t1)
    save_file(p1)
Esempio n. 22
0
 def updateBoard(self, inBoard):
     """
     Takes 2d  array of 1/0 's and converts to string board
     """
     for i in range(self.board.getSize()):
         for j in range(self.board.getSize()):
             if inBoard[i][j] == 1 and self.board.get(p.location(i,
                                                                 j)) == " ":
                 self.board.set(p.location(i, j),
                                self.turnM.currentPlayer().getPiece())
                 #Success
                 self.recent_move.update(
                     i, j
                 )  #Store the most recent move to make checking for win faster
                 return 1
     #No update
     print("nothing changed")
     return 0
Esempio n. 23
0
 def getCentre(self):
     xloccum,yloccum = 0,0
     for v in self.__vv:
         l = v.getLocation()
         xloccum = xloccum + l.getX()
         yloccum = yloccum + l.getY()
     nieuwex = float(xloccum / self.getNumberOfBirds())
     nieuwey = float(yloccum / self.getNumberOfBirds())
     return location.location(nieuwex, nieuwey)
Esempio n. 24
0
 def death(self):
     """
     Resets location to last_save_location and HP to max_HP and deducts 10% gold
     """
     self.current_location = location(
         self.last_save_location.map, self.last_save_location.row,
         self.last_save_location.col)  # Reset location
     self.HP = self.max_HP  # Reset HP
     self.gold = int(self.gold * 0.9)  # Lose 10% gold each time you die
Esempio n. 25
0
 def checkForWin(self):
     """
     If game over returns player piece and 'wins' to be printed
     Elif game stalemate returns stalemate
     Else returns nothing
     """
     #Rows
     for i in range(self.board_size):
         if not self.board.get(
                 p.location(self.recent_move.row(),
                            i)) == self.turnM.currentPlayer().getPiece():
             break
         if i == (self.board_size - 1):
             return str(self.turnM.currentPlayer()) + " wins"
     #Column
     for i in range(self.board_size):
         if not self.board.get(p.location(i, self.recent_move.column())
                               ) == self.turnM.currentPlayer().getPiece():
             break
         if i == (self.board_size - 1):
             return str(self.turnM.currentPlayer()) + " wins"
     #Diag
     if self.recent_move.row() == self.recent_move.column():
         for i in range(self.board_size):
             if not self.board.get(p.location(
                     i, i)) == self.turnM.currentPlayer().getPiece():
                 break
             if i == (self.board_size - 1):
                 return str(self.turnM.currentPlayer()) + " wins"
     #Other Diag
     if (self.recent_move.row() +
             self.recent_move.column()) == (self.board_size - 1):
         for i in range(self.board_size):
             if not self.board.get(p.location(
                     i, (self.board_size - 1) -
                     i)) == self.turnM.currentPlayer().getPiece():
                 break
             if i == (self.board_size - 1):
                 return str(self.turnM.currentPlayer()) + " wins"
     #Stalemate
     if self.turnM.count() == self.board_size**2:
         return "Stalemate"
     return None
Esempio n. 26
0
def getListOfLocations(version):
	locationFile = getLocationFile(version)
	if(locationFile == 0):
		return [];
	listOfLocations = []
	locationFile.readline() #Read the first line and throw it away, it's just world size and whatnot
	for line in locationFile.readlines():
		l = location.location(line)
		listOfLocations.append(l)
	return listOfLocations
Esempio n. 27
0
 def __init__(self, orid=-1, epochtime=0, lon=0, lat=0, depth=0, ml=-999.9, mb=-999.9, ms=-999.9, mw=-999.9):
     """ initialise an origin object """
     import converttime
     self.orid = orid
     self.datetime = converttime.epoch2datetime(epochtime)
     self.location = location.location(lon, lat, depth, 'down')
     self.ml = ml
     self.mb = mb
     self.ms = ms
     self.mw = mw
Esempio n. 28
0
    def test_sort_location(self):
        a = [{
            'loc': location("chr1:1000-2000")
        }, {
            'loc': location("chr1:1001-2000")
        }, {
            'loc': location("chr1:1000-2001")
        }, {
            'loc': location("chr2:1050-2000")
        }, {
            'loc': location("chr1:999-2000")
        }]

        gl = glbase3.genelist()
        gl.load_list(a)
        gl.sort('loc')

        self.assertEqual(str(gl[-1]['loc']), "chr2:1050-2000")
        self.assertEqual(str(gl[0]['loc']), "chr1:999-2000")
Esempio n. 29
0
def startJourney(chasis, ssos_passenger, lat, lng):
    p1 = load_file(ssos_passenger, passenger.Passenger)
    locationStart = location.location(str(time.strftime("%c")), lat, lng)
    t1 = travels.Travels(chasis, locationStart)
    p1.set_travels(t1)
    save_file(p1)
    v1 = load_file(chasis, vehicle.Vehicle)
    v1.set_passengers(p1)
    save_file(v1)
    return str(v1.get_ap_mac())
Esempio n. 30
0
    def test_pass_throughs(self):
        # pass a var through and check it is properly copied/modifiable.
        a = location(loc="chr1:100-200")
        b = location(loc=a)  # this will copy.
        c = location(loc=a)
        a = a.pointify()
        b = b.expand(5)
        self.assertEqual(str(a), "chr1:150-150")
        self.assertEqual(str(b), "chr1:95-205")
        self.assertEqual(str(c), "chr1:100-200")  # should still be original.

        b = location(chr=c["chr"], left=c["left"], right=c["right"])
        b = b.expand(5)
        self.assertEqual(str(c), "chr1:100-200")
        self.assertEqual(str(b), "chr1:95-205")

        a = b.expand(10)  # b should be left untouched.
        self.assertEqual(str(b), "chr1:95-205")
        self.assertEqual(str(a), "chr1:85-215")
Esempio n. 31
0
    def __init__(self,
                 current_location=location(home, 1, 1),
                 last_save_location=location(home, 1, 1),
                 level=1,
                 name="No Name",
                 EXP=0,
                 exp_needed=500,
                 gold=0,
                 items={},
                 story_tracker=1):
        """
        Constructor
        ...

        Parameters
        ----------
        :param current_location: stores position at any time
        :type current_location: location
        :param last_save_location: stores position of last save point
        :type last_save_location: location
        :param level: character strength level - determines HP, AD
        :type level: int
        :param name: chosen name for character (default = "No Name")
        :type name: str
        :param EXP: experience points
        :type EXP: int
        :param exp_needed: number of experience points required to hit next level
        :type exp_needed: int
        :param gold: Currency used in game (default = 0)
        :type gold: int
        :param items: Items carried by user (default = {})
        :type items: dictionary
        """
        super().__init__(level, name, gold, items)
        self.current_location = current_location
        self.last_save_location = last_save_location
        self.EXP = EXP
        self.exp_needed = exp_needed
        self.HP = 500 + self.level * 200  # HP increases 200 per level
        self.max_HP = 500 + self.level * 200
        self.AD = self.level * 50  # AD increases 50 per level
        self.story_tracker = story_tracker  #Tracks story and allows for starting game at various points in story
Esempio n. 32
0
 def updateBoardfromScan(self, board, scanData, currentPlayer):
     #Compares board to scan
     #finds differences and updates board
     #returns false if two pieces different
     pieceToSet = p.location(
         -1,
         -1)  #Stores the location of the piece to be set to currentPlayer
     oldPieces = list(
     )  #Stores the locations of the piece to that need to be removed
     scan = grid.grid(0)
     scan.massSet(scanData)
     pieceTypeToSet = currentPlayer  #this gets changed if their is a missing king, therefore piece moved was a king kindof hacky
     for i in range(8):
         for j in range(8):
             currentPos = p.location(i, j)
             if scan.get(
                     currentPos) == 1 and not board.get(currentPos) == " ":
                 continue
             elif scan.get(currentPos) == 1 and board.get(
                     currentPos) == " ":
                 pieceToSet = currentPos
             elif scan.get(
                     currentPos) == 0 and not board.get(currentPos) == " ":
                 if board.get(currentPos)[0] == currentPlayer:
                     pieceTypeToSet = board.get(
                         currentPos
                     )  #if the piece removed was of the current player, set that type to be set
                 oldPieces.append(currentPos)
             elif scan.get(currentPos) == 0 and board.get(
                     currentPos) == " ":
                 continue
             else:
                 print("ERROR IN SETTING BOARD")
                 return False
     done = board.set(pieceToSet, pieceTypeToSet)
     if done == None:
         print("no move done")
         return False
     for l in oldPieces:
         board.set(l, " ")
     self.updateToKings(board)
     return None
Esempio n. 33
0
    def get(self):
        try:
            getUserFromToken(self.get_argument("token"))
            global locations
            name = self.get_argument("name")
            for l in locations:
                if l.name == name:
                    self.write(json.dumps({'type': 'addLocation','response': 'failure','reason':'location_exists'}\
                     ,indent=4,separators=(',', ': ')))
                    return
            try:
                lat = self.get_argument("latitude")
                log = self.get_argument("longitude")
                rad = self.get_argument("radius")
                locations += [
                    location(name=name,
                             latitude=lat,
                             longitude=log,
                             radius=rad),
                ]
            except tornado.web.MissingArgumentError:
                try:
                    bssids = parseIds(self.get_argument("bssids"))
                    ssids = self.get_argument("ssid")
                    locations += [
                        location(name=name, bssids=bssids, ssids=ssids),
                    ]
                except tornado.web.MissingArgumentError:
                    ssids = self.get_argument("ssid")
                    locations += [
                        location(name=name, ssids=ssids),
                    ]

        except LoginError:
            self.write(json.dumps({'type': 'addLocation','response': 'failure','reason':'invalid_token'}\
             ,indent=4,separators=(',', ': ')))
        except:
            self.write(json.dumps({'type': 'addLocation','response': 'failure'}\
             ,indent=4,separators=(',', ': ')))
Esempio n. 34
0
	def generate(self, n, start, end):

		self.start = start
		self.end = end

		for i in range(n):
			self.Locations.append(location())
			if i == 0:
				self.Locations[0].id_location = i
				self.Locations[0].name = "start"
				self.Locations[0].opening = self.start
				self.Locations[0].closing = self.end
				self.Locations[0].score = 0
				self.Locations[0].max_shift = 0
				self.Locations[0].shift = 0
				self.Locations[0].ratio = 0
				self.Locations[0].arrival = 0
				self.Locations[0].leave = 0
			elif i == n-1:
				self.Locations[i].id_location = i
				self.Locations[i].name = "End"
				self.Locations[i].opening = start
				self.Locations[i].closing = end
				self.Locations[i].score = 0
				self.Locations[i].wait = 0
				self.Locations[i].max_shift = 0
				self.Locations[i].shift = 0
				self.Locations[i].ratio = 0
				self.Locations[i].arrival = 0
				self.Locations[i].leave = 0
			else:
				self.Locations[i].id_location = i
				self.Locations[i].name = "Loc"+str(i)
				self.Locations[i].opening = random.randint(8,11)
				self.Locations[i].closing = random.randint(self.Locations[i].opening,20)+1
				self.Locations[i].score = random.randint(1,5)
				self.Locations[i].wait = 0
				self.Locations[i].max_shift = 0
				self.Locations[i].shift = 0
				self.Locations[i].ratio = 0
				self.Locations[i].arrival = 0
				self.Locations[i].leave = 0

		return self.Locations
Esempio n. 35
0
def search(location1Id, location2Id, departureDate, departureTime,
        arrivalDate, arrivalTime):
    resultFound = True
    resultNum = 0

    trips = []

    while(resultFound):
        r = requests.get("http://www.yathra.se/finder.php?" + \
                "avgnr=" + str(resultNum) + "&" +  \
                "from=" + location1Id + "&" + \
                "to=" + location2Id + "&" + \
                "departureDate=" + departureDate + "&" + \
                "departureTime=" + departureTime + "&" + \
                "arrivalDate=" + arrivalDate + "&" + \
                "arrivalTime=" + arrivalTime)
        r.encoding = 'ISO-8859-1'

        #f = codecs.open('result.json','w','utf-8')
        #f.write(json.dumps(r.json(), sort_keys=True, indent=2))
        #f.close()

        data = json.loads(r.text)


        if (data.keys() != [u'error']):
            for i in range (len(data['timetableresult']['ttitem'])):

                trip = ttitem.ttitem()
                trip.totalPrice = float(data['timetableresult']['ttitem'][i]['price'])
                trip.sellerName = data['timetableresult']['ttitem'][i]['sellername']
                trip.totalTravelTime = data['timetableresult']['ttitem'][i]['traveltimetotal']
                trip.URL = data['timetableresult']['ttitem'][i]['url']
                trip.segments = []

                for j in range (len(data['timetableresult']['ttitem'][i]['segment'])):
                    currentSegment = segment.segment()
                    currentSegment.arrivalTime = \
                        time.strptime(data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['datetime'], \
                            "%Y-%m-%d %H:%M")
                    currentSegment.arrivalLocation = location.location(
                             data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['id'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['name'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['x'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['y'] \
                             )
                    currentSegment.departureTime = \
                        time.strptime(data['timetableresult']['ttitem'][i]['segment'][j]['departure']['datetime'], \
                            "%Y-%m-%d %H:%M")
                    currentSegment.departureLocation = location.location(
                             data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['id'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['name'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['x'], \
                             data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['y'] \
                             )
                    if('direction' in data['timetableresult']['ttitem'][i]['segment'][j].keys()):
                        currentSegment.direction = data['timetableresult']['ttitem'][i]['segment'][j]['direction']
                    currentSegment.lowestPrice = data['timetableresult']['ttitem'][i]['segment'][j]['lowestprice']
                    currentSegment.lowestPriceCompany = data['timetableresult']['ttitem'][i]['segment'][j]['lowestpriceseller']['name']
                    currentSegment.lowestPriceURL = data['timetableresult']['ttitem'][i]['segment'][j]['lowestpriceseller']['url']
                    currentSegment.segmentNumber = j
                    trip.segments.append(currentSegment)
                trips.append(trip)
            resultNum += 1
            print str(int(trip.totalPrice)) + " sek " + \
                    datetime.fromtimestamp(mktime(currentSegment.departureTime)).strftime("%Y-%m-%d %H:%M") + "\n\t" + trip.totalTravelTime + "\n\t" + trip.URL 
        else:
            if data.keys() == [u'error']:
                print data['error']
            resultFound = False
    return trips
Esempio n. 36
0
 def test_y_larger_than_0(self):
     loc = location.location()
     self.assertTrue(0 < loc.getY())
Esempio n. 37
0
	def load_instance(self, n, file_name):

		n = n+2 # + start and end

		#file = open('c101.txt', 'r') #identify file name
		file = open(file_name, 'r') #identify file name

		lines = file.readlines()

		new_lines = []

		for line in lines:
			new_lines.append( line.split() )


		self.start = 0
		self.end = float(new_lines[2][8])

		for i in range(n):
			self.Locations.append(location())
			if i == 0:
				self.Locations[0].id_location = i
				self.Locations[0].name = "start"
				self.Locations[0].opening = self.start
				self.Locations[0].closing = self.end
				self.Locations[0].score = 0
				self.Locations[0].max_shift = 0
				self.Locations[0].shift = 0
				self.Locations[0].ratio = 0
				self.Locations[0].arrival = 0
				self.Locations[0].leave = 0
				self.Locations[0].x = new_lines[2][1]
				self.Locations[0].y = new_lines[2][2]
				self.Locations[0].required_time = float(new_lines[2][3])

				new_lines.pop(0)
				new_lines.pop(0)

			elif i == n-1:
				self.Locations[i].id_location = i
				self.Locations[i].name = "End"
				self.Locations[i].opening = self.start
				self.Locations[i].closing = self.end
				self.Locations[i].score = 0
				self.Locations[i].wait = 0
				self.Locations[i].max_shift = 0
				self.Locations[i].shift = 0
				self.Locations[i].ratio = 0
				self.Locations[i].arrival = 0
				self.Locations[i].leave = 0
				self.Locations[i].x = new_lines[0][1]
				self.Locations[i].y = new_lines[0][2]
				self.Locations[i].required_time = float(new_lines[0][3])

			else:
				self.Locations[i].id_location = i
				self.Locations[i].name = "Loc"+str(i)
				self.Locations[i].opening = float(new_lines[i][8])
				self.Locations[i].closing = float(new_lines[i][9])
				self.Locations[i].score = float(new_lines[i][4])
				self.Locations[i].wait = 0
				self.Locations[i].max_shift = 0
				self.Locations[i].shift = 0
				self.Locations[i].ratio = 0
				self.Locations[i].arrival = 0
				self.Locations[i].leave = 0
				self.Locations[i].x = new_lines[i][1]
				self.Locations[i].y = new_lines[i][2]
				self.Locations[i].required_time = float(new_lines[i][3])

		return self.Locations, self.start, self.end
Esempio n. 38
0
 def test_y_smaller_than_scherm(self):
     loc = location.location()
     self.assertTrue(loc.getY() < g_groottescherm)
Esempio n. 39
0
 def test_division_x(self):
     setx = float(1)/2
     sety = 1
     loc = location.location(x=setx, y=1)
     self.assertTrue(loc.getX(), 0.5)
Esempio n. 40
0
 def test_init(self):
     loc = location.location()
     pass
Esempio n. 41
0
 def __init__(self):
     self.sailors = {boat.boat(): location.location(10, 10)}
     self.buoys = [location.location(10, 100)]
     self.wind = np.random.random() * 16 + 4
     self.direction = 0
     self.init_draw()
Esempio n. 42
0
            trip = ttitem.ttitem()
            trip.totalPrice = float(data['timetableresult']['ttitem'][i]['price'])
            trip.sellerName = data['timetableresult']['ttitem'][i]['sellername']
            trip.totalTravelTime = data['timetableresult']['ttitem'][i]['traveltimetotal']
            trip.URL = data['timetableresult']['ttitem'][i]['url']
            trip.segments = []

            for j in range (len(data['timetableresult']['ttitem'][i]['segment'])):
                currentSegment = segment.segment()
                currentSegment.arrivalTime = \
                    time.strptime(data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['datetime'], \
                        "%Y-%m-%d %H:%M")
                currentSegment.arrivalLocation = location.location(
                         data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['id'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['name'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['x'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['arrival']['location']['y'] \
                         )
                currentSegment.departureTime = \
                    time.strptime(data['timetableresult']['ttitem'][i]['segment'][j]['departure']['datetime'], \
                        "%Y-%m-%d %H:%M")
                currentSegment.departureLocation = location.location(
                         data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['id'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['name'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['x'], \
                         data['timetableresult']['ttitem'][i]['segment'][j]['departure']['location']['y'] \
                         )
                if('direction' in data['timetableresult']['ttitem'][i]['segment'][j].keys()):
                    currentSegment.direction = data['timetableresult']['ttitem'][i]['segment'][j]['direction']
                currentSegment.lowestPrice = data['timetableresult']['ttitem'][i]['segment'][j]['lowestprice']
                currentSegment.lowestPriceCompany = data['timetableresult']['ttitem'][i]['segment'][j]['lowestpriceseller']['name']
Esempio n. 43
0
		print "-- name: ",e.name
		print "-- score: ",e.score
		print "-- wait: ",e.wait
		print "-- max_shift: ",e.max_shift
		print "-- shift: ",e.shift
		print "-- ratio: ",e.ratio
		print " "
		

start = 9 #hours
end = 20 #hours

Locations = []

for e in range(5):
	Locations.append(location())

#Instance of 4 elements
Locations[0].id_location = 0
Locations[0].name = "start"
Locations[0].opening = start
Locations[0].closing = start
Locations[0].score = 0
Locations[0].max_shift = 0
Locations[0].shift = 0
Locations[0].ratio = 0
Locations[0].arrival = 0

Locations[1].id_location = 1		
Locations[1].name = "Loc2"
Locations[1].opening = 9
Esempio n. 44
0
 def __init__(self,swarm,ifv):
     self.__ifv = ifv
     self.__ll = location.location()
     self.__ifv.drawBird(self)
     self.__swarm = swarm