Pygame Key Press

[亡魂溺海] 提交于 2019-12-24 19:05:20

问题


I'm writing a basic drawing program to practice Pygame, but I have a problem I'm using key press events to change the drawing color but when you let go of the key it goes back to the default color black. I'm sure there is a easy way to fix this I just don't know how!

Here is my code:

import pygame
from pygame.locals import *
import sys

RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
WHITE = (255,255,255)

class Draw(object):


    def update(self, screen):
        color = (0,0,0)
        key = pygame.key.get_pressed()
        if key[pygame.K_r]:
            color = RED
        if key[pygame.K_g]:
            color = GREEN
        if key[pygame.K_b]:
            color = BLUE
        if key[pygame.K_w]:
            color = WHITE

        mouse_pos = pygame.mouse.get_pos()
        pygame.draw.circle(screen, (color), (mouse_pos),30)


    def main(self):

        pygame.init()
        screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('Basic Pygame program')
        background = pygame.Surface(screen.get_size())
        background = background.convert()
        background.fill((0, 0, 0))
        screen.blit(background, (0, 0))
        while 1:
            for event in pygame.event.get():
                if event.type == QUIT:
                     sys.exit()
            self.update(screen)
            pygame.display.flip()


if __name__ == '__main__':
    draw = Draw()
    draw.main()

Also any pointers or easier ways to write my code are much appreciated

Thank You!


回答1:


At each update, you set color to (0,0,0). If a key is not pressed this is not changed. You need to maintain a color variable that is initially black, changes if the key is pressed, and is not reset at each update.



来源:https://stackoverflow.com/questions/16869940/pygame-key-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!