J.Gor
J.Gor

Reputation: 171

Draw a Line in Pygame

I want to draw a line in Python, but when I run the code below, this line never appears. In fact, I need to make a field with 4x4 sections, but let's begin with a line. My code:

import sys, pygame
from pygame.locals import*

width = 1000
height = 500
screen_color = (49, 150, 100)
line_color = (255, 0, 0)

def main():
    screen=pygame.display.set_mode((width,height))
    screen.fill(screen_color)
    pygame.display.flip()
    pygame.draw.line(screen,line_color, (60, 80), (130, 100))

    while True:
        for events in pygame.event.get():
            if events.type == QUIT:
                sys.exit(0)
main()

What's wrong?

Upvotes: 17

Views: 62910

Answers (6)

Teodora Desić
Teodora Desić

Reputation: 11

import pygame as pg

# Initializing the screen
pg.init()
screen = pg.display.set_mode((200, 200))

# Setting a white background
screen.fill(pg.Color("white"))

# Initializing event loop (1 pass = 1 frame)
while True:
    # Drawing a red line from (0, 100) to (200, 100) of thickness 5
    pg.draw.line(screen, pg.Color("red"), (0, 100), (200, 100), 5)
    
    # Refreshing screen, otherwise no changes will occur
    pg.display.update()
    
    # Restarting event loop in 5 seconds
    # (can also use a pg.time.Clock to specify the framerate)
    pg.time.wait(5000)

The event loop isn't necessary in this snippet, but it's good practice. As well, the screen should typically only be refreshed at the end of the event loop, as updating changes individually can get rather inefficient, instead of updating them in compound. For specifying the framerate rather than waiting hardcoded times after each frame, see pygame.time.Clock and its tick method.

Upvotes: 0

Aarav Sinha
Aarav Sinha

Reputation: 1

you forgot to do: pygame.display.flip()

Upvotes: -1

Chats
Chats

Reputation: 95

Try giving a width to the line (the last parameter to the line method) and update the display

pygame.draw.line(screen, Color_line, (60, 80), (130, 100), 1)
pygame.display.update()

Upvotes: 2

juykfuykjhsddg
juykfuykjhsddg

Reputation: 11

Add pygame.display.flip() after you draw your line.

Upvotes: 0

Yash
Yash

Reputation: 396

Do pygame.display.flip() after you draw your line you are doing this:

screen.fill(color)
pygame.display.flip()
pygame.draw.line(...)

The problem is you're covering the line up before it can show up. Do this instead:

screen.fill(color)
pygame.draw.line(...)
pygame.display.flip()

Upvotes: 0

skrx
skrx

Reputation: 20438

You have to update the display of your computer with pygame.display.flip after you draw the line.

pygame.draw.line(screen, Color_line, (60, 80), (130, 100))
pygame.display.flip()

That's usually done at the bottom of the while loop once per frame.

Upvotes: 21

Related Questions