-1

I'm trying to render a numpy array, that is, its content to a screen in pygame. However, pygame text renderer only supports Unicode.

I tried to convert my array to chararray, but it wasn't a solution.

Are there any function in numpy that converts an array to a string, while maintaining the shape. Another approach was parsing the numpy array to string; albeit it worked, the array lost its shape.

Here's my code.

    import pygame
    import numpy as np

    pygame.init()
    pygame.font.init()

    screen = pygame.display.set_mode((400, 400))
    b = np.array([[1, 2, 3, 4],
                 [3, 5, 6, 5]])

    print(b)
    running = True
    font = pygame.font.SysFont("Arial", 20)

    while running:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                running = False

        text = font.render(b, False, (255, 255, 255))

        screen.blit(text, (30, 30))

        pygame.display.flip()

    pygame.quit()
    quit()

Cast Fellow
  • 63
  • 2
  • 11
  • Pygame doesn't have multiline text rendering. You could iterate over the array and then font.render and blit row by row and increment the y coordinate. I think there are third party modules that handle multiline text, but I can't say anything about their quality (I've only checked out one before but it looked like a beginner project). – skrx Jun 11 '17 at 08:34

1 Answers1

1

I believe np.array_str(b) does what you want. Check the docs on np.array_str.

It literally returns the string representation of the data in the array. quoted from the doc that also matches your request.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • It still doesn't keep the shape, though. That is, it's not representing a rowXcol array. – Cast Fellow Jun 10 '17 at 19:59
  • 1
    It does. At least in string mode. Pygame might not be recognizing line break character `\n`. – Imanol Luengo Jun 10 '17 at 20:14
  • @CastFellow If you want more detailed control on how to format the string check [array2string](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array2string.html#numpy.array2string) – Imanol Luengo Jun 10 '17 at 20:23