Connect the dots

If you look really closely, you might notice that the sine wave isn't continuous—there are spaces between the points in the middle. That's because, at the steep part of the sine wave, we have to move up (or down) by 3 pixels when we move one pixel to the right. And because we're drawing individual points, not lines, there's nothing to fill the space in between.

Let's try the same thing using a short line to join each plot point. Pygame has a method to draw a single line, but it also has a method that will draw lines between a series of points (like "connect the dots"). That method is pygame.draw.lines(), and it needs five parameters:

■ pygame window

/ \

/

r\

j j \ j

\ j

\ / Vy

\J

■ whether the shape will be closed by drawing a line joining the last point back to the first one. We don't want to enclose our sine wave, so this will be False for us.

So in our sine wave example, the pygame.draw.linesO method would look like this:

pygame.draw.lines(screen, [0,0,0],False, plotPoints, 1)

In the for loop, instead of drawing each point, we'll just create the list of points that draw.lines() will connect. Then we have a single call to draw.lines(), which is outside the for loop. The whole program is shown in listing 16.9.

Listing 16.9 A well-connected sine wave

Calculates y-position for each point import pygame, sys import math pygame.init()

screen = pygame.display.set_mode([64 0,48 0]) screen.fill([255, 255, 255]) plotPoints = [] for x in range(0, 640):

y = int(math.sin(x/640.0 * 4 * math.pi) plotPoints.append([x, y]) pygame.draw.lines(screen, [0,0,0],False, plotPoints, pygame.display.flip()

while True: Draws the whole for event in pygame.event.get(): curve with the if event.type == pygame.QUIT: draw-lines()

function sys.exit()

Adds each point to the list

Now when we run it, it looks like this:

Now when we run it, it looks like this:

Pygame Tutorial

That's better—no gaps between the points. If we increase the line width to 2, it looks even better:

0 -1

Responses

  • lena
    How to connect dots in python loop?
    6 years ago
  • Cristoforo
    How to prgram python connecting lines between dots?
    6 years ago
  • Daniel
    How to connect two dots in python turtle?
    3 years ago

Post a comment