Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having problem with drawing lines thickness in pygame

Tags:

python

pygame

Here is the board I drew using pygame: https://i.sstatic.net/Hne6A.png

I'm facing a bug with the thickness of the last two lines as I marked them on the image. I believe there is something wrong with the if statement in my code but I can't quite figure it out, it just won't take effect.

here is the code that has drawn the board above:

import pygame, sys


pygame.init()

width, height = 750, 750
rows, cols = 9, 9
BLACK = (0,0,0)

screen = pygame.display.set_mode((width, height))
screen.fill((255, 255, 255, 255))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            sys.exit()

    surf = pygame.Surface((600, 600))
    surf.fill((255,255,255))

    padding = surf.get_width()/9
    for i in range(rows+1):
        if i % 3 == 0:
            thick = 4
        else:
            thick = 1

        pygame.draw.line(surf, BLACK, (0, i*padding), (width, i*padding), width=thick)
        pygame.draw.line(surf, BLACK, (i*padding, 0), (i*padding, height), width=thick)

    

    surf_center = (
        (width-surf.get_width())/2,
        (height-surf.get_height())/2
    )
    screen.blit(surf, surf_center)
    pygame.display.update()
    pygame.display.flip()

like image 221
arshia mohammadi Avatar asked Sep 06 '25 03:09

arshia mohammadi


1 Answers

To draw a thick line, half the thickness is applied to both sides of the line. The simplest solution is to make the target surface a little larger and add a small offset to the coordinates of the lines.
For performance reasons, I also recommend creating the surface before the application loop and continuously blit it in the application loop:

import pygame, sys

pygame.init()

width, height = 750, 750
rows, cols = 9, 9
BLACK = (0,0,0)

screen = pygame.display.set_mode((width, height))

surf_size = 600
surf = pygame.Surface((surf_size+4, surf_size+4))
surf.fill((255,255,255))
padding = surf_size/9
for i in range(rows+1):
    thick = 4 if i % 3 == 0 else 1
    offset = i * padding + 1
    pygame.draw.line(surf, BLACK, (0, offset), (width, offset), width=thick)
    pygame.draw.line(surf, BLACK, (offset, 0), (offset, height), width=thick)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            
    screen.fill((255, 255, 255, 255))
    screen.blit(surf, surf.get_rect(center = screen.get_rect().center))
    pygame.display.update()
    pygame.display.flip()

pygame.quit()
sys.exit()

like image 57
Rabbid76 Avatar answered Sep 08 '25 00:09

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!