def __init__(self, row, col, p):
        """
        Intializes board: 
            M = number of rows
            N = number of columns
            P = number of rows containing initial checker pieces
        Adds the white checkers and black checkers to the board based on the board variables (M,N,P)
        provided. N*P should be even to ensure that both players get the same number of checker pieces at the start

        @param row: number of rows in the board
        @param col: number of columns in the board
        @param p: number of rows to be filled with checker pieces at the start
        @return :
        @raise :
        """
        self.tie_counter = 0
        self.tie_max = 40
        self.row = row
        self.col = col
        self.p = p
        self.board = []
        self.saved_move = []  #self.saved_move = [Move([]),[],False]
        for row in range(self.row):
            self.board.append([])
            for col in range(self.col):
                self.board[row].append(Checker.Checker(".", [row, col]))

        self.black_count = 0
        self.white_count = 0
Exemple #2
0
    def __check(self, key, value):
        func = Checker.Checker(value)
        updated = [x for x in self.data[key] if func.is_not_found(x)]
        if not func.found:
            updated.append(value)

        if not updated:
            self.data.pop(key)
        else:
            self.data[key] = updated
Exemple #3
0
 def initialize_game(self):
     """
     Intializes game. Adds the white checkers and black checkers to the board based on the board variables (M,N,P)
     when the game starts
     @param :
     @return :
     @raise :
     """
     self.check_initial_variable()
     for i in reversed(range(self.p)):
         for j in range((self.p - i - 1) % 2, self.col, 2):
             # put white pieces
             i_white = self.row - self.p + i
             self.board[i_white][j] = Checker.Checker("W", [i_white, j])
             # put black pieces
             if (self.row % 2 + self.p % 2) % 2:  # row,p = even,odd or odd,even
                 if i % 2:
                     # odd row, shift to the left and attach a piece to the end when needed
                     if j - 1 >= 0:
                         self.board[i][j-1] = Checker.Checker("B", [i, j-1])
                     if j == self.col - 2 and not self.col % 2:
                         self.board[i][self.col-1] = Checker.Checker("B", [i,self.col-1])
                 else:
                     # even row, shift to the right and attach a piece to the beginning when needed
                     if j + 1 <= self.col - 1:
                         self.board[i][j+1] = Checker.Checker("B", [i,j+1])
                     if (j == self.col - 1 or j == self.col - 2) and not self.p % 2:
                         self.board[i][0] = Checker.Checker("B", [i,0])
             else:  # row,p = even,even or odd,odd
                 self.board[i][j] = Checker.Checker("B", [i,j])
             self.white_count += 1
             self.black_count += 1
 def iniciar(self):
     self.AST = Nodo_Programa("PROGRAMA", "", [])
     puntero_ast = self.AST
     puntero_token = 0
     if (self.parsear_programa(0) == True):
         checker = Checker(self.AST)
         informe = checker.checkear()
         if (type(informe) != str):  #no hay errores de tipos
             return
         else:
             print(informe)
     else:
         self.generar_error()
Exemple #5
0
def main():
    socket = Server(PORT)
    data = {'any': ['INPUT'], IP1: ['INPUT'], IP2: ['INPUT']}
    board = Checker()
    while True:
        input_data, address = socket.watch(data)
        if input_data != 'CHECK':
            print(input_data)
        input_data = input_data.split()
        address = address[0]
        if input_data[0] == 'CHECK':
            data[address].append('INPUT')
        elif input_data[0] == 'MOVE':
            if address in board.active_player:
                x1, y1 = int(input_data[1]), int(input_data[2])
                x2, y2 = int(input_data[3]), int(input_data[4])
                err = board.move(x1, y1, x2, y2, address)
                if err:
                    board.change_player()
                    for ip in data:
                        data[ip].append('OUTPUT' + ' ' +
                                        ' '.join(input_data[1:]))
                else:
                    data[address].append('ERROR wrong step')

            else:
                data[address].append('ERROR wrong player')
        elif input_data[0] == 'LOGIN':
            found = False
            need_place = True
            for i in data:
                if address == i:
                    need_place = False
                    break
            for i in data:
                if i in DEFAULT_IP and need_place:
                    data.pop(i)
                    data[address] = []
                    data[address].append('SUCCESS ' + address)
                    if board.white == (2, 4):
                        board.set_white((address, 3))
                    elif board.black == (1, 3):
                        board.set_black((address, 4))
                    found = True
                    break
            if not need_place:
                data[address].append('SUCCESS ' + address)
            if not found:
                data[address].append('ERROR cant connection')
Exemple #6
0
 def authorized(self, user: str, password: str) -> bool:
     if isinstance(user, str) and isinstance(password, str) is False:
         print("Неверный тип данных!")
         return False
     if not os.path.exists(user):
         print('Неверные данные!')
         return False
     with open(os.path.abspath(user) + '/USER_INFO/password.txt',
               'r') as file:
         user_password = file.read()
     if Checker.Checker().check_password(user_password, password):
         with open(os.path.abspath(user) + '/USER_INFO/enc_key.txt',
                   'rb') as byte_enc_key_file:
             self.__user_secret_key = byte_enc_key_file.read()
         return True
     else:
         print('Неверные данные!')
         return False
                self.board[x][y].color = c
                self.board[x][y].is_king = k
                if c == "W":
                    self.white_count += 1
                if c == "B":
                    self.black_count += 1
            self.tie_counter -= 1
            self.saved_move.pop(-1)
        else:
            raise Exception("Cannot undo operation")


if __name__ == "__main__":

    b = Board(7, 7, 2)
    b.board[1][3] = Checker.Checker("W", [1, 3])

    b.show_board()
    m = b.get_all_possible_moves("W")[0][0]
    b.make_move(m, "W")
    b.show_board()
    m = b.get_all_possible_moves("W")[0][0]
    b.make_move(m, "W")
    b.show_board()
    m = b.get_all_possible_moves("W")[0][0]
    b.make_move(m, "W")
    b.show_board()
    print("Undo")
    b.undo()
    b.show_board()
    print("Undo")
Exemple #8
0
    controlador = Controlador(f)
    i = controlador.verificar_Archivo()
    if i == 1:
        sc = Scanner

        Tokens = sc.verificar_Scanner(controlador.get_Archivo())
        sc.getReportErrors()
        #print (Tokens)
        if (sc.getReportErrors() == 0):
            Tree = Parser.iniciar_Parser(Tokens)
            if (Parser.get_reportErrors() is True):

                print(
                    "\n\n*********************************************************\n----------> Inicio proceso ANALISIS SEMANTICO\n\n"
                )
                visitor = Checker.Checker()
                Checker.Checker.check(Tree)

                print(
                    "\n\nImprimiendo arbol decorado...\n----------------------------------------------------------------\n"
                )
                impresion = ImprimirArbol.ImprimirArbol(Tree)
                impresion.imprime_Arbol(Tree)

            else:
                print("--------------------------------------------------")
        else:
            print(
                "\n---------------------------------------------------\n Se obtuvieron errores en el analisis sintactico"
            )
Exemple #9
0
                self.board[target_point[0]][target_point[1]].color = "."
                self.board[target_point[0]][target_point[1]].is_king = False
            for saved_enemy in temp_saved_move[1]:  #self.saved_move[1]:
                x, y, c, k = saved_enemy
                self.board[x][y].color = c
                self.board[x][y].is_king = k

            self.saved_move.pop(-1)
        else:
            raise Exception("Cannot undo operation")


if __name__ == "__main__":

    b = Board(10, 10, 2)
    b.board[4][3] = Checker.Checker("W", [4, 3])
    b.board[4][5] = Checker.Checker("W", [4, 5])
    b.board[6][5] = Checker.Checker("W", [6, 5])
    b.board[8][1] = Checker.Checker("B", [8, 1])
    b.board[2][7] = Checker.Checker("W", [2, 7])
    b.board[2][5] = Checker.Checker("W", [2, 5])
    b.board[2][3] = Checker.Checker("W", [2, 3])

    b.board[8][1].become_king()
    b.show_board()
    m = b.get_all_possible_moves("B")[0][0]
    b.make_move(m, "B")
    b.show_board()
    b.undo()
    b.show_board()
Exemple #10
0
class Connection:
    """An SSL connection."""

    clientPostConnectionCheck = Checker.Checker()
    serverPostConnectionCheck = _serverPostConnectionCheck

    m2_bio_free = m2.bio_free
    m2_ssl_free = m2.ssl_free

    def __init__(self, ctx, sock=None):
        self.ctx = ctx
        self.ssl = m2.ssl_new(self.ctx.ctx)
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._fileno = self.socket.fileno()

        self._timeout = self.socket.gettimeout()
        if self._timeout is None:
            self._timeout = -1.0

        self.ssl_close_flag = m2.bio_noclose

        if self.ctx.post_connection_check is not None:
            self.set_post_connection_check_callback \
                (self.ctx.post_connection_check)

    def __del__(self):
        if getattr(self, 'sslbio', None):
            self.m2_bio_free(self.sslbio)
        if getattr(self, 'sockbio', None):
            self.m2_bio_free(self.sockbio)
        if self.ssl_close_flag == m2.bio_noclose and getattr(
                self, 'ssl', None):
            self.m2_ssl_free(self.ssl)
        self.socket.close()

    def close(self):
        m2.ssl_shutdown(self.ssl)

    def clear(self):
        """
        If there were errors in this connection, call clear() rather
        than close() to end it, so that bad sessions will be cleared
        from cache.
        """
        return m2.ssl_clear(self.ssl)

    def set_shutdown(self, mode):
        m2.ssl_set_shutdown1(self.ssl, mode)

    def get_shutdown(self):
        return m2.ssl_get_shutdown(self.ssl)

    def bind(self, addr):
        self.socket.bind(addr)

    def listen(self, qlen=5):
        self.socket.listen(qlen)

    def ssl_get_error(self, ret):
        return m2.ssl_get_error(self.ssl, ret)

    def set_bio(self, readbio, writebio):
        """
        Explicitly set read and write bios
        """
        m2.ssl_set_bio(self.ssl, readbio._ptr(), writebio._ptr())

    def set_client_CA_list_from_file(self, cafile):
        """
        Set the acceptable client CA list. If the client
        returns a certificate, it must have been issued by
        one of the CAs listed in cafile.
        
        Makes sense only for servers.
        
        @param cafile: Filename from which to load the CA list.
        """
        m2.ssl_set_client_CA_list_from_file(self.ssl, cafile)

    def set_client_CA_list_from_context(self):
        """
        Set the acceptable client CA list. If the client
        returns a certificate, it must have been issued by
        one of the CAs listed in context.
        
        Makes sense only for servers.
        """
        m2.ssl_set_client_CA_list_from_context(self.ssl, self.ctx.ctx)

    def setup_addr(self, addr):
        self.addr = addr

    def set_ssl_close_flag(self, flag):
        """
        By default, SSL struct will be freed in __del__. Call with
        m2.bio_close to override this default.
        """
        if flag not in (m2.bio_close, m2.bio_noclose):
            raise ValueError("flag must be m2.bio_close or m2.bio_noclose")
        self.ssl_close_flag = flag

    def setup_ssl(self):
        # Make a BIO_s_socket.
        self.sockbio = m2.bio_new_socket(self.socket.fileno(), 0)
        # Link SSL struct with the BIO_socket.
        m2.ssl_set_bio(self.ssl, self.sockbio, self.sockbio)
        # Make a BIO_f_ssl.
        self.sslbio = m2.bio_new(m2.bio_f_ssl())
        # Link BIO_f_ssl with the SSL struct.
        m2.bio_set_ssl(self.sslbio, self.ssl, m2.bio_noclose)

    def _setup_ssl(self, addr):
        """Deprecated"""
        self.setup_addr(addr)
        self.setup_ssl()

    def set_accept_state(self):
        m2.ssl_set_accept_state(self.ssl)

    def accept_ssl(self):
        return m2.ssl_accept(self.ssl, self._timeout)

    def accept(self):
        """Accept an SSL connection. The return value is a pair (ssl, addr) where
        ssl is a new SSL connection object and addr is the address bound to the
        the other end of the SSL connection."""
        sock, addr = self.socket.accept()
        ssl = Connection(self.ctx, sock)
        ssl.addr = addr
        ssl.setup_ssl()
        ssl.set_accept_state()
        ssl.accept_ssl()
        check = getattr(self, 'postConnectionCheck',
                        self.serverPostConnectionCheck)
        if check is not None:
            if not check(self.get_peer_cert(), ssl.addr[0]):
                raise Checker.SSLVerificationError, 'post connection check failed'
        return ssl, addr

    def set_connect_state(self):
        m2.ssl_set_connect_state(self.ssl)

    def connect_ssl(self):
        return m2.ssl_connect(self.ssl, self._timeout)

    def connect(self, addr):
        self.socket.connect(addr)
        self.addr = addr
        self.setup_ssl()
        self.set_connect_state()
        ret = self.connect_ssl()
        check = getattr(self, 'postConnectionCheck',
                        self.clientPostConnectionCheck)
        if check is not None:
            if not check(self.get_peer_cert(), self.addr[0]):
                raise Checker.SSLVerificationError, 'post connection check failed'
        return ret

    def shutdown(self, how):
        m2.ssl_set_shutdown(self.ssl, how)

    def renegotiate(self):
        """Renegotiate this connection's SSL parameters."""
        return m2.ssl_renegotiate(self.ssl)

    def pending(self):
        """Return the numbers of octets that can be read from the 
        connection."""
        return m2.ssl_pending(self.ssl)

    def _write_bio(self, data):
        return m2.ssl_write(self.ssl, data, self._timeout)

    def _write_nbio(self, data):
        return m2.ssl_write_nbio(self.ssl, data)

    def _read_bio(self, size=1024):
        if size <= 0:
            raise ValueError, 'size <= 0'
        return m2.ssl_read(self.ssl, size, self._timeout)

    def _read_nbio(self, size=1024):
        if size <= 0:
            raise ValueError, 'size <= 0'
        return m2.ssl_read_nbio(self.ssl, size)

    def write(self, data):
        if self._timeout != 0.0:
            return self._write_bio(data)
        return self._write_nbio(data)

    sendall = send = write

    def read(self, size=1024):
        if self._timeout != 0.0:
            return self._read_bio(size)
        return self._read_nbio(size)

    recv = read

    def setblocking(self, mode):
        """Set this connection's underlying socket to _mode_."""
        self.socket.setblocking(mode)
        if mode:
            self._timeout = -1.0
        else:
            self._timeout = 0.0

    def settimeout(self, timeout):
        """Set this connection's underlying socket's timeout to _timeout_."""
        self.socket.settimeout(timeout)
        self._timeout = timeout
        if self._timeout is None:
            self._timeout = -1.0

    def fileno(self):
        return self.socket.fileno()

    def getsockopt(self, *args):
        return apply(self.socket.getsockopt, args)

    def setsockopt(self, *args):
        return apply(self.socket.setsockopt, args)

    def get_context(self):
        """Return the SSL.Context object associated with this 
        connection."""
        return m2.ssl_get_ssl_ctx(self.ssl)

    def get_state(self):
        """Return the SSL state of this connection."""
        return m2.ssl_get_state(self.ssl)

    def verify_ok(self):
        return (m2.ssl_get_verify_result(self.ssl) == m2.X509_V_OK)

    def get_verify_mode(self):
        """Return the peer certificate verification mode."""
        return m2.ssl_get_verify_mode(self.ssl)

    def get_verify_depth(self):
        """Return the peer certificate verification depth."""
        return m2.ssl_get_verify_depth(self.ssl)

    def get_verify_result(self):
        """Return the peer certificate verification result."""
        return m2.ssl_get_verify_result(self.ssl)

    def get_peer_cert(self):
        """Return the peer certificate; if the peer did not provide 
        a certificate, return None."""
        c = m2.ssl_get_peer_cert(self.ssl)
        if c is None:
            return None
        # Need to free the pointer coz OpenSSL doesn't.
        return X509.X509(c, 1)

    def get_peer_cert_chain(self):
        """Return the peer certificate chain; if the peer did not provide 
        a certificate chain, return None."""
        c = m2.ssl_get_peer_cert_chain(self.ssl)
        if c is None:
            return None
        # No need to free the pointer coz OpenSSL does.
        return X509.X509_Stack(c)

    def get_cipher(self):
        """Return an M2Crypto.SSL.Cipher object for this connection; if the 
        connection has not been initialised with a cipher suite, return None."""
        c = m2.ssl_get_current_cipher(self.ssl)
        if c is None:
            return None
        # XXX Need to free the pointer?
        return Cipher(c)

    def get_ciphers(self):
        """Return an M2Crypto.SSL.Cipher_Stack object for this connection; if the
        connection has not been initialised with cipher suites, return None."""
        c = m2.ssl_get_ciphers(self.ssl)
        if c is None:
            return None
        # XXX Need to free the pointer?
        return Cipher_Stack(c)

    def get_cipher_list(self, idx=0):
        """Return the cipher suites for this connection as a string object."""
        return m2.ssl_get_cipher_list(self.ssl, idx)

    def set_cipher_list(self, cipher_list):
        """Set the cipher suites for this connection."""
        return m2.ssl_set_cipher_list(self.ssl, cipher_list)

    def makefile(self, mode='rb', bufsize=-1):
        return socket._fileobject(self, mode, bufsize)

    def getsockname(self):
        return self.socket.getsockname()

    def getpeername(self):
        return self.socket.getpeername()

    def set_session_id_ctx(self, id):
        ret = m2.ssl_set_session_id_context(self.ssl, id)
        if not ret:
            raise SSLError(m2.err_reason_error_string(m2.err_get_error()))

    def get_session(self):
        sess = m2.ssl_get_session(self.ssl)
        return Session(sess)

    def set_session(self, session):
        m2.ssl_set_session(self.ssl, session._ptr())

    def get_default_session_timeout(self):
        return m2.ssl_get_default_session_timeout(self.ssl)

    def get_socket_read_timeout(self):
        return timeout.struct_to_timeout(
            self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, 8))

    def get_socket_write_timeout(self):
        return timeout.struct_to_timeout(
            self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, 8))

    def set_socket_read_timeout(self, timeo):
        assert isinstance(timeo, timeout.timeout)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO,
                               timeo.pack())

    def set_socket_write_timeout(self, timeo):
        assert isinstance(timeo, timeout.timeout)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO,
                               timeo.pack())

    def get_version(self):
        "Return the TLS/SSL protocol version for this connection."
        return m2.ssl_get_version(self.ssl)

    def set_post_connection_check_callback(self, postConnectionCheck):
        self.postConnectionCheck = postConnectionCheck
Exemple #11
0
        @param col: number of columns in the board
        @param p: number of rows to be filled with checker pieces at the start
        @return :
        @raise :
        """
        self.tie_counter = 0
        self.tie_max = 40
        self.row = row
        self.col = col
        self.p = p
        self.board = []
        self.saved_move = [ ]#self.saved_move = [Move([]),[],False]
        for row in range(self.row):
            self.board.append([])
            for col in range(self.col):
                self.board[row].append(Checker.Checker(".", [row, col]))

        self.black_count = 0
        self.white_count = 0


    def initialize_game(self):
        """
        Intializes game. Adds the white checkers and black checkers to the board based on the board variables (M,N,P)
        when the game starts
        @param :
        @return :
        @raise :
        """
        self.check_initial_variable()
        for i in reversed(range(self.p)):
    # print(m)
    # print(m[0])
    # print(m[0][0])
    # b.make_move(m[0][0], "B")
    # b.show_board()

    b = Board(7, 7, 2)
    # b.initialize_game()
    # b.show_board()
    # m = b.get_all_possible_moves(1)
    # print(m)
    # b.make_move(m[0][0],1)
    # b.show_board()
    # m = b.get_all_possible_moves(1)

    b.board[0][0] = Checker.Checker("B", [0, 0])
    b.show_board()
    m = b.get_all_possible_moves("B")
    print(m)
    # b.make_move(m,"W")
    # b.show_board()
    # m = b.get_all_possible_moves("W")[0][0]
    # print(m)
    # b.make_move(m,"W")
    # b.show_board()
    # m = b.get_all_possible_moves("W")[0][0]
    # print(m)
    # b.make_move(m,"W")
    # b.show_board()
    # print("Undo")
    # b.undo()
Exemple #13
0
    print('3-Обновить заметку')
    print('4-Удалить заметку')
    print('5-Количество заметок')
    print('6-Выход в меню управления аккаунтом')
    return None


db = Data.Data()
db.create_new_user_db()
os.chdir('DB')
sec = Security.Security()
auth_flag = False
secret_key = b''
while True:
    main_menu()
    main_menu_choice = Checker.Checker().menu_choice_check()
    print()
    if main_menu_choice == 1:
        user = ''
        password = ''
        while True:
            user = Checker.Checker().get_correct_str('логин')
            password = Checker.Checker().get_password()
            if db.authorized(user, password):
                print('Авторизация прошла успешно')
                auth_flag = True
                master_key = sec.gen_master_key(password)
                secret_key = sec.decrypt(db.get_secret_key(), master_key)
            else:
                auth_flag = False
            if auth_flag:
Exemple #14
0
def main():

    # Hard-coded table holding clock frequency information for HW
    frequencyTable = {
        5: 193.723,
        6: 257.931,
        7: 266.241,
        8: 311.818,
        9: 405.844
    }

    # Create option parser
    parser = OptionParser(
        usage="usage: run-simulator.py [-hvcqmpfdews] filename", version="1.0")

    # Add options (self-documenting)
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="log cycle by cycle debug information")
    parser.add_option("-c",
                      "--core",
                      action="store_true",
                      dest="core",
                      default=False,
                      help="show only core cycles")
    parser.add_option("-q",
                      "--quiet",
                      action="store_true",
                      dest="quiet",
                      default=False,
                      help="less terminal output")
    parser.add_option("-m",
                      "--mute",
                      action="store_true",
                      dest="mute",
                      default=False,
                      help="no summary output")
    parser.add_option(
        "-p",  # "--pipeline",
        type="int",
        dest="pipeline",
        default=5,
        help="set number of pipeline stages [default 5]")
    parser.add_option(
        "-f",  # "--IFStages",
        type="int",
        dest="ifcycles",
        default=-1,
        help="set number of Fetch (IF) Stage cycles")
    parser.add_option(
        "-d",  # "--IDStages",
        type="int",
        dest="idcycles",
        default=-1,
        help="set number of Decode (ID) Stage cycles")
    parser.add_option(
        "-e",  # "--EXStages",
        type="int",
        dest="excycles",
        default=-1,
        help="set number of Execution (EX) Stage cycles")
    parser.add_option(
        "-w",  # "--WBStages",
        type="int",
        dest="wbcycles",
        default=-1,
        help="set number of Writeback (WB) Stage cycles")
    parser.add_option(
        "-s",  # "--WBStages",
        type="int",
        dest="startAddr",
        default=0x0,
        help="set execution start address")

    (options, args) = parser.parse_args()

    # For automated coloured testing output
    B = bcolors()

    # Integer conversion
    options.pipeline = int(options.pipeline)
    options.ifcycles = int(options.ifcycles)
    options.idcycles = int(options.idcycles)
    options.excycles = int(options.excycles)
    options.wbcycles = int(options.wbcycles)

    pipelineConfigError = False

    # Pipeline checking
    if (options.pipeline < 4):
        pipelineConfigError = True

    # Use 1 ID and WB Cycle by default
    if (options.idcycles == -1):
        options.idcycles = 1
    if (options.wbcycles == -1):
        options.wbcycles = 1
    # Use maximum number of EX/MEM Cycles by default (ugly code...)
    if (options.excycles == -1 and options.pipeline >= 5):
        if (options.pipeline == 5):
            options.excycles = 2
        elif (options.pipeline == 6):
            options.excycles = 3
        else:
            options.excycles = 4
    # The rest of the instructions will be WB
    if (options.ifcycles == -1):
        remCycles = options.pipeline - options.idcycles - options.excycles - options.wbcycles
        if (remCycles < 1):
            pipelineConfigError = True
        options.ifcycles = remCycles

    # Double check for correct pipeline configuration
    pipelineSum = options.ifcycles + options.idcycles + options.excycles + options.wbcycles
    if (pipelineSum != options.pipeline):
        pipelineConfigError = True

    # Give error if something is wrong
    if (pipelineConfigError):
        B.printError("Error: Incorrect pipeline configuration")
        sys.exit()

    inputFile = None

    # Open the input file
    try:
        inputFile = open(args[0], "r")
    except IOError:
        B.printError("Error: Could not open input file\t" + args[0])
        sys.exit()

    # Default values
    defaultSimASMFile = "simasm.sim"
    defaultDataMemFile = "datamem.sim"
    defaultPreProcLogFile = "preprocLog.sim"
    defaultSimRunFile = "simrun.sim"

    oldstdout = sys.stdout

    # Initialize parsers
    iparser = InstructionParser.InstructionParser()
    eparser = elf32parser.elf32parser()

    # If custom simulation assembly file output is set
    SimAsmFileName = args[2] if len(args) >= 3 else defaultSimASMFile
    SimAsmFile = open(SimAsmFileName, 'w')
    sys.stdout = SimAsmFile

    # If custom data memory file output is set
    DataMemFileName = args[4] if len(args) >= 5 else defaultDataMemFile

    if (not options.quiet):
        oldstdout.write("> Starting Parser...\n")

    # Convert elf32-bigmips to simulator friendly format
    eparser.convertToSimASM(args[0], SimAsmFileName, DataMemFileName)

    # Extract statistics
    lines = eparser.getLines()
    datamem = eparser.getDataMem()
    mainAddr = eparser.getMainAddr()
    coreInstr = eparser.getCCoreInstr()

    # IF custom preprocessing log file name is set
    PPLogFileName = args[3] if len(args) >= 4 else defaultPreProcLogFile
    PPLogFile = open(PPLogFileName, 'w')
    sys.stdout = PPLogFile

    if (not options.quiet):
        oldstdout.write("> Starting Assembler...\n")

    # Parse in lines, do preprocessing and check for dependencies
    lines = iparser.parseLines(lines, (options.pipeline - options.ifcycles),
                               options.ifcycles, coreInstr)

    pipelineInfo = [
        options.pipeline, options.ifcycles, options.idcycles, options.excycles,
        options.wbcycles
    ]

    # Initialize simulator
    pipelinesim = PipelineSimulator.PipelineSimulator(
        lines, datamem, options.startAddr, oldstdout, options.verbose,
        options.quiet, pipelineInfo)

    if (not options.quiet):
        print "> Starting Simulation..."

    startTime = time.clock()

    # Set logfile
    simulationFileName = args[1] if len(args) >= 2 else defaultSimRunFile
    simulationFile = open(simulationFileName, 'w')
    sys.stdout = simulationFile

    # Run simulation
    pipelinesim.run()

    elapsedTime = (time.clock() - startTime)

    if (not options.quiet):
        oldstdout.write("\n> Simulation Completed in ")
        oldstdout.write(str(elapsedTime))
        oldstdout.write(" s")

    # Close output files
    simulationFile.close()
    PPLogFile.close()

    sys.stdout = oldstdout
    checker = Checker.Checker(simulationFileName, options.quiet)
    success = False

    # Give output according to the settings

    # Normal terminal-based single run output
    if (not options.quiet):
        checker.runCheck()

    # Only summary and statistics output (for use in automated scripts)
    elif (not options.mute):
        success = checker.runCheck()
        if (success):
            if (options.core):
                B.printCoreOnly(checker.getCoreCycles())
            else:
                # Compile statistics
                pNOPs = str(
                    round(
                        float(
                            str(
                                float(checker.getCoreNops()) /
                                (float(checker.getCoreCycles())))) * 100, 1))
                c = checker.getCycles()
                n = checker.getNOPs()
                cpi = checker.getCPI()
                cc = checker.getCoreCycles()
                cn = checker.getCoreNops()
                ex = str(
                    round(
                        float(
                            int(c) *
                            float(1 / frequencyTable.get(options.pipeline))),
                        8)) + "us"
                cex = str(
                    round(
                        float(
                            int(cc) *
                            float(1 / frequencyTable.get(options.pipeline))),
                        8)) + "us"
                # Print successful test
                B.printPass(args[0], [c, n, cpi, cc, cn, pNOPs, ex, cex])
        else:
            # Indicate failure
            B.printFail(args[0], "")
Exemple #15
0
 def __init__(self, _black, position, control_type):
     self.color = WHITE if not _black else BLACK
     self.checker = None if control_type == NONE else Checker(
         control_type, position)
    def make_move(self, move, turn):
        """
        Makes Move on the board
        @param move: Move object provided by the StudentAI, Uses this parameter to make the move on the board
        @param turn: this parameter tracks the current turn. either player 1 (white) or player 2(black)
        @return:
        @raise InvalidMoveError: raises this objection if the move provided isn't valid on the current board
        """
        temp_saved_move = [Move([]), [], False]
        if type(turn) is int:
            if turn == 1:
                turn = 'B'
            elif turn == 2:
                turn = 'W'
            else:
                raise InvalidMoveError
        move_list = move.seq
        move_to_check = []
        ultimate_start = move_list[0]
        ultimate_end = move_list[-1]
        is_start_checker_king = self.board[ultimate_start[0]][
            ultimate_start[1]].is_king
        past_positions = [ultimate_start]
        capture_positions = []
        for i in range(len(move_list) - 1):
            move_to_check.append((move_list[i], move_list[i + 1]))
        # e.g move = Move((0,0)-(2,2)-(0,4))
        #     move_to_check = [((0,0),(2,2)),((2,2),(0,4))]
        if_capture = False
        self.tie_counter += 1
        saved_enemy_position = []
        for t in range(len(move_to_check)):
            start = move_to_check[t][0]  # e.g. (0,0)
            target = move_to_check[t][1]  # e.g. (2,2)
            if self.is_valid_move(
                    start[0], start[1], target[0], target[1],
                    turn) or (if_capture and abs(start[0] - target[0]) == 1):
                # invailid move or attempting to make a single move after capture
                self.board[start[0]][start[1]].color = "."
                self.board[target[0]][target[1]].color = turn
                self.board[target[0]][target[1]].is_king = self.board[
                    start[0]][start[1]].is_king
                self.board[start[0]][start[1]].become_man()
                past_positions.append(target)
                if abs(start[0] - target[0]) == 2:
                    # capture happened
                    if_capture = True
                    self.tie_counter = 0
                    capture_position = ((start[0] +
                                         (target[0] - start[0]) // 2),
                                        (start[1] +
                                         (target[1] - start[1]) // 2))
                    # calculate capture position
                    capture_positions.append(capture_position)
                    # record capture position
                    saved_enemy_position.append(
                        (capture_position[0], capture_position[1], self.board[
                            capture_position[0]][capture_position[1]].color,
                         self.board[capture_position[0]][
                             capture_position[1]].is_king))
                    self.board[capture_position[0]][
                        capture_position[1]] = Checker.Checker(
                            ".", [capture_position[0], capture_position[1]])
                    # capture
                    if turn == "B":
                        self.white_count -= 1
                    else:
                        self.black_count -= 1
                if (turn == 'B' and target[0] == self.row - 1
                    ):  # and not self.board[target[0]][target[1]].is_king):
                    if not is_start_checker_king:
                        temp_saved_move[2] = True
                    self.board[target[0]][target[1]].become_king()
                    #self.saved_move[2] = True

                elif (turn == 'W' and target[0] == 0
                      ):  # and not self.board[target[0]][target[1]].is_king):
                    if not is_start_checker_king:
                        temp_saved_move[2] = True
                    self.board[target[0]][target[1]].become_king()
                    #self.saved_move[2] = True
                else:
                    temp_saved_move[2] = False  #self.saved_move[2] = False

            else:
                for failed_capture in capture_positions:
                    # recover failed captures
                    self.board[failed_capture[0]][
                        failed_capture[1]] = Checker.Checker(
                            self.opponent[turn],
                            [failed_capture[0], failed_capture[1]])
                for failed_position in past_positions:
                    # recover failed moves
                    self.board[failed_position[0]][
                        failed_position[1]] = Checker.Checker(
                            ".", [failed_position[0], failed_position[1]])
                self.board[ultimate_start[0]][
                    ultimate_start[1]] = Checker.Checker(
                        turn, [ultimate_start[0], ultimate_start[1]])
                raise InvalidMoveError

        temp_saved_move[0] = copy.deepcopy(
            move)  #self.saved_move[0] = copy.deepcopy(move)
        temp_saved_move[
            1] = saved_enemy_position  #self.saved_move[1] = saved_enemy_position
        self.saved_move.append(temp_saved_move)
Exemple #17
0
        if (depth >= bounceDepth): return Vector3()
        if (not bounce.scatter): return bounce.attenuation
        return colour(bounce.scatter, roster, depth + 1) * bounce.attenuation
    else:
        unitDirection = ray.direction.unit()
        t = (unitDirection.y + 1.0) / 2
        return Vector3(1.0, 1.0, 1.0) * (1.0 - t) + Vector3(0.1, 0.2, 0.8) * t


frames = 1
width = 600
height = 600
samples = 2
pic = Picture(width, height * frames)

check = Checker(Vector3(0.0, 0.0, 0.3), Vector3(0.9, 0.9, 0.8))
gold = Colour(Vector3(0.8, 0.6, 0.4))
blue = Colour(Vector3(0.8, 0.3, 0.3))

roster = Roster()
brick = Lambert(blue)
grass = Lambert(check)
mirror = Metal(gold)

roster.add(Sphere(brick, Vector3(0.0, 0.0, 0.0), 0.5))
roster.add(Sphere(grass, Vector3(0.0, -100.5, 0.0), 100.0))
roster.add(Sphere(mirror, Vector3(1.0, 0.0, 0.0), 0.5))
roster.add(Sphere(mirror, Vector3(-1.0, 0.0, 0.0), 0.5))

for f in range(frames):
    eye = Eye(Vector3(2.0, 0.0 + float(f) * 0.5, 10.0),