pygame按键 [英] Pygame Key Press

查看:140
本文介绍了pygame按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基本的绘画程序来练习Pygame,但是我有一个问题,我正在使用按键事件来更改绘图颜色,但是当您放开按键时,它将恢复为默认的黑色.我敢肯定有一种简单的方法可以解决此问题,我只是不知道该怎么做!

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!

这是我的代码:

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

谢谢!

推荐答案

每次更新时,您将颜色设置为(0,0,0).如果未按任何键,则不会更改.您需要维护一个颜色变量,该颜色变量最初是黑色的,如果按下该键会更改,并且在每次更新时都不会重置.

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.

这篇关于pygame按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆