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

classHangman():def__init__(self):
    self.lines = 0#Number of lines to be drawndefdraw(self,screen):
    #TODO draw to screen based on self.lines#More code setting up pygame

drawlist = []
myMan = Hangman()
drawlist.append(myMan)
#mainloopwhile1:
  screen.fill('#000000')
  for item indrawlist:
    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/pythonimport pygame
pygame.init()

classHangman():
  def__init__(self):
    self.lines = 0#Number of lines to be drawndefhang(self):
    self.lines += 1defdraw(self,screen):
    for x inrange(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 = Truewhile running:
  #EVENT HANDLING#for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = Falseif 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"