1

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
mcali
  • 13
  • 4
  • 1
    The height of the `road` is `road_height`. So `(SCREEN_HEIGHT-road_height)/2+st_ratio*road_height)` is out of bounds. – Rabbid76 Mar 28 '23 at 16:57
  • @Rabbid76 it is not. Actually, if I omit blitting the road surface and only draw the line on the display instead, it appears as I would want it. – mcali Mar 28 '23 at 17:01
  • Of course it is. You draw the line 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`. – Rabbid76 Mar 28 '23 at 17:02
  • @Rabbid76 Now I got the error. I was wrong about the reference frame. – mcali Mar 28 '23 at 17:05

1 Answers1

0

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.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174