skip to Main Content

I’m studying a data science bootcamp and we’re learning Python. One of the exercises is to make a battleship game. We’re using a NumPy array as the ocean, we want to use blue squares, 🟦 , to represente the sea… It runs fine in Visual Studio Code but not when opened directly with Python… Does anyone know how to fix it?

I try by using unicode, intalen emoji (doing pip install emoji on my console)…I saw many videos on youtube and asking for help to my friend gpt… but nothing appers to works.

def tablero(Tm): 
   nosotros = np.full((Tm, Tm), "🟦") 
   ordenador = np.full((Tm, Tm), "🟦") 
   separador = np.full((Tm+1, 2), "🟫") 
   numeros_de_columnas = []

2

Answers


  1. You can use ANSI codes instead of symbol:

    print("33[48;5;21m33[38;5;21m . 33[0;0m")
    

    Relevant parts:

    • . is only to provide wide enough to make square foreground object, that can have adjusted foreground color.
    • 21m – first instance refers to background, second to foreground – you can replace it with (n)m where (n) represents number per the link below:

    per: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors (read for more details).


    EDIT:

    In order to print numpy array with rendered colors, and squares you need to explicitly render it to string see trivial example below:

    import numpy as np
    
    def print_rendered(obj: np.array):
        if len(obj.shape) == 2:
            print("n".join(map("".join, obj)))
        else:
            print("".join(obj))
    
    def tablero(Tm): 
        print_rendered(np.full((Tm, Tm), "33[48;5;21m33[38;5;21m . 33[0;0m"))
        print_rendered(np.full((Tm, Tm), "33[48;5;91m33[38;5;91m . 33[0;0m"))
        print_rendered(np.full((Tm+1, 2), "33[48;5;9m33[38;5;9m . 33[0;0m"))
       
    tablero(3)
    

    i.e. print(obj) where obj is numpy.array won’t do for you.

    Login or Signup to reply.
  2. Colorist can be the library you are looking for.
    Please check this code:

    from colorist import ColorHex, BgColorHex
    
    watermelon_red = ColorHex("#ff5733")
    bg_mint_green = BgColorHex("#99ff99")
    
    print(f"I want to use {watermelon_red}watermelon pink{watermelon_red.OFF} and {bg_mint_green}mint green{bg_mint_green.OFF} colors inside this paragraph")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search