def __init__(self):
        self.slot_0 = Slot()
        self.slot_1 = Slot()
        self.slot_2 = Slot()
        self.slot_3 = Slot()

        self.foundation_0 = Foundation()
        self.foundation_1 = Foundation()
        self.foundation_2 = Foundation()
        self.foundation_3 = Foundation()

        self.cascade_deck_0 = Cascade_deck()
        self.cascade_deck_1 = Cascade_deck()
        self.cascade_deck_2 = Cascade_deck()
        self.cascade_deck_3 = Cascade_deck()
        self.cascade_deck_4 = Cascade_deck()
        self.cascade_deck_5 = Cascade_deck()
        self.cascade_deck_6 = Cascade_deck()
        self.cascade_deck_7 = Cascade_deck()

        self.deck = Deck(1, 13, 4)

        # lists that contain the all objects from the same class
        self.list_slot = [self.slot_0, self.slot_1, self.slot_2, self.slot_3]

        self.list_foundation = [
            self.foundation_0, self.foundation_1, self.foundation_2,
            self.foundation_3
        ]

        self.list_cascade_deck = [
            self.cascade_deck_0, self.cascade_deck_1, self.cascade_deck_2,
            self.cascade_deck_3, self.cascade_deck_4, self.cascade_deck_5,
            self.cascade_deck_6, self.cascade_deck_7
        ]
Exemple #2
0
 def __init__(self, value_start, value_end, number_of_suits):
     self.cascades = [Cascade() for i in range(8)]
     self.foundations = [Foundation(i) for i in range(4)]
     self.cells = [Cell() for i in range(4)]
     self.cards = []
     # init the cards
     for i in range(number_of_suits):
         suit = CardSuit(i)
         for j in range(value_start, value_end + 1):
             self.cards.append(Card(j, suit))
     # shuffle the cards
     self.shuffle()
     # draw card from cards and place them onto eight cascades
     while self.cards.__len__() > 0:
         for cascade in self.cascades:
             card = self.draw_card()
             if card:
                 cascade.cards.append(card)
             else:
                 break
class Notfrecell:
    # Notfreecell comprise of 4 slots, 4 foundations, 8 cascade_deck, 1 deck
    def __init__(self):
        self.slot_0 = Slot()
        self.slot_1 = Slot()
        self.slot_2 = Slot()
        self.slot_3 = Slot()

        self.foundation_0 = Foundation()
        self.foundation_1 = Foundation()
        self.foundation_2 = Foundation()
        self.foundation_3 = Foundation()

        self.cascade_deck_0 = Cascade_deck()
        self.cascade_deck_1 = Cascade_deck()
        self.cascade_deck_2 = Cascade_deck()
        self.cascade_deck_3 = Cascade_deck()
        self.cascade_deck_4 = Cascade_deck()
        self.cascade_deck_5 = Cascade_deck()
        self.cascade_deck_6 = Cascade_deck()
        self.cascade_deck_7 = Cascade_deck()

        self.deck = Deck(1, 13, 4)

        # lists that contain the all objects from the same class
        self.list_slot = [self.slot_0, self.slot_1, self.slot_2, self.slot_3]

        self.list_foundation = [
            self.foundation_0, self.foundation_1, self.foundation_2,
            self.foundation_3
        ]

        self.list_cascade_deck = [
            self.cascade_deck_0, self.cascade_deck_1, self.cascade_deck_2,
            self.cascade_deck_3, self.cascade_deck_4, self.cascade_deck_5,
            self.cascade_deck_6, self.cascade_deck_7
        ]

    # translate user's input to correspond component.e.g. SO means Slot_0
    def position_translate(self, position):
        list_position = [
            'S0', 'S1', 'S2', 'S3', 'F0', 'F1', 'F2', 'F3', 'C0', 'C1', 'C2',
            'C3', 'C4', 'C5', 'C6', 'C7'
        ]
        list_notfreecell = self.list_slot + self.list_foundation + self.list_cascade_deck
        position_dict = dict(list(zip(list_position, list_notfreecell)))
        return position_dict[position]

    # shuffle deck , then deal the card in the order that C0-C7, then from C0 again
    def deal(self):
        self.deck.shuffle()
        cascade_deck_number = 0
        for i in self.deck.get_deck():
            self.list_cascade_deck[cascade_deck_number % 8].append_card(i)
            cascade_deck_number += 1

    # the position that user need to input is like S0,F1,C5, represent slot_0
    # foundation_1,cascade_deck_5 respectively. The from_position means topmost
    # card in which position is to be moved, to_position means move card to which position
    def move_card(self, from_position, to_position):
        removed_card = self.position_translate(from_position).remove_card()
        # if the removed action is invalid,stop the function
        if removed_card == False:
            return None
        flag = self.position_translate(to_position).add_card(removed_card)
        # if the add_card action is invalid, return the removed card back to where it was
        if flag == False:
            self.position_translate(from_position).append_card(removed_card)
            return None

    # check user's input
    def move_check(self, move):
        if move in [
                'S0', 'S1', 'S2', 'S3', 'F0', 'F1', 'F2', 'F3', 'C0', 'C1',
                'C2', 'C3', 'C4', 'C5', 'C6', 'C7'
        ]:
            return True
        else:
            return False

    # if length of all foundation equal 13, then win
    def game_win(self):
        if self.foundation_0.length_foudation() == 13 and \
                        self.foundation_0.length_foudation() == 13 and \
                        self.foundation_0.length_foudation() == 13 and \
                        self.foundation_0.length_foudation() == 13:
            return True
        else:
            return False

    # max length of all cascade_deck
    def max_length(self):
        self.list_of_length = []
        for j in self.list_cascade_deck:
            self.list_of_length.append(j.length_cascade_deck())
        return max(self.list_of_length)

    def __str__(self):
        display_notfreecell = 'S0' + '\t' + 'S1' + '\t' + 'S2' + '\t' + 'S3' + '\t' \
                                                                               'F0' + '\t' + 'F1' + '\t' + 'F2' + '\t' + 'F3' + '\n'
        # print all slot in one line
        for n in self.list_slot:
            display_notfreecell += str(n) + '\t'
        # print all foundation in the same line
        for m in self.list_foundation:
            display_notfreecell += str(m) + '\t'
        display_notfreecell += '\n' + '\n'
        display_notfreecell += 'C0' + '\t' + 'C1' + '\t' + 'C2' + '\t' + 'C3' + '\t' \
                                                                                'C4' + '\t' + 'C5' + '\t' + 'C6' + '\t' + 'C7' + '\n'

        # start from first row, print each cascade_deck's first item
        # then ..... second...............................second item until reach the max length of all cascade_deck
        for row in range(self.max_length()):
            for item in self.list_cascade_deck:
                # if index out of range, display '   '
                if row >= item.length_cascade_deck():
                    display_notfreecell += '   ' + '\t'
                else:
                    display_notfreecell += str(
                        item.get_cascade_deck(row)) + '\t'
            display_notfreecell += '\n'
        # change the color back to normal
        return display_notfreecell

    # just save the board
    def save_game(self):
        saved_game = open('saved_file.txt', 'w')
        saved_game.write(str(self))
        saved_game.close()
Exemple #4
0
 def __init__(self):
     Foundation.__init__(self)
     self.loginfo = Foundation()
Exemple #5
0
class Connection(Foundation):

    logger = ft_logger.Logger("connection").getLogger()

    def __init__(self):
        Foundation.__init__(self)
        self.loginfo = Foundation()

    def AddKnownHost(self, handle, ipaddr, username, password):
        """
        Add an user to known host,so that onos can login in with onos $ipaddr.
        parameters:
        ipaddr:   ip address
        username: login user name
        password: login password
        """
        self.logger.info("Now Adding an user to known hosts " + ipaddr)
        login = handle
        login.sendline("ssh -l %s -p 8101 %s" % (username, ipaddr))
        index = 0
        while index != 2:
            index = login.expect(['assword:', 'yes/no', pexpect.EOF,
                                  pexpect.TIMEOUT])
            if index == 0:
                login.sendline(password)
                login.sendline("logout")
                index = login.expect(["closed", pexpect.EOF])
                if index == 0:
                    self.loginfo.log("Add SSH Known Host Success!")
                    break
                else:
                    self.loginfo.log("Add SSH Known Host Failed! "
                                     "Please Check!")
                    break
                login.prompt()

            if index == 1:
                login.sendline('yes')

    def GetEnvValue(self, handle, envname):
        """
        os.getenv only returns current user value
        GetEnvValue returns a environment value of
            current handle
        eg: GetEnvValue(handle,'HOME')
        """
        envhandle = handle
        envhandle.sendline('echo $' + envname)
        envhandle.prompt()
        reg = envname + '\r\n(.*)\r'
        envaluereg = re.compile(reg)
        envalue = envaluereg.search(envhandle.before)
        if envalue:
            return envalue.groups()[0]
        else:
            return None

    def Gensshkey(self, handle):
        """
        Generate ssh keys, used for some server have no sshkey.
        """
        self.logger.info("Now Generating SSH keys...")
        # Here file name may be id_rsa or id_ecdsa or others
        # So here will have a judgement
        keysub = handle
        filepath = self.GetEnvValue(keysub, 'HOME') + '/.ssh'
        filelist = os.listdir(filepath)
        for item in filelist:
            if 'id' in item:
                self.loginfo.log("SSH keys are exsit in ssh directory.")
                return True
        keysub.sendline("ssh-keygen -t rsa")
        Result = 0
        while Result != 2:
            Result = keysub.expect(["Overwrite", "Enter", pexpect.EOF,
                                    'PEXPECT]#', pexpect.TIMEOUT])
            if Result == 0:
                keysub.sendline("y")
            if Result == 1 or Result == 2:
                keysub.sendline("\n")
            if Result == 3:
                self.loginfo.log("Generate SSH key success.")
                keysub.prompt()
                break
            if Result == 4:
                self.loginfo.log("Generate SSH key failed.")
                keysub.prompt()
                break

    def GetRootAuth(self, password):
        """
        Get root user
        parameters:
        password: root login password
        """
        self.logger.info("Now changing to user root")
        login = pexpect.spawn("su - root")
        index = 0
        while index != 2:
            index = login.expect(['assword:', "failure",
                                  pexpect.EOF, pexpect.TIMEOUT])
            if index == 0:
                login.sendline(password)
            if index == 1:
                self.loginfo.log("Change user to root failed.")

        login.interact()

    def ReleaseRootAuth(self):
        """
        Exit root user.
        """
        self.logger.info("Now Release user root")
        login = pexpect.spawn("exit")
        index = login.expect(['logout', pexpect.EOF, pexpect.TIMEOUT])
        if index == 0:
            self.loginfo.log("Release root user success.")
        if index == 1:
            self.loginfo.log("Release root user failed.")

        login.interact()

    def AddEnvIntoBashrc(self, envalue):
        """
        Add Env var into /etc/profile.
        parameters:
        envalue: environment value to add
        """
        self.logger.info("Now Adding bash environment")
        fileopen = open("/etc/profile", 'r')
        findContext = 1
        while findContext:
            findContext = fileopen.readline()
            result = findContext.find(envalue)
            if result != -1:
                break
        fileopen.close
        if result == -1:
            envAdd = open("/etc/profile", 'a+')
            envAdd.writelines("\n" + envalue)
            envAdd.close()
        self.loginfo.log("Add env to bashrc success!")

    def OnosRootPathChange(self, onospath):
        """
        Change ONOS root path in file:bash_profile
        onospath: path of onos root
        """
        self.logger.info("Now Changing ONOS Root Path")
        filepath = onospath + 'onos/tools/dev/bash_profile'
        line = open(filepath, 'r').readlines()
        lenall = len(line) - 1
        for i in range(lenall):
            if "export ONOS_ROOT" in line[i]:
                line[i] = 'export ONOS_ROOT=' + onospath + 'onos\n'
        NewFile = open(filepath, 'w')
        NewFile.writelines(line)
        NewFile.close
        self.logger.info("Done!")

    def OnosConnectionSet(self):
        """
        Intergrate for ONOS connection setup
        """
        if self.masterusername == 'root':
            filepath = '/root/'
        else:
            filepath = '/home/' + self.masterusername + '/'
        filepath = os.path.join(filepath, "onos/tools/dev/bash_profile")
        self.AddEnvIntoBashrc("source " + filepath + "\n")
        self.AddEnvIntoBashrc("export OCT=" + self.OCT)
        self.AddEnvIntoBashrc("export OC1=" + self.OC1)
        self.AddEnvIntoBashrc("export OC2=" + self.OC2)
        self.AddEnvIntoBashrc("export OC3=" + self.OC3)
        self.AddEnvIntoBashrc("export OCN=" + self.OCN)
        self.AddEnvIntoBashrc("export OCN2=" + self.OCN2)
        self.AddEnvIntoBashrc("export localhost=" + self.localhost)