示例#1
0
def main():
    """Llama a todas las funciones, para asi correr el juego"""
    posiciones_serpiente = [(0, 0, "abajo")]
    tablero = actualizar_tablero()
    posicion_fruta = inicializar_fruta(posiciones_serpiente)
    actualizar_serpiente(tablero, posiciones_serpiente)
    imprimir_tablero(tablero)

    while True:
        direccion = obtener_direccion()
        hay_fruta = mover_serpiente(posicion_fruta, direccion,
                                    posiciones_serpiente)
        if hay_fruta:
            posicion_fruta = inicializar_fruta(posiciones_serpiente)
        clear_terminal()
        tablero = actualizar_tablero()
        actualizar_serpiente(tablero, posiciones_serpiente)
        actualizar_fruta(tablero, posicion_fruta)
        imprimir_tablero(tablero)
        if me_comi_el_cuerpo(posiciones_serpiente) or me_comi_la_pared(
                posiciones_serpiente):
            perdiste()
            break
        if len(posiciones_serpiente) == TAMAÑO_FINAL_SERPIENTE:
            ganaste()
            break
        movimientos_validos()
示例#2
0
def main():
    fruta = generarFruta()
    movimiento = 'w'
    posCero = TABLERO_SIZE // 2
    snake = [(posCero, posCero)]

    while True:
        clear_terminal()

        snake, fruta = checkFruta(movimientoSnake(snake, movimiento), fruta)

        if not checkBordes(snake) or not checkAutoColision(snake):
            print('¡Game Over! :(')
            break
        if len(snake) == SNAKE_MAX_LENGHT:
            print('¡Ganaste! Alcanzaste la longitud máxima de snake.')
            break

        imprimirTablero(generarTablero(), snake, fruta)

        entrada = inputJugada(movimiento)
        if entrada == False:
            print('Gracias por jugar.')
            break
        if not entrada == None:
            movimiento = entrada
示例#3
0
def imprimir_jugada(tablero):
    '''Recibe por parametro el tablero creado y lo imprime.'''
    terminal.clear_terminal()
    for fila in tablero:
        print()
        for columna in fila:
            print(columna, end=" ")
 def run(self):
     camera.exit_pressed = False
     print("File is encrypted with a key.")
     x = input("encryption key: ")
     if x == self.encryption_key:
         camera.run_image_processor(self.solution_file)
         time.sleep(1)
         terminal.clear_terminal()
     else:
         print("Wrong password")
示例#5
0
def start_game_loop():
  """Comienza el loop de renderizacion del tablero de juego"""
  global snake
  snake = [(random.randint(0, board_size - 1), random.randint(0, board_size - 1))]
  direction = 'w'
  while True:
    user_input = parse_user_input(timed_input(seconds_between_key_input))
    if user_input in directions.keys():
      direction = user_input

    generate_fruit()

    if not try_to_move_snake(direction): return False

    update_snake_position()
    clear_terminal()
    render_frame()
    if snake_size == max_snake_size: return True
示例#6
0
def update_screen(grid):
    """ 
    update_screen: Takes the grid and updates the terminal to display it.
    (Making this function more efficient and informative is a to-do)
    """
    terminal.clear_terminal()
    print(terminal.bcolors.RED + ' GAME OF LIFE' + terminal.bcolors.ENDC)
    print(terminal.bcolors.YELLOW + '-' * (len(grid[0]) + 5) +
          terminal.bcolors.ENDC)
    print
    for i, line in enumerate(grid):
        print(terminal.bcolors.BLUE + '%3d ' % i + terminal.bcolors.ENDC)
        for element in line:
            if element:
                sys.stdout.write(terminal.bcolors.RED + str(element) +
                                 terminal.bcolors.ENDC)
            else:
                sys.stdout.write('0')
        print()
    print(terminal.bcolors.YELLOW + '-' * (len(grid[0]) + 5) +
          terminal.bcolors.ENDC)
示例#7
0
def server_hack_task():
    terminal.clear_terminal()

    head_gda = terminal.bold_green_text(
        open_file_and_get_content('assets/head2.txt'))
    print(f"{head_gda}\n")

    # Server log file
    server_log_text = open_file_and_get_content('assets/server_log.txt')
    # Inline coloring of server log text
    server_log_text = '\033[1m'.join(server_log_text.split("$%B%$"))
    server_log_text = '\033[0m\033[37m\033[2m'.join(
        server_log_text.split("$%E%$"))
    server_log = TextFile('server.log', server_log_text)

    # Fake files
    fake_file_1 = TextFile(
        'g.txt', open_file_and_get_content('assets/files/camera_tip.txt'))
    fake_file_2 = TextFile(
        'dconf.txt', open_file_and_get_content('assets/files/log_tip.txt'))
    fake_file_3 = TextFile(
        'yuri.txt', open_file_and_get_content('assets/files/empty_file.txt'))
    fake_file_4 = TextFile(
        'iporf.txt', open_file_and_get_content('assets/files/exe_read.txt'))
    fake_file_5 = TextFile(
        'abcd.txt', open_file_and_get_content('assets/files/empty_file.txt'))

    # Zip file
    printable_file = PrintableFile('cr.pdf', SOLUTIONS.first_clue_pdf)
    cam_file = ExecutableFile('camera.exe', 'camera.py',
                              SOLUTIONS.encryption_key,
                              SOLUTIONS.image_recognition_pdf)
    zip_file = ZipFile('tools.zip', 0.91,
                       [printable_file, fake_file_1, cam_file])

    # Folders
    folder1 = VirtualFolder('log', [server_log], None)
    folder2 = VirtualFolder('usr', [fake_file_2, fake_file_3], None)
    folder3 = VirtualFolder('lib', [fake_file_5], None)
    root = VirtualFolder('', [folder1, folder2, folder3, fake_file_4], None)
    folder1.parent = root
    folder2.parent = root
    folder3.parent = root

    # Handle commands
    current_directory = root
    while True:
        try:
            x = input(
                terminal.bold_green_text(
                    f'CE:{IP}-BASE:$~{current_directory.path()}/ '.strip()))
            if x == '':
                continue
            x = x.split()
            command = x.pop(0)
            arg = '.' if len(x) == 0 else x.pop(0)

            if command in ['list', 'ls']:
                VirtualInstance.list_command(current_directory)
            elif command in ['cd']:
                current_directory = current_directory.cd(arg)
            elif command in ['read']:
                VirtualInstance.read_file_command(current_directory, arg)
            elif command in ['download']:
                VirtualInstance.download_file_command(current_directory,
                                                      zip_file, arg)
            elif command in ['extract', 'unzip']:
                VirtualInstance.extract_file_command(current_directory, arg)
            elif command in ['run']:
                VirtualInstance.run_file_command(current_directory, arg)
            elif command in ['clear', 'cls']:
                terminal.clear_terminal()
                print(f"{head_gda}\n")
            elif command in ['print']:
                VirtualInstance.print_file_command(current_directory, arg)
            elif command in ['help']:
                VirtualInstance.help_command()
            elif command in ['exit']:
                terminal.clear_terminal()
                exit(0)
            elif command in ['execute']:
                subprocess.call(x)
            else:
                print("unknown command:", command)
        except NotImplementedError:
            print("invalid usage of command", command, "with args:", arg)
        except Exception as e:
            print(e)
示例#8
0
if __name__ == "__main__":
    signal.signal(signal.SIGTSTP, signal.SIG_IGN)

    group = ''
    while True:
        group = input("[Group Initialize] Input Group Number: ")
        try:
            group = int(group)
            assert (1 <= group <= 9)
            break
        except:
            print("Invalid group Number.")

    SOLUTIONS = Solutions(group)
    terminal.clear_terminal()

    # Show head text (SERVER LOGIN)
    head_text = open_file_and_get_content('assets/head.txt')
    print(terminal.bold_green_text(head_text))

    # Login password guard block
    while True:
        x = input(terminal.bold_yellow_text(f"Enter {IP} password: "******"Verifing password...")
        if x == SOLUTIONS.server_login_password:
            terminal.show_progress(0.01, 100)
            print(terminal.green_text("\nLogging in..."))

            terminal.show_progress(0.08, 100)
def run_image_processor(solution_file):
    '''Main Entry Point'''
    global exit_pressed, detected
    exit_pressed = False

    terminal.set_handler(signal_handler)

    width = terminal.TERMINAL_WIDTH
    height = terminal.TERMINAL_HEIGHT - 10
    img_width = int(width * 0.75)
    aspect_ratio = height / width

    while not exit_pressed:
        if detected:
            art = ""
            with open(solution_file, 'r', encoding="utf-8") as f:
                art = f.read()
            tmp_art = ""
            for line in art.split('\n'):
                tmp_art += f"{line}\n"
            art = tmp_art

            frame_color = 'white'
            color = 'green'
            attrs = ['bold', 'underline']
            art = art.split('\n')
            time.sleep(0.1)
        else:
            frame = getCameraFrame()

            if frame is None:
                # Frame lag - stop
                break

            frame, threshed, angle = imageprocess.process(frame)
            frame = cv2.rotate(threshed, cv2.ROTATE_90_COUNTERCLOCKWISE)

            if detected or abs(angle - 45) < 8:
                # Puzzle Solved
                # print("Detected... Printing...", solution_file)
                # subprocess.call(['lp', solution_file])
                time.sleep(1)
                terminal.clear_terminal()
                time.sleep(1)

                detected = True
            else:
                frame = np.pad(frame,
                               pad_width=1,
                               mode='constant',
                               constant_values=0)
                art = ascii.frame_to_ascii_art(frame, img_width, aspect_ratio,
                                               ascii.gscale1)

                if angle == float("inf"):
                    frame_color = 'yellow'
                    color = 'white'
                    attrs = ['bold', 'blink']
                else:
                    frame_color = 'green'
                    color = 'green'
                    attrs = ['bold']

        art = terminal.center(art)
        text = "=" * width + '\n'
        text += "Streaming CAMERA 1: Searching for the correct Symbol\nPress CTRL+C to exit..\n"
        text += "=" * width + '\n\n'
        text = terminal.center(text)
        text += "Output[]: " + \
            colored(imageprocess.message_from_image_processor,
                    color, attrs=attrs)
        text += "\n\n\n"
        art = text + colored(art, frame_color, attrs=['bold'])
        terminal.clear_terminal()
        print(art)

    try:
        cap.release()
        terminal.set_handler(terminal.handler)
    except:
        pass
示例#10
0
def server_hack_task():
    terminal.clear_terminal()
    with open('head2.txt', 'r', encoding="utf-8") as f:
        msg = colored(f.read().strip(), 'green', attrs=['bold'])
        print(msg)
    print()

    # Server log file
    with open('server_log.txt', 'r', encoding="utf-8-sig") as f:
        server_log_text = f.read().strip()
    server_log_text = '\033[1m'.join(server_log_text.split("$%B%$"))
    server_log_text = '\033[0m\033[37m\033[2m'.join(
        server_log_text.split("$%E%$"))
    server_log = TextFile('server.log', server_log_text)

    # Fake files
    fake_file_1 = TextFile(
        'g.txt',
        'camera.exe requires an encryption key which is an addition of 2 strings.'
    )
    fake_file_2 = TextFile(
        'dconf.txt',
        'TIP:\nServers, firewalls, and other IT equipment keep log files that record important events and transactions. Log data can also provide information for identifying and troubleshooting equipment problems including configuration problems and hardware failure.'
    )
    fake_file_3 = TextFile('yuri.txt', '--- empty file ---')
    fake_file_4 = TextFile(
        'iporf.txt',
        'TIP:\nReading unreadable files (ZIP/EXE/PDF/...) will show binary data. (Random unicode strings)'
    )
    fake_file_5 = TextFile('abcd.txt', '--- empty file ---')

    # Zip file
    printable_file = PrintableFile('cr.pdf')
    cam_file = ExecutableFile('camera.exe', 'camera.py')
    zip_file = ZipFile('tools.zip', 0.91,
                       [printable_file, fake_file_1, cam_file])

    # Folders
    folder1 = VirtualFolder('log', [server_log], None)
    folder2 = VirtualFolder('usr', [fake_file_2, fake_file_3], None)
    folder3 = VirtualFolder('lib', [fake_file_5], None)
    root = VirtualFolder('',
                         [folder1, folder2, folder3, fake_file_4, cam_file],
                         None)
    folder1.parent = root
    folder2.parent = root
    folder3.parent = root

    current_directory = root
    while True:
        try:
            x = input(
                colored('CE:' + IP +
                        '-BASE:$~{}/ '.format(current_directory.path()),
                        'green',
                        attrs=['bold'])).strip()
            if x == '':
                continue
            x = x.split()
            command = x.pop(0)
            arg = '.' if len(x) == 0 else x.pop(0)

            if command == 'list':
                VirtualInstance.list_command(current_directory)
            elif command == 'cd':
                current_directory = current_directory.cd(arg)
            elif command == 'read':
                VirtualInstance.read_file_command(current_directory, arg)
            elif command == 'download':
                VirtualInstance.download_file_command(current_directory,
                                                      zip_file, arg)
            elif command == 'extract':
                VirtualInstance.extract_file_command(current_directory, arg)
            elif command == 'run':
                VirtualInstance.run_file_command(current_directory, arg)
            elif command == 'clear':
                terminal.clear_terminal()
                with open('head2.txt', 'r', encoding="utf-8") as f:
                    msg = colored(f.read().strip(), 'green', attrs=['bold'])
                    print(msg)
                print()
            elif command == 'print':
                VirtualInstance.print_file_command(current_directory, arg)
            elif command == 'help':
                VirtualInstance.help_command()
            elif command == 'exit':
                terminal.clear_terminal()
                exit(0)
            else:
                print("unknown command:", command)
        except NotImplementedError:
            print("invalid usage of command", command, "with args:", arg)
        except Exception as e:
            print(e)
示例#11
0
def run_image_processor():
    '''Main Entry Point'''
    global exit_pressed
    exit_pressed = False

    terminal.set_handler(signal_handler)

    with open('cameraclue.txt', encoding="utf-8") as f:
        camera_clue = f.read()

    width = terminal.TERMINAL_WIDTH
    height = terminal.TERMINAL_HEIGHT - 10
    img_width = int(width * 0.75)
    aspect_ratio = height / width

    while not exit_pressed:
        frame = getCameraFrame()

        if frame is None:
            # Frame lag - stop
            break

        frame, threshed, angle = imageprocess.process(frame)
        frame = cv2.rotate(threshed, cv2.ROTATE_90_COUNTERCLOCKWISE)

        if abs(angle - 45) < 8:
            art = camera_clue
            frame_color = 'white'
            color = 'green'
            attrs = ['bold', 'underline']
            art = art.split('\n')
        else:
            frame = np.pad(frame,
                           pad_width=1,
                           mode='constant',
                           constant_values=0)
            art = ascii.frame_to_ascii_art(frame, img_width, aspect_ratio,
                                           ascii.gscale3)

            if angle == float("inf"):
                frame_color = 'yellow'
                color = 'white'
                attrs = ['bold', 'blink']
            else:
                frame_color = 'green'
                color = 'green'
                attrs = ['bold']

        art = terminal.center(art)
        text = "=" * width + '\n'
        text += "Press CTRL+C to exit..\n"
        text += "=" * width + '\n\n'
        text = terminal.center(text)
        text += "Output[]: " + colored(
            imageprocess.message_from_image_processor, color, attrs=attrs)
        text += "\n\n\n"
        art = text + colored(art, frame_color, attrs=['bold'])
        terminal.clear_terminal()
        print(art)

    try:
        cap.release()
        terminal.set_handler(terminal.handler)
    except:
        pass
示例#12
0
def main():
    snake = 'O'
    tamañoSnake = 0
    fruta = '+'
    frutaCol, frutaFil = generarFruta()
    direccion = '+y'
    posX = (FILAS // 2)
    posY = (COLUMNAS // 2)

    for t in range(0, TIEMPO):
        tablero = []
        clear_terminal()
        print('Tiempo restante: ' + str(TIEMPO - t))
        print(f'Score: {tamañoSnake}')

        #Construir tablero
        for fila in range(0, FILAS):
            tablero.append([])
            for col in range(0, COLUMNAS):
                tablero[fila].append('.')

        if direccion == '+y': posY -= 1
        if direccion == '-y': posY += 1

        if direccion == '+x': posX += 1
        if direccion == '-x': posX -= 1

        #Posicionar fruta
        tablero[frutaFil][frutaCol] = COLOR_ROJO + '+' + COLOR_NORMAL

        #Snake come la fruta
        if frutaFil == abs(posY) and frutaCol == abs(posX):
            tamañoSnake += 1
            frutaCol, frutaFil = generarFruta()

        tablero[(posY)][(posX)] = COLOR_VERDE + snake + COLOR_NORMAL

        for s in range(0, tamañoSnake):
            if direccion == '+x': tablero[(posY + s)][(posX)] += snake
            if direccion == '-x': tablero[(posY - s)][(posX)] += snake

            if direccion == '+y': tablero[(posY)][(posX + s)] += snake
            if direccion == '-y': tablero[(posY)][(posX - s)] += snake

        #DEBUG ZONE
        #print(f"({posX}, {posY})")
        #END DEBUG ZONE

        if tamañoSnake == SNAKE_MAX_LENGHT: break

        #Imprime el tablero
        for fila in range(0, FILAS):
            lst = tablero[fila]
            tableroFinal = ""
            for dot in lst:
                tableroFinal += dot
            print(tableroFinal)

        #Recibe el input y fija una direccion
        entrada = timed_input(VELOCIDAD)

        if entrada == '' or len(entrada) > 1: continue
        if entrada.isspace() == True: break

        if entrada == 'w': direccion = '+y'
        if entrada == 's': direccion = '-y'
        if entrada == 'd': direccion = '+x'
        if entrada == 'a': direccion = '-x'

    print('Gracias por jugar!')
示例#13
0
def main():
    """Llama a todas las funciones, para asi correr el juego"""
    ESPECIALES = []
    POSICION_OBSTACULOS = []
    velocidad = 0
    CANT_FILAS = 0
    CANT_COLUMNAS = 0
    TAMAÑO_FINAL_SERPIENTE = 0
    NIVEL_ACTUAL = 1
    MOCHILA = []
    posicion_fruta = None
    dif_tamaño = 0
    dif_velocidad = 0

    TAMAÑO_FINAL_SERPIENTE, velocidad, CANT_COLUMNAS, CANT_FILAS, ESPECIALES, POSICION_OBSTACULOS, dif_tamaño = asignacion_niveles(
        NIVEL_ACTUAL, TAMAÑO_FINAL_SERPIENTE, velocidad, CANT_COLUMNAS,
        CANT_FILAS, ESPECIALES, dif_tamaño)
    posiciones_serpiente = inicializar_serpiente()
    tablero = actualizar_tablero(CANT_FILAS, CANT_COLUMNAS)
    valor_1, valor_2, simbolo = inicializar_especiales(ESPECIALES, CANT_FILAS,
                                                       CANT_COLUMNAS,
                                                       posiciones_serpiente,
                                                       POSICION_OBSTACULOS,
                                                       posicion_fruta, tablero)
    posicion_especial = (valor_1, valor_2)
    posicion_fruta = inicializar_fruta(posiciones_serpiente, CANT_FILAS,
                                       CANT_COLUMNAS, POSICION_OBSTACULOS,
                                       posicion_especial)
    MOCHILA = inicializar_mochila()
    actualizar_obstaculos(tablero, POSICION_OBSTACULOS)
    tablero = actualizar_especial(tablero, posicion_especial, simbolo)
    actualizar_serpiente(tablero, posiciones_serpiente, CANT_FILAS,
                         CANT_COLUMNAS)
    imprimir_tablero(tablero)

    while True:
        direccion, poder_especial = obtener_direccion(velocidad, dif_velocidad)
        dif_velocidad, dif_tamaño, MOCHILA = ejecutar_especial(
            poder_especial, ESPECIALES, dif_velocidad, dif_tamaño, MOCHILA)
        hay_fruta, hay_especial, dif_tamaño = mover_serpiente(
            posicion_fruta, direccion, posiciones_serpiente, posicion_especial,
            dif_tamaño)
        if hay_fruta:
            posicion_fruta = inicializar_fruta(posiciones_serpiente,
                                               CANT_FILAS, CANT_COLUMNAS,
                                               POSICION_OBSTACULOS,
                                               posicion_especial)
        if me_comi_el_cuerpo(posiciones_serpiente) or me_comi_la_pared(
                posiciones_serpiente,
                CANT_FILAS, CANT_COLUMNAS) or me_comi_el_obstaculo(
                    posiciones_serpiente, tablero):
            perdiste()
            break
        if len(posiciones_serpiente) == TAMAÑO_FINAL_SERPIENTE:
            ganaste()
            posiciones_serpiente = inicializar_serpiente()
            NIVEL_ACTUAL += 1
            if NIVEL_ACTUAL > 2:
                break
            TAMAÑO_FINAL_SERPIENTE, velocidad, CANT_COLUMNAS, CANT_FILAS, ESPECIALES, POSICION_OBSTACULOS, dif_tamaño = asignacion_niveles(
                NIVEL_ACTUAL, TAMAÑO_FINAL_SERPIENTE, velocidad, CANT_COLUMNAS,
                CANT_FILAS, ESPECIALES, dif_tamaño)
            MOCHILA = inicializar_mochila()
        if hay_especial:
            MOCHILA = actualizar_mochila(MOCHILA, simbolo)
            valor_1, valor_2, simbolo = inicializar_especiales(
                ESPECIALES, CANT_FILAS, CANT_COLUMNAS, posiciones_serpiente,
                POSICION_OBSTACULOS, posicion_fruta, tablero)

        clear_terminal()
        tablero = actualizar_tablero(CANT_FILAS, CANT_COLUMNAS)
        actualizar_obstaculos(tablero, POSICION_OBSTACULOS)
        posicion_especial = (valor_1, valor_2)
        actualizar_fruta(tablero, posicion_fruta)
        actualizar_serpiente(tablero, posiciones_serpiente, CANT_FILAS,
                             CANT_COLUMNAS)
        tablero = actualizar_especial(tablero, posicion_especial, simbolo)
        imprimir_nivel(NIVEL_ACTUAL)
        imprimir_tablero(tablero)
        movimientos_validos()
        imprimir_mochila(MOCHILA)