can't blit a surface with its lines on display

Question:

I’m trying to draw a line on a surface that I then blit on the display.
When I’m doing so, only the surface appeares while the line is not drawned.

The code I wrote is

import pygame as pg
import numpy as np

pg.init()

# Define constants for the screen width and height
SCREEN_WIDTH = 750
SCREEN_HEIGHT = 500

# Create the screen object
screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen.fill((40,158,80))

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

    # Road surface
    road_height = 100
    road = pg.Surface((SCREEN_WIDTH+10,road_height))
    road.fill((0,0,0))
    road_topleft = [0,(SCREEN_HEIGHT-road_height)/2]
    
    # Side lines
    st_ratio = 0.0375 # side to total road width ratio
    sl_width = int(np.rint(st_ratio*road_height))
    sideline_topleft = road_topleft+[0,st_ratio*SCREEN_HEIGHT]

    pg.draw.line(road, (255,255,255),[0, (SCREEN_HEIGHT-road_height)/2+st_ratio*road_height], 
                 [SCREEN_WIDTH, (SCREEN_HEIGHT-road_height)/2+st_ratio*road_height], sl_width)
    
    screen.blit(road, road_topleft)
    pg.display.flip()

pg.quit()

The idea is to design a road and I’m currently trying to add the lines to the "road" surface.
The output I’m obtaining is however

Output screen

Asked By: mcali

||

Answers:

The height of the road is road_height. So (SCREEN_HEIGHT-road_height)/2+st_ratio*road_height) is out of bounds. The center of the road is road_height//2:

pg.draw.line(road, (255,255,255), [0, road_height//2], [SCREEN_WIDTH, road_height//2], sl_width)

Note, the line is drawn on the road, but not on the screen. At the end, the road is blit on the screen at a certain point, yet you can’t use screen coordinates to draw on the road.

Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.