Pygame:在“pygame.Surface.fill()”之后无法在屏幕上绘制任何内容

问题描述

我正在尝试制作国际象棋游戏,但遇到了一个问题: 我正在尝试使用 pygame.Surface.fill(black_sc) 更新每个“刻度”的显示。 但结果,我似乎无法在现在的黑屏上绘制任何东西:

#GAME LOOP
while True:
    screen.fill(black_sc)
    
    #SQUARE DRAWING LOOP
    s_draw_loop()
    
    #DRAW THE PIECES
    draw_pieces()
    
    m_pos = pygame.mouse.get_pos()
    
    for x in pygame.event.get():
        if x.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE] == True:
            exit()
        
        if x.type == pygame.MOUSEBUTTONDOWN:
            for space in range(len(rect_database)):
                if rect_database[space].collidepoint(m_pos) == True:
                    print(space)
    
    pygame.display.flip()

这是 s_draw_loop():

class s_draw_loop():
    s_posx = 0
    s_posy = 0
    s_w = size[0] / 8
    s_h = size[1] / 8
    row = 0
    
    i = 0
    while i < 64:
        if i % 2 == 0:
            if row % 2 == 0:
                current_rect = pygame.Rect(s_posx,s_posy,s_w,s_h)
                screen.fill(white,current_rect)
            else:
                current_rect = pygame.Rect(s_posx,s_h)
                screen.fill(black,current_rect)
            s_posx += s_w
            i += 1
        
        else:
            if row % 2 == 0:
                current_rect = pygame.Rect(s_posx,current_rect)
            s_posx += s_w
            i += 1
        
        if i % 8 == 0:
            s_posx = 0
            s_posy += s_h
            row += 1

除非您需要,否则我将免除您绘制碎片的整个功能,但它基本上只是使用 pygame.Surface.blit() 将图片绘制到显示器上。

我尝试将“绘图功能”包含到游戏循环本身中,但似乎没有任何区别。

Here's the output when including 'screen.fill(black_sc)'

And here it is when commenting 'screen.fill(black_sc)' out

解决方法

这是因为 s_draw_loop 是一个类,而不是一个函数。

s_draw_loop 中的绘图代码只执行一次,在进入游戏循环之前,当 python 运行时读取类的代码时。

在您的游戏循环中调用 s_draw_loop() 实际上什么也没做(除了创建一个什么都不做的类的无用实例)。


简单的改变

class s_draw_loop():
    ...

def s_draw_loop():
    ...

所以 s_draw_loop 中的代码每帧都会执行。