1

Quiero dibujar círculos sobre una tablero de juego. Utilicé una función para transformar las coordenadas en la lista en coordenadas en píxeles que funcionó bien con un tablero de juego más grande. Sin embargo ahora ella le da esto:

La bola blanca, que debía estar en el medio, está en la parte inferior izquierda.

La bola blanca, que debía estar en el medio, está en la parte inferior izquierda.

Aqui esta el codigo para dibujar:

for sailor in sailors:
    x = sailor.x
    y = sailor.y
    print(x,y)
    centerx, centery = translateBoardToPixelCoord(x, y)
    print(centerx, centery)
    if sailor.player == 'white' or sailor.player == 'black':
        if sailor.player == 'white':
            tileColor = WHITE
        else:
            tileColor = BLACK
        print(DISPLAYSURF, tileColor, (centerx, centery), int(SPACESIZE / 2) - 4)
        pygame.draw.circle(DISPLAYSURF, tileColor, (centerx, centery -100), int(SPACESIZE / 2) - 4)

Y aqui el codigo para transformar coordenadas tabulares en coordenadas de píxeles.

def translateBoardToPixelCoord(x, y):
    return XMARGIN + x * SPACESIZE + int(SPACESIZE / 2), YMARGIN + y * SPACESIZE + int(SPACESIZE / 2)

Aquí están todas las constantes :

FPS = 10 # frames per second to update the screen
WINDOWWIDTH = 640 # width of the program's window, in pixels
WINDOWHEIGHT = 480 # height in pixels
SPACESIZE = 50 # width & height of each space on the board, in pixels
BOARDWIDTH = 11 # how many columns of spaces on the game board
BOARDHEIGHT = 3 # how many rows of spaces on the game board
EARTHWIDTH = 11
EARTHHEIGHT = 1
WHITE_TILE = 'WHITE_TILE' # an arbitrary but unique value
BLACK_TILE = 'BLACK_TILE' # an arbitrary but unique value
EMPTY_SPACE = 'EMPTY_SPACE' # an arbitrary but unique value
HINT_TILE = 'HINT_TILE' # an arbitrary but unique value
ANIMATIONSPEED = 25 # integer from 1 to 100, higher is faster animation

# Amount of space on the left & right side (XMARGIN) or above and below
# (YMARGIN) the game board, in pixels.
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * SPACESIZE)) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * SPACESIZE)) / 2)

Y aqui esta lo que me contesta el console:

C:\Users\antoi\Documents\Programming\projects\Videogames>python projet_ambroise.py
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
[['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE'], ['EMPTY_SPACE', 'EMPTY_SPACE', 'EMPTY_SPACE']]
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2])
11
(1, 6)
(120, 490)
(<Surface(640x480x32 SW)>, (0, 0, 0), (120, 490), 21)
(1, 6)
(120, 490)
(<Surface(640x480x32 SW)>, (0, 0, 0), (120, 490), 21)
(1, 6)
(120, 490)
(<Surface(640x480x32 SW)>, (255, 255, 255), (120, 490), 21)
(1, 6)
(120, 490)
(<Surface(640x480x32 SW)>, (255, 255, 255), (120, 490), 21)

¿Ya no son adecuados los márgenes?

1 respuesta 1

1

Si he entendido el problema, quieres que el círculo aparezca en la celda que hay entre las palabras WHITE y BLACK:

Si estoy en lo cierto, en principio tu código es correcto, solamente creo que te sobra restar 100 a centery en:

pygame.draw.circle(DISPLAYSURF, tileColor, (centerx, centery -100), int(SPACESIZE / 2) - 4)

El problema es que las coordenadas 1, 6 del tablero no se corresponden con esa casilla (de hecho esa celda no existe en el tablero, por lo que se dibuja fuera del mismo). Esa casilla tiene las coordenadas 5, 2 realmente. En Pygame el pixel 0, 0 está situado en la esquina superior izquierda de la pantalla.

Mejor verlo con un ejemplo reproducible:

import pygame


FPS = 10 # frames per second to update the screen
WINDOWWIDTH = 640 # width of the program's window, in pixels
WINDOWHEIGHT = 480 # height in pixels
SPACESIZE = 50 # width & height of each space on the board, in pixels
BOARDWIDTH = 11 # how many columns of spaces on the game board
BOARDHEIGHT = 3 # how many rows of spaces on the game board
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * SPACESIZE)) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * SPACESIZE)) / 2)

BLUE  = ( 70, 130, 180)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Size:
    def __init__(self, width, height):
        self.height = height
        self.width = width

class Sailor(Point):
    def __init__(self, x, y, player):
        self.x = x
        self.y = y
        self.player = player

def translate_board_to_pixel_coord(x, y):
    return (XMARGIN + x * SPACESIZE + int(SPACESIZE / 2),
            YMARGIN + y * SPACESIZE + int(SPACESIZE / 2))       

def main():
    pygame.init()
    screen_center = Point(WINDOWWIDTH // 2, WINDOWHEIGHT // 2)
    board_size = Size(BOARDWIDTH * SPACESIZE, BOARDHEIGHT * SPACESIZE)
    board_lt_vert = Point(screen_center.x - board_size.width // 2,
                          screen_center.y - board_size.height // 2)             
    board_rd_vert = Point(board_lt_vert.x + board_size.width,
                          board_lt_vert.y + board_size.height)

    points = [(x, y) for x in range(board_lt_vert.x, board_rd_vert.x, SPACESIZE)
                         for y in range(board_lt_vert.y, board_rd_vert.y, SPACESIZE)]

    screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    clock = pygame.time.Clock()
    pygame.font.init()
    myfont = pygame.font.SysFont('Comic Sans MS', 30)

    done = False
    while not done:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        screen.fill(BLUE)

        # Dibujamos la retícula
        for point in points:
            pygame.draw.rect(screen, BLACK, (*point, SPACESIZE, SPACESIZE ), 2)
        # Creamos una lista con las instancias de "sailors"
        sailors = [Sailor(x, y, "white") for x in range(BOARDWIDTH)
                                             for y in range(BOARDHEIGHT)]
        for sailor in sailors:
            x = sailor.x
            y = sailor.y
            centerx, centery = translate_board_to_pixel_coord(x, y)
            if sailor.player == 'white' or sailor.player == 'black':
                if sailor.player == 'white':
                    tileColor = WHITE
                else:
                    tileColor = BLACK
                pygame.draw.circle(screen, tileColor, (centerx, centery),
                                   int(SPACESIZE / 2) - 4)

            textsurface = myfont.render(f'{x}, {y}', False, (250, 0, 0))
            screen.blit(textsurface,(centerx - textsurface.get_width() // 2,
                                     centery - textsurface.get_height() // 2))


        pygame.display.flip()
    pygame.quit()


if __name__ == "__main__":
    main()

introducir la descripción de la imagen aquí

En la imagen podemos ver las coordenadas del tablero que cada Sailor debe tener para dibujarse en esa casilla.

De ser necesario se podría modificar la función para que acepte otro sistema de coordenadas y las convierta al que usa PyGame. Según tu ejemplo (1, 6):

  • 1 -> primera fila desde abajo.

  • 6 -> sexta columna desde la izquierda (contando desde 1)

para ello puedes modificar translate_board_to_pixel_coord(x, y) de la siguiente forma:

def translate_board_to_pixel_coord(x, y):
    return (XMARGIN + (y - 1) * SPACESIZE + int(SPACESIZE / 2),
            YMARGIN + (BOARDHEIGHT - x) * SPACESIZE + int(SPACESIZE / 2)) 

El ejemplo completo:

import pygame


FPS = 10 # frames per second to update the screen
WINDOWWIDTH = 640 # width of the program's window, in pixels
WINDOWHEIGHT = 480 # height in pixels
SPACESIZE = 50 # width & height of each space on the board, in pixels
BOARDWIDTH = 11 # how many columns of spaces on the game board
BOARDHEIGHT = 3 # how many rows of spaces on the game board
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * SPACESIZE)) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * SPACESIZE)) / 2)

BLUE  = ( 70, 130, 180)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Size:
    def __init__(self, width, height):
        self.height = height
        self.width = width

class Sailor(Point):
    def __init__(self, x, y, player):
        self.x = x
        self.y = y
        self.player = player

def translate_board_to_pixel_coord(x, y):
    return (XMARGIN + (y - 1) * SPACESIZE + int(SPACESIZE / 2),
            YMARGIN + (BOARDHEIGHT - x) * SPACESIZE + int(SPACESIZE / 2))       

def main():
    pygame.init()
    screen_center = Point(WINDOWWIDTH // 2, WINDOWHEIGHT // 2)
    board_size = Size(BOARDWIDTH * SPACESIZE, BOARDHEIGHT * SPACESIZE)
    board_lt_vert = Point(screen_center.x - board_size.width // 2,
                          screen_center.y - board_size.height // 2)             
    board_rd_vert = Point(board_lt_vert.x + board_size.width,
                          board_lt_vert.y + board_size.height)

    points = [(x, y) for x in range(board_lt_vert.x, board_rd_vert.x, SPACESIZE)
                         for y in range(board_lt_vert.y, board_rd_vert.y, SPACESIZE)]

    screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    clock = pygame.time.Clock()
    pygame.font.init()
    myfont = pygame.font.SysFont('Comic Sans MS', 30)

    done = False
    while not done:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        screen.fill(BLUE)

        # Dibujamos la retícula
        for point in points:
            pygame.draw.rect(screen, BLACK, (*point, SPACESIZE, SPACESIZE ), 2)

        sailors = [Sailor(x, y, "white") for x in range(1, BOARDHEIGHT + 1)
                                             for y in range(1, BOARDWIDTH + 1)]
        for sailor in sailors:
            x = sailor.x
            y = sailor.y
            centerx, centery = translate_board_to_pixel_coord(x, y)
            if sailor.player == 'white' or sailor.player == 'black':
                if sailor.player == 'white':
                    tileColor = WHITE
                else:
                    tileColor = BLACK
                pygame.draw.circle(screen, tileColor, (centerx, centery),
                                   int(SPACESIZE / 2) - 4)

            textsurface = myfont.render(f'{x}, {y}', False, (250, 0, 0))
            screen.blit(textsurface,(centerx - textsurface.get_width() // 2,
                                     centery - textsurface.get_height() // 2))


        pygame.display.flip()
    pygame.quit()


if __name__ == "__main__":
    main() 

introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.