During my quest to learn pygame I came across a tutorial that was really helping me through. However I came across a piece of code that has confused me. Being that this tutorial has a very vague explanation on each of the snippets, I need someone to explain this to me.

#! /usr/bin/env python
 
import pygame

y = 0
dir = 1
running = 1
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
linecolor = 255, 0, 0
bgcolor = 0, 0, 0

while running:
     event = pygame.event.poll()
     if event.type == pygame.QUIT:
          running = 0
 
     screen.fill(bgcolor)
     pygame.draw.line(screen, linecolor, (0, y), (width-1, y))
 
     y += dir
      if y == 0 or y == height-1: dir *= -1
 
     pygame.display.flip()

I can understand everything above screen.fill(). So pretty much I wanna know what all this is:

pygame.draw.line(screen, linecolor, (0, y), (width-1, y))

whats width-1 do?
And this

y += dir
      if y == 0 or y == height-1: dir *= -1

There is of course an indent error in your code sample. I added some comments:

# move a line down and up the display window

import pygame

y = 0
dir = 1
running = True
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
linecolor = 255, 0, 0  # red
#bgcolor = 0, 0, 0  # black
bgcolor = 255, 255, 255  # white

while running:
    event = pygame.event.poll()
    # quit when window corner x is clicked
    if event.type == pygame.QUIT:
        running = False
 
    screen.fill(bgcolor)
    pygame.draw.line(screen, linecolor, (0, y), (width-1, y))
 
    y += dir
    # reverse direction if line hits bottom or top
    if y == 0 or y == height-1:
        #dir *= -1
        dir = -dir
    # update display 
    pygame.display.flip()

width -1 simply draws the line short one notch of hitting the right edge of the display.

This article has been dead for over six months. Start a new discussion instead.