Search code examples
pythonpygamepixel

Trying to draw to the screen using pygame, cant get any method to work


This is a snippet of my code that takes a text input and plots pixels to the screen, this is the command format !pixel 32,32 255,255,255

##Command Format !Pixel X,Y R,G,B
def screencontrol():
##now we open the PyGame window
(width, height) = (256, 256) #more window setup
screen = pygame.display.set_mode((width, height)) #more window setup
pygame.display.flip() #more window setup
global message
#global splitmsg
while True:
    commandmessage = message
    pygame.init()
    pygame.event.pump() ##keeps pygame window refreshed / not crash
    if "!pixel" == commandmessage.lower().split(" ", 1)[0]: #Split message and check for pixel command
        print("Received a draw pixel request!") #debug output

        coordsforpix = commandmessage.lower().split(" ", -1)[1]
        print("Extracting draw... ")
        plotpixx = coordsforpix.split(",", 2)[0]
        print("X = " + plotpixx)
        plotpixy =coordsforpix.split(",", 2)[1]
        print("Y = " + plotpixy)
        plotpixrgb = commandmessage.lower().split(" ", -1)[2]
        print("RGB = " + plotpixrgb)
        plotpixr = plotpixrgb.split(",", 3)[0]
        plotpixg =plotpixrgb.split(",", 3)[1]
        plotpixb =plotpixrgb.split(",", 3)[2]
        print("R G B = " + plotpixr + plotpixg + plotpixb)
        print("Done extracting")
        pygame.draw.circle(screen, tuple(map(int, plotpixrgb.split(",", -1))), (int(plotpixx), int(plotpixy)),  1)#plot point
        commandmessage = ""
        message = ""
        pass
    else:
        pass

I've been pulling my hair out for 2 days trying to make it work, everything else works perfectly, debugging outputs what it should but it just won't plot any pixels... Thanks in advance!


Solution

  • pygame.display.flip() updates the full display Surface to the screen and has to be done at the end of the application loop, but pygame.init() initialize all imported pygame modules and has to be done only once. It has to be the 1st pygame instruction.

    def screencontrol():
    
        pygame.init() # init pygame
    
        ##now we open the PyGame window
        (width, height) = (256, 256) #more window setup
        screen = pygame.display.set_mode((width, height)) # create window
    
        global message
        #global splitmsg
        while True:
            commandmessage = message
            pygame.event.pump() ##k
    
            if "!pixel" == commandmessage.lower().split(" ", 1)[0]:
                # [...]
    
            pygame.display.flip() # update display at the end of the loop