Skip to content Skip to sidebar Skip to footer

Pygame: Drawing Lines

In my previous question For Loop Functions in Python, I had trouble with putting functions that contained a command to draw a line for a hangman game. It didn't exactly draw the li

Solution 1:

After you are calling pygame.draw.line() you are probably redrawing your screen completely white, this will draw over the line and hide it. Instead of drawing lines like you are, I would build a hangman class draw from that

class Hangman():
  def __init__(self):
    self.lines = 0 #Number of lines to be drawn

  def draw(self,screen):
    #TODO draw to screen based on self.lines

#More code setting up pygame

drawlist = []
myMan = Hangman()
drawlist.append(myMan)
#mainloop
while 1:
  screen.fill('#000000')
  for item in drawlist:
    item.draw(screen)

This way you are redrawing you hangman every frame, and thus he is always being showed

EDIT Added a running example

#!/usr/bin/python
import pygame
pygame.init()

class Hangman():
  def __init__(self):
    self.lines = 0 #Number of lines to be drawn

  def hang(self):
    self.lines += 1

  def draw(self,screen):
    for x in range(self.lines):
      coord1 = (x*10,20)
      coord2 = (x*10,50)
      pygame.draw.line(screen,(0,0,0),coord1,coord2)

size = screenWidth,screenHeight = 200,70
screen = pygame.display.set_mode(size)
pygame.display.flip()

myman = Hangman()

drawlist = []
drawlist.append(myman)
#mainloop
running = True
while running:
  #EVENT HANDLING#
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False
    if event.type == pygame.KEYDOWN:
      if event.key == 32: #Spacebar
        myman.hang()

  #DRAWING#
  screen.fill((255,255,255))
  for item in drawlist:
    item.draw(screen)
  pygame.display.flip()

Post a Comment for "Pygame: Drawing Lines"