【问题标题】:Python PyGame rectangle won't change color on key press?Python PyGame矩形不会在按键时改变颜色?
【发布时间】:2021-08-24 07:53:51
【问题描述】:

当按下向下键时,我想更改矩形网格中第二个矩形(平铺)的颜色。到目前为止,我能够渲染 144 个矩形(图块),但是当按下时矩形不会改变颜色。顺便说一句,我是 pygame 的新手。这是我的代码。

import pygame, sys
from pygame.locals import *

SCREEN_HEIGHT = 500
SCREEN_WIDTH = 500
COLUMNS = 12
PURPLE = (97, 30, 130)
ROWS = 12
SIZE = 20
WHITE = (255, 255, 255) 
BLACK = (0, 0, 0)

def main():
  
    changed = False
    
    colors = []
    tiles = []

    pygame.init()
    DISPLAY = pygame.display.set_mode((SCREEN_HEIGHT,SCREEN_WIDTH))

    while True:

        for i in range(COLUMNS*ROWS):
            
            colors.append((255, 255, 255))

        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    sys.exit()
                elif event.key == K_DOWN:
                    changed = True
                   
        print(changed)

        if changed:
            colors[2] = BLACK


        def Draw():
            for color in colors:
                surf_tile = pygame.Surface((SIZE,SIZE), pygame.SRCALPHA)
                tile = pygame.Rect(0,0,SIZE,SIZE)
                pygame.draw.rect(surf_tile,color,tile)
                tiles.append(surf_tile)

            count = 0
            for column in range(COLUMNS):
                for row in range(ROWS):
                    DISPLAY.blit(tiles[count],(column*SIZE,row*SIZE))
                    count += count
            count += count
        
        
        Draw()
        pygame.display.flip()
        
        
        DISPLAY.fill(PURPLE)



main()

非常感谢任何形式的帮助!

【问题讨论】:

    标签: python pygame pygame-surface


    【解决方案1】:

    您必须在应用程序循环之前初始化一次颜色,而不是在循环中连续初始化:

    def main():
        global colors
        colors = []
    
        # [...]
    
        # INSERT
        for i in range(COLUMNS*ROWS):
            colors.append((256,255,255))
    
        while True:
    
            # DELETE
            #for i in range(COLUMNS*ROWS):
            #   colors.append((255, 255, 255))
    
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit()
    

    【讨论】:

    • 还是没有运气。我完全按照你说的做了,它仍然不会改变颜色!
    • @TharushaJayasooriya global colors 不见了。
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 2019-03-26
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多