pygame实现重复按住键

    科技2024-08-19  23

    1.参考官方文档

    https://www.pygame.org/docs/ref/key.html#pygame.key.set_repeat 

    2.实现功能代码

    pygame.key.set_repeat(pygame.KEYDOWN,10) # 实现重复按下的功能,间隔10毫秒

     3.案例代码

     

     wasd键控制方向

    import sys, pygame pygame.init() size = width, height = 500, 400 black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("intro_ball.gif") ballrect = ball.get_rect() pygame.key.set_repeat(pygame.KEYDOWN,10) # 实现重复按下的功能,间隔10毫秒 while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: ballrect = ballrect.move([-5,0]) if event.key == pygame.K_d: ballrect = ballrect.move([5,0]) if event.key == pygame.K_w: ballrect = ballrect.move([0,-5]) if event.key == pygame.K_s: ballrect = ballrect.move([0,5]) screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip()

     

     

    Processed: 0.009, SQL: 8